descriptor.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  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. # TODO(robinson): We probably need to provide deep-copy methods for
  31. # descriptor types. When a FieldDescriptor is passed into
  32. # Descriptor.__init__(), we should make a deep copy and then set
  33. # containing_type on it. Alternatively, we could just get
  34. # rid of containing_type (iit's not needed for reflection.py, at least).
  35. #
  36. # TODO(robinson): Print method?
  37. #
  38. # TODO(robinson): Useful __repr__?
  39. """Descriptors essentially contain exactly the information found in a .proto
  40. file, in types that make this information accessible in Python.
  41. """
  42. __author__ = 'robinson@google.com (Will Robinson)'
  43. class DescriptorBase(object):
  44. """Descriptors base class.
  45. This class is the base of all descriptor classes. It provides common options
  46. related functionaility.
  47. """
  48. def __init__(self, options, options_class_name):
  49. """Initialize the descriptor given its options message and the name of the
  50. class of the options message. The name of the class is required in case
  51. the options message is None and has to be created.
  52. """
  53. self._options = options
  54. self._options_class_name = options_class_name
  55. def GetOptions(self):
  56. """Retrieves descriptor options.
  57. This method returns the options set or creates the default options for the
  58. descriptor.
  59. """
  60. if self._options:
  61. return self._options
  62. from google.protobuf import descriptor_pb2
  63. try:
  64. options_class = getattr(descriptor_pb2, self._options_class_name)
  65. except AttributeError:
  66. raise RuntimeError('Unknown options class name %s!' %
  67. (self._options_class_name))
  68. self._options = options_class()
  69. return self._options
  70. class Descriptor(DescriptorBase):
  71. """Descriptor for a protocol message type.
  72. A Descriptor instance has the following attributes:
  73. name: (str) Name of this protocol message type.
  74. full_name: (str) Fully-qualified name of this protocol message type,
  75. which will include protocol "package" name and the name of any
  76. enclosing types.
  77. filename: (str) Name of the .proto file containing this message.
  78. containing_type: (Descriptor) Reference to the descriptor of the
  79. type containing us, or None if we have no containing type.
  80. fields: (list of FieldDescriptors) Field descriptors for all
  81. fields in this type.
  82. fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor
  83. objects as in |fields|, but indexed by "number" attribute in each
  84. FieldDescriptor.
  85. fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor
  86. objects as in |fields|, but indexed by "name" attribute in each
  87. FieldDescriptor.
  88. nested_types: (list of Descriptors) Descriptor references
  89. for all protocol message types nested within this one.
  90. nested_types_by_name: (dict str -> Descriptor) Same Descriptor
  91. objects as in |nested_types|, but indexed by "name" attribute
  92. in each Descriptor.
  93. enum_types: (list of EnumDescriptors) EnumDescriptor references
  94. for all enums contained within this type.
  95. enum_types_by_name: (dict str ->EnumDescriptor) Same EnumDescriptor
  96. objects as in |enum_types|, but indexed by "name" attribute
  97. in each EnumDescriptor.
  98. enum_values_by_name: (dict str -> EnumValueDescriptor) Dict mapping
  99. from enum value name to EnumValueDescriptor for that value.
  100. extensions: (list of FieldDescriptor) All extensions defined directly
  101. within this message type (NOT within a nested type).
  102. extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor
  103. objects as |extensions|, but indexed by "name" attribute of each
  104. FieldDescriptor.
  105. options: (descriptor_pb2.MessageOptions) Protocol message options or None
  106. to use default message options.
  107. """
  108. def __init__(self, name, full_name, filename, containing_type,
  109. fields, nested_types, enum_types, extensions, options=None):
  110. """Arguments to __init__() are as described in the description
  111. of Descriptor fields above.
  112. """
  113. super(Descriptor, self).__init__(options, 'MessageOptions')
  114. self.name = name
  115. self.full_name = full_name
  116. self.filename = filename
  117. self.containing_type = containing_type
  118. # We have fields in addition to fields_by_name and fields_by_number,
  119. # so that:
  120. # 1. Clients can index fields by "order in which they're listed."
  121. # 2. Clients can easily iterate over all fields with the terse
  122. # syntax: for f in descriptor.fields: ...
  123. self.fields = fields
  124. for field in self.fields:
  125. field.containing_type = self
  126. self.fields_by_number = dict((f.number, f) for f in fields)
  127. self.fields_by_name = dict((f.name, f) for f in fields)
  128. self.nested_types = nested_types
  129. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  130. self.enum_types = enum_types
  131. for enum_type in self.enum_types:
  132. enum_type.containing_type = self
  133. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  134. self.enum_values_by_name = dict(
  135. (v.name, v) for t in enum_types for v in t.values)
  136. self.extensions = extensions
  137. for extension in self.extensions:
  138. extension.extension_scope = self
  139. self.extensions_by_name = dict((f.name, f) for f in extensions)
  140. # TODO(robinson): We should have aggressive checking here,
  141. # for example:
  142. # * If you specify a repeated field, you should not be allowed
  143. # to specify a default value.
  144. # * [Other examples here as needed].
  145. #
  146. # TODO(robinson): for this and other *Descriptor classes, we
  147. # might also want to lock things down aggressively (e.g.,
  148. # prevent clients from setting the attributes). Having
  149. # stronger invariants here in general will reduce the number
  150. # of runtime checks we must do in reflection.py...
  151. class FieldDescriptor(DescriptorBase):
  152. """Descriptor for a single field in a .proto file.
  153. A FieldDescriptor instance has the following attriubtes:
  154. name: (str) Name of this field, exactly as it appears in .proto.
  155. full_name: (str) Name of this field, including containing scope. This is
  156. particularly relevant for extensions.
  157. index: (int) Dense, 0-indexed index giving the order that this
  158. field textually appears within its message in the .proto file.
  159. number: (int) Tag number declared for this field in the .proto file.
  160. type: (One of the TYPE_* constants below) Declared type.
  161. cpp_type: (One of the CPPTYPE_* constants below) C++ type used to
  162. represent this field.
  163. label: (One of the LABEL_* constants below) Tells whether this
  164. field is optional, required, or repeated.
  165. default_value: (Varies) Default value of this field. Only
  166. meaningful for non-repeated scalar fields. Repeated fields
  167. should always set this to [], and non-repeated composite
  168. fields should always set this to None.
  169. containing_type: (Descriptor) Descriptor of the protocol message
  170. type that contains this field. Set by the Descriptor constructor
  171. if we're passed into one.
  172. Somewhat confusingly, for extension fields, this is the
  173. descriptor of the EXTENDED message, not the descriptor
  174. of the message containing this field. (See is_extension and
  175. extension_scope below).
  176. message_type: (Descriptor) If a composite field, a descriptor
  177. of the message type contained in this field. Otherwise, this is None.
  178. enum_type: (EnumDescriptor) If this field contains an enum, a
  179. descriptor of that enum. Otherwise, this is None.
  180. is_extension: True iff this describes an extension field.
  181. extension_scope: (Descriptor) Only meaningful if is_extension is True.
  182. Gives the message that immediately contains this extension field.
  183. Will be None iff we're a top-level (file-level) extension field.
  184. options: (descriptor_pb2.FieldOptions) Protocol message field options or
  185. None to use default field options.
  186. """
  187. # Must be consistent with C++ FieldDescriptor::Type enum in
  188. # descriptor.h.
  189. #
  190. # TODO(robinson): Find a way to eliminate this repetition.
  191. TYPE_DOUBLE = 1
  192. TYPE_FLOAT = 2
  193. TYPE_INT64 = 3
  194. TYPE_UINT64 = 4
  195. TYPE_INT32 = 5
  196. TYPE_FIXED64 = 6
  197. TYPE_FIXED32 = 7
  198. TYPE_BOOL = 8
  199. TYPE_STRING = 9
  200. TYPE_GROUP = 10
  201. TYPE_MESSAGE = 11
  202. TYPE_BYTES = 12
  203. TYPE_UINT32 = 13
  204. TYPE_ENUM = 14
  205. TYPE_SFIXED32 = 15
  206. TYPE_SFIXED64 = 16
  207. TYPE_SINT32 = 17
  208. TYPE_SINT64 = 18
  209. MAX_TYPE = 18
  210. # Must be consistent with C++ FieldDescriptor::CppType enum in
  211. # descriptor.h.
  212. #
  213. # TODO(robinson): Find a way to eliminate this repetition.
  214. CPPTYPE_INT32 = 1
  215. CPPTYPE_INT64 = 2
  216. CPPTYPE_UINT32 = 3
  217. CPPTYPE_UINT64 = 4
  218. CPPTYPE_DOUBLE = 5
  219. CPPTYPE_FLOAT = 6
  220. CPPTYPE_BOOL = 7
  221. CPPTYPE_ENUM = 8
  222. CPPTYPE_STRING = 9
  223. CPPTYPE_MESSAGE = 10
  224. MAX_CPPTYPE = 10
  225. # Must be consistent with C++ FieldDescriptor::Label enum in
  226. # descriptor.h.
  227. #
  228. # TODO(robinson): Find a way to eliminate this repetition.
  229. LABEL_OPTIONAL = 1
  230. LABEL_REQUIRED = 2
  231. LABEL_REPEATED = 3
  232. MAX_LABEL = 3
  233. def __init__(self, name, full_name, index, number, type, cpp_type, label,
  234. default_value, message_type, enum_type, containing_type,
  235. is_extension, extension_scope, options=None):
  236. """The arguments are as described in the description of FieldDescriptor
  237. attributes above.
  238. Note that containing_type may be None, and may be set later if necessary
  239. (to deal with circular references between message types, for example).
  240. Likewise for extension_scope.
  241. """
  242. super(FieldDescriptor, self).__init__(options, 'FieldOptions')
  243. self.name = name
  244. self.full_name = full_name
  245. self.index = index
  246. self.number = number
  247. self.type = type
  248. self.cpp_type = cpp_type
  249. self.label = label
  250. self.default_value = default_value
  251. self.containing_type = containing_type
  252. self.message_type = message_type
  253. self.enum_type = enum_type
  254. self.is_extension = is_extension
  255. self.extension_scope = extension_scope
  256. class EnumDescriptor(DescriptorBase):
  257. """Descriptor for an enum defined in a .proto file.
  258. An EnumDescriptor instance has the following attributes:
  259. name: (str) Name of the enum type.
  260. full_name: (str) Full name of the type, including package name
  261. and any enclosing type(s).
  262. filename: (str) Name of the .proto file in which this appears.
  263. values: (list of EnumValueDescriptors) List of the values
  264. in this enum.
  265. values_by_name: (dict str -> EnumValueDescriptor) Same as |values|,
  266. but indexed by the "name" field of each EnumValueDescriptor.
  267. values_by_number: (dict int -> EnumValueDescriptor) Same as |values|,
  268. but indexed by the "number" field of each EnumValueDescriptor.
  269. containing_type: (Descriptor) Descriptor of the immediate containing
  270. type of this enum, or None if this is an enum defined at the
  271. top level in a .proto file. Set by Descriptor's constructor
  272. if we're passed into one.
  273. options: (descriptor_pb2.EnumOptions) Enum options message or
  274. None to use default enum options.
  275. """
  276. def __init__(self, name, full_name, filename, values,
  277. containing_type=None, options=None):
  278. """Arguments are as described in the attribute description above."""
  279. super(EnumDescriptor, self).__init__(options, 'EnumOptions')
  280. self.name = name
  281. self.full_name = full_name
  282. self.filename = filename
  283. self.values = values
  284. for value in self.values:
  285. value.type = self
  286. self.values_by_name = dict((v.name, v) for v in values)
  287. self.values_by_number = dict((v.number, v) for v in values)
  288. self.containing_type = containing_type
  289. class EnumValueDescriptor(DescriptorBase):
  290. """Descriptor for a single value within an enum.
  291. name: (str) Name of this value.
  292. index: (int) Dense, 0-indexed index giving the order that this
  293. value appears textually within its enum in the .proto file.
  294. number: (int) Actual number assigned to this enum value.
  295. type: (EnumDescriptor) EnumDescriptor to which this value
  296. belongs. Set by EnumDescriptor's constructor if we're
  297. passed into one.
  298. options: (descriptor_pb2.EnumValueOptions) Enum value options message or
  299. None to use default enum value options options.
  300. """
  301. def __init__(self, name, index, number, type=None, options=None):
  302. """Arguments are as described in the attribute description above."""
  303. super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions')
  304. self.name = name
  305. self.index = index
  306. self.number = number
  307. self.type = type
  308. class ServiceDescriptor(DescriptorBase):
  309. """Descriptor for a service.
  310. name: (str) Name of the service.
  311. full_name: (str) Full name of the service, including package name.
  312. index: (int) 0-indexed index giving the order that this services
  313. definition appears withing the .proto file.
  314. methods: (list of MethodDescriptor) List of methods provided by this
  315. service.
  316. options: (descriptor_pb2.ServiceOptions) Service options message or
  317. None to use default service options.
  318. """
  319. def __init__(self, name, full_name, index, methods, options=None):
  320. super(ServiceDescriptor, self).__init__(options, 'ServiceOptions')
  321. self.name = name
  322. self.full_name = full_name
  323. self.index = index
  324. self.methods = methods
  325. # Set the containing service for each method in this service.
  326. for method in self.methods:
  327. method.containing_service = self
  328. def FindMethodByName(self, name):
  329. """Searches for the specified method, and returns its descriptor."""
  330. for method in self.methods:
  331. if name == method.name:
  332. return method
  333. return None
  334. class MethodDescriptor(DescriptorBase):
  335. """Descriptor for a method in a service.
  336. name: (str) Name of the method within the service.
  337. full_name: (str) Full name of method.
  338. index: (int) 0-indexed index of the method inside the service.
  339. containing_service: (ServiceDescriptor) The service that contains this
  340. method.
  341. input_type: The descriptor of the message that this method accepts.
  342. output_type: The descriptor of the message that this method returns.
  343. options: (descriptor_pb2.MethodOptions) Method options message or
  344. None to use default method options.
  345. """
  346. def __init__(self, name, full_name, index, containing_service,
  347. input_type, output_type, options=None):
  348. """The arguments are as described in the description of MethodDescriptor
  349. attributes above.
  350. Note that containing_service may be None, and may be set later if necessary.
  351. """
  352. super(MethodDescriptor, self).__init__(options, 'MethodOptions')
  353. self.name = name
  354. self.full_name = full_name
  355. self.index = index
  356. self.containing_service = containing_service
  357. self.input_type = input_type
  358. self.output_type = output_type
  359. def _ParseOptions(message, string):
  360. """Parses serialized options.
  361. This helper function is used to parse serialized options in generated
  362. proto2 files. It must not be used outside proto2.
  363. """
  364. message.ParseFromString(string)
  365. return message;