Debian Codegraph @

strictyaml/parser.py

raw
1 """
2 Parsing code for strictyaml.
3 """
4 import sys
5
6 from strictyaml import ruamel as ruamelyaml
7 from strictyaml import exceptions
8 from strictyaml.ruamel.comments import CommentedSeq, CommentedMap
9
10 from strictyaml.any_validator import Any
11 from strictyaml.yamllocation import YAMLChunk
12 from strictyaml import utils
13
14 from strictyaml.ruamel.reader import Reader
15 from strictyaml.ruamel.scanner import RoundTripScanner
16 from strictyaml.ruamel.parser import RoundTripParser
17 from strictyaml.ruamel.composer import Composer
18 from strictyaml.ruamel.constructor import RoundTripConstructor
19 from strictyaml.ruamel.resolver import VersionedResolver
20 from strictyaml.ruamel.nodes import MappingNode
21 from strictyaml.ruamel.compat import PY2
22 from strictyaml.ruamel.constructor import ConstructorError
23
24 if sys.version_info[:2] > (3, 4):
25 from collections.abc import Hashable
26 else:
27 from collections import Hashable
28
29
30 # StrictYAMLConstructor is mostly taken from RoundTripConstructor ruamel/yaml/constructor.py
31 # Differences:
32 # * If a duplicate key is found, an exception is raised
33
34
35 class StrictYAMLConstructor(RoundTripConstructor):
36 yaml_constructors = {}
37
38 def construct_mapping(self, node, maptyp, deep=False):
39 if not isinstance(node, MappingNode):
40 raise ConstructorError(
41 None,
42 None,
43 "expected a mapping node, but found %s" % node.id,
44 node.start_mark,
45 )
46 merge_map = self.flatten_mapping(node)
47
48 # mapping = {}
49 if node.comment:
50 maptyp._yaml_add_comment(node.comment[:2])
51 if len(node.comment) > 2:
52 maptyp.yaml_end_comment_extend(node.comment[2], clear=True)
53 if node.anchor:
54 from strictyaml.ruamel.serializer import templated_id
55
56 if not templated_id(node.anchor):
57 maptyp.yaml_set_anchor(node.anchor)
58 for key_node, value_node in node.value:
59 # keys can be list -> deep
60 key = self.construct_object(key_node, deep=True)
61 # lists are not hashable, but tuples are
62 if not isinstance(key, Hashable):
63 if isinstance(key, list):
64 key = tuple(key)
65 if PY2:
66 try:
67 hash(key)
68 except TypeError as exc:
69 raise ConstructorError(
70 "while constructing a mapping",
71 node.start_mark,
72 "found unacceptable key (%s)" % exc,
73 key_node.start_mark,
74 )
75 else:
76 if not isinstance(key, Hashable):
77 raise ConstructorError(
78 "while constructing a mapping",
79 node.start_mark,
80 "found unhashable key",
81 key_node.start_mark,
82 )
83 value = self.construct_object(value_node, deep=deep)
84 if key_node.comment:
85 maptyp._yaml_add_comment(key_node.comment, key=key)
86 if value_node.comment:
87 maptyp._yaml_add_comment(value_node.comment, value=key)
88 maptyp._yaml_set_kv_line_col(
89 key,
90 [
91 key_node.start_mark.line,
92 key_node.start_mark.column,
93 value_node.start_mark.line,
94 value_node.start_mark.column,
95 ],
96 )
97 if key in maptyp:
98 key_node.start_mark.name = self.label
99 key_node.end_mark.name = self.label
100
101 raise exceptions.DuplicateKeysDisallowed(
102 "While parsing",
103 key_node.start_mark,
104 "Duplicate key '{0}' found".format(key),
105 key_node.end_mark,
106 )
107 maptyp[key] = value
108 # do this last, or <<: before a key will prevent insertion in instances
109 # of collections.OrderedDict (as they have no __contains__
110 if merge_map:
111 maptyp.add_yaml_merge(merge_map)
112
113 # Don't verify Mapping indentation when allowing flow,
114 # as that disallows:
115 # short_key: { x = 1 }
116 # very_long_key: { x = 1 }
117 if not self.allow_flow_style:
118 previous_indentation = None
119
120 for node in [
121 nodegroup[1]
122 for nodegroup in node.value
123 if isinstance(nodegroup[1], ruamelyaml.nodes.MappingNode)
124 ]:
125 if previous_indentation is None:
126 previous_indentation = node.start_mark.column
127 if node.start_mark.column != previous_indentation:
128 raise exceptions.InconsistentIndentationDisallowed(
129 "While parsing",
130 node.start_mark,
131 "Found mapping with indentation "
132 "inconsistent with previous mapping",
133 node.end_mark,
134 )
135
136
137 StrictYAMLConstructor.add_constructor(
138 "tag:yaml.org,2002:null", RoundTripConstructor.construct_yaml_str
139 )
140
141 StrictYAMLConstructor.add_constructor(
142 "tag:yaml.org,2002:bool", RoundTripConstructor.construct_yaml_str
143 )
144
145 StrictYAMLConstructor.add_constructor(
146 "tag:yaml.org,2002:int", RoundTripConstructor.construct_yaml_str
147 )
148
149 StrictYAMLConstructor.add_constructor(
150 "tag:yaml.org,2002:float", RoundTripConstructor.construct_yaml_str
151 )
152
153 StrictYAMLConstructor.add_constructor(
154 "tag:yaml.org,2002:binary", RoundTripConstructor.construct_yaml_str
155 )
156
157 StrictYAMLConstructor.add_constructor(
158 "tag:yaml.org,2002:timestamp", RoundTripConstructor.construct_yaml_str
159 )
160
161 StrictYAMLConstructor.add_constructor(
162 "tag:yaml.org,2002:omap", RoundTripConstructor.construct_yaml_omap
163 )
164
165 StrictYAMLConstructor.add_constructor(
166 "tag:yaml.org,2002:pairs", RoundTripConstructor.construct_yaml_pairs
167 )
168
169 StrictYAMLConstructor.add_constructor(
170 "tag:yaml.org,2002:set", RoundTripConstructor.construct_yaml_set
171 )
172
173 StrictYAMLConstructor.add_constructor(
174 "tag:yaml.org,2002:str", RoundTripConstructor.construct_yaml_str
175 )
176
177 StrictYAMLConstructor.add_constructor(
178 "tag:yaml.org,2002:seq", RoundTripConstructor.construct_yaml_seq
179 )
180
181 StrictYAMLConstructor.add_constructor(
182 "tag:yaml.org,2002:map", RoundTripConstructor.construct_yaml_map
183 )
184
185 StrictYAMLConstructor.add_constructor(None, RoundTripConstructor.construct_undefined)
186
187
188 # StrictYAMLScanner is mostly taken from RoundTripScanner in ruamel/yaml/scanner.py
189 # Differences:
190 # * Tokens are checked for disallowed tokens.
191
192
193 class StrictYAMLScanner(RoundTripScanner):
194 def check_token(self, *choices):
195 # Check if the next token is one of the given types.
196 while self.need_more_tokens():
197 self.fetch_more_tokens()
198 self._gather_comments()
199 if self.tokens:
200 if not choices:
201 return True
202 for choice in choices:
203 if isinstance(self.tokens[0], choice):
204 token = self.tokens[0]
205 token.start_mark.name = self.label
206 token.end_mark.name = self.label
207
208 if isinstance(token, ruamelyaml.tokens.TagToken):
209 raise exceptions.TagTokenDisallowed(
210 "While scanning",
211 token.end_mark,
212 "Found disallowed tag tokens "
213 "(do not specify types in markup)",
214 token.start_mark,
215 )
216 if not self.allow_flow_style:
217 if isinstance(
218 token, ruamelyaml.tokens.FlowMappingStartToken
219 ) or isinstance(
220 token, ruamelyaml.tokens.FlowSequenceStartToken
221 ):
222 raise exceptions.FlowMappingDisallowed(
223 "While scanning",
224 token.start_mark,
225 "Found ugly disallowed JSONesque flow mapping "
226 "(surround with ' and ' to make text appear literally)",
227 token.end_mark,
228 )
229 if isinstance(token, ruamelyaml.tokens.AnchorToken):
230 raise exceptions.AnchorTokenDisallowed(
231 "While scanning",
232 token.start_mark,
233 "Found confusing disallowed anchor token "
234 "(surround with ' and ' to make text appear literally)",
235 token.end_mark,
236 )
237 return True
238 return False
239
240
241 class StrictYAMLLoader(
242 Reader,
243 StrictYAMLScanner,
244 RoundTripParser,
245 Composer,
246 StrictYAMLConstructor,
247 VersionedResolver,
248 ):
249 def __init__(self, stream, version=None, preserve_quotes=None):
250 Reader.__init__(self, stream, loader=self)
251 StrictYAMLScanner.__init__(self, loader=self)
252 RoundTripParser.__init__(self, loader=self)
253 Composer.__init__(self, loader=self)
254 StrictYAMLConstructor.__init__(
255 self, preserve_quotes=preserve_quotes, loader=self
256 )
257 VersionedResolver.__init__(self, version, loader=self)
258
259
260 def as_document(data, schema=None, label="<unicode string>"):
261 """
262 Translate dicts/lists and scalar (string/bool/float/int/etc.) values into a
263 YAML object which can be dumped out.
264 """
265 if schema is None:
266 schema = Any()
267
268 return schema(YAMLChunk(schema.to_yaml(data), label=label))
269
270
271 def generic_load(
272 yaml_string, schema=None, label="<unicode string>", allow_flow_style=False
273 ):
274 if not utils.is_string(yaml_string):
275 raise TypeError("StrictYAML can only read a string of valid YAML.")
276
277 # We manufacture a class that has the label we want
278 DynamicStrictYAMLLoader = type(
279 "DynamicStrictYAMLLoader",
280 (StrictYAMLLoader,),
281 {"label": label, "allow_flow_style": allow_flow_style},
282 )
283
284 try:
285 document = ruamelyaml.load(yaml_string, Loader=DynamicStrictYAMLLoader)
286 except ruamelyaml.YAMLError as parse_error:
287 if parse_error.context_mark is not None:
288 parse_error.context_mark.name = label
289 if parse_error.problem_mark is not None:
290 parse_error.problem_mark.name = label
291
292 raise parse_error
293
294 # Document is just a (string, int, etc.)
295 if type(document) not in (CommentedMap, CommentedSeq):
296 document = yaml_string
297
298 if schema is None:
299 schema = Any()
300
301 return schema(YAMLChunk(document, label=label))
302
303
304 def dirty_load(
305 yaml_string, schema=None, label="<unicode string>", allow_flow_style=False
306 ):
307 """
308 Parse the first YAML document in a string
309 and produce corresponding YAML object.
310
311 If allow_flow_style is set to True, then flow style is allowed.
312 """
313 return generic_load(
314 yaml_string, schema=schema, label=label, allow_flow_style=allow_flow_style
315 )
316
317
318 def load(yaml_string, schema=None, label="<unicode string>"):
319 """
320 Parse the first YAML document in a string
321 and produce corresponding YAML object.
322 """
323 return generic_load(yaml_string, schema=schema, label=label)