descriptor.py 52 KB

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