图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1266 lines
47 KiB

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