descriptor_pool.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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 sys
  52. from google.protobuf import descriptor
  53. from google.protobuf import descriptor_database
  54. from google.protobuf import text_encoding
  55. def _NormalizeFullyQualifiedName(name):
  56. """Remove leading period from fully-qualified type name.
  57. Due to b/13860351 in descriptor_database.py, types in the root namespace are
  58. generated with a leading period. This function removes that prefix.
  59. Args:
  60. name: A str, the fully-qualified symbol name.
  61. Returns:
  62. A str, the normalized fully-qualified symbol name.
  63. """
  64. return name.lstrip('.')
  65. class DescriptorPool(object):
  66. """A collection of protobufs dynamically constructed by descriptor protos."""
  67. def __init__(self, descriptor_db=None):
  68. """Initializes a Pool of proto buffs.
  69. The descriptor_db argument to the constructor is provided to allow
  70. specialized file descriptor proto lookup code to be triggered on demand. An
  71. example would be an implementation which will read and compile a file
  72. specified in a call to FindFileByName() and not require the call to Add()
  73. at all. Results from this database will be cached internally here as well.
  74. Args:
  75. descriptor_db: A secondary source of file descriptors.
  76. """
  77. self._internal_db = descriptor_database.DescriptorDatabase()
  78. self._descriptor_db = descriptor_db
  79. self._descriptors = {}
  80. self._enum_descriptors = {}
  81. self._file_descriptors = {}
  82. def Add(self, file_desc_proto):
  83. """Adds the FileDescriptorProto and its types to this pool.
  84. Args:
  85. file_desc_proto: The FileDescriptorProto to add.
  86. """
  87. self._internal_db.Add(file_desc_proto)
  88. def AddDescriptor(self, desc):
  89. """Adds a Descriptor to the pool, non-recursively.
  90. If the Descriptor contains nested messages or enums, the caller must
  91. explicitly register them. This method also registers the FileDescriptor
  92. associated with the message.
  93. Args:
  94. desc: A Descriptor.
  95. """
  96. if not isinstance(desc, descriptor.Descriptor):
  97. raise TypeError('Expected instance of descriptor.Descriptor.')
  98. self._descriptors[desc.full_name] = desc
  99. self.AddFileDescriptor(desc.file)
  100. def AddEnumDescriptor(self, enum_desc):
  101. """Adds an EnumDescriptor to the pool.
  102. This method also registers the FileDescriptor associated with the message.
  103. Args:
  104. enum_desc: An EnumDescriptor.
  105. """
  106. if not isinstance(enum_desc, descriptor.EnumDescriptor):
  107. raise TypeError('Expected instance of descriptor.EnumDescriptor.')
  108. self._enum_descriptors[enum_desc.full_name] = enum_desc
  109. self.AddFileDescriptor(enum_desc.file)
  110. def AddFileDescriptor(self, file_desc):
  111. """Adds a FileDescriptor to the pool, non-recursively.
  112. If the FileDescriptor contains messages or enums, the caller must explicitly
  113. register them.
  114. Args:
  115. file_desc: A FileDescriptor.
  116. """
  117. if not isinstance(file_desc, descriptor.FileDescriptor):
  118. raise TypeError('Expected instance of descriptor.FileDescriptor.')
  119. self._file_descriptors[file_desc.name] = file_desc
  120. def FindFileByName(self, file_name):
  121. """Gets a FileDescriptor by file name.
  122. Args:
  123. file_name: The path to the file to get a descriptor for.
  124. Returns:
  125. A FileDescriptor for the named file.
  126. Raises:
  127. KeyError: if the file can not be found in the pool.
  128. """
  129. try:
  130. return self._file_descriptors[file_name]
  131. except KeyError:
  132. pass
  133. try:
  134. file_proto = self._internal_db.FindFileByName(file_name)
  135. except KeyError:
  136. _, error, _ = sys.exc_info() #PY25 compatible for GAE.
  137. if self._descriptor_db:
  138. file_proto = self._descriptor_db.FindFileByName(file_name)
  139. else:
  140. raise error
  141. if not file_proto:
  142. raise KeyError('Cannot find a file named %s' % file_name)
  143. return self._ConvertFileProtoToFileDescriptor(file_proto)
  144. def FindFileContainingSymbol(self, symbol):
  145. """Gets the FileDescriptor for the file containing the specified symbol.
  146. Args:
  147. symbol: The name of the symbol to search for.
  148. Returns:
  149. A FileDescriptor that contains the specified symbol.
  150. Raises:
  151. KeyError: if the file can not be found in the pool.
  152. """
  153. symbol = _NormalizeFullyQualifiedName(symbol)
  154. try:
  155. return self._descriptors[symbol].file
  156. except KeyError:
  157. pass
  158. try:
  159. return self._enum_descriptors[symbol].file
  160. except KeyError:
  161. pass
  162. try:
  163. file_proto = self._internal_db.FindFileContainingSymbol(symbol)
  164. except KeyError:
  165. _, error, _ = sys.exc_info() #PY25 compatible for GAE.
  166. if self._descriptor_db:
  167. file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
  168. else:
  169. raise error
  170. if not file_proto:
  171. raise KeyError('Cannot find a file containing %s' % symbol)
  172. return self._ConvertFileProtoToFileDescriptor(file_proto)
  173. def FindMessageTypeByName(self, full_name):
  174. """Loads the named descriptor from the pool.
  175. Args:
  176. full_name: The full name of the descriptor to load.
  177. Returns:
  178. The descriptor for the named type.
  179. """
  180. full_name = _NormalizeFullyQualifiedName(full_name)
  181. if full_name not in self._descriptors:
  182. self.FindFileContainingSymbol(full_name)
  183. return self._descriptors[full_name]
  184. def FindEnumTypeByName(self, full_name):
  185. """Loads the named enum descriptor from the pool.
  186. Args:
  187. full_name: The full name of the enum descriptor to load.
  188. Returns:
  189. The enum descriptor for the named type.
  190. """
  191. full_name = _NormalizeFullyQualifiedName(full_name)
  192. if full_name not in self._enum_descriptors:
  193. self.FindFileContainingSymbol(full_name)
  194. return self._enum_descriptors[full_name]
  195. def _ConvertFileProtoToFileDescriptor(self, file_proto):
  196. """Creates a FileDescriptor from a proto or returns a cached copy.
  197. This method also has the side effect of loading all the symbols found in
  198. the file into the appropriate dictionaries in the pool.
  199. Args:
  200. file_proto: The proto to convert.
  201. Returns:
  202. A FileDescriptor matching the passed in proto.
  203. """
  204. if file_proto.name not in self._file_descriptors:
  205. built_deps = list(self._GetDeps(file_proto.dependency))
  206. direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
  207. file_descriptor = descriptor.FileDescriptor(
  208. name=file_proto.name,
  209. package=file_proto.package,
  210. options=file_proto.options,
  211. serialized_pb=file_proto.SerializeToString(),
  212. dependencies=direct_deps)
  213. scope = {}
  214. # This loop extracts all the message and enum types from all the
  215. # dependencoes of the file_proto. This is necessary to create the
  216. # scope of available message types when defining the passed in
  217. # file proto.
  218. for dependency in built_deps:
  219. scope.update(self._ExtractSymbols(
  220. dependency.message_types_by_name.values()))
  221. scope.update((_PrefixWithDot(enum.full_name), enum)
  222. for enum in dependency.enum_types_by_name.values())
  223. for message_type in file_proto.message_type:
  224. message_desc = self._ConvertMessageDescriptor(
  225. message_type, file_proto.package, file_descriptor, scope)
  226. file_descriptor.message_types_by_name[message_desc.name] = message_desc
  227. for enum_type in file_proto.enum_type:
  228. file_descriptor.enum_types_by_name[enum_type.name] = (
  229. self._ConvertEnumDescriptor(enum_type, file_proto.package,
  230. file_descriptor, None, scope))
  231. for index, extension_proto in enumerate(file_proto.extension):
  232. extension_desc = self.MakeFieldDescriptor(
  233. extension_proto, file_proto.package, index, is_extension=True)
  234. extension_desc.containing_type = self._GetTypeFromScope(
  235. file_descriptor.package, extension_proto.extendee, scope)
  236. self.SetFieldType(extension_proto, extension_desc,
  237. file_descriptor.package, scope)
  238. file_descriptor.extensions_by_name[extension_desc.name] = extension_desc
  239. for desc_proto in file_proto.message_type:
  240. self.SetAllFieldTypes(file_proto.package, desc_proto, scope)
  241. if file_proto.package:
  242. desc_proto_prefix = _PrefixWithDot(file_proto.package)
  243. else:
  244. desc_proto_prefix = ''
  245. for desc_proto in file_proto.message_type:
  246. desc = self._GetTypeFromScope(desc_proto_prefix, desc_proto.name, scope)
  247. file_descriptor.message_types_by_name[desc_proto.name] = desc
  248. self.Add(file_proto)
  249. self._file_descriptors[file_proto.name] = file_descriptor
  250. return self._file_descriptors[file_proto.name]
  251. def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
  252. scope=None):
  253. """Adds the proto to the pool in the specified package.
  254. Args:
  255. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  256. package: The package the proto should be located in.
  257. file_desc: The file containing this message.
  258. scope: Dict mapping short and full symbols to message and enum types.
  259. Returns:
  260. The added descriptor.
  261. """
  262. if package:
  263. desc_name = '.'.join((package, desc_proto.name))
  264. else:
  265. desc_name = desc_proto.name
  266. if file_desc is None:
  267. file_name = None
  268. else:
  269. file_name = file_desc.name
  270. if scope is None:
  271. scope = {}
  272. nested = [
  273. self._ConvertMessageDescriptor(nested, desc_name, file_desc, scope)
  274. for nested in desc_proto.nested_type]
  275. enums = [
  276. self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)
  277. for enum in desc_proto.enum_type]
  278. fields = [self.MakeFieldDescriptor(field, desc_name, index)
  279. for index, field in enumerate(desc_proto.field)]
  280. extensions = [
  281. self.MakeFieldDescriptor(extension, desc_name, index, is_extension=True)
  282. for index, extension in enumerate(desc_proto.extension)]
  283. oneofs = [
  284. descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
  285. index, None, [])
  286. for index, desc in enumerate(desc_proto.oneof_decl)]
  287. extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
  288. if extension_ranges:
  289. is_extendable = True
  290. else:
  291. is_extendable = False
  292. desc = descriptor.Descriptor(
  293. name=desc_proto.name,
  294. full_name=desc_name,
  295. filename=file_name,
  296. containing_type=None,
  297. fields=fields,
  298. oneofs=oneofs,
  299. nested_types=nested,
  300. enum_types=enums,
  301. extensions=extensions,
  302. options=desc_proto.options,
  303. is_extendable=is_extendable,
  304. extension_ranges=extension_ranges,
  305. file=file_desc,
  306. serialized_start=None,
  307. serialized_end=None)
  308. for nested in desc.nested_types:
  309. nested.containing_type = desc
  310. for enum in desc.enum_types:
  311. enum.containing_type = desc
  312. for field_index, field_desc in enumerate(desc_proto.field):
  313. if field_desc.HasField('oneof_index'):
  314. oneof_index = field_desc.oneof_index
  315. oneofs[oneof_index].fields.append(fields[field_index])
  316. fields[field_index].containing_oneof = oneofs[oneof_index]
  317. scope[_PrefixWithDot(desc_name)] = desc
  318. self._descriptors[desc_name] = desc
  319. return desc
  320. def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
  321. containing_type=None, scope=None):
  322. """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
  323. Args:
  324. enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
  325. package: Optional package name for the new message EnumDescriptor.
  326. file_desc: The file containing the enum descriptor.
  327. containing_type: The type containing this enum.
  328. scope: Scope containing available types.
  329. Returns:
  330. The added descriptor
  331. """
  332. if package:
  333. enum_name = '.'.join((package, enum_proto.name))
  334. else:
  335. enum_name = enum_proto.name
  336. if file_desc is None:
  337. file_name = None
  338. else:
  339. file_name = file_desc.name
  340. values = [self._MakeEnumValueDescriptor(value, index)
  341. for index, value in enumerate(enum_proto.value)]
  342. desc = descriptor.EnumDescriptor(name=enum_proto.name,
  343. full_name=enum_name,
  344. filename=file_name,
  345. file=file_desc,
  346. values=values,
  347. containing_type=containing_type,
  348. options=enum_proto.options)
  349. scope['.%s' % enum_name] = desc
  350. self._enum_descriptors[enum_name] = desc
  351. return desc
  352. def MakeFieldDescriptor(self, field_proto, message_name, index,
  353. is_extension=False):
  354. """Creates a field descriptor from a FieldDescriptorProto.
  355. For message and enum type fields, this method will do a look up
  356. in the pool for the appropriate descriptor for that type. If it
  357. is unavailable, it will fall back to the _source function to
  358. create it. If this type is still unavailable, construction will
  359. fail.
  360. Args:
  361. field_proto: The proto describing the field.
  362. message_name: The name of the containing message.
  363. index: Index of the field
  364. is_extension: Indication that this field is for an extension.
  365. Returns:
  366. An initialized FieldDescriptor object
  367. """
  368. if message_name:
  369. full_name = '.'.join((message_name, field_proto.name))
  370. else:
  371. full_name = field_proto.name
  372. return descriptor.FieldDescriptor(
  373. name=field_proto.name,
  374. full_name=full_name,
  375. index=index,
  376. number=field_proto.number,
  377. type=field_proto.type,
  378. cpp_type=None,
  379. message_type=None,
  380. enum_type=None,
  381. containing_type=None,
  382. label=field_proto.label,
  383. has_default_value=False,
  384. default_value=None,
  385. is_extension=is_extension,
  386. extension_scope=None,
  387. options=field_proto.options)
  388. def SetAllFieldTypes(self, package, desc_proto, scope):
  389. """Sets all the descriptor's fields's types.
  390. This method also sets the containing types on any extensions.
  391. Args:
  392. package: The current package of desc_proto.
  393. desc_proto: The message descriptor to update.
  394. scope: Enclosing scope of available types.
  395. """
  396. package = _PrefixWithDot(package)
  397. main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
  398. if package == '.':
  399. nested_package = _PrefixWithDot(desc_proto.name)
  400. else:
  401. nested_package = '.'.join([package, desc_proto.name])
  402. for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
  403. self.SetFieldType(field_proto, field_desc, nested_package, scope)
  404. for extension_proto, extension_desc in (
  405. zip(desc_proto.extension, main_desc.extensions)):
  406. extension_desc.containing_type = self._GetTypeFromScope(
  407. nested_package, extension_proto.extendee, scope)
  408. self.SetFieldType(extension_proto, extension_desc, nested_package, scope)
  409. for nested_type in desc_proto.nested_type:
  410. self.SetAllFieldTypes(nested_package, nested_type, scope)
  411. def SetFieldType(self, field_proto, field_desc, package, scope):
  412. """Sets the field's type, cpp_type, message_type and enum_type.
  413. Args:
  414. field_proto: Data about the field in proto format.
  415. field_desc: The descriptor to modiy.
  416. package: The package the field's container is in.
  417. scope: Enclosing scope of available types.
  418. """
  419. if field_proto.type_name:
  420. desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
  421. else:
  422. desc = None
  423. if not field_proto.HasField('type'):
  424. if isinstance(desc, descriptor.Descriptor):
  425. field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
  426. else:
  427. field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
  428. field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
  429. field_proto.type)
  430. if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
  431. or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
  432. field_desc.message_type = desc
  433. if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  434. field_desc.enum_type = desc
  435. if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  436. field_desc.has_default_value = False
  437. field_desc.default_value = []
  438. elif field_proto.HasField('default_value'):
  439. field_desc.has_default_value = True
  440. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  441. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  442. field_desc.default_value = float(field_proto.default_value)
  443. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  444. field_desc.default_value = field_proto.default_value
  445. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  446. field_desc.default_value = field_proto.default_value.lower() == 'true'
  447. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  448. field_desc.default_value = field_desc.enum_type.values_by_name[
  449. field_proto.default_value].number
  450. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  451. field_desc.default_value = text_encoding.CUnescape(
  452. field_proto.default_value)
  453. else:
  454. field_desc.default_value = int(field_proto.default_value)
  455. else:
  456. field_desc.has_default_value = False
  457. field_desc.default_value = None
  458. field_desc.type = field_proto.type
  459. def _MakeEnumValueDescriptor(self, value_proto, index):
  460. """Creates a enum value descriptor object from a enum value proto.
  461. Args:
  462. value_proto: The proto describing the enum value.
  463. index: The index of the enum value.
  464. Returns:
  465. An initialized EnumValueDescriptor object.
  466. """
  467. return descriptor.EnumValueDescriptor(
  468. name=value_proto.name,
  469. index=index,
  470. number=value_proto.number,
  471. options=value_proto.options,
  472. type=None)
  473. def _ExtractSymbols(self, descriptors):
  474. """Pulls out all the symbols from descriptor protos.
  475. Args:
  476. descriptors: The messages to extract descriptors from.
  477. Yields:
  478. A two element tuple of the type name and descriptor object.
  479. """
  480. for desc in descriptors:
  481. yield (_PrefixWithDot(desc.full_name), desc)
  482. for symbol in self._ExtractSymbols(desc.nested_types):
  483. yield symbol
  484. for enum in desc.enum_types:
  485. yield (_PrefixWithDot(enum.full_name), enum)
  486. def _GetDeps(self, dependencies):
  487. """Recursively finds dependencies for file protos.
  488. Args:
  489. dependencies: The names of the files being depended on.
  490. Yields:
  491. Each direct and indirect dependency.
  492. """
  493. for dependency in dependencies:
  494. dep_desc = self.FindFileByName(dependency)
  495. yield dep_desc
  496. for parent_dep in dep_desc.dependencies:
  497. yield parent_dep
  498. def _GetTypeFromScope(self, package, type_name, scope):
  499. """Finds a given type name in the current scope.
  500. Args:
  501. package: The package the proto should be located in.
  502. type_name: The name of the type to be found in the scope.
  503. scope: Dict mapping short and full symbols to message and enum types.
  504. Returns:
  505. The descriptor for the requested type.
  506. """
  507. if type_name not in scope:
  508. components = _PrefixWithDot(package).split('.')
  509. while components:
  510. possible_match = '.'.join(components + [type_name])
  511. if possible_match in scope:
  512. type_name = possible_match
  513. break
  514. else:
  515. components.pop(-1)
  516. return scope[type_name]
  517. def _PrefixWithDot(name):
  518. return name if name.startswith('.') else '.%s' % name