descriptor_pool.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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. """Provides DescriptorPool to use as a container for proto2 descriptors.
  31. The DescriptorPool is used in conjection with a DescriptorDatabase to maintain
  32. a collection of protocol buffer descriptors for use when dynamically creating
  33. message types at runtime.
  34. For most applications protocol buffers should be used via modules generated by
  35. the protocol buffer compiler tool. This should only be used when the type of
  36. protocol buffers used in an application or library cannot be predetermined.
  37. Below is a straightforward example on how to use this class:
  38. pool = DescriptorPool()
  39. file_descriptor_protos = [ ... ]
  40. for file_descriptor_proto in file_descriptor_protos:
  41. pool.Add(file_descriptor_proto)
  42. my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType')
  43. The message descriptor can be used in conjunction with the message_factory
  44. module in order to create a protocol buffer class that can be encoded and
  45. decoded.
  46. If you want to get a Python class for the specified proto, use the
  47. helper functions inside google.protobuf.message_factory
  48. directly instead of this class.
  49. """
  50. __author__ = 'matthewtoia@google.com (Matt Toia)'
  51. import collections
  52. from google.protobuf import descriptor
  53. from google.protobuf import descriptor_database
  54. from google.protobuf import text_encoding
  55. _USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access
  56. def _NormalizeFullyQualifiedName(name):
  57. """Remove leading period from fully-qualified type name.
  58. Due to b/13860351 in descriptor_database.py, types in the root namespace are
  59. generated with a leading period. This function removes that prefix.
  60. Args:
  61. name: A str, the fully-qualified symbol name.
  62. Returns:
  63. A str, the normalized fully-qualified symbol name.
  64. """
  65. return name.lstrip('.')
  66. def _OptionsOrNone(descriptor_proto):
  67. """Returns the value of the field `options`, or None if it is not set."""
  68. if descriptor_proto.HasField('options'):
  69. return descriptor_proto.options
  70. else:
  71. return None
  72. def _IsMessageSetExtension(field):
  73. return (field.is_extension and
  74. field.containing_type.has_options and
  75. field.containing_type.GetOptions().message_set_wire_format and
  76. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  77. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL)
  78. class DescriptorPool(object):
  79. """A collection of protobufs dynamically constructed by descriptor protos."""
  80. if _USE_C_DESCRIPTORS:
  81. def __new__(cls, descriptor_db=None):
  82. # pylint: disable=protected-access
  83. return descriptor._message.DescriptorPool(descriptor_db)
  84. def __init__(self, descriptor_db=None):
  85. """Initializes a Pool of proto buffs.
  86. The descriptor_db argument to the constructor is provided to allow
  87. specialized file descriptor proto lookup code to be triggered on demand. An
  88. example would be an implementation which will read and compile a file
  89. specified in a call to FindFileByName() and not require the call to Add()
  90. at all. Results from this database will be cached internally here as well.
  91. Args:
  92. descriptor_db: A secondary source of file descriptors.
  93. """
  94. self._internal_db = descriptor_database.DescriptorDatabase()
  95. self._descriptor_db = descriptor_db
  96. self._descriptors = {}
  97. self._enum_descriptors = {}
  98. self._service_descriptors = {}
  99. self._file_descriptors = {}
  100. self._toplevel_extensions = {}
  101. # TODO(jieluo): Remove _file_desc_by_toplevel_extension when
  102. # FieldDescriptor.file is added in code gen.
  103. self._file_desc_by_toplevel_extension = {}
  104. # We store extensions in two two-level mappings: The first key is the
  105. # descriptor of the message being extended, the second key is the extension
  106. # full name or its tag number.
  107. self._extensions_by_name = collections.defaultdict(dict)
  108. self._extensions_by_number = collections.defaultdict(dict)
  109. def Add(self, file_desc_proto):
  110. """Adds the FileDescriptorProto and its types to this pool.
  111. Args:
  112. file_desc_proto: The FileDescriptorProto to add.
  113. """
  114. self._internal_db.Add(file_desc_proto)
  115. def AddSerializedFile(self, serialized_file_desc_proto):
  116. """Adds the FileDescriptorProto and its types to this pool.
  117. Args:
  118. serialized_file_desc_proto: A bytes string, serialization of the
  119. FileDescriptorProto to add.
  120. """
  121. # pylint: disable=g-import-not-at-top
  122. from google.protobuf import descriptor_pb2
  123. file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
  124. serialized_file_desc_proto)
  125. self.Add(file_desc_proto)
  126. def AddDescriptor(self, desc):
  127. """Adds a Descriptor to the pool, non-recursively.
  128. If the Descriptor contains nested messages or enums, the caller must
  129. explicitly register them. This method also registers the FileDescriptor
  130. associated with the message.
  131. Args:
  132. desc: A Descriptor.
  133. """
  134. if not isinstance(desc, descriptor.Descriptor):
  135. raise TypeError('Expected instance of descriptor.Descriptor.')
  136. self._descriptors[desc.full_name] = desc
  137. self._AddFileDescriptor(desc.file)
  138. def AddEnumDescriptor(self, enum_desc):
  139. """Adds an EnumDescriptor to the pool.
  140. This method also registers the FileDescriptor associated with the enum.
  141. Args:
  142. enum_desc: An EnumDescriptor.
  143. """
  144. if not isinstance(enum_desc, descriptor.EnumDescriptor):
  145. raise TypeError('Expected instance of descriptor.EnumDescriptor.')
  146. self._enum_descriptors[enum_desc.full_name] = enum_desc
  147. self._AddFileDescriptor(enum_desc.file)
  148. def AddServiceDescriptor(self, service_desc):
  149. """Adds a ServiceDescriptor to the pool.
  150. Args:
  151. service_desc: A ServiceDescriptor.
  152. """
  153. if not isinstance(service_desc, descriptor.ServiceDescriptor):
  154. raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
  155. self._service_descriptors[service_desc.full_name] = service_desc
  156. def AddExtensionDescriptor(self, extension):
  157. """Adds a FieldDescriptor describing an extension to the pool.
  158. Args:
  159. extension: A FieldDescriptor.
  160. Raises:
  161. AssertionError: when another extension with the same number extends the
  162. same message.
  163. TypeError: when the specified extension is not a
  164. descriptor.FieldDescriptor.
  165. """
  166. if not (isinstance(extension, descriptor.FieldDescriptor) and
  167. extension.is_extension):
  168. raise TypeError('Expected an extension descriptor.')
  169. if extension.extension_scope is None:
  170. self._toplevel_extensions[extension.full_name] = extension
  171. try:
  172. existing_desc = self._extensions_by_number[
  173. extension.containing_type][extension.number]
  174. except KeyError:
  175. pass
  176. else:
  177. if extension is not existing_desc:
  178. raise AssertionError(
  179. 'Extensions "%s" and "%s" both try to extend message type "%s" '
  180. 'with field number %d.' %
  181. (extension.full_name, existing_desc.full_name,
  182. extension.containing_type.full_name, extension.number))
  183. self._extensions_by_number[extension.containing_type][
  184. extension.number] = extension
  185. self._extensions_by_name[extension.containing_type][
  186. extension.full_name] = extension
  187. # Also register MessageSet extensions with the type name.
  188. if _IsMessageSetExtension(extension):
  189. self._extensions_by_name[extension.containing_type][
  190. extension.message_type.full_name] = extension
  191. def AddFileDescriptor(self, file_desc):
  192. """Adds a FileDescriptor to the pool, non-recursively.
  193. If the FileDescriptor contains messages or enums, the caller must explicitly
  194. register them.
  195. Args:
  196. file_desc: A FileDescriptor.
  197. """
  198. self._AddFileDescriptor(file_desc)
  199. # TODO(jieluo): This is a temporary solution for FieldDescriptor.file.
  200. # Remove it when FieldDescriptor.file is added in code gen.
  201. for extension in file_desc.extensions_by_name.values():
  202. self._file_desc_by_toplevel_extension[
  203. extension.full_name] = file_desc
  204. def _AddFileDescriptor(self, file_desc):
  205. """Adds a FileDescriptor to the pool, non-recursively.
  206. If the FileDescriptor contains messages or enums, the caller must explicitly
  207. register them.
  208. Args:
  209. file_desc: A FileDescriptor.
  210. """
  211. if not isinstance(file_desc, descriptor.FileDescriptor):
  212. raise TypeError('Expected instance of descriptor.FileDescriptor.')
  213. self._file_descriptors[file_desc.name] = file_desc
  214. def FindFileByName(self, file_name):
  215. """Gets a FileDescriptor by file name.
  216. Args:
  217. file_name: The path to the file to get a descriptor for.
  218. Returns:
  219. A FileDescriptor for the named file.
  220. Raises:
  221. KeyError: if the file cannot be found in the pool.
  222. """
  223. try:
  224. return self._file_descriptors[file_name]
  225. except KeyError:
  226. pass
  227. try:
  228. file_proto = self._internal_db.FindFileByName(file_name)
  229. except KeyError as error:
  230. if self._descriptor_db:
  231. file_proto = self._descriptor_db.FindFileByName(file_name)
  232. else:
  233. raise error
  234. if not file_proto:
  235. raise KeyError('Cannot find a file named %s' % file_name)
  236. return self._ConvertFileProtoToFileDescriptor(file_proto)
  237. def FindFileContainingSymbol(self, symbol):
  238. """Gets the FileDescriptor for the file containing the specified symbol.
  239. Args:
  240. symbol: The name of the symbol to search for.
  241. Returns:
  242. A FileDescriptor that contains the specified symbol.
  243. Raises:
  244. KeyError: if the file cannot be found in the pool.
  245. """
  246. symbol = _NormalizeFullyQualifiedName(symbol)
  247. try:
  248. return self._descriptors[symbol].file
  249. except KeyError:
  250. pass
  251. try:
  252. return self._enum_descriptors[symbol].file
  253. except KeyError:
  254. pass
  255. try:
  256. return self._FindFileContainingSymbolInDb(symbol)
  257. except KeyError:
  258. pass
  259. try:
  260. return self._file_desc_by_toplevel_extension[symbol]
  261. except KeyError:
  262. pass
  263. # Try nested extensions inside a message.
  264. message_name, _, extension_name = symbol.rpartition('.')
  265. try:
  266. message = self.FindMessageTypeByName(message_name)
  267. assert message.extensions_by_name[extension_name]
  268. return message.file
  269. except KeyError:
  270. raise KeyError('Cannot find a file containing %s' % symbol)
  271. def FindMessageTypeByName(self, full_name):
  272. """Loads the named descriptor from the pool.
  273. Args:
  274. full_name: The full name of the descriptor to load.
  275. Returns:
  276. The descriptor for the named type.
  277. Raises:
  278. KeyError: if the message cannot be found in the pool.
  279. """
  280. full_name = _NormalizeFullyQualifiedName(full_name)
  281. if full_name not in self._descriptors:
  282. self._FindFileContainingSymbolInDb(full_name)
  283. return self._descriptors[full_name]
  284. def FindEnumTypeByName(self, full_name):
  285. """Loads the named enum descriptor from the pool.
  286. Args:
  287. full_name: The full name of the enum descriptor to load.
  288. Returns:
  289. The enum descriptor for the named type.
  290. Raises:
  291. KeyError: if the enum cannot be found in the pool.
  292. """
  293. full_name = _NormalizeFullyQualifiedName(full_name)
  294. if full_name not in self._enum_descriptors:
  295. self._FindFileContainingSymbolInDb(full_name)
  296. return self._enum_descriptors[full_name]
  297. def FindFieldByName(self, full_name):
  298. """Loads the named field descriptor from the pool.
  299. Args:
  300. full_name: The full name of the field descriptor to load.
  301. Returns:
  302. The field descriptor for the named field.
  303. Raises:
  304. KeyError: if the field cannot be found in the pool.
  305. """
  306. full_name = _NormalizeFullyQualifiedName(full_name)
  307. message_name, _, field_name = full_name.rpartition('.')
  308. message_descriptor = self.FindMessageTypeByName(message_name)
  309. return message_descriptor.fields_by_name[field_name]
  310. def FindExtensionByName(self, full_name):
  311. """Loads the named extension descriptor from the pool.
  312. Args:
  313. full_name: The full name of the extension descriptor to load.
  314. Returns:
  315. A FieldDescriptor, describing the named extension.
  316. Raises:
  317. KeyError: if the extension cannot be found in the pool.
  318. """
  319. full_name = _NormalizeFullyQualifiedName(full_name)
  320. try:
  321. # The proto compiler does not give any link between the FileDescriptor
  322. # and top-level extensions unless the FileDescriptorProto is added to
  323. # the DescriptorDatabase, but this can impact memory usage.
  324. # So we registered these extensions by name explicitly.
  325. return self._toplevel_extensions[full_name]
  326. except KeyError:
  327. pass
  328. message_name, _, extension_name = full_name.rpartition('.')
  329. try:
  330. # Most extensions are nested inside a message.
  331. scope = self.FindMessageTypeByName(message_name)
  332. except KeyError:
  333. # Some extensions are defined at file scope.
  334. scope = self._FindFileContainingSymbolInDb(full_name)
  335. return scope.extensions_by_name[extension_name]
  336. def FindExtensionByNumber(self, message_descriptor, number):
  337. """Gets the extension of the specified message with the specified number.
  338. Extensions have to be registered to this pool by calling
  339. AddExtensionDescriptor.
  340. Args:
  341. message_descriptor: descriptor of the extended message.
  342. number: integer, number of the extension field.
  343. Returns:
  344. A FieldDescriptor describing the extension.
  345. Raises:
  346. KeyError: when no extension with the given number is known for the
  347. specified message.
  348. """
  349. return self._extensions_by_number[message_descriptor][number]
  350. def FindAllExtensions(self, message_descriptor):
  351. """Gets all the known extension of a given message.
  352. Extensions have to be registered to this pool by calling
  353. AddExtensionDescriptor.
  354. Args:
  355. message_descriptor: descriptor of the extended message.
  356. Returns:
  357. A list of FieldDescriptor describing the extensions.
  358. """
  359. return list(self._extensions_by_number[message_descriptor].values())
  360. def FindServiceByName(self, full_name):
  361. """Loads the named service descriptor from the pool.
  362. Args:
  363. full_name: The full name of the service descriptor to load.
  364. Returns:
  365. The service descriptor for the named service.
  366. Raises:
  367. KeyError: if the service cannot be found in the pool.
  368. """
  369. full_name = _NormalizeFullyQualifiedName(full_name)
  370. if full_name not in self._service_descriptors:
  371. self._FindFileContainingSymbolInDb(full_name)
  372. return self._service_descriptors[full_name]
  373. def _FindFileContainingSymbolInDb(self, symbol):
  374. """Finds the file in descriptor DB containing the specified symbol.
  375. Args:
  376. symbol: The name of the symbol to search for.
  377. Returns:
  378. A FileDescriptor that contains the specified symbol.
  379. Raises:
  380. KeyError: if the file cannot be found in the descriptor database.
  381. """
  382. try:
  383. file_proto = self._internal_db.FindFileContainingSymbol(symbol)
  384. except KeyError as error:
  385. if self._descriptor_db:
  386. file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
  387. else:
  388. raise error
  389. if not file_proto:
  390. raise KeyError('Cannot find a file containing %s' % symbol)
  391. return self._ConvertFileProtoToFileDescriptor(file_proto)
  392. def _ConvertFileProtoToFileDescriptor(self, file_proto):
  393. """Creates a FileDescriptor from a proto or returns a cached copy.
  394. This method also has the side effect of loading all the symbols found in
  395. the file into the appropriate dictionaries in the pool.
  396. Args:
  397. file_proto: The proto to convert.
  398. Returns:
  399. A FileDescriptor matching the passed in proto.
  400. """
  401. if file_proto.name not in self._file_descriptors:
  402. built_deps = list(self._GetDeps(file_proto.dependency))
  403. direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
  404. public_deps = [direct_deps[i] for i in file_proto.public_dependency]
  405. file_descriptor = descriptor.FileDescriptor(
  406. pool=self,
  407. name=file_proto.name,
  408. package=file_proto.package,
  409. syntax=file_proto.syntax,
  410. options=_OptionsOrNone(file_proto),
  411. serialized_pb=file_proto.SerializeToString(),
  412. dependencies=direct_deps,
  413. public_dependencies=public_deps)
  414. scope = {}
  415. # This loop extracts all the message and enum types from all the
  416. # dependencies of the file_proto. This is necessary to create the
  417. # scope of available message types when defining the passed in
  418. # file proto.
  419. for dependency in built_deps:
  420. scope.update(self._ExtractSymbols(
  421. dependency.message_types_by_name.values()))
  422. scope.update((_PrefixWithDot(enum.full_name), enum)
  423. for enum in dependency.enum_types_by_name.values())
  424. for message_type in file_proto.message_type:
  425. message_desc = self._ConvertMessageDescriptor(
  426. message_type, file_proto.package, file_descriptor, scope,
  427. file_proto.syntax)
  428. file_descriptor.message_types_by_name[message_desc.name] = (
  429. message_desc)
  430. for enum_type in file_proto.enum_type:
  431. file_descriptor.enum_types_by_name[enum_type.name] = (
  432. self._ConvertEnumDescriptor(enum_type, file_proto.package,
  433. file_descriptor, None, scope))
  434. for index, extension_proto in enumerate(file_proto.extension):
  435. extension_desc = self._MakeFieldDescriptor(
  436. extension_proto, file_proto.package, index, is_extension=True)
  437. extension_desc.containing_type = self._GetTypeFromScope(
  438. file_descriptor.package, extension_proto.extendee, scope)
  439. self._SetFieldType(extension_proto, extension_desc,
  440. file_descriptor.package, scope)
  441. file_descriptor.extensions_by_name[extension_desc.name] = (
  442. extension_desc)
  443. for desc_proto in file_proto.message_type:
  444. self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
  445. if file_proto.package:
  446. desc_proto_prefix = _PrefixWithDot(file_proto.package)
  447. else:
  448. desc_proto_prefix = ''
  449. for desc_proto in file_proto.message_type:
  450. desc = self._GetTypeFromScope(
  451. desc_proto_prefix, desc_proto.name, scope)
  452. file_descriptor.message_types_by_name[desc_proto.name] = desc
  453. for index, service_proto in enumerate(file_proto.service):
  454. file_descriptor.services_by_name[service_proto.name] = (
  455. self._MakeServiceDescriptor(service_proto, index, scope,
  456. file_proto.package, file_descriptor))
  457. self.Add(file_proto)
  458. self._file_descriptors[file_proto.name] = file_descriptor
  459. return self._file_descriptors[file_proto.name]
  460. def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
  461. scope=None, syntax=None):
  462. """Adds the proto to the pool in the specified package.
  463. Args:
  464. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  465. package: The package the proto should be located in.
  466. file_desc: The file containing this message.
  467. scope: Dict mapping short and full symbols to message and enum types.
  468. syntax: string indicating syntax of the file ("proto2" or "proto3")
  469. Returns:
  470. The added descriptor.
  471. """
  472. if package:
  473. desc_name = '.'.join((package, desc_proto.name))
  474. else:
  475. desc_name = desc_proto.name
  476. if file_desc is None:
  477. file_name = None
  478. else:
  479. file_name = file_desc.name
  480. if scope is None:
  481. scope = {}
  482. nested = [
  483. self._ConvertMessageDescriptor(
  484. nested, desc_name, file_desc, scope, syntax)
  485. for nested in desc_proto.nested_type]
  486. enums = [
  487. self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)
  488. for enum in desc_proto.enum_type]
  489. fields = [self._MakeFieldDescriptor(field, desc_name, index)
  490. for index, field in enumerate(desc_proto.field)]
  491. extensions = [
  492. self._MakeFieldDescriptor(extension, desc_name, index,
  493. is_extension=True)
  494. for index, extension in enumerate(desc_proto.extension)]
  495. oneofs = [
  496. descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
  497. index, None, [], desc.options)
  498. for index, desc in enumerate(desc_proto.oneof_decl)]
  499. extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
  500. if extension_ranges:
  501. is_extendable = True
  502. else:
  503. is_extendable = False
  504. desc = descriptor.Descriptor(
  505. name=desc_proto.name,
  506. full_name=desc_name,
  507. filename=file_name,
  508. containing_type=None,
  509. fields=fields,
  510. oneofs=oneofs,
  511. nested_types=nested,
  512. enum_types=enums,
  513. extensions=extensions,
  514. options=_OptionsOrNone(desc_proto),
  515. is_extendable=is_extendable,
  516. extension_ranges=extension_ranges,
  517. file=file_desc,
  518. serialized_start=None,
  519. serialized_end=None,
  520. syntax=syntax)
  521. for nested in desc.nested_types:
  522. nested.containing_type = desc
  523. for enum in desc.enum_types:
  524. enum.containing_type = desc
  525. for field_index, field_desc in enumerate(desc_proto.field):
  526. if field_desc.HasField('oneof_index'):
  527. oneof_index = field_desc.oneof_index
  528. oneofs[oneof_index].fields.append(fields[field_index])
  529. fields[field_index].containing_oneof = oneofs[oneof_index]
  530. scope[_PrefixWithDot(desc_name)] = desc
  531. self._descriptors[desc_name] = desc
  532. return desc
  533. def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
  534. containing_type=None, scope=None):
  535. """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
  536. Args:
  537. enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
  538. package: Optional package name for the new message EnumDescriptor.
  539. file_desc: The file containing the enum descriptor.
  540. containing_type: The type containing this enum.
  541. scope: Scope containing available types.
  542. Returns:
  543. The added descriptor
  544. """
  545. if package:
  546. enum_name = '.'.join((package, enum_proto.name))
  547. else:
  548. enum_name = enum_proto.name
  549. if file_desc is None:
  550. file_name = None
  551. else:
  552. file_name = file_desc.name
  553. values = [self._MakeEnumValueDescriptor(value, index)
  554. for index, value in enumerate(enum_proto.value)]
  555. desc = descriptor.EnumDescriptor(name=enum_proto.name,
  556. full_name=enum_name,
  557. filename=file_name,
  558. file=file_desc,
  559. values=values,
  560. containing_type=containing_type,
  561. options=_OptionsOrNone(enum_proto))
  562. scope['.%s' % enum_name] = desc
  563. self._enum_descriptors[enum_name] = desc
  564. return desc
  565. def _MakeFieldDescriptor(self, field_proto, message_name, index,
  566. is_extension=False):
  567. """Creates a field descriptor from a FieldDescriptorProto.
  568. For message and enum type fields, this method will do a look up
  569. in the pool for the appropriate descriptor for that type. If it
  570. is unavailable, it will fall back to the _source function to
  571. create it. If this type is still unavailable, construction will
  572. fail.
  573. Args:
  574. field_proto: The proto describing the field.
  575. message_name: The name of the containing message.
  576. index: Index of the field
  577. is_extension: Indication that this field is for an extension.
  578. Returns:
  579. An initialized FieldDescriptor object
  580. """
  581. if message_name:
  582. full_name = '.'.join((message_name, field_proto.name))
  583. else:
  584. full_name = field_proto.name
  585. return descriptor.FieldDescriptor(
  586. name=field_proto.name,
  587. full_name=full_name,
  588. index=index,
  589. number=field_proto.number,
  590. type=field_proto.type,
  591. cpp_type=None,
  592. message_type=None,
  593. enum_type=None,
  594. containing_type=None,
  595. label=field_proto.label,
  596. has_default_value=False,
  597. default_value=None,
  598. is_extension=is_extension,
  599. extension_scope=None,
  600. options=_OptionsOrNone(field_proto))
  601. def _SetAllFieldTypes(self, package, desc_proto, scope):
  602. """Sets all the descriptor's fields's types.
  603. This method also sets the containing types on any extensions.
  604. Args:
  605. package: The current package of desc_proto.
  606. desc_proto: The message descriptor to update.
  607. scope: Enclosing scope of available types.
  608. """
  609. package = _PrefixWithDot(package)
  610. main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
  611. if package == '.':
  612. nested_package = _PrefixWithDot(desc_proto.name)
  613. else:
  614. nested_package = '.'.join([package, desc_proto.name])
  615. for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
  616. self._SetFieldType(field_proto, field_desc, nested_package, scope)
  617. for extension_proto, extension_desc in (
  618. zip(desc_proto.extension, main_desc.extensions)):
  619. extension_desc.containing_type = self._GetTypeFromScope(
  620. nested_package, extension_proto.extendee, scope)
  621. self._SetFieldType(extension_proto, extension_desc, nested_package, scope)
  622. for nested_type in desc_proto.nested_type:
  623. self._SetAllFieldTypes(nested_package, nested_type, scope)
  624. def _SetFieldType(self, field_proto, field_desc, package, scope):
  625. """Sets the field's type, cpp_type, message_type and enum_type.
  626. Args:
  627. field_proto: Data about the field in proto format.
  628. field_desc: The descriptor to modiy.
  629. package: The package the field's container is in.
  630. scope: Enclosing scope of available types.
  631. """
  632. if field_proto.type_name:
  633. desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
  634. else:
  635. desc = None
  636. if not field_proto.HasField('type'):
  637. if isinstance(desc, descriptor.Descriptor):
  638. field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
  639. else:
  640. field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
  641. field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
  642. field_proto.type)
  643. if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
  644. or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
  645. field_desc.message_type = desc
  646. if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  647. field_desc.enum_type = desc
  648. if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  649. field_desc.has_default_value = False
  650. field_desc.default_value = []
  651. elif field_proto.HasField('default_value'):
  652. field_desc.has_default_value = True
  653. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  654. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  655. field_desc.default_value = float(field_proto.default_value)
  656. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  657. field_desc.default_value = field_proto.default_value
  658. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  659. field_desc.default_value = field_proto.default_value.lower() == 'true'
  660. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  661. field_desc.default_value = field_desc.enum_type.values_by_name[
  662. field_proto.default_value].number
  663. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  664. field_desc.default_value = text_encoding.CUnescape(
  665. field_proto.default_value)
  666. else:
  667. # All other types are of the "int" type.
  668. field_desc.default_value = int(field_proto.default_value)
  669. else:
  670. field_desc.has_default_value = False
  671. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  672. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  673. field_desc.default_value = 0.0
  674. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  675. field_desc.default_value = u''
  676. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  677. field_desc.default_value = False
  678. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  679. field_desc.default_value = field_desc.enum_type.values[0].number
  680. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  681. field_desc.default_value = b''
  682. else:
  683. # All other types are of the "int" type.
  684. field_desc.default_value = 0
  685. field_desc.type = field_proto.type
  686. def _MakeEnumValueDescriptor(self, value_proto, index):
  687. """Creates a enum value descriptor object from a enum value proto.
  688. Args:
  689. value_proto: The proto describing the enum value.
  690. index: The index of the enum value.
  691. Returns:
  692. An initialized EnumValueDescriptor object.
  693. """
  694. return descriptor.EnumValueDescriptor(
  695. name=value_proto.name,
  696. index=index,
  697. number=value_proto.number,
  698. options=_OptionsOrNone(value_proto),
  699. type=None)
  700. def _MakeServiceDescriptor(self, service_proto, service_index, scope,
  701. package, file_desc):
  702. """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
  703. Args:
  704. service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
  705. service_index: The index of the service in the File.
  706. scope: Dict mapping short and full symbols to message and enum types.
  707. package: Optional package name for the new message EnumDescriptor.
  708. file_desc: The file containing the service descriptor.
  709. Returns:
  710. The added descriptor.
  711. """
  712. if package:
  713. service_name = '.'.join((package, service_proto.name))
  714. else:
  715. service_name = service_proto.name
  716. methods = [self._MakeMethodDescriptor(method_proto, service_name, package,
  717. scope, index)
  718. for index, method_proto in enumerate(service_proto.method)]
  719. desc = descriptor.ServiceDescriptor(name=service_proto.name,
  720. full_name=service_name,
  721. index=service_index,
  722. methods=methods,
  723. options=_OptionsOrNone(service_proto),
  724. file=file_desc)
  725. self._service_descriptors[service_name] = desc
  726. return desc
  727. def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
  728. index):
  729. """Creates a method descriptor from a MethodDescriptorProto.
  730. Args:
  731. method_proto: The proto describing the method.
  732. service_name: The name of the containing service.
  733. package: Optional package name to look up for types.
  734. scope: Scope containing available types.
  735. index: Index of the method in the service.
  736. Returns:
  737. An initialized MethodDescriptor object.
  738. """
  739. full_name = '.'.join((service_name, method_proto.name))
  740. input_type = self._GetTypeFromScope(
  741. package, method_proto.input_type, scope)
  742. output_type = self._GetTypeFromScope(
  743. package, method_proto.output_type, scope)
  744. return descriptor.MethodDescriptor(name=method_proto.name,
  745. full_name=full_name,
  746. index=index,
  747. containing_service=None,
  748. input_type=input_type,
  749. output_type=output_type,
  750. options=_OptionsOrNone(method_proto))
  751. def _ExtractSymbols(self, descriptors):
  752. """Pulls out all the symbols from descriptor protos.
  753. Args:
  754. descriptors: The messages to extract descriptors from.
  755. Yields:
  756. A two element tuple of the type name and descriptor object.
  757. """
  758. for desc in descriptors:
  759. yield (_PrefixWithDot(desc.full_name), desc)
  760. for symbol in self._ExtractSymbols(desc.nested_types):
  761. yield symbol
  762. for enum in desc.enum_types:
  763. yield (_PrefixWithDot(enum.full_name), enum)
  764. def _GetDeps(self, dependencies):
  765. """Recursively finds dependencies for file protos.
  766. Args:
  767. dependencies: The names of the files being depended on.
  768. Yields:
  769. Each direct and indirect dependency.
  770. """
  771. for dependency in dependencies:
  772. dep_desc = self.FindFileByName(dependency)
  773. yield dep_desc
  774. for parent_dep in dep_desc.dependencies:
  775. yield parent_dep
  776. def _GetTypeFromScope(self, package, type_name, scope):
  777. """Finds a given type name in the current scope.
  778. Args:
  779. package: The package the proto should be located in.
  780. type_name: The name of the type to be found in the scope.
  781. scope: Dict mapping short and full symbols to message and enum types.
  782. Returns:
  783. The descriptor for the requested type.
  784. """
  785. if type_name not in scope:
  786. components = _PrefixWithDot(package).split('.')
  787. while components:
  788. possible_match = '.'.join(components + [type_name])
  789. if possible_match in scope:
  790. type_name = possible_match
  791. break
  792. else:
  793. components.pop(-1)
  794. return scope[type_name]
  795. def _PrefixWithDot(name):
  796. return name if name.startswith('.') else '.%s' % name
  797. if _USE_C_DESCRIPTORS:
  798. # TODO(amauryfa): This pool could be constructed from Python code, when we
  799. # support a flag like 'use_cpp_generated_pool=True'.
  800. # pylint: disable=protected-access
  801. _DEFAULT = descriptor._message.default_pool
  802. else:
  803. _DEFAULT = DescriptorPool()
  804. def Default():
  805. return _DEFAULT