Debian Codegraph @

third_party/python/fluent.syntax/fluent/syntax/parser.py

raw
1 import re
2 from typing import Any, Callable, List, Set, TypeVar, Union, cast
3 from . import ast
4 from .stream import EOL, FluentParserStream
5 from .errors import ParseError
6
7 R = TypeVar("R", bound=ast.SyntaxNode)
8
9
10 def with_span(fn: Callable[..., R]) -> Callable[..., R]:
11 def decorated(self: 'FluentParser', ps: FluentParserStream, *args: Any, **kwargs: Any) -> Any:
12 if not self.with_spans:
13 return fn(self, ps, *args, **kwargs)
14
15 start = ps.index
16 node = fn(self, ps, *args, **kwargs)
17
18 # Don't re-add the span if the node already has it. This may happen
19 # when one decorated function calls another decorated function.
20 if node.span is not None:
21 return node
22
23 end = ps.index
24 node.add_span(start, end)
25 return node
26
27 return decorated
28
29
30 class FluentParser:
31 """This class is used to parse Fluent source content.
32
33 ``with_spans`` enables source information in the form of
34 :class:`.ast.Span` objects for each :class:`.ast.SyntaxNode`.
35 """
36
37 def __init__(self, with_spans: bool = True):
38 self.with_spans = with_spans
39
40 def parse(self, source: str) -> ast.Resource:
41 """Create a :class:`.ast.Resource` from a Fluent source.
42 """
43 ps = FluentParserStream(source)
44 ps.skip_blank_block()
45
46 entries: List[ast.EntryType] = []
47 last_comment = None
48
49 while ps.current_char:
50 entry = self.get_entry_or_junk(ps)
51 blank_lines = ps.skip_blank_block()
52
53 # Regular Comments require special logic. Comments may be attached
54 # to Messages or Terms if they are followed immediately by them.
55 # However they should parse as standalone when they're followed by
56 # Junk. Consequently, we only attach Comments once we know that the
57 # Message or the Term parsed successfully.
58 if isinstance(entry, ast.Comment) and len(blank_lines) == 0 \
59 and ps.current_char:
60 # Stash the comment and decide what to do with it
61 # in the next pass.
62 last_comment = entry
63 continue
64
65 if last_comment is not None:
66 if isinstance(entry, (ast.Message, ast.Term)):
67 entry.comment = last_comment
68 if self.with_spans:
69 cast(ast.Span, entry.span).start = cast(ast.Span, entry.comment.span).start
70 else:
71 entries.append(last_comment)
72 # In either case, the stashed comment has been dealt with;
73 # clear it.
74 last_comment = None
75
76 entries.append(entry)
77
78 res = ast.Resource(entries)
79
80 if self.with_spans:
81 res.add_span(0, ps.index)
82
83 return res
84
85 def parse_entry(self, source: str) -> ast.EntryType:
86 """Parse the first :class:`.ast.Entry` in source.
87
88 Skip all encountered comments and start parsing at the first :class:`.ast.Message`
89 or :class:`.ast.Term` start. Return :class:`.ast.Junk` if the parsing is not successful.
90
91 Preceding comments are ignored unless they contain syntax errors
92 themselves, in which case :class:`.ast.Junk` for the invalid comment is returned.
93 """
94 ps = FluentParserStream(source)
95 ps.skip_blank_block()
96
97 while ps.current_char == '#':
98 skipped = self.get_entry_or_junk(ps)
99 if isinstance(skipped, ast.Junk):
100 # Don't skip Junk comments.
101 return skipped
102 ps.skip_blank_block()
103
104 return self.get_entry_or_junk(ps)
105
106 def get_entry_or_junk(self, ps: FluentParserStream) -> ast.EntryType:
107 entry_start_pos = ps.index
108
109 try:
110 entry = self.get_entry(ps)
111 ps.expect_line_end()
112 return entry
113 except ParseError as err:
114 error_index = ps.index
115 ps.skip_to_next_entry_start(entry_start_pos)
116 next_entry_start = ps.index
117 if next_entry_start < error_index:
118 # The position of the error must be inside of the Junk's span.
119 error_index = next_entry_start
120
121 # Create a Junk instance
122 slice = ps.string[entry_start_pos:next_entry_start]
123 junk = ast.Junk(slice)
124 if self.with_spans:
125 junk.add_span(entry_start_pos, next_entry_start)
126 annot = ast.Annotation(err.code, list(err.args) if err.args else None, err.message)
127 annot.add_span(error_index, error_index)
128 junk.add_annotation(annot)
129 return junk
130
131 def get_entry(self, ps: FluentParserStream) -> ast.EntryType:
132 if ps.current_char == '#':
133 return self.get_comment(ps)
134
135 if ps.current_char == '-':
136 return self.get_term(ps)
137
138 if ps.is_identifier_start():
139 return self.get_message(ps)
140
141 raise ParseError('E0002')
142
143 @with_span
144 def get_comment(self, ps: FluentParserStream) -> Union[ast.Comment, ast.GroupComment, ast.ResourceComment]:
145 # 0 - comment
146 # 1 - group comment
147 # 2 - resource comment
148 level = -1
149 content = ''
150
151 while True:
152 i = -1
153 while ps.current_char == '#' \
154 and (i < (2 if level == -1 else level)):
155 ps.next()
156 i += 1
157
158 if level == -1:
159 level = i
160
161 if ps.current_char != EOL:
162 ps.expect_char(' ')
163 ch = ps.take_char(lambda x: x != EOL)
164 while ch:
165 content += ch
166 ch = ps.take_char(lambda x: x != EOL)
167
168 if ps.is_next_line_comment(level=level):
169 content += cast(str, ps.current_char)
170 ps.next()
171 else:
172 break
173
174 if level == 0:
175 return ast.Comment(content)
176 elif level == 1:
177 return ast.GroupComment(content)
178 elif level == 2:
179 return ast.ResourceComment(content)
180
181 # never happens if ps.current_char == '#' when called
182 return cast(ast.Comment, None)
183
184 @with_span
185 def get_message(self, ps: FluentParserStream) -> ast.Message:
186 id = self.get_identifier(ps)
187 ps.skip_blank_inline()
188 ps.expect_char('=')
189
190 value = self.maybe_get_pattern(ps)
191 attrs = self.get_attributes(ps)
192
193 if value is None and len(attrs) == 0:
194 raise ParseError('E0005', id.name)
195
196 return ast.Message(id, value, attrs)
197
198 @with_span
199 def get_term(self, ps: FluentParserStream) -> ast.Term:
200 ps.expect_char('-')
201 id = self.get_identifier(ps)
202
203 ps.skip_blank_inline()
204 ps.expect_char('=')
205
206 value = self.maybe_get_pattern(ps)
207 if value is None:
208 raise ParseError('E0006', id.name)
209
210 attrs = self.get_attributes(ps)
211 return ast.Term(id, value, attrs)
212
213 @with_span
214 def get_attribute(self, ps: FluentParserStream) -> ast.Attribute:
215 ps.expect_char('.')
216
217 key = self.get_identifier(ps)
218
219 ps.skip_blank_inline()
220 ps.expect_char('=')
221
222 value = self.maybe_get_pattern(ps)
223 if value is None:
224 raise ParseError('E0012')
225
226 return ast.Attribute(key, value)
227
228 def get_attributes(self, ps: FluentParserStream) -> List[ast.Attribute]:
229 attrs: List[ast.Attribute] = []
230 ps.peek_blank()
231
232 while ps.is_attribute_start():
233 ps.skip_to_peek()
234 attr = self.get_attribute(ps)
235 attrs.append(attr)
236 ps.peek_blank()
237
238 return attrs
239
240 @with_span
241 def get_identifier(self, ps: FluentParserStream) -> ast.Identifier:
242 name = ps.take_id_start()
243 if name is None:
244 raise ParseError('E0004', 'a-zA-Z')
245
246 ch = ps.take_id_char()
247 while ch:
248 name += ch
249 ch = ps.take_id_char()
250
251 return ast.Identifier(name)
252
253 def get_variant_key(self, ps: FluentParserStream) -> Union[ast.Identifier, ast.NumberLiteral]:
254 ch = ps.current_char
255
256 if ch is None:
257 raise ParseError('E0013')
258
259 cc = ord(ch)
260 if ((cc >= 48 and cc <= 57) or cc == 45): # 0-9, -
261 return self.get_number(ps)
262
263 return self.get_identifier(ps)
264
265 @with_span
266 def get_variant(self, ps: FluentParserStream, has_default: bool) -> ast.Variant:
267 default_index = False
268
269 if ps.current_char == '*':
270 if has_default:
271 raise ParseError('E0015')
272 ps.next()
273 default_index = True
274
275 ps.expect_char('[')
276 ps.skip_blank()
277
278 key = self.get_variant_key(ps)
279
280 ps.skip_blank()
281 ps.expect_char(']')
282
283 value = self.maybe_get_pattern(ps)
284 if value is None:
285 raise ParseError('E0012')
286
287 return ast.Variant(key, value, default_index)
288
289 def get_variants(self, ps: FluentParserStream) -> List[ast.Variant]:
290 variants: List[ast.Variant] = []
291 has_default = False
292
293 ps.skip_blank()
294 while ps.is_variant_start():
295 variant = self.get_variant(ps, has_default)
296
297 if variant.default:
298 has_default = True
299
300 variants.append(variant)
301 ps.expect_line_end()
302 ps.skip_blank()
303
304 if len(variants) == 0:
305 raise ParseError('E0011')
306
307 if not has_default:
308 raise ParseError('E0010')
309
310 return variants
311
312 def get_digits(self, ps: FluentParserStream) -> str:
313 num = ''
314
315 ch = ps.take_digit()
316 while ch:
317 num += ch
318 ch = ps.take_digit()
319
320 if len(num) == 0:
321 raise ParseError('E0004', '0-9')
322
323 return num
324
325 @with_span
326 def get_number(self, ps: FluentParserStream) -> ast.NumberLiteral:
327 num = ''
328
329 if ps.current_char == '-':
330 num += '-'
331 ps.next()
332
333 num += self.get_digits(ps)
334
335 if ps.current_char == '.':
336 num += '.'
337 ps.next()
338 num += self.get_digits(ps)
339
340 return ast.NumberLiteral(num)
341
342 def maybe_get_pattern(self, ps: FluentParserStream) -> Union[ast.Pattern, None]:
343 '''Parse an inline or a block Pattern, or None
344
345 maybe_get_pattern distinguishes between patterns which start on the
346 same line as the indentifier (aka inline singleline patterns and inline
347 multiline patterns), and patterns which start on a new line (aka block
348 patterns). The distinction is important for the dedentation logic: the
349 indent of the first line of a block pattern must be taken into account
350 when calculating the maximum common indent.
351 '''
352 ps.peek_blank_inline()
353 if ps.is_value_start():
354 ps.skip_to_peek()
355 return self.get_pattern(ps, is_block=False)
356
357 ps.peek_blank_block()
358 if ps.is_value_continuation():
359 ps.skip_to_peek()
360 return self.get_pattern(ps, is_block=True)
361
362 return None
363
364 @with_span
365 def get_pattern(self, ps: FluentParserStream, is_block: bool) -> ast.Pattern:
366 elements: List[Any] = []
367 if is_block:
368 # A block pattern is a pattern which starts on a new line. Measure
369 # the indent of this first line for the dedentation logic.
370 blank_start = ps.index
371 first_indent = ps.skip_blank_inline()
372 elements.append(self.Indent(first_indent, blank_start, ps.index))
373 common_indent_length = len(first_indent)
374 else:
375 # Should get fixed by the subsequent min() operation
376 common_indent_length = cast(int, float('infinity'))
377
378 while ps.current_char:
379 if ps.current_char == EOL:
380 blank_start = ps.index
381 blank_lines = ps.peek_blank_block()
382 if ps.is_value_continuation():
383 ps.skip_to_peek()
384 indent = ps.skip_blank_inline()
385 common_indent_length = min(common_indent_length, len(indent))
386 elements.append(self.Indent(blank_lines + indent, blank_start, ps.index))
387 continue
388
389 # The end condition for get_pattern's while loop is a newline
390 # which is not followed by a valid pattern continuation.
391 ps.reset_peek()
392 break
393
394 if ps.current_char == '}':
395 raise ParseError('E0027')
396
397 element: Union[ast.TextElement, ast.Placeable]
398 if ps.current_char == '{':
399 element = self.get_placeable(ps)
400 else:
401 element = self.get_text_element(ps)
402
403 elements.append(element)
404
405 dedented = self.dedent(elements, common_indent_length)
406 return ast.Pattern(dedented)
407
408 class Indent(ast.SyntaxNode):
409 def __init__(self, value: str, start: int, end: int):
410 super(FluentParser.Indent, self).__init__()
411 self.value = value
412 self.add_span(start, end)
413
414 def dedent(self,
415 elements: List[Union[ast.TextElement, ast.Placeable, Indent]],
416 common_indent: int
417 ) -> List[Union[ast.TextElement, ast.Placeable]]:
418 '''Dedent a list of elements by removing the maximum common indent from
419 the beginning of text lines. The common indent is calculated in
420 get_pattern.
421 '''
422 trimmed: List[Union[ast.TextElement, ast.Placeable]] = []
423
424 for element in elements:
425 if isinstance(element, ast.Placeable):
426 trimmed.append(element)
427 continue
428
429 if isinstance(element, self.Indent):
430 # Strip the common indent.
431 element.value = element.value[:len(element.value) - common_indent]
432 if len(element.value) == 0:
433 continue
434
435 prev = trimmed[-1] if len(trimmed) > 0 else None
436 if isinstance(prev, ast.TextElement):
437 # Join adjacent TextElements by replacing them with their sum.
438 sum = ast.TextElement(prev.value + element.value)
439 if self.with_spans:
440 sum.add_span(cast(ast.Span, prev.span).start, cast(ast.Span, element.span).end)
441 trimmed[-1] = sum
442 continue
443
444 if isinstance(element, self.Indent):
445 # If the indent hasn't been merged into a preceding
446 # TextElements, convert it into a new TextElement.
447 text_element = ast.TextElement(element.value)
448 if self.with_spans:
449 text_element.add_span(cast(ast.Span, element.span).start, cast(ast.Span, element.span).end)
450 element = text_element
451
452 trimmed.append(element)
453
454 # Trim trailing whitespace from the Pattern.
455 last_element = trimmed[-1] if len(trimmed) > 0 else None
456 if isinstance(last_element, ast.TextElement):
457 last_element.value = last_element.value.rstrip(' \n\r')
458 if last_element.value == "":
459 trimmed.pop()
460
461 return trimmed
462
463 @with_span
464 def get_text_element(self, ps: FluentParserStream) -> ast.TextElement:
465 buf = ''
466
467 while ps.current_char:
468 ch = ps.current_char
469
470 if ch == '{' or ch == '}':
471 return ast.TextElement(buf)
472
473 if ch == EOL:
474 return ast.TextElement(buf)
475
476 buf += ch
477 ps.next()
478
479 return ast.TextElement(buf)
480
481 def get_escape_sequence(self, ps: FluentParserStream) -> str:
482 next = ps.current_char
483
484 if next == '\\' or next == '"':
485 ps.next()
486 return f'\\{next}'
487
488 if next == 'u':
489 return self.get_unicode_escape_sequence(ps, next, 4)
490
491 if next == 'U':
492 return self.get_unicode_escape_sequence(ps, next, 6)
493
494 raise ParseError('E0025', next)
495
496 def get_unicode_escape_sequence(self, ps: FluentParserStream, u: str, digits: int) -> str:
497 ps.expect_char(u)
498 sequence = ''
499 for _ in range(digits):
500 ch = ps.take_hex_digit()
501 if not ch:
502 raise ParseError('E0026', f'\\{u}{sequence}{ps.current_char}')
503 sequence += ch
504
505 return f'\\{u}{sequence}'
506
507 @with_span
508 def get_placeable(self, ps: FluentParserStream) -> ast.Placeable:
509 ps.expect_char('{')
510 ps.skip_blank()
511 expression = self.get_expression(ps)
512 ps.expect_char('}')
513 return ast.Placeable(expression)
514
515 @with_span
516 def get_expression(self, ps: FluentParserStream) -> Union[ast.InlineExpression,
517 ast.Placeable,
518 ast.SelectExpression]:
519 selector = self.get_inline_expression(ps)
520
521 ps.skip_blank()
522
523 if ps.current_char == '-':
524 if ps.peek() != '>':
525 ps.reset_peek()
526 return selector
527
528 if isinstance(selector, ast.MessageReference):
529 if selector.attribute is None:
530 raise ParseError('E0016')
531 else:
532 raise ParseError('E0018')
533
534 elif (
535 isinstance(selector, ast.TermReference)
536 ):
537 if selector.attribute is None:
538 raise ParseError('E0017')
539 elif not (
540 isinstance(selector, (
541 ast.StringLiteral,
542 ast.NumberLiteral,
543 ast.VariableReference,
544 ast.FunctionReference,
545 ))
546 ):
547 raise ParseError('E0029')
548
549 ps.next()
550 ps.next()
551
552 ps.skip_blank_inline()
553 ps.expect_line_end()
554
555 variants = self.get_variants(ps)
556 return ast.SelectExpression(selector, variants)
557
558 if (
559 isinstance(selector, ast.TermReference)
560 and selector.attribute is not None
561 ):
562 raise ParseError('E0019')
563
564 return selector
565
566 @with_span
567 def get_inline_expression(self, ps: FluentParserStream) -> Union[ast.InlineExpression, ast.Placeable]:
568 if ps.current_char == '{':
569 return self.get_placeable(ps)
570
571 if ps.is_number_start():
572 return self.get_number(ps)
573
574 if ps.current_char == '"':
575 return self.get_string(ps)
576
577 if ps.current_char == '$':
578 ps.next()
579 id = self.get_identifier(ps)
580 return ast.VariableReference(id)
581
582 if ps.current_char == '-':
583 ps.next()
584 id = self.get_identifier(ps)
585 attribute = None
586 if ps.current_char == '.':
587 ps.next()
588 attribute = self.get_identifier(ps)
589 arguments = None
590 ps.peek_blank()
591 if ps.current_peek == '(':
592 ps.skip_to_peek()
593 arguments = self.get_call_arguments(ps)
594 return ast.TermReference(id, attribute, arguments)
595
596 if ps.is_identifier_start():
597 id = self.get_identifier(ps)
598 ps.peek_blank()
599
600 if ps.current_peek == '(':
601 # It's a Function. Ensure it's all upper-case.
602 if not re.match('^[A-Z][A-Z0-9_-]*$', id.name):
603 raise ParseError('E0008')
604 ps.skip_to_peek()
605 args = self.get_call_arguments(ps)
606 return ast.FunctionReference(id, args)
607
608 attribute = None
609 if ps.current_char == '.':
610 ps.next()
611 attribute = self.get_identifier(ps)
612
613 return ast.MessageReference(id, attribute)
614
615 raise ParseError('E0028')
616
617 @with_span
618 def get_call_argument(self,
619 ps: FluentParserStream
620 ) -> Union[ast.InlineExpression, ast.NamedArgument, ast.Placeable]:
621 exp = self.get_inline_expression(ps)
622
623 ps.skip_blank()
624
625 if ps.current_char != ':':
626 return exp
627
628 if isinstance(exp, ast.MessageReference) and exp.attribute is None:
629 ps.next()
630 ps.skip_blank()
631
632 value = self.get_literal(ps)
633 return ast.NamedArgument(exp.id, value)
634
635 raise ParseError('E0009')
636
637 @with_span
638 def get_call_arguments(self, ps: FluentParserStream) -> ast.CallArguments:
639 positional: List[Union[ast.InlineExpression, ast.Placeable]] = []
640 named: List[ast.NamedArgument] = []
641 argument_names: Set[str] = set()
642
643 ps.expect_char('(')
644 ps.skip_blank()
645
646 while True:
647 if ps.current_char == ')':
648 break
649
650 arg = self.get_call_argument(ps)
651 if isinstance(arg, ast.NamedArgument):
652 if arg.name.name in argument_names:
653 raise ParseError('E0022')
654 named.append(arg)
655 argument_names.add(arg.name.name)
656 elif len(argument_names) > 0:
657 raise ParseError('E0021')
658 else:
659 positional.append(arg)
660
661 ps.skip_blank()
662
663 if ps.current_char == ',':
664 ps.next()
665 ps.skip_blank()
666 continue
667
668 break
669
670 ps.expect_char(')')
671 return ast.CallArguments(positional, named)
672
673 @with_span
674 def get_string(self, ps: FluentParserStream) -> ast.StringLiteral:
675 value = ''
676
677 ps.expect_char('"')
678
679 while True:
680 ch = ps.take_char(lambda x: x != '"' and x != EOL)
681 if not ch:
682 break
683 if ch == '\\':
684 value += self.get_escape_sequence(ps)
685 else:
686 value += ch
687
688 if ps.current_char == EOL:
689 raise ParseError('E0020')
690
691 ps.expect_char('"')
692
693 return ast.StringLiteral(value)
694
695 @with_span
696 def get_literal(self, ps: FluentParserStream) -> Union[ast.NumberLiteral, ast.StringLiteral]:
697 if ps.is_number_start():
698 return self.get_number(ps)
699 if ps.current_char == '"':
700 return self.get_string(ps)
701 raise ParseError('E0014')