resolver.py 8.9 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(object):
  8. DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str'
  9. DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq'
  10. DEFAULT_MAPPING_TAG = u'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. def add_implicit_resolver(cls, tag, regexp, first):
  17. if not 'yaml_implicit_resolvers' in cls.__dict__:
  18. implicit_resolvers = {}
  19. for key in cls.yaml_implicit_resolvers:
  20. implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:]
  21. cls.yaml_implicit_resolvers = implicit_resolvers
  22. if first is None:
  23. first = [None]
  24. for ch in first:
  25. cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp))
  26. add_implicit_resolver = classmethod(add_implicit_resolver)
  27. def add_path_resolver(cls, tag, path, kind=None):
  28. # Note: `add_path_resolver` is experimental. The API could be changed.
  29. # `new_path` is a pattern that is matched against the path from the
  30. # root to the node that is being considered. `node_path` elements are
  31. # tuples `(node_check, index_check)`. `node_check` is a node class:
  32. # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None`
  33. # matches any kind of a node. `index_check` could be `None`, a boolean
  34. # value, a string value, or a number. `None` and `False` match against
  35. # any _value_ of sequence and mapping nodes. `True` matches against
  36. # any _key_ of a mapping node. A string `index_check` matches against
  37. # a mapping value that corresponds to a scalar key which content is
  38. # equal to the `index_check` value. An integer `index_check` matches
  39. # against a sequence value with the index equal to `index_check`.
  40. if not 'yaml_path_resolvers' in cls.__dict__:
  41. cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy()
  42. new_path = []
  43. for element in path:
  44. if isinstance(element, (list, tuple)):
  45. if len(element) == 2:
  46. node_check, index_check = element
  47. elif len(element) == 1:
  48. node_check = element[0]
  49. index_check = True
  50. else:
  51. raise ResolverError("Invalid path element: %s" % element)
  52. else:
  53. node_check = None
  54. index_check = element
  55. if node_check is str:
  56. node_check = ScalarNode
  57. elif node_check is list:
  58. node_check = SequenceNode
  59. elif node_check is dict:
  60. node_check = MappingNode
  61. elif node_check not in [ScalarNode, SequenceNode, MappingNode] \
  62. and not isinstance(node_check, basestring) \
  63. and node_check is not None:
  64. raise ResolverError("Invalid node checker: %s" % node_check)
  65. if not isinstance(index_check, (basestring, int)) \
  66. and index_check is not None:
  67. raise ResolverError("Invalid index checker: %s" % index_check)
  68. new_path.append((node_check, index_check))
  69. if kind is str:
  70. kind = ScalarNode
  71. elif kind is list:
  72. kind = SequenceNode
  73. elif kind is dict:
  74. kind = MappingNode
  75. elif kind not in [ScalarNode, SequenceNode, MappingNode] \
  76. and kind is not None:
  77. raise ResolverError("Invalid node kind: %s" % kind)
  78. cls.yaml_path_resolvers[tuple(new_path), kind] = tag
  79. add_path_resolver = classmethod(add_path_resolver)
  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, basestring):
  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, basestring):
  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 == u'':
  132. resolvers = self.yaml_implicit_resolvers.get(u'', [])
  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. u'tag:yaml.org,2002:bool',
  156. re.compile(ur'''^(?:yes|Yes|YES|no|No|NO
  157. |true|True|TRUE|false|False|FALSE
  158. |on|On|ON|off|Off|OFF)$''', re.X),
  159. list(u'yYnNtTfFoO'))
  160. Resolver.add_implicit_resolver(
  161. u'tag:yaml.org,2002:float',
  162. re.compile(ur'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
  163. |\.[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(u'-+0123456789.'))
  168. Resolver.add_implicit_resolver(
  169. u'tag:yaml.org,2002:int',
  170. re.compile(ur'''^(?:[-+]?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(u'-+0123456789'))
  176. Resolver.add_implicit_resolver(
  177. u'tag:yaml.org,2002:merge',
  178. re.compile(ur'^(?:<<)$'),
  179. [u'<'])
  180. Resolver.add_implicit_resolver(
  181. u'tag:yaml.org,2002:null',
  182. re.compile(ur'''^(?: ~
  183. |null|Null|NULL
  184. | )$''', re.X),
  185. [u'~', u'n', u'N', u''])
  186. Resolver.add_implicit_resolver(
  187. u'tag:yaml.org,2002:timestamp',
  188. re.compile(ur'''^(?:[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(u'0123456789'))
  194. Resolver.add_implicit_resolver(
  195. u'tag:yaml.org,2002:value',
  196. re.compile(ur'^(?:=)$'),
  197. [u'='])
  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. u'tag:yaml.org,2002:yaml',
  202. re.compile(ur'^(?:!|&|\*)$'),
  203. list(u'!&*'))