resolver.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # SPDX-License-Identifier: MIT
  2. __all__ = ['BaseResolver', 'Resolver']
  3. from error import *
  4. from nodes import *
  5. import re
  6. class ResolverError(YAMLError):
  7. pass
  8. class BaseResolver(object):
  9. DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str'
  10. DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq'
  11. DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map'
  12. yaml_implicit_resolvers = {}
  13. yaml_path_resolvers = {}
  14. def __init__(self):
  15. self.resolver_exact_paths = []
  16. self.resolver_prefix_paths = []
  17. def add_implicit_resolver(cls, tag, regexp, first):
  18. if not 'yaml_implicit_resolvers' in cls.__dict__:
  19. cls.yaml_implicit_resolvers = cls.yaml_implicit_resolvers.copy()
  20. if first is None:
  21. first = [None]
  22. for ch in first:
  23. cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp))
  24. add_implicit_resolver = classmethod(add_implicit_resolver)
  25. def add_path_resolver(cls, tag, path, kind=None):
  26. # Note: `add_path_resolver` is experimental. The API could be changed.
  27. # `new_path` is a pattern that is matched against the path from the
  28. # root to the node that is being considered. `node_path` elements are
  29. # tuples `(node_check, index_check)`. `node_check` is a node class:
  30. # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None`
  31. # matches any kind of a node. `index_check` could be `None`, a boolean
  32. # value, a string value, or a number. `None` and `False` match against
  33. # any _value_ of sequence and mapping nodes. `True` matches against
  34. # any _key_ of a mapping node. A string `index_check` matches against
  35. # a mapping value that corresponds to a scalar key which content is
  36. # equal to the `index_check` value. An integer `index_check` matches
  37. # against a sequence value with the index equal to `index_check`.
  38. if not 'yaml_path_resolvers' in cls.__dict__:
  39. cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy()
  40. new_path = []
  41. for element in path:
  42. if isinstance(element, (list, tuple)):
  43. if len(element) == 2:
  44. node_check, index_check = element
  45. elif len(element) == 1:
  46. node_check = element[0]
  47. index_check = True
  48. else:
  49. raise ResolverError("Invalid path element: %s" % element)
  50. else:
  51. node_check = None
  52. index_check = element
  53. if node_check is str:
  54. node_check = ScalarNode
  55. elif node_check is list:
  56. node_check = SequenceNode
  57. elif node_check is dict:
  58. node_check = MappingNode
  59. elif node_check not in [ScalarNode, SequenceNode, MappingNode] \
  60. and not isinstance(node_check, basestring) \
  61. and node_check is not None:
  62. raise ResolverError("Invalid node checker: %s" % node_check)
  63. if not isinstance(index_check, (basestring, int)) \
  64. and index_check is not None:
  65. raise ResolverError("Invalid index checker: %s" % index_check)
  66. new_path.append((node_check, index_check))
  67. if kind is str:
  68. kind = ScalarNode
  69. elif kind is list:
  70. kind = SequenceNode
  71. elif kind is dict:
  72. kind = MappingNode
  73. elif kind not in [ScalarNode, SequenceNode, MappingNode] \
  74. and kind is not None:
  75. raise ResolverError("Invalid node kind: %s" % kind)
  76. cls.yaml_path_resolvers[tuple(new_path), kind] = tag
  77. add_path_resolver = classmethod(add_path_resolver)
  78. def descend_resolver(self, current_node, current_index):
  79. if not self.yaml_path_resolvers:
  80. return
  81. exact_paths = {}
  82. prefix_paths = []
  83. if current_node:
  84. depth = len(self.resolver_prefix_paths)
  85. for path, kind in self.resolver_prefix_paths[-1]:
  86. if self.check_resolver_prefix(depth, path, kind,
  87. current_node, current_index):
  88. if len(path) > depth:
  89. prefix_paths.append((path, kind))
  90. else:
  91. exact_paths[kind] = self.yaml_path_resolvers[path, kind]
  92. else:
  93. for path, kind in self.yaml_path_resolvers:
  94. if not path:
  95. exact_paths[kind] = self.yaml_path_resolvers[path, kind]
  96. else:
  97. prefix_paths.append((path, kind))
  98. self.resolver_exact_paths.append(exact_paths)
  99. self.resolver_prefix_paths.append(prefix_paths)
  100. def ascend_resolver(self):
  101. if not self.yaml_path_resolvers:
  102. return
  103. self.resolver_exact_paths.pop()
  104. self.resolver_prefix_paths.pop()
  105. def check_resolver_prefix(self, depth, path, kind,
  106. current_node, current_index):
  107. node_check, index_check = path[depth-1]
  108. if isinstance(node_check, basestring):
  109. if current_node.tag != node_check:
  110. return
  111. elif node_check is not None:
  112. if not isinstance(current_node, node_check):
  113. return
  114. if index_check is True and current_index is not None:
  115. return
  116. if (index_check is False or index_check is None) \
  117. and current_index is None:
  118. return
  119. if isinstance(index_check, basestring):
  120. if not (isinstance(current_index, ScalarNode)
  121. and index_check == current_index.value):
  122. return
  123. elif isinstance(index_check, int) and not isinstance(index_check, bool):
  124. if index_check != current_index:
  125. return
  126. return True
  127. def resolve(self, kind, value, implicit):
  128. if kind is ScalarNode and implicit[0]:
  129. if value == u'':
  130. resolvers = self.yaml_implicit_resolvers.get(u'', [])
  131. else:
  132. resolvers = self.yaml_implicit_resolvers.get(value[0], [])
  133. resolvers += self.yaml_implicit_resolvers.get(None, [])
  134. for tag, regexp in resolvers:
  135. if regexp.match(value):
  136. return tag
  137. implicit = implicit[1]
  138. if self.yaml_path_resolvers:
  139. exact_paths = self.resolver_exact_paths[-1]
  140. if kind in exact_paths:
  141. return exact_paths[kind]
  142. if None in exact_paths:
  143. return exact_paths[None]
  144. if kind is ScalarNode:
  145. return self.DEFAULT_SCALAR_TAG
  146. elif kind is SequenceNode:
  147. return self.DEFAULT_SEQUENCE_TAG
  148. elif kind is MappingNode:
  149. return self.DEFAULT_MAPPING_TAG
  150. class Resolver(BaseResolver):
  151. pass
  152. Resolver.add_implicit_resolver(
  153. u'tag:yaml.org,2002:bool',
  154. re.compile(ur'''^(?:yes|Yes|YES|no|No|NO
  155. |true|True|TRUE|false|False|FALSE
  156. |on|On|ON|off|Off|OFF)$''', re.X),
  157. list(u'yYnNtTfFoO'))
  158. Resolver.add_implicit_resolver(
  159. u'tag:yaml.org,2002:float',
  160. re.compile(ur'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
  161. |\.[0-9_]+(?:[eE][-+][0-9]+)?
  162. |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
  163. |[-+]?\.(?:inf|Inf|INF)
  164. |\.(?:nan|NaN|NAN))$''', re.X),
  165. list(u'-+0123456789.'))
  166. Resolver.add_implicit_resolver(
  167. u'tag:yaml.org,2002:int',
  168. re.compile(ur'''^(?:[-+]?0b[0-1_]+
  169. |[-+]?0[0-7_]+
  170. |[-+]?(?:0|[1-9][0-9_]*)
  171. |[-+]?0x[0-9a-fA-F_]+
  172. |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
  173. list(u'-+0123456789'))
  174. Resolver.add_implicit_resolver(
  175. u'tag:yaml.org,2002:merge',
  176. re.compile(ur'^(?:<<)$'),
  177. [u'<'])
  178. Resolver.add_implicit_resolver(
  179. u'tag:yaml.org,2002:null',
  180. re.compile(ur'''^(?: ~
  181. |null|Null|NULL
  182. | )$''', re.X),
  183. [u'~', u'n', u'N', u''])
  184. Resolver.add_implicit_resolver(
  185. u'tag:yaml.org,2002:timestamp',
  186. re.compile(ur'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
  187. |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
  188. (?:[Tt]|[ \t]+)[0-9][0-9]?
  189. :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
  190. (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
  191. list(u'0123456789'))
  192. Resolver.add_implicit_resolver(
  193. u'tag:yaml.org,2002:value',
  194. re.compile(ur'^(?:=)$'),
  195. [u'='])
  196. # The following resolver is only for documentation purposes. It cannot work
  197. # because plain scalars cannot start with '!', '&', or '*'.
  198. Resolver.add_implicit_resolver(
  199. u'tag:yaml.org,2002:yaml',
  200. re.compile(ur'^(?:!|&|\*)$'),
  201. list(u'!&*'))