descriptor.py 35 KB

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