Debian Codegraph @

third_party/python/fluent.syntax/fluent/syntax/ast.py

raw
1 import re
2 import sys
3 import json
4 from typing import Any, Callable, Dict, List, TypeVar, Union, cast
5
6 Node = TypeVar('Node', bound='BaseNode')
7 ToJsonFn = Callable[[Dict[str, Any]], Any]
8
9
10 def to_json(value: Any, fn: Union[ToJsonFn, None] = None) -> Any:
11 if isinstance(value, BaseNode):
12 return value.to_json(fn)
13 if isinstance(value, list):
14 return list(to_json(item, fn) for item in value)
15 if isinstance(value, tuple):
16 return list(to_json(item, fn) for item in value)
17 else:
18 return value
19
20
21 def from_json(value: Any) -> Any:
22 if isinstance(value, dict):
23 cls = getattr(sys.modules[__name__], value['type'])
24 args = {
25 k: from_json(v)
26 for k, v in value.items()
27 if k != 'type'
28 }
29 return cls(**args)
30 if isinstance(value, list):
31 return list(map(from_json, value))
32 else:
33 return value
34
35
36 def scalars_equal(node1: Any, node2: Any, ignored_fields: List[str]) -> bool:
37 """Compare two nodes which are not lists."""
38
39 if type(node1) != type(node2):
40 return False
41
42 if isinstance(node1, BaseNode):
43 return node1.equals(node2, ignored_fields)
44
45 return cast(bool, node1 == node2)
46
47
48 class BaseNode:
49 """Base class for all Fluent AST nodes.
50
51 All productions described in the ASDL subclass BaseNode, including Span and
52 Annotation. Implements __str__, to_json and traverse.
53 """
54
55 def clone(self: Node) -> Node:
56 """Create a deep clone of the current node."""
57 def visit(value: Any) -> Any:
58 """Clone node and its descendants."""
59 if isinstance(value, BaseNode):
60 return value.clone()
61 if isinstance(value, list):
62 return [visit(child) for child in value]
63 if isinstance(value, tuple):
64 return tuple(visit(child) for child in value)
65 return value
66
67 # Use all attributes found on the node as kwargs to the constructor.
68 return self.__class__(
69 **{name: visit(value) for name, value in vars(self).items()}
70 )
71
72 def equals(self, other: 'BaseNode', ignored_fields: List[str] = ['span']) -> bool:
73 """Compare two nodes.
74
75 Nodes are deeply compared on a field by field basis. If possible, False
76 is returned early. When comparing attributes and variants in
77 SelectExpressions, the order doesn't matter. By default, spans are not
78 taken into account.
79 """
80
81 self_keys = set(vars(self).keys())
82 other_keys = set(vars(other).keys())
83
84 if ignored_fields:
85 for key in ignored_fields:
86 self_keys.discard(key)
87 other_keys.discard(key)
88
89 if self_keys != other_keys:
90 return False
91
92 for key in self_keys:
93 field1 = getattr(self, key)
94 field2 = getattr(other, key)
95
96 # List-typed nodes are compared item-by-item. When comparing
97 # attributes and variants, the order of items doesn't matter.
98 if isinstance(field1, list) and isinstance(field2, list):
99 if len(field1) != len(field2):
100 return False
101
102 for elem1, elem2 in zip(field1, field2):
103 if not scalars_equal(elem1, elem2, ignored_fields):
104 return False
105
106 elif not scalars_equal(field1, field2, ignored_fields):
107 return False
108
109 return True
110
111 def to_json(self, fn: Union[ToJsonFn, None] = None) -> Any:
112 obj = {
113 name: to_json(value, fn)
114 for name, value in vars(self).items()
115 }
116 obj.update(
117 {'type': self.__class__.__name__}
118 )
119 return fn(obj) if fn else obj
120
121 def __str__(self) -> str:
122 return json.dumps(self.to_json())
123
124
125 class SyntaxNode(BaseNode):
126 """Base class for AST nodes which can have Spans."""
127
128 def __init__(self, span: Union['Span', None] = None, **kwargs: Any):
129 super().__init__(**kwargs)
130 self.span = span
131
132 def add_span(self, start: int, end: int) -> None:
133 self.span = Span(start, end)
134
135
136 class Resource(SyntaxNode):
137 def __init__(self, body: Union[List['EntryType'], None] = None, **kwargs: Any):
138 super().__init__(**kwargs)
139 self.body = body or []
140
141
142 class Entry(SyntaxNode):
143 """An abstract base class for useful elements of Resource.body."""
144
145
146 class Message(Entry):
147 def __init__(self,
148 id: 'Identifier',
149 value: Union['Pattern', None] = None,
150 attributes: Union[List['Attribute'], None] = None,
151 comment: Union['Comment', None] = None,
152 **kwargs: Any):
153 super().__init__(**kwargs)
154 self.id = id
155 self.value = value
156 self.attributes = attributes or []
157 self.comment = comment
158
159
160 class Term(Entry):
161 def __init__(self, id: 'Identifier', value: 'Pattern', attributes: Union[List['Attribute'], None] = None,
162 comment: Union['Comment', None] = None, **kwargs: Any):
163 super().__init__(**kwargs)
164 self.id = id
165 self.value = value
166 self.attributes = attributes or []
167 self.comment = comment
168
169
170 class Pattern(SyntaxNode):
171 def __init__(self, elements: List[Union['TextElement', 'Placeable']], **kwargs: Any):
172 super().__init__(**kwargs)
173 self.elements = elements
174
175
176 class PatternElement(SyntaxNode):
177 """An abstract base class for elements of Patterns."""
178
179
180 class TextElement(PatternElement):
181 def __init__(self, value: str, **kwargs: Any):
182 super().__init__(**kwargs)
183 self.value = value
184
185
186 class Placeable(PatternElement):
187 def __init__(self,
188 expression: Union['InlineExpression', 'Placeable', 'SelectExpression'],
189 **kwargs: Any):
190 super().__init__(**kwargs)
191 self.expression = expression
192
193
194 class Expression(SyntaxNode):
195 """An abstract base class for expressions."""
196
197
198 class Literal(Expression):
199 """An abstract base class for literals."""
200
201 def __init__(self, value: str, **kwargs: Any):
202 super().__init__(**kwargs)
203 self.value = value
204
205 def parse(self) -> Dict[str, Any]:
206 return {'value': self.value}
207
208
209 class StringLiteral(Literal):
210 def parse(self) -> Dict[str, str]:
211 def from_escape_sequence(matchobj: Any) -> str:
212 c, codepoint4, codepoint6 = matchobj.groups()
213 if c:
214 return cast(str, c)
215 codepoint = int(codepoint4 or codepoint6, 16)
216 if codepoint <= 0xD7FF or 0xE000 <= codepoint:
217 return chr(codepoint)
218 # Escape sequences reresenting surrogate code points are
219 # well-formed but invalid in Fluent. Replace them with U+FFFD
220 # REPLACEMENT CHARACTER.
221 return '�'
222
223 value = re.sub(
224 r'\\(?:(\\|")|u([0-9a-fA-F]{4})|U([0-9a-fA-F]{6}))',
225 from_escape_sequence,
226 self.value
227 )
228 return {'value': value}
229
230
231 class NumberLiteral(Literal):
232 def parse(self) -> Dict[str, Union[float, int]]:
233 value = float(self.value)
234 decimal_position = self.value.find('.')
235 precision = 0
236 if decimal_position >= 0:
237 precision = len(self.value) - decimal_position - 1
238 return {
239 'value': value,
240 'precision': precision
241 }
242
243
244 class MessageReference(Expression):
245 def __init__(self, id: 'Identifier', attribute: Union['Identifier', None] = None, **kwargs: Any):
246 super().__init__(**kwargs)
247 self.id = id
248 self.attribute = attribute
249
250
251 class TermReference(Expression):
252 def __init__(self,
253 id: 'Identifier',
254 attribute: Union['Identifier', None] = None,
255 arguments: Union['CallArguments', None] = None,
256 **kwargs: Any):
257 super().__init__(**kwargs)
258 self.id = id
259 self.attribute = attribute
260 self.arguments = arguments
261
262
263 class VariableReference(Expression):
264 def __init__(self, id: 'Identifier', **kwargs: Any):
265 super().__init__(**kwargs)
266 self.id = id
267
268
269 class FunctionReference(Expression):
270 def __init__(self, id: 'Identifier', arguments: 'CallArguments', **kwargs: Any):
271 super().__init__(**kwargs)
272 self.id = id
273 self.arguments = arguments
274
275
276 class SelectExpression(Expression):
277 def __init__(self, selector: 'InlineExpression', variants: List['Variant'], **kwargs: Any):
278 super().__init__(**kwargs)
279 self.selector = selector
280 self.variants = variants
281
282
283 class CallArguments(SyntaxNode):
284 def __init__(self,
285 positional: Union[List[Union['InlineExpression', Placeable]], None] = None,
286 named: Union[List['NamedArgument'], None] = None,
287 **kwargs: Any):
288 super().__init__(**kwargs)
289 self.positional = [] if positional is None else positional
290 self.named = [] if named is None else named
291
292
293 class Attribute(SyntaxNode):
294 def __init__(self, id: 'Identifier', value: Pattern, **kwargs: Any):
295 super().__init__(**kwargs)
296 self.id = id
297 self.value = value
298
299
300 class Variant(SyntaxNode):
301 def __init__(self, key: Union['Identifier', NumberLiteral], value: Pattern, default: bool = False, **kwargs: Any):
302 super().__init__(**kwargs)
303 self.key = key
304 self.value = value
305 self.default = default
306
307
308 class NamedArgument(SyntaxNode):
309 def __init__(self, name: 'Identifier', value: Union[NumberLiteral, StringLiteral], **kwargs: Any):
310 super().__init__(**kwargs)
311 self.name = name
312 self.value = value
313
314
315 class Identifier(SyntaxNode):
316 def __init__(self, name: str, **kwargs: Any):
317 super().__init__(**kwargs)
318 self.name = name
319
320
321 class BaseComment(Entry):
322 def __init__(self, content: Union[str, None] = None, **kwargs: Any):
323 super().__init__(**kwargs)
324 self.content = content
325
326
327 class Comment(BaseComment):
328 def __init__(self, content: Union[str, None] = None, **kwargs: Any):
329 super().__init__(content, **kwargs)
330
331
332 class GroupComment(BaseComment):
333 def __init__(self, content: Union[str, None] = None, **kwargs: Any):
334 super().__init__(content, **kwargs)
335
336
337 class ResourceComment(BaseComment):
338 def __init__(self, content: Union[str, None] = None, **kwargs: Any):
339 super().__init__(content, **kwargs)
340
341
342 class Junk(SyntaxNode):
343 def __init__(self,
344 content: Union[str, None] = None,
345 annotations: Union[List['Annotation'], None] = None,
346 **kwargs: Any):
347 super().__init__(**kwargs)
348 self.content = content
349 self.annotations = annotations or []
350
351 def add_annotation(self, annot: 'Annotation') -> None:
352 self.annotations.append(annot)
353
354
355 class Span(BaseNode):
356 def __init__(self, start: int, end: int, **kwargs: Any):
357 super().__init__(**kwargs)
358 self.start = start
359 self.end = end
360
361
362 class Annotation(SyntaxNode):
363 def __init__(self,
364 code: str,
365 arguments: Union[List[Any], None] = None,
366 message: Union[str, None] = None,
367 **kwargs: Any):
368 super().__init__(**kwargs)
369 self.code = code
370 self.arguments = arguments or []
371 self.message = message
372
373
374 EntryType = Union[Message, Term, Comment, GroupComment, ResourceComment, Junk]
375 InlineExpression = Union[NumberLiteral, StringLiteral, MessageReference,
376 TermReference, VariableReference, FunctionReference]