descriptor.py 32 KB

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