resolver.py 8.8 KB

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