resolver.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. 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. @classmethod
  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, str) \
  61. and node_check is not None:
  62. raise ResolverError("Invalid node checker: %s" % node_check)
  63. if not isinstance(index_check, (str, 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. def descend_resolver(self, current_node, current_index):
  78. if not self.yaml_path_resolvers:
  79. return
  80. exact_paths = {}
  81. prefix_paths = []
  82. if current_node:
  83. depth = len(self.resolver_prefix_paths)
  84. for path, kind in self.resolver_prefix_paths[-1]:
  85. if self.check_resolver_prefix(depth, path, kind,
  86. current_node, current_index):
  87. if len(path) > depth:
  88. prefix_paths.append((path, kind))
  89. else:
  90. exact_paths[kind] = self.yaml_path_resolvers[path, kind]
  91. else:
  92. for path, kind in self.yaml_path_resolvers:
  93. if not path:
  94. exact_paths[kind] = self.yaml_path_resolvers[path, kind]
  95. else:
  96. prefix_paths.append((path, kind))
  97. self.resolver_exact_paths.append(exact_paths)
  98. self.resolver_prefix_paths.append(prefix_paths)
  99. def ascend_resolver(self):
  100. if not self.yaml_path_resolvers:
  101. return
  102. self.resolver_exact_paths.pop()
  103. self.resolver_prefix_paths.pop()
  104. def check_resolver_prefix(self, depth, path, kind,
  105. current_node, current_index):
  106. node_check, index_check = path[depth-1]
  107. if isinstance(node_check, str):
  108. if current_node.tag != node_check:
  109. return
  110. elif node_check is not None:
  111. if not isinstance(current_node, node_check):
  112. return
  113. if index_check is True and current_index is not None:
  114. return
  115. if (index_check is False or index_check is None) \
  116. and current_index is None:
  117. return
  118. if isinstance(index_check, str):
  119. if not (isinstance(current_index, ScalarNode)
  120. and index_check == current_index.value):
  121. return
  122. elif isinstance(index_check, int) and not isinstance(index_check, bool):
  123. if index_check != current_index:
  124. return
  125. return True
  126. def resolve(self, kind, value, implicit):
  127. if kind is ScalarNode and implicit[0]:
  128. if value == '':
  129. resolvers = self.yaml_implicit_resolvers.get('', [])
  130. else:
  131. resolvers = self.yaml_implicit_resolvers.get(value[0], [])
  132. resolvers += self.yaml_implicit_resolvers.get(None, [])
  133. for tag, regexp in resolvers:
  134. if regexp.match(value):
  135. return tag
  136. implicit = implicit[1]
  137. if self.yaml_path_resolvers:
  138. exact_paths = self.resolver_exact_paths[-1]
  139. if kind in exact_paths:
  140. return exact_paths[kind]
  141. if None in exact_paths:
  142. return exact_paths[None]
  143. if kind is ScalarNode:
  144. return self.DEFAULT_SCALAR_TAG
  145. elif kind is SequenceNode:
  146. return self.DEFAULT_SEQUENCE_TAG
  147. elif kind is MappingNode:
  148. return self.DEFAULT_MAPPING_TAG
  149. class Resolver(BaseResolver):
  150. pass
  151. Resolver.add_implicit_resolver(
  152. 'tag:yaml.org,2002:bool',
  153. re.compile(r'''^(?:yes|Yes|YES|no|No|NO
  154. |true|True|TRUE|false|False|FALSE
  155. |on|On|ON|off|Off|OFF)$''', re.X),
  156. list('yYnNtTfFoO'))
  157. Resolver.add_implicit_resolver(
  158. 'tag:yaml.org,2002:float',
  159. re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
  160. |\.[0-9_]+(?:[eE][-+][0-9]+)?
  161. |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
  162. |[-+]?\.(?:inf|Inf|INF)
  163. |\.(?:nan|NaN|NAN))$''', re.X),
  164. list('-+0123456789.'))
  165. Resolver.add_implicit_resolver(
  166. 'tag:yaml.org,2002:int',
  167. re.compile(r'''^(?:[-+]?0b[0-1_]+
  168. |[-+]?0[0-7_]+
  169. |[-+]?(?:0|[1-9][0-9_]*)
  170. |[-+]?0x[0-9a-fA-F_]+
  171. |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
  172. list('-+0123456789'))
  173. Resolver.add_implicit_resolver(
  174. 'tag:yaml.org,2002:merge',
  175. re.compile(r'^(?:<<)$'),
  176. ['<'])
  177. Resolver.add_implicit_resolver(
  178. 'tag:yaml.org,2002:null',
  179. re.compile(r'''^(?: ~
  180. |null|Null|NULL
  181. | )$''', re.X),
  182. ['~', 'n', 'N', ''])
  183. Resolver.add_implicit_resolver(
  184. 'tag:yaml.org,2002:timestamp',
  185. re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
  186. |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
  187. (?:[Tt]|[ \t]+)[0-9][0-9]?
  188. :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
  189. (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
  190. list('0123456789'))
  191. Resolver.add_implicit_resolver(
  192. 'tag:yaml.org,2002:value',
  193. re.compile(r'^(?:=)$'),
  194. ['='])
  195. # The following resolver is only for documentation purposes. It cannot work
  196. # because plain scalars cannot start with '!', '&', or '*'.
  197. Resolver.add_implicit_resolver(
  198. 'tag:yaml.org,2002:yaml',
  199. re.compile(r'^(?:!|&|\*)$'),
  200. list('!&*'))