descriptor.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. """Descriptors essentially contain exactly the information found in a .proto
  8. file, in types that make this information accessible in Python.
  9. """
  10. __author__ = 'robinson@google.com (Will Robinson)'
  11. import abc
  12. import binascii
  13. import os
  14. import threading
  15. import warnings
  16. from google.protobuf.internal import api_implementation
  17. _USE_C_DESCRIPTORS = False
  18. if api_implementation.Type() != 'python':
  19. # pylint: disable=protected-access
  20. _message = api_implementation._c_module
  21. # TODO: Remove this import after fix api_implementation
  22. if _message is None:
  23. from google.protobuf.pyext import _message
  24. _USE_C_DESCRIPTORS = True
  25. class Error(Exception):
  26. """Base error for this module."""
  27. class TypeTransformationError(Error):
  28. """Error transforming between python proto type and corresponding C++ type."""
  29. if _USE_C_DESCRIPTORS:
  30. # This metaclass allows to override the behavior of code like
  31. # isinstance(my_descriptor, FieldDescriptor)
  32. # and make it return True when the descriptor is an instance of the extension
  33. # type written in C++.
  34. class DescriptorMetaclass(type):
  35. def __instancecheck__(cls, obj):
  36. if super(DescriptorMetaclass, cls).__instancecheck__(obj):
  37. return True
  38. if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
  39. return True
  40. return False
  41. else:
  42. # The standard metaclass; nothing changes.
  43. DescriptorMetaclass = abc.ABCMeta
  44. class _Lock(object):
  45. """Wrapper class of threading.Lock(), which is allowed by 'with'."""
  46. def __new__(cls):
  47. self = object.__new__(cls)
  48. self._lock = threading.Lock() # pylint: disable=protected-access
  49. return self
  50. def __enter__(self):
  51. self._lock.acquire()
  52. def __exit__(self, exc_type, exc_value, exc_tb):
  53. self._lock.release()
  54. _lock = threading.Lock()
  55. def _Deprecated(
  56. name,
  57. alternative='get/find descriptors from generated code or query the descriptor_pool',
  58. ):
  59. if _Deprecated.count > 0:
  60. _Deprecated.count -= 1
  61. warnings.warn(
  62. 'Call to deprecated %s, use %s instead.' % (name, alternative),
  63. category=DeprecationWarning,
  64. stacklevel=3,
  65. )
  66. # These must match the values in descriptor.proto, but we can't use them
  67. # directly because we sometimes need to reference them in feature helpers
  68. # below *during* the build of descriptor.proto.
  69. _FEATURESET_MESSAGE_ENCODING_DELIMITED = 2
  70. _FEATURESET_FIELD_PRESENCE_IMPLICIT = 2
  71. _FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED = 3
  72. _FEATURESET_REPEATED_FIELD_ENCODING_PACKED = 1
  73. _FEATURESET_ENUM_TYPE_CLOSED = 2
  74. # Deprecated warnings will print 100 times at most which should be enough for
  75. # users to notice and do not cause timeout.
  76. _Deprecated.count = 100
  77. _internal_create_key = object()
  78. class DescriptorBase(metaclass=DescriptorMetaclass):
  79. """Descriptors base class.
  80. This class is the base of all descriptor classes. It provides common options
  81. related functionality.
  82. Attributes:
  83. has_options: True if the descriptor has non-default options. Usually it is
  84. not necessary to read this -- just call GetOptions() which will happily
  85. return the default instance. However, it's sometimes useful for
  86. efficiency, and also useful inside the protobuf implementation to avoid
  87. some bootstrapping issues.
  88. file (FileDescriptor): Reference to file info.
  89. """
  90. if _USE_C_DESCRIPTORS:
  91. # The class, or tuple of classes, that are considered as "virtual
  92. # subclasses" of this descriptor class.
  93. _C_DESCRIPTOR_CLASS = ()
  94. def __init__(self, file, options, serialized_options, options_class_name):
  95. """Initialize the descriptor given its options message and the name of the
  96. class of the options message. The name of the class is required in case
  97. the options message is None and has to be created.
  98. """
  99. self._features = None
  100. self.file = file
  101. self._original_options = options
  102. # These two fields are duplicated as a compatibility shim for old gencode
  103. # that resets them. In 26.x (cl/580304039) we renamed _options to,
  104. # _loaded_options breaking backwards compatibility.
  105. self._options = self._loaded_options = None
  106. self._options_class_name = options_class_name
  107. self._serialized_options = serialized_options
  108. # Does this descriptor have non-default options?
  109. self.has_options = (self._original_options is not None) or (
  110. self._serialized_options is not None
  111. )
  112. @property
  113. @abc.abstractmethod
  114. def _parent(self):
  115. pass
  116. def _InferLegacyFeatures(self, edition, options, features):
  117. """Infers features from proto2/proto3 syntax so that editions logic can be used everywhere.
  118. Args:
  119. edition: The edition to infer features for.
  120. options: The options for this descriptor that are being processed.
  121. features: The feature set object to modify with inferred features.
  122. """
  123. pass
  124. def _GetFeatures(self):
  125. if not self._features:
  126. self._LazyLoadOptions()
  127. return self._features
  128. def _ResolveFeatures(self, edition, raw_options):
  129. """Resolves features from the raw options of this descriptor.
  130. Args:
  131. edition: The edition to use for feature defaults.
  132. raw_options: The options for this descriptor that are being processed.
  133. Returns:
  134. A fully resolved feature set for making runtime decisions.
  135. """
  136. # pylint: disable=g-import-not-at-top
  137. from google.protobuf import descriptor_pb2
  138. if self._parent:
  139. features = descriptor_pb2.FeatureSet()
  140. features.CopyFrom(self._parent._GetFeatures())
  141. else:
  142. features = self.file.pool._CreateDefaultFeatures(edition)
  143. unresolved = descriptor_pb2.FeatureSet()
  144. unresolved.CopyFrom(raw_options.features)
  145. self._InferLegacyFeatures(edition, raw_options, unresolved)
  146. features.MergeFrom(unresolved)
  147. # Use the feature cache to reduce memory bloat.
  148. return self.file.pool._InternFeatures(features)
  149. def _LazyLoadOptions(self):
  150. """Lazily initializes descriptor options towards the end of the build."""
  151. if self._options and self._loaded_options == self._options:
  152. # If neither has been reset by gencode, use the cache.
  153. return
  154. # pylint: disable=g-import-not-at-top
  155. from google.protobuf import descriptor_pb2
  156. if not hasattr(descriptor_pb2, self._options_class_name):
  157. raise RuntimeError(
  158. 'Unknown options class name %s!' % self._options_class_name
  159. )
  160. options_class = getattr(descriptor_pb2, self._options_class_name)
  161. features = None
  162. edition = self.file._edition
  163. if not self.has_options:
  164. if not self._features:
  165. features = self._ResolveFeatures(
  166. descriptor_pb2.Edition.Value(edition), options_class()
  167. )
  168. with _lock:
  169. self._options = self._loaded_options = options_class()
  170. if not self._features:
  171. self._features = features
  172. else:
  173. if not self._serialized_options:
  174. options = self._original_options
  175. else:
  176. options = _ParseOptions(options_class(), self._serialized_options)
  177. if not self._features:
  178. features = self._ResolveFeatures(
  179. descriptor_pb2.Edition.Value(edition), options
  180. )
  181. with _lock:
  182. self._options = self._loaded_options = options
  183. if not self._features:
  184. self._features = features
  185. if options.HasField('features'):
  186. options.ClearField('features')
  187. if not options.SerializeToString():
  188. self._options = self._loaded_options = options_class()
  189. self.has_options = False
  190. def GetOptions(self):
  191. """Retrieves descriptor options.
  192. Returns:
  193. The options set on this descriptor.
  194. """
  195. # If either has been reset by gencode, reload options.
  196. if not self._options or not self._loaded_options:
  197. self._LazyLoadOptions()
  198. if (
  199. self._options
  200. and hasattr(self._options, '_SetFrozen')
  201. and not getattr(self._options, '_frozen', False)
  202. ):
  203. self._options._SetFrozen()
  204. return self._options
  205. class _NestedDescriptorBase(DescriptorBase):
  206. """Common class for descriptors that can be nested."""
  207. def __init__(
  208. self,
  209. options,
  210. options_class_name,
  211. name,
  212. full_name,
  213. file,
  214. containing_type,
  215. serialized_start=None,
  216. serialized_end=None,
  217. serialized_options=None,
  218. ):
  219. """Constructor.
  220. Args:
  221. options: Protocol message options or None to use default message options.
  222. options_class_name (str): The class name of the above options.
  223. name (str): Name of this protocol message type.
  224. full_name (str): Fully-qualified name of this protocol message type, which
  225. will include protocol "package" name and the name of any enclosing
  226. types.
  227. containing_type: if provided, this is a nested descriptor, with this
  228. descriptor as parent, otherwise None.
  229. serialized_start: The start index (inclusive) in block in the
  230. file.serialized_pb that describes this descriptor.
  231. serialized_end: The end index (exclusive) in block in the
  232. file.serialized_pb that describes this descriptor.
  233. serialized_options: Protocol message serialized options or None.
  234. """
  235. super(_NestedDescriptorBase, self).__init__(
  236. file, options, serialized_options, options_class_name
  237. )
  238. self.name = name
  239. # TODO: Add function to calculate full_name instead of having it in
  240. # memory?
  241. self.full_name = full_name
  242. self.containing_type = containing_type
  243. self._serialized_start = serialized_start
  244. self._serialized_end = serialized_end
  245. def CopyToProto(self, proto):
  246. """Copies this to the matching proto in descriptor_pb2.
  247. Args:
  248. proto: An empty proto instance from descriptor_pb2.
  249. Raises:
  250. Error: If self couldn't be serialized, due to to few constructor
  251. arguments.
  252. """
  253. if (
  254. self.file is not None
  255. and self._serialized_start is not None
  256. and self._serialized_end is not None
  257. ):
  258. proto.ParseFromString(
  259. self.file.serialized_pb[self._serialized_start : self._serialized_end]
  260. )
  261. else:
  262. raise Error('Descriptor does not contain serialization.')
  263. class Descriptor(_NestedDescriptorBase):
  264. """Descriptor for a protocol message type.
  265. Attributes:
  266. name (str): Name of this protocol message type.
  267. full_name (str): Fully-qualified name of this protocol message type, which
  268. will include protocol "package" name and the name of any enclosing
  269. types.
  270. containing_type (Descriptor): Reference to the descriptor of the type
  271. containing us, or None if this is top-level.
  272. fields (list[FieldDescriptor]): Field descriptors for all fields in this
  273. type.
  274. fields_by_number (dict(int, FieldDescriptor)): Same
  275. :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by
  276. "number" attribute in each FieldDescriptor.
  277. fields_by_name (dict(str, FieldDescriptor)): Same :class:`FieldDescriptor`
  278. objects as in :attr:`fields`, but indexed by "name" attribute in each
  279. :class:`FieldDescriptor`.
  280. nested_types (list[Descriptor]): Descriptor references for all protocol
  281. message types nested within this one.
  282. nested_types_by_name (dict(str, Descriptor)): Same Descriptor objects as
  283. in :attr:`nested_types`, but indexed by "name" attribute in each
  284. Descriptor.
  285. enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references for
  286. all enums contained within this type.
  287. enum_types_by_name (dict(str, EnumDescriptor)): Same
  288. :class:`EnumDescriptor` objects as in :attr:`enum_types`, but indexed by
  289. "name" attribute in each EnumDescriptor.
  290. enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping from
  291. enum value name to :class:`EnumValueDescriptor` for that value.
  292. extensions (list[FieldDescriptor]): All extensions defined directly within
  293. this message type (NOT within a nested type).
  294. extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor
  295. objects as :attr:`extensions`, but indexed by "name" attribute of each
  296. FieldDescriptor.
  297. is_extendable (bool): Does this type define any extension ranges?
  298. oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields
  299. in this message.
  300. oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in
  301. :attr:`oneofs`, but indexed by "name" attribute.
  302. file (FileDescriptor): Reference to file descriptor.
  303. is_map_entry: If the message type is a map entry.
  304. """
  305. if _USE_C_DESCRIPTORS:
  306. _C_DESCRIPTOR_CLASS = _message.Descriptor
  307. def __new__(
  308. cls,
  309. name=None,
  310. full_name=None,
  311. filename=None,
  312. containing_type=None,
  313. fields=None,
  314. nested_types=None,
  315. enum_types=None,
  316. extensions=None,
  317. options=None,
  318. serialized_options=None,
  319. is_extendable=True,
  320. extension_ranges=None,
  321. oneofs=None,
  322. file=None, # pylint: disable=redefined-builtin
  323. serialized_start=None,
  324. serialized_end=None,
  325. syntax=None,
  326. is_map_entry=False,
  327. create_key=None,
  328. ):
  329. _message.Message._CheckCalledFromGeneratedFile()
  330. return _message.default_pool.FindMessageTypeByName(full_name)
  331. # NOTE: The file argument redefining a builtin is nothing we can
  332. # fix right now since we don't know how many clients already rely on the
  333. # name of the argument.
  334. def __init__(
  335. self,
  336. name,
  337. full_name,
  338. filename,
  339. containing_type,
  340. fields,
  341. nested_types,
  342. enum_types,
  343. extensions,
  344. options=None,
  345. serialized_options=None,
  346. is_extendable=True,
  347. extension_ranges=None,
  348. oneofs=None,
  349. file=None,
  350. serialized_start=None,
  351. serialized_end=None, # pylint: disable=redefined-builtin
  352. syntax=None,
  353. is_map_entry=False,
  354. create_key=None,
  355. ):
  356. """Arguments to __init__() are as described in the description
  357. of Descriptor fields above.
  358. Note that filename is an obsolete argument, that is not used anymore.
  359. Please use file.name to access this as an attribute.
  360. """
  361. if create_key is not _internal_create_key:
  362. _Deprecated('create function Descriptor()')
  363. super(Descriptor, self).__init__(
  364. options,
  365. 'MessageOptions',
  366. name,
  367. full_name,
  368. file,
  369. containing_type,
  370. serialized_start=serialized_start,
  371. serialized_end=serialized_end,
  372. serialized_options=serialized_options,
  373. )
  374. # We have fields in addition to fields_by_name and fields_by_number,
  375. # so that:
  376. # 1. Clients can index fields by "order in which they're listed."
  377. # 2. Clients can easily iterate over all fields with the terse
  378. # syntax: for f in descriptor.fields: ...
  379. self.fields = fields
  380. for field in self.fields:
  381. field.containing_type = self
  382. field.file = file
  383. self.fields_by_number = dict((f.number, f) for f in fields)
  384. self.fields_by_name = dict((f.name, f) for f in fields)
  385. self._fields_by_camelcase_name = None
  386. self.nested_types = nested_types
  387. for nested_type in nested_types:
  388. nested_type.containing_type = self
  389. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  390. self.enum_types = enum_types
  391. for enum_type in self.enum_types:
  392. enum_type.containing_type = self
  393. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  394. self.enum_values_by_name = dict(
  395. (v.name, v) for t in enum_types for v in t.values
  396. )
  397. self.extensions = extensions
  398. for extension in self.extensions:
  399. extension.extension_scope = self
  400. self.extensions_by_name = dict((f.name, f) for f in extensions)
  401. self.is_extendable = is_extendable
  402. self.extension_ranges = extension_ranges
  403. self.oneofs = oneofs if oneofs is not None else []
  404. self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
  405. for oneof in self.oneofs:
  406. oneof.containing_type = self
  407. oneof.file = file
  408. self._is_map_entry = is_map_entry
  409. @property
  410. def _parent(self):
  411. return self.containing_type or self.file
  412. @property
  413. def fields_by_camelcase_name(self):
  414. """Same FieldDescriptor objects as in :attr:`fields`, but indexed by
  415. :attr:`FieldDescriptor.camelcase_name`.
  416. """
  417. if self._fields_by_camelcase_name is None:
  418. self._fields_by_camelcase_name = dict(
  419. (f.camelcase_name, f) for f in self.fields
  420. )
  421. return self._fields_by_camelcase_name
  422. def EnumValueName(self, enum, value):
  423. """Returns the string name of an enum value.
  424. This is just a small helper method to simplify a common operation.
  425. Args:
  426. enum: string name of the Enum.
  427. value: int, value of the enum.
  428. Returns:
  429. string name of the enum value.
  430. Raises:
  431. KeyError if either the Enum doesn't exist or the value is not a valid
  432. value for the enum.
  433. """
  434. return self.enum_types_by_name[enum].values_by_number[value].name
  435. def CopyToProto(self, proto):
  436. """Copies this to a descriptor_pb2.DescriptorProto.
  437. Args:
  438. proto: An empty descriptor_pb2.DescriptorProto.
  439. """
  440. # This function is overridden to give a better doc comment.
  441. super(Descriptor, self).CopyToProto(proto)
  442. # TODO: We should have aggressive checking here,
  443. # for example:
  444. # * If you specify a repeated field, you should not be allowed
  445. # to specify a default value.
  446. # * [Other examples here as needed].
  447. #
  448. # TODO: for this and other *Descriptor classes, we
  449. # might also want to lock things down aggressively (e.g.,
  450. # prevent clients from setting the attributes). Having
  451. # stronger invariants here in general will reduce the number
  452. # of runtime checks we must do in reflection.py...
  453. class FieldDescriptor(DescriptorBase):
  454. """Descriptor for a single field in a .proto file.
  455. Attributes:
  456. name (str): Name of this field, exactly as it appears in .proto.
  457. full_name (str): Name of this field, including containing scope. This is
  458. particularly relevant for extensions.
  459. index (int): Dense, 0-indexed index giving the order that this field
  460. textually appears within its message in the .proto file.
  461. number (int): Tag number declared for this field in the .proto file.
  462. type (int): (One of the TYPE_* constants below) Declared type.
  463. cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to
  464. represent this field.
  465. label (int): (One of the LABEL_* constants below) Tells whether this field
  466. is optional, required, or repeated.
  467. has_default_value (bool): True if this field has a default value defined,
  468. otherwise false.
  469. default_value (Varies): Default value of this field. Only meaningful for
  470. non-repeated scalar fields. Repeated fields should always set this to [],
  471. and non-repeated composite fields should always set this to None.
  472. containing_type (Descriptor): Descriptor of the protocol message type that
  473. contains this field. Set by the Descriptor constructor if we're passed
  474. into one. Somewhat confusingly, for extension fields, this is the
  475. descriptor of the EXTENDED message, not the descriptor of the message
  476. containing this field. (See is_extension and extension_scope below).
  477. message_type (Descriptor): If a composite field, a descriptor of the message
  478. type contained in this field. Otherwise, this is None.
  479. enum_type (EnumDescriptor): If this field contains an enum, a descriptor of
  480. that enum. Otherwise, this is None.
  481. is_extension: True iff this describes an extension field.
  482. extension_scope (Descriptor): Only meaningful if is_extension is True. Gives
  483. the message that immediately contains this extension field. Will be None
  484. iff we're a top-level (file-level) extension field.
  485. options (descriptor_pb2.FieldOptions): Protocol message field options or
  486. None to use default field options.
  487. containing_oneof (OneofDescriptor): If the field is a member of a oneof
  488. union, contains its descriptor. Otherwise, None.
  489. file (FileDescriptor): Reference to file descriptor.
  490. """
  491. # Must be consistent with C++ FieldDescriptor::Type enum in
  492. # descriptor.h.
  493. #
  494. # TODO: Find a way to eliminate this repetition.
  495. TYPE_DOUBLE = 1
  496. TYPE_FLOAT = 2
  497. TYPE_INT64 = 3
  498. TYPE_UINT64 = 4
  499. TYPE_INT32 = 5
  500. TYPE_FIXED64 = 6
  501. TYPE_FIXED32 = 7
  502. TYPE_BOOL = 8
  503. TYPE_STRING = 9
  504. TYPE_GROUP = 10
  505. TYPE_MESSAGE = 11
  506. TYPE_BYTES = 12
  507. TYPE_UINT32 = 13
  508. TYPE_ENUM = 14
  509. TYPE_SFIXED32 = 15
  510. TYPE_SFIXED64 = 16
  511. TYPE_SINT32 = 17
  512. TYPE_SINT64 = 18
  513. MAX_TYPE = 18
  514. # Must be consistent with C++ FieldDescriptor::CppType enum in
  515. # descriptor.h.
  516. #
  517. # TODO: Find a way to eliminate this repetition.
  518. CPPTYPE_INT32 = 1
  519. CPPTYPE_INT64 = 2
  520. CPPTYPE_UINT32 = 3
  521. CPPTYPE_UINT64 = 4
  522. CPPTYPE_DOUBLE = 5
  523. CPPTYPE_FLOAT = 6
  524. CPPTYPE_BOOL = 7
  525. CPPTYPE_ENUM = 8
  526. CPPTYPE_STRING = 9
  527. CPPTYPE_MESSAGE = 10
  528. MAX_CPPTYPE = 10
  529. _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
  530. TYPE_DOUBLE: CPPTYPE_DOUBLE,
  531. TYPE_FLOAT: CPPTYPE_FLOAT,
  532. TYPE_ENUM: CPPTYPE_ENUM,
  533. TYPE_INT64: CPPTYPE_INT64,
  534. TYPE_SINT64: CPPTYPE_INT64,
  535. TYPE_SFIXED64: CPPTYPE_INT64,
  536. TYPE_UINT64: CPPTYPE_UINT64,
  537. TYPE_FIXED64: CPPTYPE_UINT64,
  538. TYPE_INT32: CPPTYPE_INT32,
  539. TYPE_SFIXED32: CPPTYPE_INT32,
  540. TYPE_SINT32: CPPTYPE_INT32,
  541. TYPE_UINT32: CPPTYPE_UINT32,
  542. TYPE_FIXED32: CPPTYPE_UINT32,
  543. TYPE_BYTES: CPPTYPE_STRING,
  544. TYPE_STRING: CPPTYPE_STRING,
  545. TYPE_BOOL: CPPTYPE_BOOL,
  546. TYPE_MESSAGE: CPPTYPE_MESSAGE,
  547. TYPE_GROUP: CPPTYPE_MESSAGE,
  548. }
  549. # Must be consistent with C++ FieldDescriptor::Label enum in
  550. # descriptor.h.
  551. #
  552. # TODO: Find a way to eliminate this repetition.
  553. LABEL_OPTIONAL = 1
  554. LABEL_REQUIRED = 2
  555. LABEL_REPEATED = 3
  556. MAX_LABEL = 3
  557. # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
  558. # and kLastReservedNumber in descriptor.h
  559. MAX_FIELD_NUMBER = (1 << 29) - 1
  560. FIRST_RESERVED_FIELD_NUMBER = 19000
  561. LAST_RESERVED_FIELD_NUMBER = 19999
  562. if _USE_C_DESCRIPTORS:
  563. _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
  564. def __new__(
  565. cls,
  566. name,
  567. full_name,
  568. index,
  569. number,
  570. type,
  571. cpp_type,
  572. label,
  573. default_value,
  574. message_type,
  575. enum_type,
  576. containing_type,
  577. is_extension,
  578. extension_scope,
  579. options=None,
  580. serialized_options=None,
  581. has_default_value=True,
  582. containing_oneof=None,
  583. json_name=None,
  584. file=None,
  585. create_key=None,
  586. ): # pylint: disable=redefined-builtin
  587. _message.Message._CheckCalledFromGeneratedFile()
  588. if is_extension:
  589. return _message.default_pool.FindExtensionByName(full_name)
  590. else:
  591. return _message.default_pool.FindFieldByName(full_name)
  592. def __init__(
  593. self,
  594. name,
  595. full_name,
  596. index,
  597. number,
  598. type,
  599. cpp_type,
  600. label,
  601. default_value,
  602. message_type,
  603. enum_type,
  604. containing_type,
  605. is_extension,
  606. extension_scope,
  607. options=None,
  608. serialized_options=None,
  609. has_default_value=True,
  610. containing_oneof=None,
  611. json_name=None,
  612. file=None,
  613. create_key=None,
  614. ): # pylint: disable=redefined-builtin
  615. """The arguments are as described in the description of FieldDescriptor
  616. attributes above.
  617. Note that containing_type may be None, and may be set later if necessary
  618. (to deal with circular references between message types, for example).
  619. Likewise for extension_scope.
  620. """
  621. if create_key is not _internal_create_key:
  622. _Deprecated('create function FieldDescriptor()')
  623. super(FieldDescriptor, self).__init__(
  624. file, options, serialized_options, 'FieldOptions'
  625. )
  626. self.name = name
  627. self.full_name = full_name
  628. self._camelcase_name = None
  629. if json_name is None:
  630. self.json_name = _ToJsonName(name)
  631. else:
  632. self.json_name = json_name
  633. self.index = index
  634. self.number = number
  635. self._type = type
  636. self.cpp_type = cpp_type
  637. self._label = label
  638. self.has_default_value = has_default_value
  639. self.default_value = default_value
  640. self.containing_type = containing_type
  641. self.message_type = message_type
  642. self.enum_type = enum_type
  643. self.is_extension = is_extension
  644. self.extension_scope = extension_scope
  645. self.containing_oneof = containing_oneof
  646. if api_implementation.Type() == 'python':
  647. self._cdescriptor = None
  648. else:
  649. if is_extension:
  650. self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
  651. else:
  652. self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
  653. @property
  654. def _parent(self):
  655. if self.containing_oneof:
  656. return self.containing_oneof
  657. if self.is_extension:
  658. return self.extension_scope or self.file
  659. return self.containing_type
  660. def _InferLegacyFeatures(self, edition, options, features):
  661. # pylint: disable=g-import-not-at-top
  662. from google.protobuf import descriptor_pb2
  663. if edition >= descriptor_pb2.Edition.EDITION_2023:
  664. return
  665. if self._label == FieldDescriptor.LABEL_REQUIRED:
  666. features.field_presence = (
  667. descriptor_pb2.FeatureSet.FieldPresence.LEGACY_REQUIRED
  668. )
  669. if self._type == FieldDescriptor.TYPE_GROUP:
  670. features.message_encoding = (
  671. descriptor_pb2.FeatureSet.MessageEncoding.DELIMITED
  672. )
  673. if options.HasField('packed'):
  674. features.repeated_field_encoding = (
  675. descriptor_pb2.FeatureSet.RepeatedFieldEncoding.PACKED
  676. if options.packed
  677. else descriptor_pb2.FeatureSet.RepeatedFieldEncoding.EXPANDED
  678. )
  679. @property
  680. def type(self):
  681. if (
  682. self._GetFeatures().message_encoding
  683. == _FEATURESET_MESSAGE_ENCODING_DELIMITED
  684. and self.message_type
  685. and not self.message_type.GetOptions().map_entry
  686. and not self.containing_type.GetOptions().map_entry
  687. ):
  688. return FieldDescriptor.TYPE_GROUP
  689. return self._type
  690. @type.setter
  691. def type(self, val):
  692. self._type = val
  693. @property
  694. def is_required(self):
  695. """Returns if the field is required."""
  696. return (
  697. self._GetFeatures().field_presence
  698. == _FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED
  699. )
  700. @property
  701. def is_repeated(self):
  702. """Returns if the field is repeated."""
  703. return self._label == FieldDescriptor.LABEL_REPEATED
  704. @property
  705. def camelcase_name(self):
  706. """Camelcase name of this field.
  707. Returns:
  708. str: the name in CamelCase.
  709. """
  710. if self._camelcase_name is None:
  711. self._camelcase_name = _ToCamelCase(self.name)
  712. return self._camelcase_name
  713. @property
  714. def has_presence(self):
  715. """Whether the field distinguishes between unpopulated and default values.
  716. Raises:
  717. RuntimeError: singular field that is not linked with message nor file.
  718. """
  719. if self.is_repeated:
  720. return False
  721. if (
  722. self.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE
  723. or self.is_extension
  724. or self.containing_oneof
  725. ):
  726. return True
  727. return (
  728. self._GetFeatures().field_presence
  729. != _FEATURESET_FIELD_PRESENCE_IMPLICIT
  730. )
  731. @property
  732. def is_packed(self):
  733. """Returns if the field is packed."""
  734. if not self.is_repeated:
  735. return False
  736. field_type = self.type
  737. if (
  738. field_type == FieldDescriptor.TYPE_STRING
  739. or field_type == FieldDescriptor.TYPE_GROUP
  740. or field_type == FieldDescriptor.TYPE_MESSAGE
  741. or field_type == FieldDescriptor.TYPE_BYTES
  742. ):
  743. return False
  744. return (
  745. self._GetFeatures().repeated_field_encoding
  746. == _FEATURESET_REPEATED_FIELD_ENCODING_PACKED
  747. )
  748. @staticmethod
  749. def ProtoTypeToCppProtoType(proto_type):
  750. """Converts from a Python proto type to a C++ Proto Type.
  751. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  752. 'C++' datatype - and they're not the same. This helper method should
  753. translate from one to another.
  754. Args:
  755. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  756. Returns:
  757. int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  758. Raises:
  759. TypeTransformationError: when the Python proto type isn't known.
  760. """
  761. try:
  762. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  763. except KeyError:
  764. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  765. class EnumDescriptor(_NestedDescriptorBase):
  766. """Descriptor for an enum defined in a .proto file.
  767. Attributes:
  768. name (str): Name of the enum type.
  769. full_name (str): Full name of the type, including package name and any
  770. enclosing type(s).
  771. values (list[EnumValueDescriptor]): List of the values in this enum.
  772. values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`, but
  773. indexed by the "name" field of each EnumValueDescriptor.
  774. values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`,
  775. but indexed by the "number" field of each EnumValueDescriptor.
  776. containing_type (Descriptor): Descriptor of the immediate containing type of
  777. this enum, or None if this is an enum defined at the top level in a .proto
  778. file. Set by Descriptor's constructor if we're passed into one.
  779. file (FileDescriptor): Reference to file descriptor.
  780. options (descriptor_pb2.EnumOptions): Enum options message or None to use
  781. default enum options.
  782. """
  783. if _USE_C_DESCRIPTORS:
  784. _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
  785. def __new__(
  786. cls,
  787. name,
  788. full_name,
  789. filename,
  790. values,
  791. containing_type=None,
  792. options=None,
  793. serialized_options=None,
  794. file=None, # pylint: disable=redefined-builtin
  795. serialized_start=None,
  796. serialized_end=None,
  797. create_key=None,
  798. ):
  799. _message.Message._CheckCalledFromGeneratedFile()
  800. return _message.default_pool.FindEnumTypeByName(full_name)
  801. def __init__(
  802. self,
  803. name,
  804. full_name,
  805. filename,
  806. values,
  807. containing_type=None,
  808. options=None,
  809. serialized_options=None,
  810. file=None, # pylint: disable=redefined-builtin
  811. serialized_start=None,
  812. serialized_end=None,
  813. create_key=None,
  814. ):
  815. """Arguments are as described in the attribute description above.
  816. Note that filename is an obsolete argument, that is not used anymore.
  817. Please use file.name to access this as an attribute.
  818. """
  819. if create_key is not _internal_create_key:
  820. _Deprecated('create function EnumDescriptor()')
  821. super(EnumDescriptor, self).__init__(
  822. options,
  823. 'EnumOptions',
  824. name,
  825. full_name,
  826. file,
  827. containing_type,
  828. serialized_start=serialized_start,
  829. serialized_end=serialized_end,
  830. serialized_options=serialized_options,
  831. )
  832. self.values = values
  833. for value in self.values:
  834. value.file = file
  835. value.type = self
  836. self.values_by_name = dict((v.name, v) for v in values)
  837. # Values are reversed to ensure that the first alias is retained.
  838. self.values_by_number = dict((v.number, v) for v in reversed(values))
  839. @property
  840. def _parent(self):
  841. return self.containing_type or self.file
  842. @property
  843. def is_closed(self):
  844. """Returns true whether this is a "closed" enum.
  845. This means that it:
  846. - Has a fixed set of values, rather than being equivalent to an int32.
  847. - Encountering values not in this set causes them to be treated as unknown
  848. fields.
  849. - The first value (i.e., the default) may be nonzero.
  850. WARNING: Some runtimes currently have a quirk where non-closed enums are
  851. treated as closed when used as the type of fields defined in a
  852. `syntax = proto2;` file. This quirk is not present in all runtimes; as of
  853. writing, we know that:
  854. - C++, Java, and C++-based Python share this quirk.
  855. - UPB and UPB-based Python do not.
  856. - PHP and Ruby treat all enums as open regardless of declaration.
  857. Care should be taken when using this function to respect the target
  858. runtime's enum handling quirks.
  859. """
  860. return self._GetFeatures().enum_type == _FEATURESET_ENUM_TYPE_CLOSED
  861. def CopyToProto(self, proto):
  862. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  863. Args:
  864. proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto.
  865. """
  866. # This function is overridden to give a better doc comment.
  867. super(EnumDescriptor, self).CopyToProto(proto)
  868. class EnumValueDescriptor(DescriptorBase):
  869. """Descriptor for a single value within an enum.
  870. Attributes:
  871. name (str): Name of this value.
  872. index (int): Dense, 0-indexed index giving the order that this value appears
  873. textually within its enum in the .proto file.
  874. number (int): Actual number assigned to this enum value.
  875. type (EnumDescriptor): :class:`EnumDescriptor` to which this value belongs.
  876. Set by :class:`EnumDescriptor`'s constructor if we're passed into one.
  877. options (descriptor_pb2.EnumValueOptions): Enum value options message or
  878. None to use default enum value options options.
  879. """
  880. if _USE_C_DESCRIPTORS:
  881. _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
  882. def __new__(
  883. cls,
  884. name,
  885. index,
  886. number,
  887. type=None, # pylint: disable=redefined-builtin
  888. options=None,
  889. serialized_options=None,
  890. create_key=None,
  891. ):
  892. _message.Message._CheckCalledFromGeneratedFile()
  893. # There is no way we can build a complete EnumValueDescriptor with the
  894. # given parameters (the name of the Enum is not known, for example).
  895. # Fortunately generated files just pass it to the EnumDescriptor()
  896. # constructor, which will ignore it, so returning None is good enough.
  897. return None
  898. def __init__(
  899. self,
  900. name,
  901. index,
  902. number,
  903. type=None, # pylint: disable=redefined-builtin
  904. options=None,
  905. serialized_options=None,
  906. create_key=None,
  907. ):
  908. """Arguments are as described in the attribute description above."""
  909. if create_key is not _internal_create_key:
  910. _Deprecated('create function EnumValueDescriptor()')
  911. super(EnumValueDescriptor, self).__init__(
  912. type.file if type else None,
  913. options,
  914. serialized_options,
  915. 'EnumValueOptions',
  916. )
  917. self.name = name
  918. self.index = index
  919. self.number = number
  920. self.type = type
  921. @property
  922. def _parent(self):
  923. return self.type
  924. class OneofDescriptor(DescriptorBase):
  925. """Descriptor for a oneof field.
  926. Attributes:
  927. name (str): Name of the oneof field.
  928. full_name (str): Full name of the oneof field, including package name.
  929. index (int): 0-based index giving the order of the oneof field inside its
  930. containing type.
  931. containing_type (Descriptor): :class:`Descriptor` of the protocol message
  932. type that contains this field. Set by the :class:`Descriptor` constructor
  933. if we're passed into one.
  934. fields (list[FieldDescriptor]): The list of field descriptors this oneof can
  935. contain.
  936. """
  937. if _USE_C_DESCRIPTORS:
  938. _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
  939. def __new__(
  940. cls,
  941. name,
  942. full_name,
  943. index,
  944. containing_type,
  945. fields,
  946. options=None,
  947. serialized_options=None,
  948. create_key=None,
  949. ):
  950. _message.Message._CheckCalledFromGeneratedFile()
  951. return _message.default_pool.FindOneofByName(full_name)
  952. def __init__(
  953. self,
  954. name,
  955. full_name,
  956. index,
  957. containing_type,
  958. fields,
  959. options=None,
  960. serialized_options=None,
  961. create_key=None,
  962. ):
  963. """Arguments are as described in the attribute description above."""
  964. if create_key is not _internal_create_key:
  965. _Deprecated('create function OneofDescriptor()')
  966. super(OneofDescriptor, self).__init__(
  967. containing_type.file if containing_type else None,
  968. options,
  969. serialized_options,
  970. 'OneofOptions',
  971. )
  972. self.name = name
  973. self.full_name = full_name
  974. self.index = index
  975. self.containing_type = containing_type
  976. self.fields = fields
  977. @property
  978. def _parent(self):
  979. return self.containing_type
  980. class ServiceDescriptor(_NestedDescriptorBase):
  981. """Descriptor for a service.
  982. Attributes:
  983. name (str): Name of the service.
  984. full_name (str): Full name of the service, including package name.
  985. index (int): 0-indexed index giving the order that this services definition
  986. appears within the .proto file.
  987. methods (list[MethodDescriptor]): List of methods provided by this service.
  988. methods_by_name (dict(str, MethodDescriptor)): Same
  989. :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but
  990. indexed by "name" attribute in each :class:`MethodDescriptor`.
  991. options (descriptor_pb2.ServiceOptions): Service options message or None to
  992. use default service options.
  993. file (FileDescriptor): Reference to file info.
  994. """
  995. if _USE_C_DESCRIPTORS:
  996. _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
  997. def __new__(
  998. cls,
  999. name=None,
  1000. full_name=None,
  1001. index=None,
  1002. methods=None,
  1003. options=None,
  1004. serialized_options=None,
  1005. file=None, # pylint: disable=redefined-builtin
  1006. serialized_start=None,
  1007. serialized_end=None,
  1008. create_key=None,
  1009. ):
  1010. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  1011. return _message.default_pool.FindServiceByName(full_name)
  1012. def __init__(
  1013. self,
  1014. name,
  1015. full_name,
  1016. index,
  1017. methods,
  1018. options=None,
  1019. serialized_options=None,
  1020. file=None, # pylint: disable=redefined-builtin
  1021. serialized_start=None,
  1022. serialized_end=None,
  1023. create_key=None,
  1024. ):
  1025. if create_key is not _internal_create_key:
  1026. _Deprecated('create function ServiceDescriptor()')
  1027. super(ServiceDescriptor, self).__init__(
  1028. options,
  1029. 'ServiceOptions',
  1030. name,
  1031. full_name,
  1032. file,
  1033. None,
  1034. serialized_start=serialized_start,
  1035. serialized_end=serialized_end,
  1036. serialized_options=serialized_options,
  1037. )
  1038. self.index = index
  1039. self.methods = methods
  1040. self.methods_by_name = dict((m.name, m) for m in methods)
  1041. # Set the containing service for each method in this service.
  1042. for method in self.methods:
  1043. method.file = self.file
  1044. method.containing_service = self
  1045. @property
  1046. def _parent(self):
  1047. return self.file
  1048. def FindMethodByName(self, name):
  1049. """Searches for the specified method, and returns its descriptor.
  1050. Args:
  1051. name (str): Name of the method.
  1052. Returns:
  1053. MethodDescriptor: The descriptor for the requested method.
  1054. Raises:
  1055. KeyError: if the method cannot be found in the service.
  1056. """
  1057. return self.methods_by_name[name]
  1058. def CopyToProto(self, proto):
  1059. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  1060. Args:
  1061. proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto.
  1062. """
  1063. # This function is overridden to give a better doc comment.
  1064. super(ServiceDescriptor, self).CopyToProto(proto)
  1065. class MethodDescriptor(DescriptorBase):
  1066. """Descriptor for a method in a service.
  1067. Attributes:
  1068. name (str): Name of the method within the service.
  1069. full_name (str): Full name of method.
  1070. index (int): 0-indexed index of the method inside the service.
  1071. containing_service (ServiceDescriptor): The service that contains this
  1072. method.
  1073. input_type (Descriptor): The descriptor of the message that this method
  1074. accepts.
  1075. output_type (Descriptor): The descriptor of the message that this method
  1076. returns.
  1077. client_streaming (bool): Whether this method uses client streaming.
  1078. server_streaming (bool): Whether this method uses server streaming.
  1079. options (descriptor_pb2.MethodOptions or None): Method options message, or
  1080. None to use default method options.
  1081. """
  1082. if _USE_C_DESCRIPTORS:
  1083. _C_DESCRIPTOR_CLASS = _message.MethodDescriptor
  1084. def __new__(
  1085. cls,
  1086. name,
  1087. full_name,
  1088. index,
  1089. containing_service,
  1090. input_type,
  1091. output_type,
  1092. client_streaming=False,
  1093. server_streaming=False,
  1094. options=None,
  1095. serialized_options=None,
  1096. create_key=None,
  1097. ):
  1098. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  1099. return _message.default_pool.FindMethodByName(full_name)
  1100. def __init__(
  1101. self,
  1102. name,
  1103. full_name,
  1104. index,
  1105. containing_service,
  1106. input_type,
  1107. output_type,
  1108. client_streaming=False,
  1109. server_streaming=False,
  1110. options=None,
  1111. serialized_options=None,
  1112. create_key=None,
  1113. ):
  1114. """The arguments are as described in the description of MethodDescriptor
  1115. attributes above.
  1116. Note that containing_service may be None, and may be set later if necessary.
  1117. """
  1118. if create_key is not _internal_create_key:
  1119. _Deprecated('create function MethodDescriptor()')
  1120. super(MethodDescriptor, self).__init__(
  1121. containing_service.file if containing_service else None,
  1122. options,
  1123. serialized_options,
  1124. 'MethodOptions',
  1125. )
  1126. self.name = name
  1127. self.full_name = full_name
  1128. self.index = index
  1129. self.containing_service = containing_service
  1130. self.input_type = input_type
  1131. self.output_type = output_type
  1132. self.client_streaming = client_streaming
  1133. self.server_streaming = server_streaming
  1134. @property
  1135. def _parent(self):
  1136. return self.containing_service
  1137. def CopyToProto(self, proto):
  1138. """Copies this to a descriptor_pb2.MethodDescriptorProto.
  1139. Args:
  1140. proto (descriptor_pb2.MethodDescriptorProto): An empty descriptor proto.
  1141. Raises:
  1142. Error: If self couldn't be serialized, due to too few constructor
  1143. arguments.
  1144. """
  1145. if self.containing_service is not None:
  1146. from google.protobuf import descriptor_pb2
  1147. service_proto = descriptor_pb2.ServiceDescriptorProto()
  1148. self.containing_service.CopyToProto(service_proto)
  1149. proto.CopyFrom(service_proto.method[self.index])
  1150. else:
  1151. raise Error('Descriptor does not contain a service.')
  1152. class FileDescriptor(DescriptorBase):
  1153. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  1154. Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and
  1155. :attr:`dependencies` fields are only set by the
  1156. :py:mod:`google.protobuf.message_factory` module, and not by the generated
  1157. proto code.
  1158. Attributes:
  1159. name (str): Name of file, relative to root of source tree.
  1160. package (str): Name of the package
  1161. edition (Edition): Enum value indicating edition of the file
  1162. serialized_pb (bytes): Byte string of serialized
  1163. :class:`descriptor_pb2.FileDescriptorProto`.
  1164. dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor`
  1165. objects this :class:`FileDescriptor` depends on.
  1166. public_dependencies (list[FileDescriptor]): A subset of
  1167. :attr:`dependencies`, which were declared as "public".
  1168. message_types_by_name (dict(str, Descriptor)): Mapping from message names to
  1169. their :class:`Descriptor`.
  1170. enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to
  1171. their :class:`EnumDescriptor`.
  1172. extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension
  1173. names declared at file scope to their :class:`FieldDescriptor`.
  1174. services_by_name (dict(str, ServiceDescriptor)): Mapping from services'
  1175. names to their :class:`ServiceDescriptor`.
  1176. pool (DescriptorPool): The pool this descriptor belongs to. When not passed
  1177. to the constructor, the global default pool is used.
  1178. """
  1179. if _USE_C_DESCRIPTORS:
  1180. _C_DESCRIPTOR_CLASS = _message.FileDescriptor
  1181. def __new__(
  1182. cls,
  1183. name,
  1184. package,
  1185. options=None,
  1186. serialized_options=None,
  1187. serialized_pb=None,
  1188. dependencies=None,
  1189. public_dependencies=None,
  1190. syntax=None,
  1191. edition=None,
  1192. pool=None,
  1193. create_key=None,
  1194. ):
  1195. # FileDescriptor() is called from various places, not only from generated
  1196. # files, to register dynamic proto files and messages.
  1197. # pylint: disable=g-explicit-bool-comparison
  1198. if serialized_pb:
  1199. return _message.default_pool.AddSerializedFile(serialized_pb)
  1200. else:
  1201. return super(FileDescriptor, cls).__new__(cls)
  1202. def __init__(
  1203. self,
  1204. name,
  1205. package,
  1206. options=None,
  1207. serialized_options=None,
  1208. serialized_pb=None,
  1209. dependencies=None,
  1210. public_dependencies=None,
  1211. syntax=None,
  1212. edition=None,
  1213. pool=None,
  1214. create_key=None,
  1215. ):
  1216. """Constructor."""
  1217. if create_key is not _internal_create_key:
  1218. _Deprecated('create function FileDescriptor()')
  1219. super(FileDescriptor, self).__init__(
  1220. self, options, serialized_options, 'FileOptions'
  1221. )
  1222. if edition and edition != 'EDITION_UNKNOWN':
  1223. self._edition = edition
  1224. elif syntax == 'proto3':
  1225. self._edition = 'EDITION_PROTO3'
  1226. else:
  1227. self._edition = 'EDITION_PROTO2'
  1228. if pool is None:
  1229. from google.protobuf import descriptor_pool
  1230. pool = descriptor_pool.Default()
  1231. self.pool = pool
  1232. self.message_types_by_name = {}
  1233. self.name = name
  1234. self.package = package
  1235. self.serialized_pb = serialized_pb
  1236. self.enum_types_by_name = {}
  1237. self.extensions_by_name = {}
  1238. self.services_by_name = {}
  1239. self.dependencies = dependencies or []
  1240. self.public_dependencies = public_dependencies or []
  1241. def CopyToProto(self, proto):
  1242. """Copies this to a descriptor_pb2.FileDescriptorProto.
  1243. Args:
  1244. proto: An empty descriptor_pb2.FileDescriptorProto.
  1245. """
  1246. proto.ParseFromString(self.serialized_pb)
  1247. @property
  1248. def _parent(self):
  1249. return None
  1250. def _ParseOptions(message, string):
  1251. """Parses serialized options.
  1252. This helper function is used to parse serialized options in generated
  1253. proto2 files. It must not be used outside proto2.
  1254. """
  1255. message.ParseFromString(string)
  1256. return message
  1257. def _ToCamelCase(name):
  1258. """Converts name to camel-case and returns it."""
  1259. capitalize_next = False
  1260. result = []
  1261. for c in name:
  1262. if c == '_':
  1263. if result:
  1264. capitalize_next = True
  1265. elif capitalize_next:
  1266. result.append(c.upper())
  1267. capitalize_next = False
  1268. else:
  1269. result += c
  1270. # Lower-case the first letter.
  1271. if result and result[0].isupper():
  1272. result[0] = result[0].lower()
  1273. return ''.join(result)
  1274. def _OptionsOrNone(descriptor_proto):
  1275. """Returns the value of the field `options`, or None if it is not set."""
  1276. if descriptor_proto.HasField('options'):
  1277. return descriptor_proto.options
  1278. else:
  1279. return None
  1280. def _ToJsonName(name):
  1281. """Converts name to Json name and returns it."""
  1282. capitalize_next = False
  1283. result = []
  1284. for c in name:
  1285. if c == '_':
  1286. capitalize_next = True
  1287. elif capitalize_next:
  1288. result.append(c.upper())
  1289. capitalize_next = False
  1290. else:
  1291. result += c
  1292. return ''.join(result)
  1293. def MakeDescriptor(
  1294. desc_proto,
  1295. package='',
  1296. build_file_if_cpp=True,
  1297. syntax=None,
  1298. edition=None,
  1299. file_desc=None,
  1300. ):
  1301. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  1302. Handles nested descriptors. Note that this is limited to the scope of defining
  1303. a message inside of another message. Composite fields can currently only be
  1304. resolved if the message is defined in the same scope as the field.
  1305. Args:
  1306. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  1307. package: Optional package name for the new message Descriptor (string).
  1308. build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to
  1309. False on recursion, so no duplicates are created.
  1310. syntax: The syntax/semantics that should be used. Set to "proto3" to get
  1311. proto3 field presence semantics.
  1312. edition: The edition that should be used if syntax is "edition".
  1313. file_desc: A FileDescriptor to place this descriptor into.
  1314. Returns:
  1315. A Descriptor for protobuf messages.
  1316. """
  1317. # pylint: disable=g-import-not-at-top
  1318. from google.protobuf import descriptor_pb2
  1319. # Generate a random name for this proto file to prevent conflicts with any
  1320. # imported ones. We need to specify a file name so the descriptor pool
  1321. # accepts our FileDescriptorProto, but it is not important what that file
  1322. # name is actually set to.
  1323. proto_name = binascii.hexlify(os.urandom(16)).decode('ascii')
  1324. if package:
  1325. file_name = os.path.join(package.replace('.', '/'), proto_name + '.proto')
  1326. else:
  1327. file_name = proto_name + '.proto'
  1328. if api_implementation.Type() != 'python' and build_file_if_cpp:
  1329. # The C++ implementation requires all descriptors to be backed by the same
  1330. # definition in the C++ descriptor pool. To do this, we build a
  1331. # FileDescriptorProto with the same definition as this descriptor and build
  1332. # it into the pool.
  1333. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  1334. file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
  1335. if package:
  1336. file_descriptor_proto.package = package
  1337. file_descriptor_proto.name = file_name
  1338. _message.default_pool.Add(file_descriptor_proto)
  1339. result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
  1340. if _USE_C_DESCRIPTORS:
  1341. return result.message_types_by_name[desc_proto.name]
  1342. if file_desc is None:
  1343. file_desc = FileDescriptor(
  1344. pool=None,
  1345. name=file_name,
  1346. package=package,
  1347. syntax=syntax,
  1348. edition=edition,
  1349. options=None,
  1350. serialized_pb='',
  1351. dependencies=[],
  1352. public_dependencies=[],
  1353. create_key=_internal_create_key,
  1354. )
  1355. full_message_name = [desc_proto.name]
  1356. if package:
  1357. full_message_name.insert(0, package)
  1358. # Create Descriptors for enum types
  1359. enum_types = {}
  1360. for enum_proto in desc_proto.enum_type:
  1361. full_name = '.'.join(full_message_name + [enum_proto.name])
  1362. enum_desc = EnumDescriptor(
  1363. enum_proto.name,
  1364. full_name,
  1365. None,
  1366. [
  1367. EnumValueDescriptor(
  1368. enum_val.name,
  1369. ii,
  1370. enum_val.number,
  1371. create_key=_internal_create_key,
  1372. )
  1373. for ii, enum_val in enumerate(enum_proto.value)
  1374. ],
  1375. file=file_desc,
  1376. create_key=_internal_create_key,
  1377. )
  1378. enum_types[full_name] = enum_desc
  1379. # Create Descriptors for nested types
  1380. nested_types = {}
  1381. for nested_proto in desc_proto.nested_type:
  1382. full_name = '.'.join(full_message_name + [nested_proto.name])
  1383. # Nested types are just those defined inside of the message, not all types
  1384. # used by fields in the message, so no loops are possible here.
  1385. nested_desc = MakeDescriptor(
  1386. nested_proto,
  1387. package='.'.join(full_message_name),
  1388. build_file_if_cpp=False,
  1389. syntax=syntax,
  1390. edition=edition,
  1391. file_desc=file_desc,
  1392. )
  1393. nested_types[full_name] = nested_desc
  1394. fields = []
  1395. for field_proto in desc_proto.field:
  1396. full_name = '.'.join(full_message_name + [field_proto.name])
  1397. enum_desc = None
  1398. nested_desc = None
  1399. if field_proto.json_name:
  1400. json_name = field_proto.json_name
  1401. else:
  1402. json_name = None
  1403. if field_proto.HasField('type_name'):
  1404. type_name = field_proto.type_name
  1405. full_type_name = '.'.join(
  1406. full_message_name + [type_name[type_name.rfind('.') + 1 :]]
  1407. )
  1408. if full_type_name in nested_types:
  1409. nested_desc = nested_types[full_type_name]
  1410. elif full_type_name in enum_types:
  1411. enum_desc = enum_types[full_type_name]
  1412. # Else type_name references a non-local type, which isn't implemented
  1413. field = FieldDescriptor(
  1414. field_proto.name,
  1415. full_name,
  1416. field_proto.number - 1,
  1417. field_proto.number,
  1418. field_proto.type,
  1419. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  1420. field_proto.label,
  1421. None,
  1422. nested_desc,
  1423. enum_desc,
  1424. None,
  1425. False,
  1426. None,
  1427. options=_OptionsOrNone(field_proto),
  1428. has_default_value=False,
  1429. json_name=json_name,
  1430. file=file_desc,
  1431. create_key=_internal_create_key,
  1432. )
  1433. fields.append(field)
  1434. desc_name = '.'.join(full_message_name)
  1435. return Descriptor(
  1436. desc_proto.name,
  1437. desc_name,
  1438. None,
  1439. None,
  1440. fields,
  1441. list(nested_types.values()),
  1442. list(enum_types.values()),
  1443. [],
  1444. options=_OptionsOrNone(desc_proto),
  1445. file=file_desc,
  1446. create_key=_internal_create_key,
  1447. )