descriptor.py 35 KB

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