descriptor_pool.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. """Provides DescriptorPool to use as a container for proto2 descriptors.
  8. The DescriptorPool is used in conjection with a DescriptorDatabase to maintain
  9. a collection of protocol buffer descriptors for use when dynamically creating
  10. message types at runtime.
  11. For most applications protocol buffers should be used via modules generated by
  12. the protocol buffer compiler tool. This should only be used when the type of
  13. protocol buffers used in an application or library cannot be predetermined.
  14. Below is a straightforward example on how to use this class::
  15. pool = DescriptorPool()
  16. file_descriptor_protos = [ ... ]
  17. for file_descriptor_proto in file_descriptor_protos:
  18. pool.Add(file_descriptor_proto)
  19. my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType')
  20. The message descriptor can be used in conjunction with the message_factory
  21. module in order to create a protocol buffer class that can be encoded and
  22. decoded.
  23. If you want to get a Python class for the specified proto, use the
  24. helper functions inside google.protobuf.message_factory
  25. directly instead of this class.
  26. """
  27. __author__ = 'matthewtoia@google.com (Matt Toia)'
  28. import collections
  29. import threading
  30. import warnings
  31. from google.protobuf import descriptor
  32. from google.protobuf import descriptor_database
  33. from google.protobuf import text_encoding
  34. from google.protobuf.internal import python_edition_defaults
  35. from google.protobuf.internal import python_message
  36. _USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access
  37. def _NormalizeFullyQualifiedName(name):
  38. """Remove leading period from fully-qualified type name.
  39. Due to b/13860351 in descriptor_database.py, types in the root namespace are
  40. generated with a leading period. This function removes that prefix.
  41. Args:
  42. name (str): The fully-qualified symbol name.
  43. Returns:
  44. str: The normalized fully-qualified symbol name.
  45. """
  46. return name.lstrip('.')
  47. def _OptionsOrNone(descriptor_proto):
  48. """Returns the value of the field `options`, or None if it is not set."""
  49. if descriptor_proto.HasField('options'):
  50. return descriptor_proto.options
  51. else:
  52. return None
  53. def _IsMessageSetExtension(field):
  54. return (field.is_extension and
  55. field.containing_type.has_options and
  56. field.containing_type.GetOptions().message_set_wire_format and
  57. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  58. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL)
  59. _edition_defaults_lock = threading.Lock()
  60. class DescriptorPool(object):
  61. """A collection of protobufs dynamically constructed by descriptor protos."""
  62. if _USE_C_DESCRIPTORS:
  63. def __new__(cls, descriptor_db=None):
  64. # pylint: disable=protected-access
  65. return descriptor._message.DescriptorPool(descriptor_db)
  66. def __init__(
  67. self, descriptor_db=None, use_deprecated_legacy_json_field_conflicts=False
  68. ):
  69. """Initializes a Pool of proto buffs.
  70. The descriptor_db argument to the constructor is provided to allow
  71. specialized file descriptor proto lookup code to be triggered on demand. An
  72. example would be an implementation which will read and compile a file
  73. specified in a call to FindFileByName() and not require the call to Add()
  74. at all. Results from this database will be cached internally here as well.
  75. Args:
  76. descriptor_db: A secondary source of file descriptors.
  77. use_deprecated_legacy_json_field_conflicts: Unused, for compatibility with
  78. C++.
  79. """
  80. self._internal_db = descriptor_database.DescriptorDatabase()
  81. self._descriptor_db = descriptor_db
  82. self._descriptors = {}
  83. self._enum_descriptors = {}
  84. self._service_descriptors = {}
  85. self._file_descriptors = {}
  86. self._toplevel_extensions = {}
  87. self._top_enum_values = {}
  88. # We store extensions in two two-level mappings: The first key is the
  89. # descriptor of the message being extended, the second key is the extension
  90. # full name or its tag number.
  91. self._extensions_by_name = collections.defaultdict(dict)
  92. self._extensions_by_number = collections.defaultdict(dict)
  93. self._serialized_edition_defaults = (
  94. python_edition_defaults._PROTOBUF_INTERNAL_PYTHON_EDITION_DEFAULTS
  95. )
  96. self._edition_defaults = None
  97. self._feature_cache = dict()
  98. def _CheckConflictRegister(self, desc, desc_name, file_name):
  99. """Check if the descriptor name conflicts with another of the same name.
  100. Args:
  101. desc: Descriptor of a message, enum, service, extension or enum value.
  102. desc_name (str): the full name of desc.
  103. file_name (str): The file name of descriptor.
  104. """
  105. for register, descriptor_type in [
  106. (self._descriptors, descriptor.Descriptor),
  107. (self._enum_descriptors, descriptor.EnumDescriptor),
  108. (self._service_descriptors, descriptor.ServiceDescriptor),
  109. (self._toplevel_extensions, descriptor.FieldDescriptor),
  110. (self._top_enum_values, descriptor.EnumValueDescriptor)]:
  111. if desc_name in register:
  112. old_desc = register[desc_name]
  113. if isinstance(old_desc, descriptor.EnumValueDescriptor):
  114. old_file = old_desc.type.file.name
  115. else:
  116. old_file = old_desc.file.name
  117. if not isinstance(desc, descriptor_type) or (
  118. old_file != file_name):
  119. error_msg = ('Conflict register for file "' + file_name +
  120. '": ' + desc_name +
  121. ' is already defined in file "' +
  122. old_file + '". Please fix the conflict by adding '
  123. 'package name on the proto file, or use different '
  124. 'name for the duplication.')
  125. if isinstance(desc, descriptor.EnumValueDescriptor):
  126. error_msg += ('\nNote: enum values appear as '
  127. 'siblings of the enum type instead of '
  128. 'children of it.')
  129. raise TypeError(error_msg)
  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 (FileDescriptorProto): The file descriptor 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 (bytes): A bytes string, serialization of the
  141. :class:`FileDescriptorProto` to add.
  142. Returns:
  143. FileDescriptor: Descriptor for the added file.
  144. """
  145. # pylint: disable=g-import-not-at-top
  146. from google.protobuf import descriptor_pb2
  147. file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
  148. serialized_file_desc_proto)
  149. file_desc = self._ConvertFileProtoToFileDescriptor(file_desc_proto)
  150. file_desc.serialized_pb = serialized_file_desc_proto
  151. return file_desc
  152. # Never call this method. It is for internal usage only.
  153. def _AddDescriptor(self, desc):
  154. """Adds a Descriptor to the pool, non-recursively.
  155. If the Descriptor contains nested messages or enums, the caller must
  156. explicitly register them. This method also registers the FileDescriptor
  157. associated with the message.
  158. Args:
  159. desc: A Descriptor.
  160. """
  161. if not isinstance(desc, descriptor.Descriptor):
  162. raise TypeError('Expected instance of descriptor.Descriptor.')
  163. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  164. self._descriptors[desc.full_name] = desc
  165. self._AddFileDescriptor(desc.file)
  166. # Never call this method. It is for internal usage only.
  167. def _AddEnumDescriptor(self, enum_desc):
  168. """Adds an EnumDescriptor to the pool.
  169. This method also registers the FileDescriptor associated with the enum.
  170. Args:
  171. enum_desc: An EnumDescriptor.
  172. """
  173. if not isinstance(enum_desc, descriptor.EnumDescriptor):
  174. raise TypeError('Expected instance of descriptor.EnumDescriptor.')
  175. file_name = enum_desc.file.name
  176. self._CheckConflictRegister(enum_desc, enum_desc.full_name, file_name)
  177. self._enum_descriptors[enum_desc.full_name] = enum_desc
  178. # Top enum values need to be indexed.
  179. # Count the number of dots to see whether the enum is toplevel or nested
  180. # in a message. We cannot use enum_desc.containing_type at this stage.
  181. if enum_desc.file.package:
  182. top_level = (enum_desc.full_name.count('.')
  183. - enum_desc.file.package.count('.') == 1)
  184. else:
  185. top_level = enum_desc.full_name.count('.') == 0
  186. if top_level:
  187. file_name = enum_desc.file.name
  188. package = enum_desc.file.package
  189. for enum_value in enum_desc.values:
  190. full_name = _NormalizeFullyQualifiedName(
  191. '.'.join((package, enum_value.name)))
  192. self._CheckConflictRegister(enum_value, full_name, file_name)
  193. self._top_enum_values[full_name] = enum_value
  194. self._AddFileDescriptor(enum_desc.file)
  195. # Never call this method. It is for internal usage only.
  196. def _AddServiceDescriptor(self, service_desc):
  197. """Adds a ServiceDescriptor to the pool.
  198. Args:
  199. service_desc: A ServiceDescriptor.
  200. """
  201. if not isinstance(service_desc, descriptor.ServiceDescriptor):
  202. raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
  203. self._CheckConflictRegister(service_desc, service_desc.full_name,
  204. service_desc.file.name)
  205. self._service_descriptors[service_desc.full_name] = service_desc
  206. # Never call this method. It is for internal usage only.
  207. def _AddExtensionDescriptor(self, extension):
  208. """Adds a FieldDescriptor describing an extension to the pool.
  209. Args:
  210. extension: A FieldDescriptor.
  211. Raises:
  212. AssertionError: when another extension with the same number extends the
  213. same message.
  214. TypeError: when the specified extension is not a
  215. descriptor.FieldDescriptor.
  216. """
  217. if not (isinstance(extension, descriptor.FieldDescriptor) and
  218. extension.is_extension):
  219. raise TypeError('Expected an extension descriptor.')
  220. if extension.extension_scope is None:
  221. self._CheckConflictRegister(
  222. extension, extension.full_name, extension.file.name)
  223. self._toplevel_extensions[extension.full_name] = extension
  224. try:
  225. existing_desc = self._extensions_by_number[
  226. extension.containing_type][extension.number]
  227. except KeyError:
  228. pass
  229. else:
  230. if extension is not existing_desc:
  231. raise AssertionError(
  232. 'Extensions "%s" and "%s" both try to extend message type "%s" '
  233. 'with field number %d.' %
  234. (extension.full_name, existing_desc.full_name,
  235. extension.containing_type.full_name, extension.number))
  236. self._extensions_by_number[extension.containing_type][
  237. extension.number] = extension
  238. self._extensions_by_name[extension.containing_type][
  239. extension.full_name] = extension
  240. # Also register MessageSet extensions with the type name.
  241. if _IsMessageSetExtension(extension):
  242. self._extensions_by_name[extension.containing_type][
  243. extension.message_type.full_name] = extension
  244. if hasattr(extension.containing_type, '_concrete_class'):
  245. python_message._AttachFieldHelpers(
  246. extension.containing_type._concrete_class, extension)
  247. # Never call this method. It is for internal usage only.
  248. def _InternalAddFileDescriptor(self, file_desc):
  249. """Adds a FileDescriptor to the pool, non-recursively.
  250. If the FileDescriptor contains messages or enums, the caller must explicitly
  251. register them.
  252. Args:
  253. file_desc: A FileDescriptor.
  254. """
  255. self._AddFileDescriptor(file_desc)
  256. def _AddFileDescriptor(self, file_desc):
  257. """Adds a FileDescriptor to the pool, non-recursively.
  258. If the FileDescriptor contains messages or enums, the caller must explicitly
  259. register them.
  260. Args:
  261. file_desc: A FileDescriptor.
  262. """
  263. if not isinstance(file_desc, descriptor.FileDescriptor):
  264. raise TypeError('Expected instance of descriptor.FileDescriptor.')
  265. self._file_descriptors[file_desc.name] = file_desc
  266. def FindFileByName(self, file_name):
  267. """Gets a FileDescriptor by file name.
  268. Args:
  269. file_name (str): The path to the file to get a descriptor for.
  270. Returns:
  271. FileDescriptor: The descriptor for the named file.
  272. Raises:
  273. KeyError: if the file cannot be found in the pool.
  274. """
  275. try:
  276. return self._file_descriptors[file_name]
  277. except KeyError:
  278. pass
  279. try:
  280. file_proto = self._internal_db.FindFileByName(file_name)
  281. except KeyError as error:
  282. if self._descriptor_db:
  283. file_proto = self._descriptor_db.FindFileByName(file_name)
  284. else:
  285. raise error
  286. if not file_proto:
  287. raise KeyError('Cannot find a file named %s' % file_name)
  288. return self._ConvertFileProtoToFileDescriptor(file_proto)
  289. def FindFileContainingSymbol(self, symbol):
  290. """Gets the FileDescriptor for the file containing the specified symbol.
  291. Args:
  292. symbol (str): The name of the symbol to search for.
  293. Returns:
  294. FileDescriptor: Descriptor for the file that contains the specified
  295. symbol.
  296. Raises:
  297. KeyError: if the file cannot be found in the pool.
  298. """
  299. symbol = _NormalizeFullyQualifiedName(symbol)
  300. try:
  301. return self._InternalFindFileContainingSymbol(symbol)
  302. except KeyError:
  303. pass
  304. try:
  305. # Try fallback database. Build and find again if possible.
  306. self._FindFileContainingSymbolInDb(symbol)
  307. return self._InternalFindFileContainingSymbol(symbol)
  308. except KeyError:
  309. raise KeyError('Cannot find a file containing %s' % symbol)
  310. def _InternalFindFileContainingSymbol(self, symbol):
  311. """Gets the already built FileDescriptor containing the specified symbol.
  312. Args:
  313. symbol (str): The name of the symbol to search for.
  314. Returns:
  315. FileDescriptor: Descriptor for the file that contains the specified
  316. symbol.
  317. Raises:
  318. KeyError: if the file cannot be found in the pool.
  319. """
  320. try:
  321. return self._descriptors[symbol].file
  322. except KeyError:
  323. pass
  324. try:
  325. return self._enum_descriptors[symbol].file
  326. except KeyError:
  327. pass
  328. try:
  329. return self._service_descriptors[symbol].file
  330. except KeyError:
  331. pass
  332. try:
  333. return self._top_enum_values[symbol].type.file
  334. except KeyError:
  335. pass
  336. try:
  337. return self._toplevel_extensions[symbol].file
  338. except KeyError:
  339. pass
  340. # Try fields, enum values and nested extensions inside a message.
  341. top_name, _, sub_name = symbol.rpartition('.')
  342. try:
  343. message = self.FindMessageTypeByName(top_name)
  344. assert (sub_name in message.extensions_by_name or
  345. sub_name in message.fields_by_name or
  346. sub_name in message.enum_values_by_name)
  347. return message.file
  348. except (KeyError, AssertionError):
  349. raise KeyError('Cannot find a file containing %s' % symbol)
  350. def FindMessageTypeByName(self, full_name):
  351. """Loads the named descriptor from the pool.
  352. Args:
  353. full_name (str): The full name of the descriptor to load.
  354. Returns:
  355. Descriptor: The descriptor for the named type.
  356. Raises:
  357. KeyError: if the message cannot be found in the pool.
  358. """
  359. full_name = _NormalizeFullyQualifiedName(full_name)
  360. if full_name not in self._descriptors:
  361. self._FindFileContainingSymbolInDb(full_name)
  362. return self._descriptors[full_name]
  363. def FindEnumTypeByName(self, full_name):
  364. """Loads the named enum descriptor from the pool.
  365. Args:
  366. full_name (str): The full name of the enum descriptor to load.
  367. Returns:
  368. EnumDescriptor: The enum descriptor for the named type.
  369. Raises:
  370. KeyError: if the enum cannot be found in the pool.
  371. """
  372. full_name = _NormalizeFullyQualifiedName(full_name)
  373. if full_name not in self._enum_descriptors:
  374. self._FindFileContainingSymbolInDb(full_name)
  375. return self._enum_descriptors[full_name]
  376. def FindFieldByName(self, full_name):
  377. """Loads the named field descriptor from the pool.
  378. Args:
  379. full_name (str): The full name of the field descriptor to load.
  380. Returns:
  381. FieldDescriptor: The field descriptor for the named field.
  382. Raises:
  383. KeyError: if the field cannot be found in the pool.
  384. """
  385. full_name = _NormalizeFullyQualifiedName(full_name)
  386. message_name, _, field_name = full_name.rpartition('.')
  387. message_descriptor = self.FindMessageTypeByName(message_name)
  388. return message_descriptor.fields_by_name[field_name]
  389. def FindOneofByName(self, full_name):
  390. """Loads the named oneof descriptor from the pool.
  391. Args:
  392. full_name (str): The full name of the oneof descriptor to load.
  393. Returns:
  394. OneofDescriptor: The oneof descriptor for the named oneof.
  395. Raises:
  396. KeyError: if the oneof cannot be found in the pool.
  397. """
  398. full_name = _NormalizeFullyQualifiedName(full_name)
  399. message_name, _, oneof_name = full_name.rpartition('.')
  400. message_descriptor = self.FindMessageTypeByName(message_name)
  401. return message_descriptor.oneofs_by_name[oneof_name]
  402. def FindExtensionByName(self, full_name):
  403. """Loads the named extension descriptor from the pool.
  404. Args:
  405. full_name (str): The full name of the extension descriptor to load.
  406. Returns:
  407. FieldDescriptor: The field descriptor for the named extension.
  408. Raises:
  409. KeyError: if the extension cannot be found in the pool.
  410. """
  411. full_name = _NormalizeFullyQualifiedName(full_name)
  412. try:
  413. # The proto compiler does not give any link between the FileDescriptor
  414. # and top-level extensions unless the FileDescriptorProto is added to
  415. # the DescriptorDatabase, but this can impact memory usage.
  416. # So we registered these extensions by name explicitly.
  417. return self._toplevel_extensions[full_name]
  418. except KeyError:
  419. pass
  420. message_name, _, extension_name = full_name.rpartition('.')
  421. try:
  422. # Most extensions are nested inside a message.
  423. scope = self.FindMessageTypeByName(message_name)
  424. except KeyError:
  425. # Some extensions are defined at file scope.
  426. scope = self._FindFileContainingSymbolInDb(full_name)
  427. return scope.extensions_by_name[extension_name]
  428. def FindExtensionByNumber(self, message_descriptor, number):
  429. """Gets the extension of the specified message with the specified number.
  430. Extensions have to be registered to this pool by calling :func:`Add` or
  431. :func:`AddExtensionDescriptor`.
  432. Args:
  433. message_descriptor (Descriptor): descriptor of the extended message.
  434. number (int): Number of the extension field.
  435. Returns:
  436. FieldDescriptor: The descriptor for the extension.
  437. Raises:
  438. KeyError: when no extension with the given number is known for the
  439. specified message.
  440. """
  441. try:
  442. return self._extensions_by_number[message_descriptor][number]
  443. except KeyError:
  444. self._TryLoadExtensionFromDB(message_descriptor, number)
  445. return self._extensions_by_number[message_descriptor][number]
  446. def FindAllExtensions(self, message_descriptor):
  447. """Gets all the known extensions of a given message.
  448. Extensions have to be registered to this pool by build related
  449. :func:`Add` or :func:`AddExtensionDescriptor`.
  450. Args:
  451. message_descriptor (Descriptor): Descriptor of the extended message.
  452. Returns:
  453. list[FieldDescriptor]: Field descriptors describing the extensions.
  454. """
  455. # Fallback to descriptor db if FindAllExtensionNumbers is provided.
  456. if self._descriptor_db and hasattr(
  457. self._descriptor_db, 'FindAllExtensionNumbers'):
  458. full_name = message_descriptor.full_name
  459. all_numbers = self._descriptor_db.FindAllExtensionNumbers(full_name)
  460. for number in all_numbers:
  461. if number in self._extensions_by_number[message_descriptor]:
  462. continue
  463. self._TryLoadExtensionFromDB(message_descriptor, number)
  464. return list(self._extensions_by_number[message_descriptor].values())
  465. def _TryLoadExtensionFromDB(self, message_descriptor, number):
  466. """Try to Load extensions from descriptor db.
  467. Args:
  468. message_descriptor: descriptor of the extended message.
  469. number: the extension number that needs to be loaded.
  470. """
  471. if not self._descriptor_db:
  472. return
  473. # Only supported when FindFileContainingExtension is provided.
  474. if not hasattr(
  475. self._descriptor_db, 'FindFileContainingExtension'):
  476. return
  477. full_name = message_descriptor.full_name
  478. file_proto = self._descriptor_db.FindFileContainingExtension(
  479. full_name, number)
  480. if file_proto is None:
  481. return
  482. try:
  483. self._ConvertFileProtoToFileDescriptor(file_proto)
  484. except:
  485. warn_msg = ('Unable to load proto file %s for extension number %d.' %
  486. (file_proto.name, number))
  487. warnings.warn(warn_msg, RuntimeWarning)
  488. def FindServiceByName(self, full_name):
  489. """Loads the named service descriptor from the pool.
  490. Args:
  491. full_name (str): The full name of the service descriptor to load.
  492. Returns:
  493. ServiceDescriptor: The service descriptor for the named service.
  494. Raises:
  495. KeyError: if the service cannot be found in the pool.
  496. """
  497. full_name = _NormalizeFullyQualifiedName(full_name)
  498. if full_name not in self._service_descriptors:
  499. self._FindFileContainingSymbolInDb(full_name)
  500. return self._service_descriptors[full_name]
  501. def FindMethodByName(self, full_name):
  502. """Loads the named service method descriptor from the pool.
  503. Args:
  504. full_name (str): The full name of the method descriptor to load.
  505. Returns:
  506. MethodDescriptor: The method descriptor for the service method.
  507. Raises:
  508. KeyError: if the method cannot be found in the pool.
  509. """
  510. full_name = _NormalizeFullyQualifiedName(full_name)
  511. service_name, _, method_name = full_name.rpartition('.')
  512. service_descriptor = self.FindServiceByName(service_name)
  513. return service_descriptor.methods_by_name[method_name]
  514. def SetFeatureSetDefaults(self, defaults):
  515. """Sets the default feature mappings used during the build.
  516. Args:
  517. defaults: a FeatureSetDefaults message containing the new mappings.
  518. """
  519. if self._edition_defaults is not None:
  520. raise ValueError(
  521. "Feature set defaults can't be changed once the pool has started"
  522. ' building!'
  523. )
  524. # pylint: disable=g-import-not-at-top
  525. from google.protobuf import descriptor_pb2
  526. if not isinstance(defaults, descriptor_pb2.FeatureSetDefaults):
  527. raise TypeError('SetFeatureSetDefaults called with invalid type')
  528. if defaults.minimum_edition > defaults.maximum_edition:
  529. raise ValueError(
  530. 'Invalid edition range %s to %s'
  531. % (
  532. descriptor_pb2.Edition.Name(defaults.minimum_edition),
  533. descriptor_pb2.Edition.Name(defaults.maximum_edition),
  534. )
  535. )
  536. prev_edition = descriptor_pb2.Edition.EDITION_UNKNOWN
  537. for d in defaults.defaults:
  538. if d.edition == descriptor_pb2.Edition.EDITION_UNKNOWN:
  539. raise ValueError('Invalid edition EDITION_UNKNOWN specified')
  540. if prev_edition >= d.edition:
  541. raise ValueError(
  542. 'Feature set defaults are not strictly increasing. %s is greater'
  543. ' than or equal to %s'
  544. % (
  545. descriptor_pb2.Edition.Name(prev_edition),
  546. descriptor_pb2.Edition.Name(d.edition),
  547. )
  548. )
  549. prev_edition = d.edition
  550. self._edition_defaults = defaults
  551. def _CreateDefaultFeatures(self, edition):
  552. """Creates a FeatureSet message with defaults for a specific edition.
  553. Args:
  554. edition: the edition to generate defaults for.
  555. Returns:
  556. A FeatureSet message with defaults for a specific edition.
  557. """
  558. # pylint: disable=g-import-not-at-top
  559. from google.protobuf import descriptor_pb2
  560. with _edition_defaults_lock:
  561. if not self._edition_defaults:
  562. self._edition_defaults = descriptor_pb2.FeatureSetDefaults()
  563. self._edition_defaults.ParseFromString(
  564. self._serialized_edition_defaults
  565. )
  566. if edition < self._edition_defaults.minimum_edition:
  567. raise TypeError(
  568. 'Edition %s is earlier than the minimum supported edition %s!'
  569. % (
  570. descriptor_pb2.Edition.Name(edition),
  571. descriptor_pb2.Edition.Name(
  572. self._edition_defaults.minimum_edition
  573. ),
  574. )
  575. )
  576. if edition > self._edition_defaults.maximum_edition:
  577. raise TypeError(
  578. 'Edition %s is later than the maximum supported edition %s!'
  579. % (
  580. descriptor_pb2.Edition.Name(edition),
  581. descriptor_pb2.Edition.Name(
  582. self._edition_defaults.maximum_edition
  583. ),
  584. )
  585. )
  586. found = None
  587. for d in self._edition_defaults.defaults:
  588. if d.edition > edition:
  589. break
  590. found = d
  591. if found is None:
  592. raise TypeError(
  593. 'No valid default found for edition %s!'
  594. % descriptor_pb2.Edition.Name(edition)
  595. )
  596. defaults = descriptor_pb2.FeatureSet()
  597. defaults.CopyFrom(found.fixed_features)
  598. defaults.MergeFrom(found.overridable_features)
  599. return defaults
  600. def _InternFeatures(self, features):
  601. serialized = features.SerializeToString()
  602. with _edition_defaults_lock:
  603. cached = self._feature_cache.get(serialized)
  604. if cached is None:
  605. self._feature_cache[serialized] = features
  606. cached = features
  607. return cached
  608. def _FindFileContainingSymbolInDb(self, symbol):
  609. """Finds the file in descriptor DB containing the specified symbol.
  610. Args:
  611. symbol (str): The name of the symbol to search for.
  612. Returns:
  613. FileDescriptor: The file that contains the specified symbol.
  614. Raises:
  615. KeyError: if the file cannot be found in the descriptor database.
  616. """
  617. try:
  618. file_proto = self._internal_db.FindFileContainingSymbol(symbol)
  619. except KeyError as error:
  620. if self._descriptor_db:
  621. file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
  622. else:
  623. raise error
  624. if not file_proto:
  625. raise KeyError('Cannot find a file containing %s' % symbol)
  626. return self._ConvertFileProtoToFileDescriptor(file_proto)
  627. def _ConvertFileProtoToFileDescriptor(self, file_proto):
  628. """Creates a FileDescriptor from a proto or returns a cached copy.
  629. This method also has the side effect of loading all the symbols found in
  630. the file into the appropriate dictionaries in the pool.
  631. Args:
  632. file_proto: The proto to convert.
  633. Returns:
  634. A FileDescriptor matching the passed in proto.
  635. """
  636. if file_proto.name not in self._file_descriptors:
  637. built_deps = list(self._GetDeps(file_proto.dependency))
  638. direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
  639. public_deps = [direct_deps[i] for i in file_proto.public_dependency]
  640. # pylint: disable=g-import-not-at-top
  641. from google.protobuf import descriptor_pb2
  642. file_descriptor = descriptor.FileDescriptor(
  643. pool=self,
  644. name=file_proto.name,
  645. package=file_proto.package,
  646. syntax=file_proto.syntax,
  647. edition=descriptor_pb2.Edition.Name(file_proto.edition),
  648. options=_OptionsOrNone(file_proto),
  649. serialized_pb=file_proto.SerializeToString(),
  650. dependencies=direct_deps,
  651. public_dependencies=public_deps,
  652. # pylint: disable=protected-access
  653. create_key=descriptor._internal_create_key,
  654. )
  655. scope = {}
  656. # This loop extracts all the message and enum types from all the
  657. # dependencies of the file_proto. This is necessary to create the
  658. # scope of available message types when defining the passed in
  659. # file proto.
  660. for dependency in built_deps:
  661. scope.update(self._ExtractSymbols(
  662. dependency.message_types_by_name.values()))
  663. scope.update((_PrefixWithDot(enum.full_name), enum)
  664. for enum in dependency.enum_types_by_name.values())
  665. for message_type in file_proto.message_type:
  666. message_desc = self._ConvertMessageDescriptor(
  667. message_type, file_proto.package, file_descriptor, scope,
  668. file_proto.syntax)
  669. file_descriptor.message_types_by_name[message_desc.name] = (
  670. message_desc)
  671. for enum_type in file_proto.enum_type:
  672. file_descriptor.enum_types_by_name[enum_type.name] = (
  673. self._ConvertEnumDescriptor(enum_type, file_proto.package,
  674. file_descriptor, None, scope, True))
  675. for index, extension_proto in enumerate(file_proto.extension):
  676. extension_desc = self._MakeFieldDescriptor(
  677. extension_proto, file_proto.package, index, file_descriptor,
  678. is_extension=True)
  679. extension_desc.containing_type = self._GetTypeFromScope(
  680. file_descriptor.package, extension_proto.extendee, scope)
  681. self._SetFieldType(extension_proto, extension_desc,
  682. file_descriptor.package, scope)
  683. file_descriptor.extensions_by_name[extension_desc.name] = (
  684. extension_desc)
  685. for desc_proto in file_proto.message_type:
  686. self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
  687. if file_proto.package:
  688. desc_proto_prefix = _PrefixWithDot(file_proto.package)
  689. else:
  690. desc_proto_prefix = ''
  691. for desc_proto in file_proto.message_type:
  692. desc = self._GetTypeFromScope(
  693. desc_proto_prefix, desc_proto.name, scope)
  694. file_descriptor.message_types_by_name[desc_proto.name] = desc
  695. for index, service_proto in enumerate(file_proto.service):
  696. file_descriptor.services_by_name[service_proto.name] = (
  697. self._MakeServiceDescriptor(service_proto, index, scope,
  698. file_proto.package, file_descriptor))
  699. self._file_descriptors[file_proto.name] = file_descriptor
  700. # Add extensions to the pool
  701. def AddExtensionForNested(message_type):
  702. for nested in message_type.nested_types:
  703. AddExtensionForNested(nested)
  704. for extension in message_type.extensions:
  705. self._AddExtensionDescriptor(extension)
  706. file_desc = self._file_descriptors[file_proto.name]
  707. for extension in file_desc.extensions_by_name.values():
  708. self._AddExtensionDescriptor(extension)
  709. for message_type in file_desc.message_types_by_name.values():
  710. AddExtensionForNested(message_type)
  711. return file_desc
  712. def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
  713. scope=None, syntax=None):
  714. """Adds the proto to the pool in the specified package.
  715. Args:
  716. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  717. package: The package the proto should be located in.
  718. file_desc: The file containing this message.
  719. scope: Dict mapping short and full symbols to message and enum types.
  720. syntax: string indicating syntax of the file ("proto2" or "proto3")
  721. Returns:
  722. The added descriptor.
  723. """
  724. if package:
  725. desc_name = '.'.join((package, desc_proto.name))
  726. else:
  727. desc_name = desc_proto.name
  728. if file_desc is None:
  729. file_name = None
  730. else:
  731. file_name = file_desc.name
  732. if scope is None:
  733. scope = {}
  734. nested = [
  735. self._ConvertMessageDescriptor(
  736. nested, desc_name, file_desc, scope, syntax)
  737. for nested in desc_proto.nested_type]
  738. enums = [
  739. self._ConvertEnumDescriptor(enum, desc_name, file_desc, None,
  740. scope, False)
  741. for enum in desc_proto.enum_type]
  742. fields = [self._MakeFieldDescriptor(field, desc_name, index, file_desc)
  743. for index, field in enumerate(desc_proto.field)]
  744. extensions = [
  745. self._MakeFieldDescriptor(extension, desc_name, index, file_desc,
  746. is_extension=True)
  747. for index, extension in enumerate(desc_proto.extension)]
  748. oneofs = [
  749. # pylint: disable=g-complex-comprehension
  750. descriptor.OneofDescriptor(
  751. desc.name,
  752. '.'.join((desc_name, desc.name)),
  753. index,
  754. None,
  755. [],
  756. _OptionsOrNone(desc),
  757. # pylint: disable=protected-access
  758. create_key=descriptor._internal_create_key)
  759. for index, desc in enumerate(desc_proto.oneof_decl)
  760. ]
  761. extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
  762. if extension_ranges:
  763. is_extendable = True
  764. else:
  765. is_extendable = False
  766. desc = descriptor.Descriptor(
  767. name=desc_proto.name,
  768. full_name=desc_name,
  769. filename=file_name,
  770. containing_type=None,
  771. fields=fields,
  772. oneofs=oneofs,
  773. nested_types=nested,
  774. enum_types=enums,
  775. extensions=extensions,
  776. options=_OptionsOrNone(desc_proto),
  777. is_extendable=is_extendable,
  778. extension_ranges=extension_ranges,
  779. file=file_desc,
  780. serialized_start=None,
  781. serialized_end=None,
  782. is_map_entry=desc_proto.options.map_entry,
  783. # pylint: disable=protected-access
  784. create_key=descriptor._internal_create_key,
  785. )
  786. for nested in desc.nested_types:
  787. nested.containing_type = desc
  788. for enum in desc.enum_types:
  789. enum.containing_type = desc
  790. for field_index, field_desc in enumerate(desc_proto.field):
  791. if field_desc.HasField('oneof_index'):
  792. oneof_index = field_desc.oneof_index
  793. oneofs[oneof_index].fields.append(fields[field_index])
  794. fields[field_index].containing_oneof = oneofs[oneof_index]
  795. scope[_PrefixWithDot(desc_name)] = desc
  796. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  797. self._descriptors[desc_name] = desc
  798. return desc
  799. def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
  800. containing_type=None, scope=None, top_level=False):
  801. """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
  802. Args:
  803. enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
  804. package: Optional package name for the new message EnumDescriptor.
  805. file_desc: The file containing the enum descriptor.
  806. containing_type: The type containing this enum.
  807. scope: Scope containing available types.
  808. top_level: If True, the enum is a top level symbol. If False, the enum
  809. is defined inside a message.
  810. Returns:
  811. The added descriptor
  812. """
  813. if package:
  814. enum_name = '.'.join((package, enum_proto.name))
  815. else:
  816. enum_name = enum_proto.name
  817. if file_desc is None:
  818. file_name = None
  819. else:
  820. file_name = file_desc.name
  821. values = [self._MakeEnumValueDescriptor(value, index)
  822. for index, value in enumerate(enum_proto.value)]
  823. desc = descriptor.EnumDescriptor(name=enum_proto.name,
  824. full_name=enum_name,
  825. filename=file_name,
  826. file=file_desc,
  827. values=values,
  828. containing_type=containing_type,
  829. options=_OptionsOrNone(enum_proto),
  830. # pylint: disable=protected-access
  831. create_key=descriptor._internal_create_key)
  832. scope['.%s' % enum_name] = desc
  833. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  834. self._enum_descriptors[enum_name] = desc
  835. # Add top level enum values.
  836. if top_level:
  837. for value in values:
  838. full_name = _NormalizeFullyQualifiedName(
  839. '.'.join((package, value.name)))
  840. self._CheckConflictRegister(value, full_name, file_name)
  841. self._top_enum_values[full_name] = value
  842. return desc
  843. def _MakeFieldDescriptor(self, field_proto, message_name, index,
  844. file_desc, is_extension=False):
  845. """Creates a field descriptor from a FieldDescriptorProto.
  846. For message and enum type fields, this method will do a look up
  847. in the pool for the appropriate descriptor for that type. If it
  848. is unavailable, it will fall back to the _source function to
  849. create it. If this type is still unavailable, construction will
  850. fail.
  851. Args:
  852. field_proto: The proto describing the field.
  853. message_name: The name of the containing message.
  854. index: Index of the field
  855. file_desc: The file containing the field descriptor.
  856. is_extension: Indication that this field is for an extension.
  857. Returns:
  858. An initialized FieldDescriptor object
  859. """
  860. if message_name:
  861. full_name = '.'.join((message_name, field_proto.name))
  862. else:
  863. full_name = field_proto.name
  864. if field_proto.json_name:
  865. json_name = field_proto.json_name
  866. else:
  867. json_name = None
  868. return descriptor.FieldDescriptor(
  869. name=field_proto.name,
  870. full_name=full_name,
  871. index=index,
  872. number=field_proto.number,
  873. type=field_proto.type,
  874. cpp_type=None,
  875. message_type=None,
  876. enum_type=None,
  877. containing_type=None,
  878. label=field_proto.label,
  879. has_default_value=False,
  880. default_value=None,
  881. is_extension=is_extension,
  882. extension_scope=None,
  883. options=_OptionsOrNone(field_proto),
  884. json_name=json_name,
  885. file=file_desc,
  886. # pylint: disable=protected-access
  887. create_key=descriptor._internal_create_key)
  888. def _SetAllFieldTypes(self, package, desc_proto, scope):
  889. """Sets all the descriptor's fields's types.
  890. This method also sets the containing types on any extensions.
  891. Args:
  892. package: The current package of desc_proto.
  893. desc_proto: The message descriptor to update.
  894. scope: Enclosing scope of available types.
  895. """
  896. package = _PrefixWithDot(package)
  897. main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
  898. if package == '.':
  899. nested_package = _PrefixWithDot(desc_proto.name)
  900. else:
  901. nested_package = '.'.join([package, desc_proto.name])
  902. for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
  903. self._SetFieldType(field_proto, field_desc, nested_package, scope)
  904. for extension_proto, extension_desc in (
  905. zip(desc_proto.extension, main_desc.extensions)):
  906. extension_desc.containing_type = self._GetTypeFromScope(
  907. nested_package, extension_proto.extendee, scope)
  908. self._SetFieldType(extension_proto, extension_desc, nested_package, scope)
  909. for nested_type in desc_proto.nested_type:
  910. self._SetAllFieldTypes(nested_package, nested_type, scope)
  911. def _SetFieldType(self, field_proto, field_desc, package, scope):
  912. """Sets the field's type, cpp_type, message_type and enum_type.
  913. Args:
  914. field_proto: Data about the field in proto format.
  915. field_desc: The descriptor to modify.
  916. package: The package the field's container is in.
  917. scope: Enclosing scope of available types.
  918. """
  919. if field_proto.type_name:
  920. desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
  921. else:
  922. desc = None
  923. if not field_proto.HasField('type'):
  924. if isinstance(desc, descriptor.Descriptor):
  925. field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
  926. else:
  927. field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
  928. field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
  929. field_proto.type)
  930. if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
  931. or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
  932. field_desc.message_type = desc
  933. if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  934. field_desc.enum_type = desc
  935. if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  936. field_desc.has_default_value = False
  937. field_desc.default_value = []
  938. elif field_proto.HasField('default_value'):
  939. field_desc.has_default_value = True
  940. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  941. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  942. field_desc.default_value = float(field_proto.default_value)
  943. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  944. field_desc.default_value = field_proto.default_value
  945. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  946. field_desc.default_value = field_proto.default_value.lower() == 'true'
  947. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  948. field_desc.default_value = field_desc.enum_type.values_by_name[
  949. field_proto.default_value].number
  950. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  951. field_desc.default_value = text_encoding.CUnescape(
  952. field_proto.default_value)
  953. elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
  954. field_desc.default_value = None
  955. else:
  956. # All other types are of the "int" type.
  957. field_desc.default_value = int(field_proto.default_value)
  958. else:
  959. field_desc.has_default_value = False
  960. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  961. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  962. field_desc.default_value = 0.0
  963. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  964. field_desc.default_value = u''
  965. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  966. field_desc.default_value = False
  967. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  968. field_desc.default_value = field_desc.enum_type.values[0].number
  969. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  970. field_desc.default_value = b''
  971. elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
  972. field_desc.default_value = None
  973. elif field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP:
  974. field_desc.default_value = None
  975. else:
  976. # All other types are of the "int" type.
  977. field_desc.default_value = 0
  978. field_desc.type = field_proto.type
  979. def _MakeEnumValueDescriptor(self, value_proto, index):
  980. """Creates a enum value descriptor object from a enum value proto.
  981. Args:
  982. value_proto: The proto describing the enum value.
  983. index: The index of the enum value.
  984. Returns:
  985. An initialized EnumValueDescriptor object.
  986. """
  987. return descriptor.EnumValueDescriptor(
  988. name=value_proto.name,
  989. index=index,
  990. number=value_proto.number,
  991. options=_OptionsOrNone(value_proto),
  992. type=None,
  993. # pylint: disable=protected-access
  994. create_key=descriptor._internal_create_key)
  995. def _MakeServiceDescriptor(self, service_proto, service_index, scope,
  996. package, file_desc):
  997. """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
  998. Args:
  999. service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
  1000. service_index: The index of the service in the File.
  1001. scope: Dict mapping short and full symbols to message and enum types.
  1002. package: Optional package name for the new message EnumDescriptor.
  1003. file_desc: The file containing the service descriptor.
  1004. Returns:
  1005. The added descriptor.
  1006. """
  1007. if package:
  1008. service_name = '.'.join((package, service_proto.name))
  1009. else:
  1010. service_name = service_proto.name
  1011. methods = [self._MakeMethodDescriptor(method_proto, service_name, package,
  1012. scope, index)
  1013. for index, method_proto in enumerate(service_proto.method)]
  1014. desc = descriptor.ServiceDescriptor(
  1015. name=service_proto.name,
  1016. full_name=service_name,
  1017. index=service_index,
  1018. methods=methods,
  1019. options=_OptionsOrNone(service_proto),
  1020. file=file_desc,
  1021. # pylint: disable=protected-access
  1022. create_key=descriptor._internal_create_key)
  1023. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  1024. self._service_descriptors[service_name] = desc
  1025. return desc
  1026. def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
  1027. index):
  1028. """Creates a method descriptor from a MethodDescriptorProto.
  1029. Args:
  1030. method_proto: The proto describing the method.
  1031. service_name: The name of the containing service.
  1032. package: Optional package name to look up for types.
  1033. scope: Scope containing available types.
  1034. index: Index of the method in the service.
  1035. Returns:
  1036. An initialized MethodDescriptor object.
  1037. """
  1038. full_name = '.'.join((service_name, method_proto.name))
  1039. input_type = self._GetTypeFromScope(
  1040. package, method_proto.input_type, scope)
  1041. output_type = self._GetTypeFromScope(
  1042. package, method_proto.output_type, scope)
  1043. return descriptor.MethodDescriptor(
  1044. name=method_proto.name,
  1045. full_name=full_name,
  1046. index=index,
  1047. containing_service=None,
  1048. input_type=input_type,
  1049. output_type=output_type,
  1050. client_streaming=method_proto.client_streaming,
  1051. server_streaming=method_proto.server_streaming,
  1052. options=_OptionsOrNone(method_proto),
  1053. # pylint: disable=protected-access
  1054. create_key=descriptor._internal_create_key)
  1055. def _ExtractSymbols(self, descriptors):
  1056. """Pulls out all the symbols from descriptor protos.
  1057. Args:
  1058. descriptors: The messages to extract descriptors from.
  1059. Yields:
  1060. A two element tuple of the type name and descriptor object.
  1061. """
  1062. for desc in descriptors:
  1063. yield (_PrefixWithDot(desc.full_name), desc)
  1064. for symbol in self._ExtractSymbols(desc.nested_types):
  1065. yield symbol
  1066. for enum in desc.enum_types:
  1067. yield (_PrefixWithDot(enum.full_name), enum)
  1068. def _GetDeps(self, dependencies, visited=None):
  1069. """Recursively finds dependencies for file protos.
  1070. Args:
  1071. dependencies: The names of the files being depended on.
  1072. visited: The names of files already found.
  1073. Yields:
  1074. Each direct and indirect dependency.
  1075. """
  1076. visited = visited or set()
  1077. for dependency in dependencies:
  1078. if dependency not in visited:
  1079. visited.add(dependency)
  1080. dep_desc = self.FindFileByName(dependency)
  1081. yield dep_desc
  1082. public_files = [d.name for d in dep_desc.public_dependencies]
  1083. yield from self._GetDeps(public_files, visited)
  1084. def _GetTypeFromScope(self, package, type_name, scope):
  1085. """Finds a given type name in the current scope.
  1086. Args:
  1087. package: The package the proto should be located in.
  1088. type_name: The name of the type to be found in the scope.
  1089. scope: Dict mapping short and full symbols to message and enum types.
  1090. Returns:
  1091. The descriptor for the requested type.
  1092. """
  1093. if type_name not in scope:
  1094. components = _PrefixWithDot(package).split('.')
  1095. while components:
  1096. possible_match = '.'.join(components + [type_name])
  1097. if possible_match in scope:
  1098. type_name = possible_match
  1099. break
  1100. else:
  1101. components.pop(-1)
  1102. return scope[type_name]
  1103. def _PrefixWithDot(name):
  1104. return name if name.startswith('.') else '.%s' % name
  1105. if _USE_C_DESCRIPTORS:
  1106. # TODO: This pool could be constructed from Python code, when we
  1107. # support a flag like 'use_cpp_generated_pool=True'.
  1108. # pylint: disable=protected-access
  1109. _DEFAULT = descriptor._message.default_pool
  1110. else:
  1111. _DEFAULT = DescriptorPool()
  1112. def Default():
  1113. return _DEFAULT