descriptor.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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 six
  35. from google.protobuf.internal import api_implementation
  36. _USE_C_DESCRIPTORS = False
  37. if api_implementation.Type() == 'cpp':
  38. # Used by MakeDescriptor in cpp mode
  39. import os
  40. import uuid
  41. from google.protobuf.pyext import _message
  42. _USE_C_DESCRIPTORS = getattr(_message, '_USE_C_DESCRIPTORS', False)
  43. class Error(Exception):
  44. """Base error for this module."""
  45. class TypeTransformationError(Error):
  46. """Error transforming between python proto type and corresponding C++ type."""
  47. if _USE_C_DESCRIPTORS:
  48. # This metaclass allows to override the behavior of code like
  49. # isinstance(my_descriptor, FieldDescriptor)
  50. # and make it return True when the descriptor is an instance of the extension
  51. # type written in C++.
  52. class DescriptorMetaclass(type):
  53. def __instancecheck__(cls, obj):
  54. if super(DescriptorMetaclass, cls).__instancecheck__(obj):
  55. return True
  56. if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
  57. return True
  58. return False
  59. else:
  60. # The standard metaclass; nothing changes.
  61. DescriptorMetaclass = type
  62. class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
  63. """Descriptors base class.
  64. This class is the base of all descriptor classes. It provides common options
  65. related functionality.
  66. Attributes:
  67. has_options: True if the descriptor has non-default options. Usually it
  68. is not necessary to read this -- just call GetOptions() which will
  69. happily return the default instance. However, it's sometimes useful
  70. for efficiency, and also useful inside the protobuf implementation to
  71. avoid some bootstrapping issues.
  72. """
  73. if _USE_C_DESCRIPTORS:
  74. # The class, or tuple of classes, that are considered as "virtual
  75. # subclasses" of this descriptor class.
  76. _C_DESCRIPTOR_CLASS = ()
  77. def __init__(self, options, options_class_name):
  78. """Initialize the descriptor given its options message and the name of the
  79. class of the options message. The name of the class is required in case
  80. the options message is None and has to be created.
  81. """
  82. self._options = options
  83. self._options_class_name = options_class_name
  84. # Does this descriptor have non-default options?
  85. self.has_options = options is not None
  86. def _SetOptions(self, options, options_class_name):
  87. """Sets the descriptor's options
  88. This function is used in generated proto2 files to update descriptor
  89. options. It must not be used outside proto2.
  90. """
  91. self._options = options
  92. self._options_class_name = options_class_name
  93. # Does this descriptor have non-default options?
  94. self.has_options = options is not None
  95. def GetOptions(self):
  96. """Retrieves descriptor options.
  97. This method returns the options set or creates the default options for the
  98. descriptor.
  99. """
  100. if self._options:
  101. return self._options
  102. from google.protobuf import descriptor_pb2
  103. try:
  104. options_class = getattr(descriptor_pb2, self._options_class_name)
  105. except AttributeError:
  106. raise RuntimeError('Unknown options class name %s!' %
  107. (self._options_class_name))
  108. self._options = options_class()
  109. return self._options
  110. class _NestedDescriptorBase(DescriptorBase):
  111. """Common class for descriptors that can be nested."""
  112. def __init__(self, options, options_class_name, name, full_name,
  113. file, containing_type, serialized_start=None,
  114. serialized_end=None):
  115. """Constructor.
  116. Args:
  117. options: Protocol message options or None
  118. to use default message options.
  119. options_class_name: (str) The class name of the above options.
  120. name: (str) Name of this protocol message type.
  121. full_name: (str) Fully-qualified name of this protocol message type,
  122. which will include protocol "package" name and the name of any
  123. enclosing types.
  124. file: (FileDescriptor) Reference to file info.
  125. containing_type: if provided, this is a nested descriptor, with this
  126. descriptor as parent, otherwise None.
  127. serialized_start: The start index (inclusive) in block in the
  128. file.serialized_pb that describes this descriptor.
  129. serialized_end: The end index (exclusive) in block in the
  130. file.serialized_pb that describes this descriptor.
  131. """
  132. super(_NestedDescriptorBase, self).__init__(
  133. options, options_class_name)
  134. self.name = name
  135. # TODO(falk): Add function to calculate full_name instead of having it in
  136. # memory?
  137. self.full_name = full_name
  138. self.file = file
  139. self.containing_type = containing_type
  140. self._serialized_start = serialized_start
  141. self._serialized_end = serialized_end
  142. def GetTopLevelContainingType(self):
  143. """Returns the root if this is a nested type, or itself if its the root."""
  144. desc = self
  145. while desc.containing_type is not None:
  146. desc = desc.containing_type
  147. return desc
  148. def CopyToProto(self, proto):
  149. """Copies this to the matching proto in descriptor_pb2.
  150. Args:
  151. proto: An empty proto instance from descriptor_pb2.
  152. Raises:
  153. Error: If self couldnt be serialized, due to to few constructor arguments.
  154. """
  155. if (self.file is not None and
  156. self._serialized_start is not None and
  157. self._serialized_end is not None):
  158. proto.ParseFromString(self.file.serialized_pb[
  159. self._serialized_start:self._serialized_end])
  160. else:
  161. raise Error('Descriptor does not contain serialization.')
  162. class Descriptor(_NestedDescriptorBase):
  163. """Descriptor for a protocol message type.
  164. A Descriptor instance has the following attributes:
  165. name: (str) Name of this protocol message type.
  166. full_name: (str) Fully-qualified name of this protocol message type,
  167. which will include protocol "package" name and the name of any
  168. enclosing types.
  169. containing_type: (Descriptor) Reference to the descriptor of the
  170. type containing us, or None if this is top-level.
  171. fields: (list of FieldDescriptors) Field descriptors for all
  172. fields in this type.
  173. fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor
  174. objects as in |fields|, but indexed by "number" attribute in each
  175. FieldDescriptor.
  176. fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor
  177. objects as in |fields|, but indexed by "name" attribute in each
  178. FieldDescriptor.
  179. fields_by_camelcase_name: (dict str -> FieldDescriptor) Same
  180. FieldDescriptor objects as in |fields|, but indexed by
  181. "camelcase_name" attribute in each FieldDescriptor.
  182. nested_types: (list of Descriptors) Descriptor references
  183. for all protocol message types nested within this one.
  184. nested_types_by_name: (dict str -> Descriptor) Same Descriptor
  185. objects as in |nested_types|, but indexed by "name" attribute
  186. in each Descriptor.
  187. enum_types: (list of EnumDescriptors) EnumDescriptor references
  188. for all enums contained within this type.
  189. enum_types_by_name: (dict str ->EnumDescriptor) Same EnumDescriptor
  190. objects as in |enum_types|, but indexed by "name" attribute
  191. in each EnumDescriptor.
  192. enum_values_by_name: (dict str -> EnumValueDescriptor) Dict mapping
  193. from enum value name to EnumValueDescriptor for that value.
  194. extensions: (list of FieldDescriptor) All extensions defined directly
  195. within this message type (NOT within a nested type).
  196. extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor
  197. objects as |extensions|, but indexed by "name" attribute of each
  198. FieldDescriptor.
  199. is_extendable: Does this type define any extension ranges?
  200. oneofs: (list of OneofDescriptor) The list of descriptors for oneof fields
  201. in this message.
  202. oneofs_by_name: (dict str -> OneofDescriptor) Same objects as in |oneofs|,
  203. but indexed by "name" attribute.
  204. file: (FileDescriptor) Reference to file descriptor.
  205. """
  206. if _USE_C_DESCRIPTORS:
  207. _C_DESCRIPTOR_CLASS = _message.Descriptor
  208. def __new__(cls, name, full_name, filename, containing_type, fields,
  209. nested_types, enum_types, extensions, options=None,
  210. is_extendable=True, extension_ranges=None, oneofs=None,
  211. file=None, serialized_start=None, serialized_end=None,
  212. syntax=None):
  213. _message.Message._CheckCalledFromGeneratedFile()
  214. return _message.default_pool.FindMessageTypeByName(full_name)
  215. # NOTE(tmarek): The file argument redefining a builtin is nothing we can
  216. # fix right now since we don't know how many clients already rely on the
  217. # name of the argument.
  218. def __init__(self, name, full_name, filename, containing_type, fields,
  219. nested_types, enum_types, extensions, options=None,
  220. is_extendable=True, extension_ranges=None, oneofs=None,
  221. file=None, serialized_start=None, serialized_end=None,
  222. syntax=None): # pylint:disable=redefined-builtin
  223. """Arguments to __init__() are as described in the description
  224. of Descriptor fields above.
  225. Note that filename is an obsolete argument, that is not used anymore.
  226. Please use file.name to access this as an attribute.
  227. """
  228. super(Descriptor, self).__init__(
  229. options, 'MessageOptions', name, full_name, file,
  230. containing_type, serialized_start=serialized_start,
  231. serialized_end=serialized_end)
  232. # We have fields in addition to fields_by_name and fields_by_number,
  233. # so that:
  234. # 1. Clients can index fields by "order in which they're listed."
  235. # 2. Clients can easily iterate over all fields with the terse
  236. # syntax: for f in descriptor.fields: ...
  237. self.fields = fields
  238. for field in self.fields:
  239. field.containing_type = self
  240. self.fields_by_number = dict((f.number, f) for f in fields)
  241. self.fields_by_name = dict((f.name, f) for f in fields)
  242. self._fields_by_camelcase_name = None
  243. self.nested_types = nested_types
  244. for nested_type in nested_types:
  245. nested_type.containing_type = self
  246. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  247. self.enum_types = enum_types
  248. for enum_type in self.enum_types:
  249. enum_type.containing_type = self
  250. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  251. self.enum_values_by_name = dict(
  252. (v.name, v) for t in enum_types for v in t.values)
  253. self.extensions = extensions
  254. for extension in self.extensions:
  255. extension.extension_scope = self
  256. self.extensions_by_name = dict((f.name, f) for f in extensions)
  257. self.is_extendable = is_extendable
  258. self.extension_ranges = extension_ranges
  259. self.oneofs = oneofs if oneofs is not None else []
  260. self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
  261. for oneof in self.oneofs:
  262. oneof.containing_type = self
  263. self.syntax = syntax or "proto2"
  264. @property
  265. def fields_by_camelcase_name(self):
  266. if self._fields_by_camelcase_name is None:
  267. self._fields_by_camelcase_name = dict(
  268. (f.camelcase_name, f) for f in self.fields)
  269. return self._fields_by_camelcase_name
  270. def EnumValueName(self, enum, value):
  271. """Returns the string name of an enum value.
  272. This is just a small helper method to simplify a common operation.
  273. Args:
  274. enum: string name of the Enum.
  275. value: int, value of the enum.
  276. Returns:
  277. string name of the enum value.
  278. Raises:
  279. KeyError if either the Enum doesn't exist or the value is not a valid
  280. value for the enum.
  281. """
  282. return self.enum_types_by_name[enum].values_by_number[value].name
  283. def CopyToProto(self, proto):
  284. """Copies this to a descriptor_pb2.DescriptorProto.
  285. Args:
  286. proto: An empty descriptor_pb2.DescriptorProto.
  287. """
  288. # This function is overriden to give a better doc comment.
  289. super(Descriptor, self).CopyToProto(proto)
  290. # TODO(robinson): We should have aggressive checking here,
  291. # for example:
  292. # * If you specify a repeated field, you should not be allowed
  293. # to specify a default value.
  294. # * [Other examples here as needed].
  295. #
  296. # TODO(robinson): for this and other *Descriptor classes, we
  297. # might also want to lock things down aggressively (e.g.,
  298. # prevent clients from setting the attributes). Having
  299. # stronger invariants here in general will reduce the number
  300. # of runtime checks we must do in reflection.py...
  301. class FieldDescriptor(DescriptorBase):
  302. """Descriptor for a single field in a .proto file.
  303. A FieldDescriptor instance has the following attributes:
  304. name: (str) Name of this field, exactly as it appears in .proto.
  305. full_name: (str) Name of this field, including containing scope. This is
  306. particularly relevant for extensions.
  307. camelcase_name: (str) Camelcase name of this field.
  308. index: (int) Dense, 0-indexed index giving the order that this
  309. field textually appears within its message in the .proto file.
  310. number: (int) Tag number declared for this field in the .proto file.
  311. type: (One of the TYPE_* constants below) Declared type.
  312. cpp_type: (One of the CPPTYPE_* constants below) C++ type used to
  313. represent this field.
  314. label: (One of the LABEL_* constants below) Tells whether this
  315. field is optional, required, or repeated.
  316. has_default_value: (bool) True if this field has a default value defined,
  317. otherwise false.
  318. default_value: (Varies) Default value of this field. Only
  319. meaningful for non-repeated scalar fields. Repeated fields
  320. should always set this to [], and non-repeated composite
  321. fields should always set this to None.
  322. containing_type: (Descriptor) Descriptor of the protocol message
  323. type that contains this field. Set by the Descriptor constructor
  324. if we're passed into one.
  325. Somewhat confusingly, for extension fields, this is the
  326. descriptor of the EXTENDED message, not the descriptor
  327. of the message containing this field. (See is_extension and
  328. extension_scope below).
  329. message_type: (Descriptor) If a composite field, a descriptor
  330. of the message type contained in this field. Otherwise, this is None.
  331. enum_type: (EnumDescriptor) If this field contains an enum, a
  332. descriptor of that enum. Otherwise, this is None.
  333. is_extension: True iff this describes an extension field.
  334. extension_scope: (Descriptor) Only meaningful if is_extension is True.
  335. Gives the message that immediately contains this extension field.
  336. Will be None iff we're a top-level (file-level) extension field.
  337. options: (descriptor_pb2.FieldOptions) Protocol message field options or
  338. None to use default field options.
  339. containing_oneof: (OneofDescriptor) If the field is a member of a oneof
  340. union, contains its descriptor. Otherwise, None.
  341. """
  342. # Must be consistent with C++ FieldDescriptor::Type enum in
  343. # descriptor.h.
  344. #
  345. # TODO(robinson): Find a way to eliminate this repetition.
  346. TYPE_DOUBLE = 1
  347. TYPE_FLOAT = 2
  348. TYPE_INT64 = 3
  349. TYPE_UINT64 = 4
  350. TYPE_INT32 = 5
  351. TYPE_FIXED64 = 6
  352. TYPE_FIXED32 = 7
  353. TYPE_BOOL = 8
  354. TYPE_STRING = 9
  355. TYPE_GROUP = 10
  356. TYPE_MESSAGE = 11
  357. TYPE_BYTES = 12
  358. TYPE_UINT32 = 13
  359. TYPE_ENUM = 14
  360. TYPE_SFIXED32 = 15
  361. TYPE_SFIXED64 = 16
  362. TYPE_SINT32 = 17
  363. TYPE_SINT64 = 18
  364. MAX_TYPE = 18
  365. # Must be consistent with C++ FieldDescriptor::CppType enum in
  366. # descriptor.h.
  367. #
  368. # TODO(robinson): Find a way to eliminate this repetition.
  369. CPPTYPE_INT32 = 1
  370. CPPTYPE_INT64 = 2
  371. CPPTYPE_UINT32 = 3
  372. CPPTYPE_UINT64 = 4
  373. CPPTYPE_DOUBLE = 5
  374. CPPTYPE_FLOAT = 6
  375. CPPTYPE_BOOL = 7
  376. CPPTYPE_ENUM = 8
  377. CPPTYPE_STRING = 9
  378. CPPTYPE_MESSAGE = 10
  379. MAX_CPPTYPE = 10
  380. _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
  381. TYPE_DOUBLE: CPPTYPE_DOUBLE,
  382. TYPE_FLOAT: CPPTYPE_FLOAT,
  383. TYPE_ENUM: CPPTYPE_ENUM,
  384. TYPE_INT64: CPPTYPE_INT64,
  385. TYPE_SINT64: CPPTYPE_INT64,
  386. TYPE_SFIXED64: CPPTYPE_INT64,
  387. TYPE_UINT64: CPPTYPE_UINT64,
  388. TYPE_FIXED64: CPPTYPE_UINT64,
  389. TYPE_INT32: CPPTYPE_INT32,
  390. TYPE_SFIXED32: CPPTYPE_INT32,
  391. TYPE_SINT32: CPPTYPE_INT32,
  392. TYPE_UINT32: CPPTYPE_UINT32,
  393. TYPE_FIXED32: CPPTYPE_UINT32,
  394. TYPE_BYTES: CPPTYPE_STRING,
  395. TYPE_STRING: CPPTYPE_STRING,
  396. TYPE_BOOL: CPPTYPE_BOOL,
  397. TYPE_MESSAGE: CPPTYPE_MESSAGE,
  398. TYPE_GROUP: CPPTYPE_MESSAGE
  399. }
  400. # Must be consistent with C++ FieldDescriptor::Label enum in
  401. # descriptor.h.
  402. #
  403. # TODO(robinson): Find a way to eliminate this repetition.
  404. LABEL_OPTIONAL = 1
  405. LABEL_REQUIRED = 2
  406. LABEL_REPEATED = 3
  407. MAX_LABEL = 3
  408. # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
  409. # and kLastReservedNumber in descriptor.h
  410. MAX_FIELD_NUMBER = (1 << 29) - 1
  411. FIRST_RESERVED_FIELD_NUMBER = 19000
  412. LAST_RESERVED_FIELD_NUMBER = 19999
  413. if _USE_C_DESCRIPTORS:
  414. _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
  415. def __new__(cls, name, full_name, index, number, type, cpp_type, label,
  416. default_value, message_type, enum_type, containing_type,
  417. is_extension, extension_scope, options=None,
  418. has_default_value=True, containing_oneof=None):
  419. _message.Message._CheckCalledFromGeneratedFile()
  420. if is_extension:
  421. return _message.default_pool.FindExtensionByName(full_name)
  422. else:
  423. return _message.default_pool.FindFieldByName(full_name)
  424. def __init__(self, name, full_name, index, number, type, cpp_type, label,
  425. default_value, message_type, enum_type, containing_type,
  426. is_extension, extension_scope, options=None,
  427. has_default_value=True, containing_oneof=None):
  428. """The arguments are as described in the description of FieldDescriptor
  429. attributes above.
  430. Note that containing_type may be None, and may be set later if necessary
  431. (to deal with circular references between message types, for example).
  432. Likewise for extension_scope.
  433. """
  434. super(FieldDescriptor, self).__init__(options, 'FieldOptions')
  435. self.name = name
  436. self.full_name = full_name
  437. self._camelcase_name = None
  438. self.index = index
  439. self.number = number
  440. self.type = type
  441. self.cpp_type = cpp_type
  442. self.label = label
  443. self.has_default_value = has_default_value
  444. self.default_value = default_value
  445. self.containing_type = containing_type
  446. self.message_type = message_type
  447. self.enum_type = enum_type
  448. self.is_extension = is_extension
  449. self.extension_scope = extension_scope
  450. self.containing_oneof = containing_oneof
  451. if api_implementation.Type() == 'cpp':
  452. if is_extension:
  453. self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
  454. else:
  455. self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
  456. else:
  457. self._cdescriptor = None
  458. @property
  459. def camelcase_name(self):
  460. if self._camelcase_name is None:
  461. self._camelcase_name = _ToCamelCase(self.name)
  462. return self._camelcase_name
  463. @staticmethod
  464. def ProtoTypeToCppProtoType(proto_type):
  465. """Converts from a Python proto type to a C++ Proto Type.
  466. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  467. 'C++' datatype - and they're not the same. This helper method should
  468. translate from one to another.
  469. Args:
  470. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  471. Returns:
  472. descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  473. Raises:
  474. TypeTransformationError: when the Python proto type isn't known.
  475. """
  476. try:
  477. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  478. except KeyError:
  479. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  480. class EnumDescriptor(_NestedDescriptorBase):
  481. """Descriptor for an enum defined in a .proto file.
  482. An EnumDescriptor instance has the following attributes:
  483. name: (str) Name of the enum type.
  484. full_name: (str) Full name of the type, including package name
  485. and any enclosing type(s).
  486. values: (list of EnumValueDescriptors) List of the values
  487. in this enum.
  488. values_by_name: (dict str -> EnumValueDescriptor) Same as |values|,
  489. but indexed by the "name" field of each EnumValueDescriptor.
  490. values_by_number: (dict int -> EnumValueDescriptor) Same as |values|,
  491. but indexed by the "number" field of each EnumValueDescriptor.
  492. containing_type: (Descriptor) Descriptor of the immediate containing
  493. type of this enum, or None if this is an enum defined at the
  494. top level in a .proto file. Set by Descriptor's constructor
  495. if we're passed into one.
  496. file: (FileDescriptor) Reference to file descriptor.
  497. options: (descriptor_pb2.EnumOptions) Enum options message or
  498. None to use default enum options.
  499. """
  500. if _USE_C_DESCRIPTORS:
  501. _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
  502. def __new__(cls, name, full_name, filename, values,
  503. containing_type=None, options=None, file=None,
  504. serialized_start=None, serialized_end=None):
  505. _message.Message._CheckCalledFromGeneratedFile()
  506. return _message.default_pool.FindEnumTypeByName(full_name)
  507. def __init__(self, name, full_name, filename, values,
  508. containing_type=None, options=None, file=None,
  509. serialized_start=None, serialized_end=None):
  510. """Arguments are as described in the attribute description above.
  511. Note that filename is an obsolete argument, that is not used anymore.
  512. Please use file.name to access this as an attribute.
  513. """
  514. super(EnumDescriptor, self).__init__(
  515. options, 'EnumOptions', name, full_name, file,
  516. containing_type, serialized_start=serialized_start,
  517. serialized_end=serialized_end)
  518. self.values = values
  519. for value in self.values:
  520. value.type = self
  521. self.values_by_name = dict((v.name, v) for v in values)
  522. self.values_by_number = dict((v.number, v) for v in values)
  523. def CopyToProto(self, proto):
  524. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  525. Args:
  526. proto: An empty descriptor_pb2.EnumDescriptorProto.
  527. """
  528. # This function is overriden to give a better doc comment.
  529. super(EnumDescriptor, self).CopyToProto(proto)
  530. class EnumValueDescriptor(DescriptorBase):
  531. """Descriptor for a single value within an enum.
  532. name: (str) Name of this value.
  533. index: (int) Dense, 0-indexed index giving the order that this
  534. value appears textually within its enum in the .proto file.
  535. number: (int) Actual number assigned to this enum value.
  536. type: (EnumDescriptor) EnumDescriptor to which this value
  537. belongs. Set by EnumDescriptor's constructor if we're
  538. passed into one.
  539. options: (descriptor_pb2.EnumValueOptions) Enum value options message or
  540. None to use default enum value options options.
  541. """
  542. if _USE_C_DESCRIPTORS:
  543. _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
  544. def __new__(cls, name, index, number, type=None, options=None):
  545. _message.Message._CheckCalledFromGeneratedFile()
  546. # There is no way we can build a complete EnumValueDescriptor with the
  547. # given parameters (the name of the Enum is not known, for example).
  548. # Fortunately generated files just pass it to the EnumDescriptor()
  549. # constructor, which will ignore it, so returning None is good enough.
  550. return None
  551. def __init__(self, name, index, number, type=None, options=None):
  552. """Arguments are as described in the attribute description above."""
  553. super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions')
  554. self.name = name
  555. self.index = index
  556. self.number = number
  557. self.type = type
  558. class OneofDescriptor(object):
  559. """Descriptor for a oneof field.
  560. name: (str) Name of the oneof field.
  561. full_name: (str) Full name of the oneof field, including package name.
  562. index: (int) 0-based index giving the order of the oneof field inside
  563. its containing type.
  564. containing_type: (Descriptor) Descriptor of the protocol message
  565. type that contains this field. Set by the Descriptor constructor
  566. if we're passed into one.
  567. fields: (list of FieldDescriptor) The list of field descriptors this
  568. oneof can contain.
  569. """
  570. if _USE_C_DESCRIPTORS:
  571. _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
  572. def __new__(cls, name, full_name, index, containing_type, fields):
  573. _message.Message._CheckCalledFromGeneratedFile()
  574. return _message.default_pool.FindOneofByName(full_name)
  575. def __init__(self, name, full_name, index, containing_type, fields):
  576. """Arguments are as described in the attribute description above."""
  577. self.name = name
  578. self.full_name = full_name
  579. self.index = index
  580. self.containing_type = containing_type
  581. self.fields = fields
  582. class ServiceDescriptor(_NestedDescriptorBase):
  583. """Descriptor for a service.
  584. name: (str) Name of the service.
  585. full_name: (str) Full name of the service, including package name.
  586. index: (int) 0-indexed index giving the order that this services
  587. definition appears withing the .proto file.
  588. methods: (list of MethodDescriptor) List of methods provided by this
  589. service.
  590. options: (descriptor_pb2.ServiceOptions) Service options message or
  591. None to use default service options.
  592. file: (FileDescriptor) Reference to file info.
  593. """
  594. def __init__(self, name, full_name, index, methods, options=None, file=None,
  595. serialized_start=None, serialized_end=None):
  596. super(ServiceDescriptor, self).__init__(
  597. options, 'ServiceOptions', name, full_name, file,
  598. None, serialized_start=serialized_start,
  599. serialized_end=serialized_end)
  600. self.index = index
  601. self.methods = methods
  602. # Set the containing service for each method in this service.
  603. for method in self.methods:
  604. method.containing_service = self
  605. def FindMethodByName(self, name):
  606. """Searches for the specified method, and returns its descriptor."""
  607. for method in self.methods:
  608. if name == method.name:
  609. return method
  610. return None
  611. def CopyToProto(self, proto):
  612. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  613. Args:
  614. proto: An empty descriptor_pb2.ServiceDescriptorProto.
  615. """
  616. # This function is overriden to give a better doc comment.
  617. super(ServiceDescriptor, self).CopyToProto(proto)
  618. class MethodDescriptor(DescriptorBase):
  619. """Descriptor for a method in a service.
  620. name: (str) Name of the method within the service.
  621. full_name: (str) Full name of method.
  622. index: (int) 0-indexed index of the method inside the service.
  623. containing_service: (ServiceDescriptor) The service that contains this
  624. method.
  625. input_type: The descriptor of the message that this method accepts.
  626. output_type: The descriptor of the message that this method returns.
  627. options: (descriptor_pb2.MethodOptions) Method options message or
  628. None to use default method options.
  629. """
  630. def __init__(self, name, full_name, index, containing_service,
  631. input_type, output_type, options=None):
  632. """The arguments are as described in the description of MethodDescriptor
  633. attributes above.
  634. Note that containing_service may be None, and may be set later if necessary.
  635. """
  636. super(MethodDescriptor, self).__init__(options, 'MethodOptions')
  637. self.name = name
  638. self.full_name = full_name
  639. self.index = index
  640. self.containing_service = containing_service
  641. self.input_type = input_type
  642. self.output_type = output_type
  643. class FileDescriptor(DescriptorBase):
  644. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  645. Note that enum_types_by_name, extensions_by_name, and dependencies
  646. fields are only set by the message_factory module, and not by the
  647. generated proto code.
  648. name: name of file, relative to root of source tree.
  649. package: name of the package
  650. syntax: string indicating syntax of the file (can be "proto2" or "proto3")
  651. serialized_pb: (str) Byte string of serialized
  652. descriptor_pb2.FileDescriptorProto.
  653. dependencies: List of other FileDescriptors this FileDescriptor depends on.
  654. message_types_by_name: Dict of message names of their descriptors.
  655. enum_types_by_name: Dict of enum names and their descriptors.
  656. extensions_by_name: Dict of extension names and their descriptors.
  657. """
  658. if _USE_C_DESCRIPTORS:
  659. _C_DESCRIPTOR_CLASS = _message.FileDescriptor
  660. def __new__(cls, name, package, options=None, serialized_pb=None,
  661. dependencies=None, syntax=None):
  662. # FileDescriptor() is called from various places, not only from generated
  663. # files, to register dynamic proto files and messages.
  664. if serialized_pb:
  665. return _message.default_pool.AddSerializedFile(serialized_pb)
  666. else:
  667. return super(FileDescriptor, cls).__new__(cls)
  668. def __init__(self, name, package, options=None, serialized_pb=None,
  669. dependencies=None, syntax=None):
  670. """Constructor."""
  671. super(FileDescriptor, self).__init__(options, 'FileOptions')
  672. self.message_types_by_name = {}
  673. self.name = name
  674. self.package = package
  675. self.syntax = syntax or "proto2"
  676. self.serialized_pb = serialized_pb
  677. self.enum_types_by_name = {}
  678. self.extensions_by_name = {}
  679. self.dependencies = (dependencies or [])
  680. if (api_implementation.Type() == 'cpp' and
  681. self.serialized_pb is not None):
  682. _message.default_pool.AddSerializedFile(self.serialized_pb)
  683. def CopyToProto(self, proto):
  684. """Copies this to a descriptor_pb2.FileDescriptorProto.
  685. Args:
  686. proto: An empty descriptor_pb2.FileDescriptorProto.
  687. """
  688. proto.ParseFromString(self.serialized_pb)
  689. def _ParseOptions(message, string):
  690. """Parses serialized options.
  691. This helper function is used to parse serialized options in generated
  692. proto2 files. It must not be used outside proto2.
  693. """
  694. message.ParseFromString(string)
  695. return message
  696. def _ToCamelCase(name):
  697. """Converts name to camel-case and returns it."""
  698. capitalize_next = False
  699. result = []
  700. for c in name:
  701. if c == '_':
  702. if result:
  703. capitalize_next = True
  704. elif capitalize_next:
  705. result.append(c.upper())
  706. capitalize_next = False
  707. else:
  708. result += c
  709. # Lower-case the first letter.
  710. if result and result[0].isupper():
  711. result[0] = result[0].lower()
  712. return ''.join(result)
  713. def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
  714. syntax=None):
  715. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  716. Handles nested descriptors. Note that this is limited to the scope of defining
  717. a message inside of another message. Composite fields can currently only be
  718. resolved if the message is defined in the same scope as the field.
  719. Args:
  720. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  721. package: Optional package name for the new message Descriptor (string).
  722. build_file_if_cpp: Update the C++ descriptor pool if api matches.
  723. Set to False on recursion, so no duplicates are created.
  724. syntax: The syntax/semantics that should be used. Set to "proto3" to get
  725. proto3 field presence semantics.
  726. Returns:
  727. A Descriptor for protobuf messages.
  728. """
  729. if api_implementation.Type() == 'cpp' and build_file_if_cpp:
  730. # The C++ implementation requires all descriptors to be backed by the same
  731. # definition in the C++ descriptor pool. To do this, we build a
  732. # FileDescriptorProto with the same definition as this descriptor and build
  733. # it into the pool.
  734. from google.protobuf import descriptor_pb2
  735. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  736. file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
  737. # Generate a random name for this proto file to prevent conflicts with any
  738. # imported ones. We need to specify a file name so the descriptor pool
  739. # accepts our FileDescriptorProto, but it is not important what that file
  740. # name is actually set to.
  741. proto_name = str(uuid.uuid4())
  742. if package:
  743. file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
  744. proto_name + '.proto')
  745. file_descriptor_proto.package = package
  746. else:
  747. file_descriptor_proto.name = proto_name + '.proto'
  748. _message.default_pool.Add(file_descriptor_proto)
  749. result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
  750. if _USE_C_DESCRIPTORS:
  751. return result.message_types_by_name[desc_proto.name]
  752. full_message_name = [desc_proto.name]
  753. if package: full_message_name.insert(0, package)
  754. # Create Descriptors for enum types
  755. enum_types = {}
  756. for enum_proto in desc_proto.enum_type:
  757. full_name = '.'.join(full_message_name + [enum_proto.name])
  758. enum_desc = EnumDescriptor(
  759. enum_proto.name, full_name, None, [
  760. EnumValueDescriptor(enum_val.name, ii, enum_val.number)
  761. for ii, enum_val in enumerate(enum_proto.value)])
  762. enum_types[full_name] = enum_desc
  763. # Create Descriptors for nested types
  764. nested_types = {}
  765. for nested_proto in desc_proto.nested_type:
  766. full_name = '.'.join(full_message_name + [nested_proto.name])
  767. # Nested types are just those defined inside of the message, not all types
  768. # used by fields in the message, so no loops are possible here.
  769. nested_desc = MakeDescriptor(nested_proto,
  770. package='.'.join(full_message_name),
  771. build_file_if_cpp=False,
  772. syntax=syntax)
  773. nested_types[full_name] = nested_desc
  774. fields = []
  775. for field_proto in desc_proto.field:
  776. full_name = '.'.join(full_message_name + [field_proto.name])
  777. enum_desc = None
  778. nested_desc = None
  779. if field_proto.HasField('type_name'):
  780. type_name = field_proto.type_name
  781. full_type_name = '.'.join(full_message_name +
  782. [type_name[type_name.rfind('.')+1:]])
  783. if full_type_name in nested_types:
  784. nested_desc = nested_types[full_type_name]
  785. elif full_type_name in enum_types:
  786. enum_desc = enum_types[full_type_name]
  787. # Else type_name references a non-local type, which isn't implemented
  788. field = FieldDescriptor(
  789. field_proto.name, full_name, field_proto.number - 1,
  790. field_proto.number, field_proto.type,
  791. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  792. field_proto.label, None, nested_desc, enum_desc, None, False, None,
  793. options=field_proto.options, has_default_value=False)
  794. fields.append(field)
  795. desc_name = '.'.join(full_message_name)
  796. return Descriptor(desc_proto.name, desc_name, None, None, fields,
  797. list(nested_types.values()), list(enum_types.values()), [],
  798. options=desc_proto.options)