descriptor_pool.py 37 KB

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