descriptor.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Descriptors essentially contain exactly the information found in a .proto
  31. file, in types that make this information accessible in Python.
  32. """
  33. __author__ = 'robinson@google.com (Will Robinson)'
  34. import threading
  35. import warnings
  36. import six
  37. from google.protobuf.internal import api_implementation
  38. _USE_C_DESCRIPTORS = False
  39. if api_implementation.Type() == 'cpp':
  40. # Used by MakeDescriptor in cpp mode
  41. import binascii
  42. import os
  43. from google.protobuf.pyext import _message
  44. _USE_C_DESCRIPTORS = True
  45. class Error(Exception):
  46. """Base error for this module."""
  47. class TypeTransformationError(Error):
  48. """Error transforming between python proto type and corresponding C++ type."""
  49. if _USE_C_DESCRIPTORS:
  50. # This metaclass allows to override the behavior of code like
  51. # isinstance(my_descriptor, FieldDescriptor)
  52. # and make it return True when the descriptor is an instance of the extension
  53. # type written in C++.
  54. class DescriptorMetaclass(type):
  55. def __instancecheck__(cls, obj):
  56. if super(DescriptorMetaclass, cls).__instancecheck__(obj):
  57. return True
  58. if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
  59. return True
  60. return False
  61. else:
  62. # The standard metaclass; nothing changes.
  63. DescriptorMetaclass = type
  64. class _Lock(object):
  65. """Wrapper class of threading.Lock(), which is allowed by 'with'."""
  66. def __new__(cls):
  67. self = object.__new__(cls)
  68. self._lock = threading.Lock() # pylint: disable=protected-access
  69. return self
  70. def __enter__(self):
  71. self._lock.acquire()
  72. def __exit__(self, exc_type, exc_value, exc_tb):
  73. self._lock.release()
  74. _lock = threading.Lock()
  75. def _Deprecated(name):
  76. if _Deprecated.count > 0:
  77. _Deprecated.count -= 1
  78. warnings.warn(
  79. 'Call to deprecated create function %s(). Note: Create unlinked '
  80. 'descriptors is going to go away. Please use get/find descriptors from '
  81. 'generated code or query the descriptor_pool.'
  82. % name,
  83. category=DeprecationWarning, stacklevel=3)
  84. # Deprecated warnings will print 100 times at most which should be enough for
  85. # users to notice and do not cause timeout.
  86. _Deprecated.count = 100
  87. _internal_create_key = object()
  88. class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
  89. """Descriptors base class.
  90. This class is the base of all descriptor classes. It provides common options
  91. related functionality.
  92. Attributes:
  93. has_options: True if the descriptor has non-default options. Usually it
  94. is not necessary to read this -- just call GetOptions() which will
  95. happily return the default instance. However, it's sometimes useful
  96. for efficiency, and also useful inside the protobuf implementation to
  97. avoid some bootstrapping issues.
  98. """
  99. if _USE_C_DESCRIPTORS:
  100. # The class, or tuple of classes, that are considered as "virtual
  101. # subclasses" of this descriptor class.
  102. _C_DESCRIPTOR_CLASS = ()
  103. def __init__(self, options, serialized_options, options_class_name):
  104. """Initialize the descriptor given its options message and the name of the
  105. class of the options message. The name of the class is required in case
  106. the options message is None and has to be created.
  107. """
  108. self._options = options
  109. self._options_class_name = options_class_name
  110. self._serialized_options = serialized_options
  111. # Does this descriptor have non-default options?
  112. self.has_options = (options is not None) or (serialized_options is not None)
  113. def _SetOptions(self, options, options_class_name):
  114. """Sets the descriptor's options
  115. This function is used in generated proto2 files to update descriptor
  116. options. It must not be used outside proto2.
  117. """
  118. self._options = options
  119. self._options_class_name = options_class_name
  120. # Does this descriptor have non-default options?
  121. self.has_options = options is not None
  122. def GetOptions(self):
  123. """Retrieves descriptor options.
  124. This method returns the options set or creates the default options for the
  125. descriptor.
  126. """
  127. if self._options:
  128. return self._options
  129. from google.protobuf import descriptor_pb2
  130. try:
  131. options_class = getattr(descriptor_pb2,
  132. self._options_class_name)
  133. except AttributeError:
  134. raise RuntimeError('Unknown options class name %s!' %
  135. (self._options_class_name))
  136. with _lock:
  137. if self._serialized_options is None:
  138. self._options = options_class()
  139. else:
  140. self._options = _ParseOptions(options_class(),
  141. self._serialized_options)
  142. return self._options
  143. class _NestedDescriptorBase(DescriptorBase):
  144. """Common class for descriptors that can be nested."""
  145. def __init__(self, options, options_class_name, name, full_name,
  146. file, containing_type, serialized_start=None,
  147. serialized_end=None, serialized_options=None):
  148. """Constructor.
  149. Args:
  150. options: Protocol message options or None
  151. to use default message options.
  152. options_class_name (str): The class name of the above options.
  153. name (str): Name of this protocol message type.
  154. full_name (str): Fully-qualified name of this protocol message type,
  155. which will include protocol "package" name and the name of any
  156. enclosing types.
  157. file (FileDescriptor): Reference to file info.
  158. containing_type: if provided, this is a nested descriptor, with this
  159. descriptor as parent, otherwise None.
  160. serialized_start: The start index (inclusive) in block in the
  161. file.serialized_pb that describes this descriptor.
  162. serialized_end: The end index (exclusive) in block in the
  163. file.serialized_pb that describes this descriptor.
  164. serialized_options: Protocol message serialized options or None.
  165. """
  166. super(_NestedDescriptorBase, self).__init__(
  167. options, serialized_options, options_class_name)
  168. self.name = name
  169. # TODO(falk): Add function to calculate full_name instead of having it in
  170. # memory?
  171. self.full_name = full_name
  172. self.file = file
  173. self.containing_type = containing_type
  174. self._serialized_start = serialized_start
  175. self._serialized_end = serialized_end
  176. def CopyToProto(self, proto):
  177. """Copies this to the matching proto in descriptor_pb2.
  178. Args:
  179. proto: An empty proto instance from descriptor_pb2.
  180. Raises:
  181. Error: If self couldnt be serialized, due to to few constructor arguments.
  182. """
  183. if (self.file is not None and
  184. self._serialized_start is not None and
  185. self._serialized_end is not None):
  186. proto.ParseFromString(self.file.serialized_pb[
  187. self._serialized_start:self._serialized_end])
  188. else:
  189. raise Error('Descriptor does not contain serialization.')
  190. class Descriptor(_NestedDescriptorBase):
  191. """Descriptor for a protocol message type.
  192. Attributes:
  193. name (str): Name of this protocol message type.
  194. full_name (str): Fully-qualified name of this protocol message type,
  195. which will include protocol "package" name and the name of any
  196. enclosing types.
  197. containing_type (Descriptor): Reference to the descriptor of the type
  198. containing us, or None if this is top-level.
  199. fields (list[FieldDescriptor]): Field descriptors for all fields in
  200. this type.
  201. fields_by_number (dict(int, FieldDescriptor)): Same
  202. :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed
  203. by "number" attribute in each FieldDescriptor.
  204. fields_by_name (dict(str, FieldDescriptor)): Same
  205. :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by
  206. "name" attribute in each :class:`FieldDescriptor`.
  207. nested_types (list[Descriptor]): Descriptor references
  208. for all protocol message types nested within this one.
  209. nested_types_by_name (dict(str, Descriptor)): Same Descriptor
  210. objects as in :attr:`nested_types`, but indexed by "name" attribute
  211. in each Descriptor.
  212. enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references
  213. for all enums contained within this type.
  214. enum_types_by_name (dict(str, EnumDescriptor)): Same
  215. :class:`EnumDescriptor` objects as in :attr:`enum_types`, but
  216. indexed by "name" attribute in each EnumDescriptor.
  217. enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping
  218. from enum value name to :class:`EnumValueDescriptor` for that value.
  219. extensions (list[FieldDescriptor]): All extensions defined directly
  220. within this message type (NOT within a nested type).
  221. extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor
  222. objects as :attr:`extensions`, but indexed by "name" attribute of each
  223. FieldDescriptor.
  224. is_extendable (bool): Does this type define any extension ranges?
  225. oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields
  226. in this message.
  227. oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in
  228. :attr:`oneofs`, but indexed by "name" attribute.
  229. file (FileDescriptor): Reference to file descriptor.
  230. """
  231. if _USE_C_DESCRIPTORS:
  232. _C_DESCRIPTOR_CLASS = _message.Descriptor
  233. def __new__(cls, name, full_name, filename, containing_type, fields,
  234. nested_types, enum_types, extensions, options=None,
  235. serialized_options=None,
  236. is_extendable=True, extension_ranges=None, oneofs=None,
  237. file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
  238. syntax=None, create_key=None):
  239. _message.Message._CheckCalledFromGeneratedFile()
  240. return _message.default_pool.FindMessageTypeByName(full_name)
  241. # NOTE(tmarek): The file argument redefining a builtin is nothing we can
  242. # fix right now since we don't know how many clients already rely on the
  243. # name of the argument.
  244. def __init__(self, name, full_name, filename, containing_type, fields,
  245. nested_types, enum_types, extensions, options=None,
  246. serialized_options=None,
  247. is_extendable=True, extension_ranges=None, oneofs=None,
  248. file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
  249. syntax=None, create_key=None):
  250. """Arguments to __init__() are as described in the description
  251. of Descriptor fields above.
  252. Note that filename is an obsolete argument, that is not used anymore.
  253. Please use file.name to access this as an attribute.
  254. """
  255. if create_key is not _internal_create_key:
  256. _Deprecated('Descriptor')
  257. super(Descriptor, self).__init__(
  258. options, 'MessageOptions', name, full_name, file,
  259. containing_type, serialized_start=serialized_start,
  260. serialized_end=serialized_end, serialized_options=serialized_options)
  261. # We have fields in addition to fields_by_name and fields_by_number,
  262. # so that:
  263. # 1. Clients can index fields by "order in which they're listed."
  264. # 2. Clients can easily iterate over all fields with the terse
  265. # syntax: for f in descriptor.fields: ...
  266. self.fields = fields
  267. for field in self.fields:
  268. field.containing_type = self
  269. self.fields_by_number = dict((f.number, f) for f in fields)
  270. self.fields_by_name = dict((f.name, f) for f in fields)
  271. self._fields_by_camelcase_name = None
  272. self.nested_types = nested_types
  273. for nested_type in nested_types:
  274. nested_type.containing_type = self
  275. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  276. self.enum_types = enum_types
  277. for enum_type in self.enum_types:
  278. enum_type.containing_type = self
  279. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  280. self.enum_values_by_name = dict(
  281. (v.name, v) for t in enum_types for v in t.values)
  282. self.extensions = extensions
  283. for extension in self.extensions:
  284. extension.extension_scope = self
  285. self.extensions_by_name = dict((f.name, f) for f in extensions)
  286. self.is_extendable = is_extendable
  287. self.extension_ranges = extension_ranges
  288. self.oneofs = oneofs if oneofs is not None else []
  289. self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
  290. for oneof in self.oneofs:
  291. oneof.containing_type = self
  292. self.syntax = syntax or "proto2"
  293. @property
  294. def fields_by_camelcase_name(self):
  295. """Same FieldDescriptor objects as in :attr:`fields`, but indexed by
  296. :attr:`FieldDescriptor.camelcase_name`.
  297. """
  298. if self._fields_by_camelcase_name is None:
  299. self._fields_by_camelcase_name = dict(
  300. (f.camelcase_name, f) for f in self.fields)
  301. return self._fields_by_camelcase_name
  302. def EnumValueName(self, enum, value):
  303. """Returns the string name of an enum value.
  304. This is just a small helper method to simplify a common operation.
  305. Args:
  306. enum: string name of the Enum.
  307. value: int, value of the enum.
  308. Returns:
  309. string name of the enum value.
  310. Raises:
  311. KeyError if either the Enum doesn't exist or the value is not a valid
  312. value for the enum.
  313. """
  314. return self.enum_types_by_name[enum].values_by_number[value].name
  315. def CopyToProto(self, proto):
  316. """Copies this to a descriptor_pb2.DescriptorProto.
  317. Args:
  318. proto: An empty descriptor_pb2.DescriptorProto.
  319. """
  320. # This function is overridden to give a better doc comment.
  321. super(Descriptor, self).CopyToProto(proto)
  322. # TODO(robinson): We should have aggressive checking here,
  323. # for example:
  324. # * If you specify a repeated field, you should not be allowed
  325. # to specify a default value.
  326. # * [Other examples here as needed].
  327. #
  328. # TODO(robinson): for this and other *Descriptor classes, we
  329. # might also want to lock things down aggressively (e.g.,
  330. # prevent clients from setting the attributes). Having
  331. # stronger invariants here in general will reduce the number
  332. # of runtime checks we must do in reflection.py...
  333. class FieldDescriptor(DescriptorBase):
  334. """Descriptor for a single field in a .proto file.
  335. Attributes:
  336. name (str): Name of this field, exactly as it appears in .proto.
  337. full_name (str): Name of this field, including containing scope. This is
  338. particularly relevant for extensions.
  339. index (int): Dense, 0-indexed index giving the order that this
  340. field textually appears within its message in the .proto file.
  341. number (int): Tag number declared for this field in the .proto file.
  342. type (int): (One of the TYPE_* constants below) Declared type.
  343. cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to
  344. represent this field.
  345. label (int): (One of the LABEL_* constants below) Tells whether this
  346. field is optional, required, or repeated.
  347. has_default_value (bool): True if this field has a default value defined,
  348. otherwise false.
  349. default_value (Varies): Default value of this field. Only
  350. meaningful for non-repeated scalar fields. Repeated fields
  351. should always set this to [], and non-repeated composite
  352. fields should always set this to None.
  353. containing_type (Descriptor): Descriptor of the protocol message
  354. type that contains this field. Set by the Descriptor constructor
  355. if we're passed into one.
  356. Somewhat confusingly, for extension fields, this is the
  357. descriptor of the EXTENDED message, not the descriptor
  358. of the message containing this field. (See is_extension and
  359. extension_scope below).
  360. message_type (Descriptor): If a composite field, a descriptor
  361. of the message type contained in this field. Otherwise, this is None.
  362. enum_type (EnumDescriptor): If this field contains an enum, a
  363. descriptor of that enum. Otherwise, this is None.
  364. is_extension: True iff this describes an extension field.
  365. extension_scope (Descriptor): Only meaningful if is_extension is True.
  366. Gives the message that immediately contains this extension field.
  367. Will be None iff we're a top-level (file-level) extension field.
  368. options (descriptor_pb2.FieldOptions): Protocol message field options or
  369. None to use default field options.
  370. containing_oneof (OneofDescriptor): If the field is a member of a oneof
  371. union, contains its descriptor. Otherwise, None.
  372. file (FileDescriptor): Reference to file descriptor.
  373. """
  374. # Must be consistent with C++ FieldDescriptor::Type enum in
  375. # descriptor.h.
  376. #
  377. # TODO(robinson): Find a way to eliminate this repetition.
  378. TYPE_DOUBLE = 1
  379. TYPE_FLOAT = 2
  380. TYPE_INT64 = 3
  381. TYPE_UINT64 = 4
  382. TYPE_INT32 = 5
  383. TYPE_FIXED64 = 6
  384. TYPE_FIXED32 = 7
  385. TYPE_BOOL = 8
  386. TYPE_STRING = 9
  387. TYPE_GROUP = 10
  388. TYPE_MESSAGE = 11
  389. TYPE_BYTES = 12
  390. TYPE_UINT32 = 13
  391. TYPE_ENUM = 14
  392. TYPE_SFIXED32 = 15
  393. TYPE_SFIXED64 = 16
  394. TYPE_SINT32 = 17
  395. TYPE_SINT64 = 18
  396. MAX_TYPE = 18
  397. # Must be consistent with C++ FieldDescriptor::CppType enum in
  398. # descriptor.h.
  399. #
  400. # TODO(robinson): Find a way to eliminate this repetition.
  401. CPPTYPE_INT32 = 1
  402. CPPTYPE_INT64 = 2
  403. CPPTYPE_UINT32 = 3
  404. CPPTYPE_UINT64 = 4
  405. CPPTYPE_DOUBLE = 5
  406. CPPTYPE_FLOAT = 6
  407. CPPTYPE_BOOL = 7
  408. CPPTYPE_ENUM = 8
  409. CPPTYPE_STRING = 9
  410. CPPTYPE_MESSAGE = 10
  411. MAX_CPPTYPE = 10
  412. _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
  413. TYPE_DOUBLE: CPPTYPE_DOUBLE,
  414. TYPE_FLOAT: CPPTYPE_FLOAT,
  415. TYPE_ENUM: CPPTYPE_ENUM,
  416. TYPE_INT64: CPPTYPE_INT64,
  417. TYPE_SINT64: CPPTYPE_INT64,
  418. TYPE_SFIXED64: CPPTYPE_INT64,
  419. TYPE_UINT64: CPPTYPE_UINT64,
  420. TYPE_FIXED64: CPPTYPE_UINT64,
  421. TYPE_INT32: CPPTYPE_INT32,
  422. TYPE_SFIXED32: CPPTYPE_INT32,
  423. TYPE_SINT32: CPPTYPE_INT32,
  424. TYPE_UINT32: CPPTYPE_UINT32,
  425. TYPE_FIXED32: CPPTYPE_UINT32,
  426. TYPE_BYTES: CPPTYPE_STRING,
  427. TYPE_STRING: CPPTYPE_STRING,
  428. TYPE_BOOL: CPPTYPE_BOOL,
  429. TYPE_MESSAGE: CPPTYPE_MESSAGE,
  430. TYPE_GROUP: CPPTYPE_MESSAGE
  431. }
  432. # Must be consistent with C++ FieldDescriptor::Label enum in
  433. # descriptor.h.
  434. #
  435. # TODO(robinson): Find a way to eliminate this repetition.
  436. LABEL_OPTIONAL = 1
  437. LABEL_REQUIRED = 2
  438. LABEL_REPEATED = 3
  439. MAX_LABEL = 3
  440. # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
  441. # and kLastReservedNumber in descriptor.h
  442. MAX_FIELD_NUMBER = (1 << 29) - 1
  443. FIRST_RESERVED_FIELD_NUMBER = 19000
  444. LAST_RESERVED_FIELD_NUMBER = 19999
  445. if _USE_C_DESCRIPTORS:
  446. _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
  447. def __new__(cls, name, full_name, index, number, type, cpp_type, label,
  448. default_value, message_type, enum_type, containing_type,
  449. is_extension, extension_scope, options=None,
  450. serialized_options=None,
  451. has_default_value=True, containing_oneof=None, json_name=None,
  452. file=None, create_key=None): # pylint: disable=redefined-builtin
  453. _message.Message._CheckCalledFromGeneratedFile()
  454. if is_extension:
  455. return _message.default_pool.FindExtensionByName(full_name)
  456. else:
  457. return _message.default_pool.FindFieldByName(full_name)
  458. def __init__(self, name, full_name, index, number, type, cpp_type, label,
  459. default_value, message_type, enum_type, containing_type,
  460. is_extension, extension_scope, options=None,
  461. serialized_options=None,
  462. has_default_value=True, containing_oneof=None, json_name=None,
  463. file=None, create_key=None): # pylint: disable=redefined-builtin
  464. """The arguments are as described in the description of FieldDescriptor
  465. attributes above.
  466. Note that containing_type may be None, and may be set later if necessary
  467. (to deal with circular references between message types, for example).
  468. Likewise for extension_scope.
  469. """
  470. if create_key is not _internal_create_key:
  471. _Deprecated('FieldDescriptor')
  472. super(FieldDescriptor, self).__init__(
  473. options, serialized_options, 'FieldOptions')
  474. self.name = name
  475. self.full_name = full_name
  476. self.file = file
  477. self._camelcase_name = None
  478. if json_name is None:
  479. self.json_name = _ToJsonName(name)
  480. else:
  481. self.json_name = json_name
  482. self.index = index
  483. self.number = number
  484. self.type = type
  485. self.cpp_type = cpp_type
  486. self.label = label
  487. self.has_default_value = has_default_value
  488. self.default_value = default_value
  489. self.containing_type = containing_type
  490. self.message_type = message_type
  491. self.enum_type = enum_type
  492. self.is_extension = is_extension
  493. self.extension_scope = extension_scope
  494. self.containing_oneof = containing_oneof
  495. if api_implementation.Type() == 'cpp':
  496. if is_extension:
  497. self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
  498. else:
  499. self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
  500. else:
  501. self._cdescriptor = None
  502. @property
  503. def camelcase_name(self):
  504. """Camelcase name of this field.
  505. Returns:
  506. str: the name in CamelCase.
  507. """
  508. if self._camelcase_name is None:
  509. self._camelcase_name = _ToCamelCase(self.name)
  510. return self._camelcase_name
  511. @staticmethod
  512. def ProtoTypeToCppProtoType(proto_type):
  513. """Converts from a Python proto type to a C++ Proto Type.
  514. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  515. 'C++' datatype - and they're not the same. This helper method should
  516. translate from one to another.
  517. Args:
  518. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  519. Returns:
  520. int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  521. Raises:
  522. TypeTransformationError: when the Python proto type isn't known.
  523. """
  524. try:
  525. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  526. except KeyError:
  527. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  528. class EnumDescriptor(_NestedDescriptorBase):
  529. """Descriptor for an enum defined in a .proto file.
  530. Attributes:
  531. name (str): Name of the enum type.
  532. full_name (str): Full name of the type, including package name
  533. and any enclosing type(s).
  534. values (list[EnumValueDescriptors]): List of the values
  535. in this enum.
  536. values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`,
  537. but indexed by the "name" field of each EnumValueDescriptor.
  538. values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`,
  539. but indexed by the "number" field of each EnumValueDescriptor.
  540. containing_type (Descriptor): Descriptor of the immediate containing
  541. type of this enum, or None if this is an enum defined at the
  542. top level in a .proto file. Set by Descriptor's constructor
  543. if we're passed into one.
  544. file (FileDescriptor): Reference to file descriptor.
  545. options (descriptor_pb2.EnumOptions): Enum options message or
  546. None to use default enum options.
  547. """
  548. if _USE_C_DESCRIPTORS:
  549. _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
  550. def __new__(cls, name, full_name, filename, values,
  551. containing_type=None, options=None,
  552. serialized_options=None, file=None, # pylint: disable=redefined-builtin
  553. serialized_start=None, serialized_end=None, create_key=None):
  554. _message.Message._CheckCalledFromGeneratedFile()
  555. return _message.default_pool.FindEnumTypeByName(full_name)
  556. def __init__(self, name, full_name, filename, values,
  557. containing_type=None, options=None,
  558. serialized_options=None, file=None, # pylint: disable=redefined-builtin
  559. serialized_start=None, serialized_end=None, create_key=None):
  560. """Arguments are as described in the attribute description above.
  561. Note that filename is an obsolete argument, that is not used anymore.
  562. Please use file.name to access this as an attribute.
  563. """
  564. if create_key is not _internal_create_key:
  565. _Deprecated('EnumDescriptor')
  566. super(EnumDescriptor, self).__init__(
  567. options, 'EnumOptions', name, full_name, file,
  568. containing_type, serialized_start=serialized_start,
  569. serialized_end=serialized_end, serialized_options=serialized_options)
  570. self.values = values
  571. for value in self.values:
  572. value.type = self
  573. self.values_by_name = dict((v.name, v) for v in values)
  574. # Values are reversed to ensure that the first alias is retained.
  575. self.values_by_number = dict((v.number, v) for v in reversed(values))
  576. def CopyToProto(self, proto):
  577. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  578. Args:
  579. proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto.
  580. """
  581. # This function is overridden to give a better doc comment.
  582. super(EnumDescriptor, self).CopyToProto(proto)
  583. class EnumValueDescriptor(DescriptorBase):
  584. """Descriptor for a single value within an enum.
  585. Attributes:
  586. name (str): Name of this value.
  587. index (int): Dense, 0-indexed index giving the order that this
  588. value appears textually within its enum in the .proto file.
  589. number (int): Actual number assigned to this enum value.
  590. type (EnumDescriptor): :class:`EnumDescriptor` to which this value
  591. belongs. Set by :class:`EnumDescriptor`'s constructor if we're
  592. passed into one.
  593. options (descriptor_pb2.EnumValueOptions): Enum value options message or
  594. None to use default enum value options options.
  595. """
  596. if _USE_C_DESCRIPTORS:
  597. _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
  598. def __new__(cls, name, index, number,
  599. type=None, # pylint: disable=redefined-builtin
  600. options=None, serialized_options=None, create_key=None):
  601. _message.Message._CheckCalledFromGeneratedFile()
  602. # There is no way we can build a complete EnumValueDescriptor with the
  603. # given parameters (the name of the Enum is not known, for example).
  604. # Fortunately generated files just pass it to the EnumDescriptor()
  605. # constructor, which will ignore it, so returning None is good enough.
  606. return None
  607. def __init__(self, name, index, number,
  608. type=None, # pylint: disable=redefined-builtin
  609. options=None, serialized_options=None, create_key=None):
  610. """Arguments are as described in the attribute description above."""
  611. if create_key is not _internal_create_key:
  612. _Deprecated('EnumValueDescriptor')
  613. super(EnumValueDescriptor, self).__init__(
  614. options, serialized_options, 'EnumValueOptions')
  615. self.name = name
  616. self.index = index
  617. self.number = number
  618. self.type = type
  619. class OneofDescriptor(DescriptorBase):
  620. """Descriptor for a oneof field.
  621. Attributes:
  622. name (str): Name of the oneof field.
  623. full_name (str): Full name of the oneof field, including package name.
  624. index (int): 0-based index giving the order of the oneof field inside
  625. its containing type.
  626. containing_type (Descriptor): :class:`Descriptor` of the protocol message
  627. type that contains this field. Set by the :class:`Descriptor` constructor
  628. if we're passed into one.
  629. fields (list[FieldDescriptor]): The list of field descriptors this
  630. oneof can contain.
  631. """
  632. if _USE_C_DESCRIPTORS:
  633. _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
  634. def __new__(
  635. cls, name, full_name, index, containing_type, fields, options=None,
  636. serialized_options=None, create_key=None):
  637. _message.Message._CheckCalledFromGeneratedFile()
  638. return _message.default_pool.FindOneofByName(full_name)
  639. def __init__(
  640. self, name, full_name, index, containing_type, fields, options=None,
  641. serialized_options=None, create_key=None):
  642. """Arguments are as described in the attribute description above."""
  643. if create_key is not _internal_create_key:
  644. _Deprecated('OneofDescriptor')
  645. super(OneofDescriptor, self).__init__(
  646. options, serialized_options, 'OneofOptions')
  647. self.name = name
  648. self.full_name = full_name
  649. self.index = index
  650. self.containing_type = containing_type
  651. self.fields = fields
  652. class ServiceDescriptor(_NestedDescriptorBase):
  653. """Descriptor for a service.
  654. Attributes:
  655. name (str): Name of the service.
  656. full_name (str): Full name of the service, including package name.
  657. index (int): 0-indexed index giving the order that this services
  658. definition appears within the .proto file.
  659. methods (list[MethodDescriptor]): List of methods provided by this
  660. service.
  661. methods_by_name (dict(str, MethodDescriptor)): Same
  662. :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but
  663. indexed by "name" attribute in each :class:`MethodDescriptor`.
  664. options (descriptor_pb2.ServiceOptions): Service options message or
  665. None to use default service options.
  666. file (FileDescriptor): Reference to file info.
  667. """
  668. if _USE_C_DESCRIPTORS:
  669. _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
  670. def __new__(cls, name, full_name, index, methods, options=None,
  671. serialized_options=None, file=None, # pylint: disable=redefined-builtin
  672. serialized_start=None, serialized_end=None, create_key=None):
  673. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  674. return _message.default_pool.FindServiceByName(full_name)
  675. def __init__(self, name, full_name, index, methods, options=None,
  676. serialized_options=None, file=None, # pylint: disable=redefined-builtin
  677. serialized_start=None, serialized_end=None, create_key=None):
  678. if create_key is not _internal_create_key:
  679. _Deprecated('ServiceDescriptor')
  680. super(ServiceDescriptor, self).__init__(
  681. options, 'ServiceOptions', name, full_name, file,
  682. None, serialized_start=serialized_start,
  683. serialized_end=serialized_end, serialized_options=serialized_options)
  684. self.index = index
  685. self.methods = methods
  686. self.methods_by_name = dict((m.name, m) for m in methods)
  687. # Set the containing service for each method in this service.
  688. for method in self.methods:
  689. method.containing_service = self
  690. def FindMethodByName(self, name):
  691. """Searches for the specified method, and returns its descriptor.
  692. Args:
  693. name (str): Name of the method.
  694. Returns:
  695. MethodDescriptor or None: the desctiptor for the requested method, if
  696. found.
  697. """
  698. return self.methods_by_name.get(name, None)
  699. def CopyToProto(self, proto):
  700. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  701. Args:
  702. proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto.
  703. """
  704. # This function is overridden to give a better doc comment.
  705. super(ServiceDescriptor, self).CopyToProto(proto)
  706. class MethodDescriptor(DescriptorBase):
  707. """Descriptor for a method in a service.
  708. Attributes:
  709. name (str): Name of the method within the service.
  710. full_name (str): Full name of method.
  711. index (int): 0-indexed index of the method inside the service.
  712. containing_service (ServiceDescriptor): The service that contains this
  713. method.
  714. input_type (Descriptor): The descriptor of the message that this method
  715. accepts.
  716. output_type (Descriptor): The descriptor of the message that this method
  717. returns.
  718. options (descriptor_pb2.MethodOptions or None): Method options message, or
  719. None to use default method options.
  720. """
  721. if _USE_C_DESCRIPTORS:
  722. _C_DESCRIPTOR_CLASS = _message.MethodDescriptor
  723. def __new__(cls, name, full_name, index, containing_service,
  724. input_type, output_type, options=None, serialized_options=None,
  725. create_key=None):
  726. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  727. return _message.default_pool.FindMethodByName(full_name)
  728. def __init__(self, name, full_name, index, containing_service,
  729. input_type, output_type, options=None, serialized_options=None,
  730. create_key=None):
  731. """The arguments are as described in the description of MethodDescriptor
  732. attributes above.
  733. Note that containing_service may be None, and may be set later if necessary.
  734. """
  735. if create_key is not _internal_create_key:
  736. _Deprecated('MethodDescriptor')
  737. super(MethodDescriptor, self).__init__(
  738. options, serialized_options, 'MethodOptions')
  739. self.name = name
  740. self.full_name = full_name
  741. self.index = index
  742. self.containing_service = containing_service
  743. self.input_type = input_type
  744. self.output_type = output_type
  745. class FileDescriptor(DescriptorBase):
  746. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  747. Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and
  748. :attr:`dependencies` fields are only set by the
  749. :py:mod:`google.protobuf.message_factory` module, and not by the generated
  750. proto code.
  751. Attributes:
  752. name (str): Name of file, relative to root of source tree.
  753. package (str): Name of the package
  754. syntax (str): string indicating syntax of the file (can be "proto2" or
  755. "proto3")
  756. serialized_pb (bytes): Byte string of serialized
  757. :class:`descriptor_pb2.FileDescriptorProto`.
  758. dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor`
  759. objects this :class:`FileDescriptor` depends on.
  760. public_dependencies (list[FileDescriptor]): A subset of
  761. :attr:`dependencies`, which were declared as "public".
  762. message_types_by_name (dict(str, Descriptor)): Mapping from message names
  763. to their :class:`Desctiptor`.
  764. enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to
  765. their :class:`EnumDescriptor`.
  766. extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension
  767. names declared at file scope to their :class:`FieldDescriptor`.
  768. services_by_name (dict(str, ServiceDescriptor)): Mapping from services'
  769. names to their :class:`ServiceDescriptor`.
  770. pool (DescriptorPool): The pool this descriptor belongs to. When not
  771. passed to the constructor, the global default pool is used.
  772. """
  773. if _USE_C_DESCRIPTORS:
  774. _C_DESCRIPTOR_CLASS = _message.FileDescriptor
  775. def __new__(cls, name, package, options=None,
  776. serialized_options=None, serialized_pb=None,
  777. dependencies=None, public_dependencies=None,
  778. syntax=None, pool=None, create_key=None):
  779. # FileDescriptor() is called from various places, not only from generated
  780. # files, to register dynamic proto files and messages.
  781. # pylint: disable=g-explicit-bool-comparison
  782. if serialized_pb == b'':
  783. # Cpp generated code must be linked in if serialized_pb is ''
  784. try:
  785. return _message.default_pool.FindFileByName(name)
  786. except KeyError:
  787. raise RuntimeError('Please link in cpp generated lib for %s' % (name))
  788. elif serialized_pb:
  789. return _message.default_pool.AddSerializedFile(serialized_pb)
  790. else:
  791. return super(FileDescriptor, cls).__new__(cls)
  792. def __init__(self, name, package, options=None,
  793. serialized_options=None, serialized_pb=None,
  794. dependencies=None, public_dependencies=None,
  795. syntax=None, pool=None, create_key=None):
  796. """Constructor."""
  797. if create_key is not _internal_create_key:
  798. _Deprecated('FileDescriptor')
  799. super(FileDescriptor, self).__init__(
  800. options, serialized_options, 'FileOptions')
  801. if pool is None:
  802. from google.protobuf import descriptor_pool
  803. pool = descriptor_pool.Default()
  804. self.pool = pool
  805. self.message_types_by_name = {}
  806. self.name = name
  807. self.package = package
  808. self.syntax = syntax or "proto2"
  809. self.serialized_pb = serialized_pb
  810. self.enum_types_by_name = {}
  811. self.extensions_by_name = {}
  812. self.services_by_name = {}
  813. self.dependencies = (dependencies or [])
  814. self.public_dependencies = (public_dependencies or [])
  815. def CopyToProto(self, proto):
  816. """Copies this to a descriptor_pb2.FileDescriptorProto.
  817. Args:
  818. proto: An empty descriptor_pb2.FileDescriptorProto.
  819. """
  820. proto.ParseFromString(self.serialized_pb)
  821. def _ParseOptions(message, string):
  822. """Parses serialized options.
  823. This helper function is used to parse serialized options in generated
  824. proto2 files. It must not be used outside proto2.
  825. """
  826. message.ParseFromString(string)
  827. return message
  828. def _ToCamelCase(name):
  829. """Converts name to camel-case and returns it."""
  830. capitalize_next = False
  831. result = []
  832. for c in name:
  833. if c == '_':
  834. if result:
  835. capitalize_next = True
  836. elif capitalize_next:
  837. result.append(c.upper())
  838. capitalize_next = False
  839. else:
  840. result += c
  841. # Lower-case the first letter.
  842. if result and result[0].isupper():
  843. result[0] = result[0].lower()
  844. return ''.join(result)
  845. def _OptionsOrNone(descriptor_proto):
  846. """Returns the value of the field `options`, or None if it is not set."""
  847. if descriptor_proto.HasField('options'):
  848. return descriptor_proto.options
  849. else:
  850. return None
  851. def _ToJsonName(name):
  852. """Converts name to Json name and returns it."""
  853. capitalize_next = False
  854. result = []
  855. for c in name:
  856. if c == '_':
  857. capitalize_next = True
  858. elif capitalize_next:
  859. result.append(c.upper())
  860. capitalize_next = False
  861. else:
  862. result += c
  863. return ''.join(result)
  864. def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
  865. syntax=None):
  866. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  867. Handles nested descriptors. Note that this is limited to the scope of defining
  868. a message inside of another message. Composite fields can currently only be
  869. resolved if the message is defined in the same scope as the field.
  870. Args:
  871. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  872. package: Optional package name for the new message Descriptor (string).
  873. build_file_if_cpp: Update the C++ descriptor pool if api matches.
  874. Set to False on recursion, so no duplicates are created.
  875. syntax: The syntax/semantics that should be used. Set to "proto3" to get
  876. proto3 field presence semantics.
  877. Returns:
  878. A Descriptor for protobuf messages.
  879. """
  880. if api_implementation.Type() == 'cpp' and build_file_if_cpp:
  881. # The C++ implementation requires all descriptors to be backed by the same
  882. # definition in the C++ descriptor pool. To do this, we build a
  883. # FileDescriptorProto with the same definition as this descriptor and build
  884. # it into the pool.
  885. from google.protobuf import descriptor_pb2
  886. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  887. file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
  888. # Generate a random name for this proto file to prevent conflicts with any
  889. # imported ones. We need to specify a file name so the descriptor pool
  890. # accepts our FileDescriptorProto, but it is not important what that file
  891. # name is actually set to.
  892. proto_name = binascii.hexlify(os.urandom(16)).decode('ascii')
  893. if package:
  894. file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
  895. proto_name + '.proto')
  896. file_descriptor_proto.package = package
  897. else:
  898. file_descriptor_proto.name = proto_name + '.proto'
  899. _message.default_pool.Add(file_descriptor_proto)
  900. result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
  901. if _USE_C_DESCRIPTORS:
  902. return result.message_types_by_name[desc_proto.name]
  903. full_message_name = [desc_proto.name]
  904. if package: full_message_name.insert(0, package)
  905. # Create Descriptors for enum types
  906. enum_types = {}
  907. for enum_proto in desc_proto.enum_type:
  908. full_name = '.'.join(full_message_name + [enum_proto.name])
  909. enum_desc = EnumDescriptor(
  910. enum_proto.name, full_name, None, [
  911. EnumValueDescriptor(enum_val.name, ii, enum_val.number,
  912. create_key=_internal_create_key)
  913. for ii, enum_val in enumerate(enum_proto.value)],
  914. create_key=_internal_create_key)
  915. enum_types[full_name] = enum_desc
  916. # Create Descriptors for nested types
  917. nested_types = {}
  918. for nested_proto in desc_proto.nested_type:
  919. full_name = '.'.join(full_message_name + [nested_proto.name])
  920. # Nested types are just those defined inside of the message, not all types
  921. # used by fields in the message, so no loops are possible here.
  922. nested_desc = MakeDescriptor(nested_proto,
  923. package='.'.join(full_message_name),
  924. build_file_if_cpp=False,
  925. syntax=syntax)
  926. nested_types[full_name] = nested_desc
  927. fields = []
  928. for field_proto in desc_proto.field:
  929. full_name = '.'.join(full_message_name + [field_proto.name])
  930. enum_desc = None
  931. nested_desc = None
  932. if field_proto.json_name:
  933. json_name = field_proto.json_name
  934. else:
  935. json_name = None
  936. if field_proto.HasField('type_name'):
  937. type_name = field_proto.type_name
  938. full_type_name = '.'.join(full_message_name +
  939. [type_name[type_name.rfind('.')+1:]])
  940. if full_type_name in nested_types:
  941. nested_desc = nested_types[full_type_name]
  942. elif full_type_name in enum_types:
  943. enum_desc = enum_types[full_type_name]
  944. # Else type_name references a non-local type, which isn't implemented
  945. field = FieldDescriptor(
  946. field_proto.name, full_name, field_proto.number - 1,
  947. field_proto.number, field_proto.type,
  948. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  949. field_proto.label, None, nested_desc, enum_desc, None, False, None,
  950. options=_OptionsOrNone(field_proto), has_default_value=False,
  951. json_name=json_name, create_key=_internal_create_key)
  952. fields.append(field)
  953. desc_name = '.'.join(full_message_name)
  954. return Descriptor(desc_proto.name, desc_name, None, None, fields,
  955. list(nested_types.values()), list(enum_types.values()), [],
  956. options=_OptionsOrNone(desc_proto),
  957. create_key=_internal_create_key)