descriptor.py 51 KB

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