-
Notifications
You must be signed in to change notification settings - Fork 33
/
python.gram
2438 lines (2149 loc) · 85.1 KB
/
python.gram
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# PEG grammar for Python
@class PythonParser
@subheader'''
import enum
import io
import itertools
import os
import sys
import token
from typing import (
Any, Callable, Iterator, List, Literal, NoReturn, Sequence, Tuple, TypeVar, Union
)
from pegen.tokenizer import Tokenizer
# Singleton ast nodes, created once for efficiency
Load = ast.Load()
Store = ast.Store()
Del = ast.Del()
Node = TypeVar("Node")
FC = TypeVar("FC", ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
EXPR_NAME_MAPPING = {
ast.Attribute: "attribute",
ast.Subscript: "subscript",
ast.Starred: "starred",
ast.Name: "name",
ast.List: "list",
ast.Tuple: "tuple",
ast.Lambda: "lambda",
ast.Call: "function call",
ast.BoolOp: "expression",
ast.BinOp: "expression",
ast.UnaryOp: "expression",
ast.GeneratorExp: "generator expression",
ast.Yield: "yield expression",
ast.YieldFrom: "yield expression",
ast.Await: "await expression",
ast.ListComp: "list comprehension",
ast.SetComp: "set comprehension",
ast.DictComp: "dict comprehension",
ast.Dict: "dict literal",
ast.Set: "set display",
ast.JoinedStr: "f-string expression",
ast.FormattedValue: "f-string expression",
ast.Compare: "comparison",
ast.IfExp: "conditional expression",
ast.NamedExpr: "named expression",
}
def parse_file(
path: str,
py_version: Optional[tuple]=None,
token_stream_factory: Optional[
Callable[[Callable[[], str]], Iterator[tokenize.TokenInfo]]
] = None,
verbose:bool = False,
) -> ast.Module:
"""Parse a file."""
with open(path) as f:
tok_stream = (
token_stream_factory(f.readline)
if token_stream_factory else
tokenize.generate_tokens(f.readline)
)
tokenizer = Tokenizer(tok_stream, verbose=verbose, path=path)
parser = PythonParser(
tokenizer,
verbose=verbose,
filename=os.path.basename(path),
py_version=py_version
)
return parser.parse("file")
def parse_string(
source: str,
mode: Union[Literal["eval"], Literal["exec"]],
py_version: Optional[tuple]=None,
token_stream_factory: Optional[
Callable[[Callable[[], str]], Iterator[tokenize.TokenInfo]]
] = None,
verbose:bool = False,
) -> Any:
"""Parse a string."""
tok_stream = (
token_stream_factory(io.StringIO(source).readline)
if token_stream_factory else
tokenize.generate_tokens(io.StringIO(source).readline)
)
tokenizer = Tokenizer(tok_stream, verbose=verbose)
parser = PythonParser(tokenizer, verbose=verbose, py_version=py_version)
return parser.parse(mode if mode == "eval" else "file")
class Target(enum.Enum):
FOR_TARGETS = enum.auto()
STAR_TARGETS = enum.auto()
DEL_TARGETS = enum.auto()
class Parser(Parser):
#: Name of the source file, used in error reports
filename : str
def __init__(self,
tokenizer: Tokenizer, *,
verbose: bool = False,
filename: str = "<unknown>",
py_version: Optional[tuple] = None,
) -> None:
super().__init__(tokenizer, verbose=verbose)
self.filename = filename
self.py_version = min(py_version, sys.version_info) if py_version else sys.version_info
def parse(self, rule: str, call_invalid_rules: bool = False) -> Optional[ast.AST]:
old = self.call_invalid_rules
self.call_invalid_rules = call_invalid_rules
res = getattr(self, rule)()
if res is None:
# Grab the last token that was parsed in the first run to avoid
# polluting a generic error reports with progress made by invalid rules.
last_token = self._tokenizer.diagnose()
if not call_invalid_rules:
self.call_invalid_rules = True
# Reset the parser cache to be able to restart parsing from the
# beginning.
self._reset(0) # type: ignore
self._cache.clear()
res = getattr(self, rule)()
self.raise_raw_syntax_error("invalid syntax", last_token.start, last_token.end)
return res
def check_version(self, min_version: Tuple[int, ...], error_msg: str, node: Node) -> Node:
"""Check that the python version is high enough for a rule to apply.
"""
if self.py_version >= min_version:
return node
else:
raise SyntaxError(
f"{error_msg} is only supported in Python {min_version} and above."
)
def raise_indentation_error(self, msg: str) -> None:
"""Raise an indentation error."""
last_token = self._tokenizer.diagnose()
args = (self.filename, last_token.start[0], last_token.start[1] + 1, last_token.line)
if sys.version_info >= (3, 10):
args += (last_token.end[0], last_token.end[1] + 1)
raise IndentationError(msg, args)
def get_expr_name(self, node) -> str:
"""Get a descriptive name for an expression."""
# See https://github.com/python/cpython/blob/master/Parser/pegen.c#L161
assert node is not None
node_t = type(node)
if node_t is ast.Constant:
v = node.value
if v is Ellipsis:
return "ellipsis"
elif v is None:
return str(v)
# Avoid treating 1 as True through == comparison
elif v is True:
return str(v)
elif v is False:
return str(v)
else:
return "literal"
try:
return EXPR_NAME_MAPPING[node_t]
except KeyError:
raise ValueError(
f"unexpected expression in assignment {type(node).__name__} "
f"(line {node.lineno})."
)
def get_invalid_target(self, target: Target, node: Optional[ast.AST]) -> Optional[ast.AST]:
"""Get the meaningful invalid target for different assignment type."""
if node is None:
return None
# We only need to visit List and Tuple nodes recursively as those
# are the only ones that can contain valid names in targets when
# they are parsed as expressions. Any other kind of expression
# that is a container (like Sets or Dicts) is directly invalid and
# we do not need to visit it recursively.
if isinstance(node, (ast.List, ast.Tuple)):
for e in node.elts:
if (inv := self.get_invalid_target(target, e)) is not None:
return inv
elif isinstance(node, ast.Starred):
if target is Target.DEL_TARGETS:
return node
return self.get_invalid_target(target, node.value)
elif isinstance(node, ast.Compare):
# This is needed, because the `a in b` in `for a in b` gets parsed
# as a comparison, and so we need to search the left side of the comparison
# for invalid targets.
if target is Target.FOR_TARGETS:
if isinstance(node.ops[0], ast.In):
return self.get_invalid_target(target, node.left)
return None
return node
elif isinstance(node, (ast.Name, ast.Subscript, ast.Attribute)):
return None
else:
return node
def set_expr_context(self, node, context):
"""Set the context (Load, Store, Del) of an ast node."""
node.ctx = context
return node
def ensure_real(self, number: tokenize.TokenInfo) -> float:
value = ast.literal_eval(number.string)
if type(value) is complex:
self.raise_syntax_error_known_location("real number required in complex literal", number)
return value
def ensure_imaginary(self, number: tokenize.TokenInfo) -> complex:
value = ast.literal_eval(number.string)
if type(value) is not complex:
self.raise_syntax_error_known_location("imaginary number required in complex literal", number)
return value
def check_fstring_conversion(self, mark: tokenize.TokenInfo, name: tokenize.TokenInfo) -> tokenize.TokenInfo:
if mark.lineno != name.lineno or mark.col_offset != name.col_offset:
self.raise_syntax_error_known_range(
"f-string: conversion type must come right after the exclamanation mark",
mark,
name
)
s = name.string
if len(s) > 1 or s not in ("s", "r", "a"):
self.raise_syntax_error_known_location(
f"f-string: invalid conversion character '{s}': expected 's', 'r', or 'a'",
name,
)
return name
def _concat_strings_in_constant(self, parts) -> Union[str, bytes]:
s = ast.literal_eval(parts[0].string)
for ss in parts[1:]:
s += ast.literal_eval(ss.string)
args = dict(
value=s,
lineno=parts[0].start[0],
col_offset=parts[0].start[1],
end_lineno=parts[-1].end[0],
end_col_offset=parts[0].end[1],
)
if parts[0].string.startswith("u"):
args["kind"] = "u"
return ast.Constant(**args)
def concatenate_strings(self, parts):
"""Concatenate multiple tokens and ast.JoinedStr"""
# Get proper start and stop
start = end = None
if isinstance(parts[0], ast.JoinedStr):
start = parts[0].lineno, parts[0].col_offset
if isinstance(parts[-1], ast.JoinedStr):
end = parts[-1].end_lineno, parts[-1].end_col_offset
# Combine the different parts
seen_joined = False
values = []
ss = []
for p in parts:
if isinstance(p, ast.JoinedStr):
seen_joined = True
if ss:
values.append(self._concat_strings_in_constant(ss))
ss.clear()
values.extend(p.values)
else:
ss.append(p)
if ss:
values.append(self._concat_strings_in_constant(ss))
consolidated = []
for p in values:
if consolidated and isinstance(consolidated[-1], ast.Constant) and isinstance(p, ast.Constant):
consolidated[-1].value += p.value
consolidated[-1].end_lineno = p.end_lineno
consolidated[-1].end_col_offset = p.end_col_offset
else:
consolidated.append(p)
if not seen_joined and len(values) == 1 and isinstance(values[0], ast.Constant):
return values[0]
else:
return ast.JoinedStr(
values=consolidated,
lineno=start[0] if start else values[0].lineno,
col_offset=start[1] if start else values[0].col_offset,
end_lineno=end[0] if end else values[-1].end_lineno,
end_col_offset=end[1] if end else values[-1].end_col_offset,
)
def generate_ast_for_string(self, tokens):
"""Generate AST nodes for strings."""
err_args = None
line_offset = tokens[0].start[0]
line = line_offset
col_offset = 0
source = "(\\n"
for t in tokens:
n_line = t.start[0] - line
if n_line:
col_offset = 0
source += """\\n""" * n_line + ' ' * (t.start[1] - col_offset) + t.string
line, col_offset = t.end
source += "\\n)"
try:
m = ast.parse(source)
except SyntaxError as err:
args = (err.filename, err.lineno + line_offset - 2, err.offset, err.text)
if sys.version_info >= (3, 10):
args += (err.end_lineno + line_offset - 2, err.end_offset)
err_args = (err.msg, args)
# Ensure we do not keep the frame alive longer than necessary
# by explicitly deleting the error once we got what we needed out
# of it
del err
# Avoid getting a triple nesting in the error report that does not
# bring anything relevant to the traceback.
if err_args is not None:
raise SyntaxError(*err_args)
node = m.body[0].value
# Since we asked Python to parse an alterred source starting at line 2
# we alter the lineno of the returned AST to recover the right line.
# If the string start at line 1, tha AST says 2 so we need to decrement by 1
# hence the -2.
ast.increment_lineno(node, line_offset - 2)
return node
def extract_import_level(self, tokens: List[tokenize.TokenInfo]) -> int:
"""Extract the relative import level from the tokens preceding the module name.
'.' count for one and '...' for 3.
"""
level = 0
for t in tokens:
if t.string == ".":
level += 1
else:
level += 3
return level
def set_decorators(self,
target: FC,
decorators: list
) -> FC:
"""Set the decorators on a function or class definition."""
target.decorator_list = decorators
return target
def get_comparison_ops(self, pairs):
return [op for op, _ in pairs]
def get_comparators(self, pairs):
return [comp for _, comp in pairs]
def set_arg_type_comment(self, arg, type_comment):
if type_comment or sys.version_info < (3, 9):
arg.type_comment = type_comment
return arg
def make_arguments(self,
pos_only: Optional[List[Tuple[ast.arg, None]]],
pos_only_with_default: List[Tuple[ast.arg, Any]],
param_no_default: Optional[List[Tuple[ast.arg, None]]],
param_default: Optional[List[Tuple[ast.arg, Any]]],
after_star: Optional[Tuple[Optional[ast.arg], List[Tuple[ast.arg, Any]], Optional[ast.arg]]]
) -> ast.arguments:
"""Build a function definition arguments."""
defaults = (
[d for _, d in pos_only_with_default if d is not None]
if pos_only_with_default else
[]
)
defaults += (
[d for _, d in param_default if d is not None]
if param_default else
[]
)
pos_only = pos_only or pos_only_with_default
# Because we need to combine pos only with and without default even
# the version with no default is a tuple
pos_only = [p for p, _ in pos_only]
params = (param_no_default or []) + ([p for p, _ in param_default] if param_default else [])
# If after_star is None, make a default tuple
after_star = after_star or (None, [], None)
return ast.arguments(
posonlyargs=pos_only,
args=params,
defaults=defaults,
vararg=after_star[0],
kwonlyargs=[p for p, _ in after_star[1]],
kw_defaults=[d for _, d in after_star[1]],
kwarg=after_star[2]
)
def _build_syntax_error(
self,
message: str,
start: Optional[Tuple[int, int]] = None,
end: Optional[Tuple[int, int]] = None
) -> SyntaxError:
line_from_token = start is None and end is None
if start is None or end is None:
tok = self._tokenizer.diagnose()
start = start or tok.start
end = end or tok.end
if line_from_token:
line = tok.line
else:
# End is used only to get the proper text
line = "\\n".join(
self._tokenizer.get_lines(list(range(start[0], end[0] + 1)))
)
# tokenize.py index column offset from 0 while Cpython index column
# offset at 1 when reporting SyntaxError, so we need to increment
# the column offset when reporting the error.
args = (self.filename, start[0], start[1] + 1, line)
if sys.version_info >= (3, 10):
args += (end[0], end[1] + 1)
return SyntaxError(message, args)
def raise_raw_syntax_error(
self,
message: str,
start: Optional[Tuple[int, int]] = None,
end: Optional[Tuple[int, int]] = None
) -> NoReturn:
raise self._build_syntax_error(message, start, end)
def make_syntax_error(self, message: str) -> SyntaxError:
return self._build_syntax_error(message)
def expect_forced(self, res: Any, expectation: str) -> Optional[tokenize.TokenInfo]:
if res is None:
last_token = self._tokenizer.diagnose()
end = last_token.start
if (
sys.version_info >= (3, 12)
or (
sys.version_info >= (3, 11)
and last_token.type != 4
)
): # i.e. not a \n
end = last_token.end
self.raise_raw_syntax_error(
f"expected {expectation}", last_token.start, end
)
return res
def raise_syntax_error(self, message: str) -> NoReturn:
"""Raise a syntax error."""
tok = self._tokenizer.diagnose()
raise self._build_syntax_error(
message, tok.start,
tok.end if sys.version_info >= (3, 12) or tok.type != 4 else tok.start
)
def raise_syntax_error_known_location(
self, message: str, node: Union[ast.AST, tokenize.TokenInfo]
) -> NoReturn:
"""Raise a syntax error that occured at a given AST node."""
if isinstance(node, tokenize.TokenInfo):
start = node.start
end = node.end
else:
start = node.lineno, node.col_offset
end = node.end_lineno, node.end_col_offset
raise self._build_syntax_error(message, start, end)
def raise_syntax_error_known_range(
self,
message: str,
start_node: Union[ast.AST, tokenize.TokenInfo],
end_node: Union[ast.AST, tokenize.TokenInfo]
) -> NoReturn:
if isinstance(start_node, tokenize.TokenInfo):
start = start_node.start
else:
start = start_node.lineno, start_node.col_offset
if isinstance(end_node, tokenize.TokenInfo):
end = end_node.end
else:
end = end_node.end_lineno, end_node.end_col_offset
raise self._build_syntax_error(message, start, end)
def raise_syntax_error_starting_from(
self,
message: str,
start_node: Union[ast.AST, tokenize.TokenInfo]
) -> NoReturn:
if isinstance(start_node, tokenize.TokenInfo):
start = start_node.start
else:
start = start_node.lineno, start_node.col_offset
last_token = self._tokenizer.diagnose()
raise self._build_syntax_error(message, start, last_token.start)
def raise_syntax_error_invalid_target(
self, target: Target, node: Optional[ast.AST]
) -> None:
invalid_target = self.get_invalid_target(target, node)
if invalid_target is None:
return None
if target in (Target.STAR_TARGETS, Target.FOR_TARGETS):
msg = f"cannot assign to {self.get_expr_name(invalid_target)}"
else:
msg = f"cannot delete {self.get_expr_name(invalid_target)}"
self.raise_syntax_error_known_location(msg, invalid_target)
def raise_syntax_error_on_next_token(self, message: str) -> NoReturn:
next_token = self._tokenizer.peek()
raise self._build_syntax_error(message, next_token.start, next_token.end)
'''
# STARTING RULES
# ==============
start: file
file[ast.Module]: a=[statements] ENDMARKER { ast.Module(body=a or [], type_ignores=[]) }
interactive[ast.Interactive]: a=statement_newline { ast.Interactive(body=a) }
eval[ast.Expression]: a=expressions NEWLINE* ENDMARKER { ast.Expression(body=a) }
func_type[ast.FunctionType]: '(' a=[type_expressions] ')' '->' b=expression NEWLINE* ENDMARKER { ast.FunctionType(argtypes=a, returns=b) }
fstring[ast.Expr]: star_expressions
# GENERAL STATEMENTS
# ==================
statements[list]: a=statement+ { list(itertools.chain.from_iterable(a)) }
statement[list]: a=compound_stmt { [a] } | a=simple_stmts { a }
statement_newline[list]:
| a=compound_stmt NEWLINE { [a] }
| simple_stmts
| NEWLINE { [ast.Pass(LOCATIONS)] }
| ENDMARKER { None }
simple_stmts[list]:
| a=simple_stmt !';' NEWLINE { [a] } # Not needed, there for speedup
| a=';'.simple_stmt+ [';'] NEWLINE { a }
# NOTE: assignment MUST precede expression, else parsing a simple assignment
# will throw a SyntaxError.
simple_stmt (memo):
| assignment
| &"type" type_alias
| e=star_expressions { ast.Expr(value=e, LOCATIONS) }
| &'return' return_stmt
| &('import' | 'from') import_stmt
| &'raise' raise_stmt
| 'pass' { ast.Pass(LOCATIONS) }
| &'del' del_stmt
| &'yield' yield_stmt
| &'assert' assert_stmt
| 'break' { ast.Break(LOCATIONS) }
| 'continue' { ast.Continue(LOCATIONS) }
| &'global' global_stmt
| &'nonlocal' nonlocal_stmt
compound_stmt:
| &('def' | '@' | 'async') function_def
| &'if' if_stmt
| &('class' | '@') class_def
| &('with' | 'async') with_stmt
| &('for' | 'async') for_stmt
| &'try' try_stmt
| &'while' while_stmt
| match_stmt
# SIMPLE STATEMENTS
# =================
# NOTE: annotated_rhs may start with 'yield'; yield_expr must start with 'yield'
assignment:
| a=NAME ':' b=expression c=['=' d=annotated_rhs { d }] {
self.check_version(
(3, 6),
"Variable annotation syntax is",
ast.AnnAssign(
target=ast.Name(
id=a.string,
ctx=Store,
lineno=a.start[0],
col_offset=a.start[1],
end_lineno=a.end[0],
end_col_offset=a.end[1],
),
annotation=b,
value=c,
simple=1,
LOCATIONS,
)
) }
| a=('(' b=single_target ')' { b }
| single_subscript_attribute_target) ':' b=expression c=['=' d=annotated_rhs { d }] {
self.check_version(
(3, 6),
"Variable annotation syntax is",
ast.AnnAssign(
target=a,
annotation=b,
value=c,
simple=0,
LOCATIONS,
)
)
}
| a=(z=star_targets '=' { z })+ b=(yield_expr | star_expressions) !'=' tc=[TYPE_COMMENT] {
ast.Assign(targets=a, value=b, type_comment=tc, LOCATIONS)
}
| a=single_target b=augassign ~ c=(yield_expr | star_expressions) {
ast.AugAssign(target = a, op=b, value=c, LOCATIONS)
}
| invalid_assignment
annotated_rhs: yield_expr | star_expressions
augassign:
| '+=' { ast.Add() }
| '-=' { ast.Sub() }
| '*=' { ast.Mult() }
| '@=' { self.check_version((3, 5), "The '@' operator is", ast.MatMult()) }
| '/=' { ast.Div() }
| '%=' { ast.Mod() }
| '&=' { ast.BitAnd() }
| '|=' { ast.BitOr() }
| '^=' { ast.BitXor() }
| '<<=' { ast.LShift() }
| '>>=' { ast.RShift() }
| '**=' { ast.Pow() }
| '//=' { ast.FloorDiv() }
return_stmt[ast.Return]:
| 'return' a=[star_expressions] { ast.Return(value=a, LOCATIONS) }
raise_stmt[ast.Raise]:
| 'raise' a=expression b=['from' z=expression { z }] { ast.Raise(exc=a, cause=b, LOCATIONS) }
| 'raise' { ast.Raise(exc=None, cause=None, LOCATIONS) }
global_stmt[ast.Global]: 'global' a=','.NAME+ {
ast.Global(names=[n.string for n in a], LOCATIONS)
}
nonlocal_stmt[ast.Nonlocal]: 'nonlocal' a=','.NAME+ {
ast.Nonlocal(names=[n.string for n in a], LOCATIONS)
}
del_stmt[ast.Delete]:
| 'del' a=del_targets &(';' | NEWLINE) { ast.Delete(targets=a, LOCATIONS) }
| invalid_del_stmt
yield_stmt[ast.Expr]: y=yield_expr { ast.Expr(value=y, LOCATIONS) }
assert_stmt[ast.Assert]: 'assert' a=expression b=[',' z=expression { z }] {
ast.Assert(test=a, msg=b, LOCATIONS)
}
import_stmt[ast.Import]:
| invalid_import
| import_name
| import_from
# Import statements
# -----------------
import_name[ast.Import]: 'import' a=dotted_as_names { ast.Import(names=a, LOCATIONS) }
# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
import_from[ast.ImportFrom]:
| 'from' a=('.' | '...')* b=dotted_name 'import' c=import_from_targets {
ast.ImportFrom(module=b, names=c, level=self.extract_import_level(a), LOCATIONS)
}
| 'from' a=('.' | '...')+ 'import' b=import_from_targets {
ast.ImportFrom(names=b, level=self.extract_import_level(a), LOCATIONS)
if sys.version_info >= (3, 9) else
ast.ImportFrom(module=None, names=b, level=self.extract_import_level(a), LOCATIONS)
}
import_from_targets[List[ast.alias]]:
| '(' a=import_from_as_names [','] ')' { a }
| import_from_as_names !','
| '*' { [ast.alias(name="*", asname=None, LOCATIONS)] }
| invalid_import_from_targets
import_from_as_names[List[ast.alias]]:
| a=','.import_from_as_name+ { a }
import_from_as_name[ast.alias]:
| a=NAME b=['as' z=NAME { z.string }] { ast.alias(name=a.string, asname=b, LOCATIONS) }
dotted_as_names[List[ast.alias]]:
| a=','.dotted_as_name+ { a }
dotted_as_name[ast.alias]:
| a=dotted_name b=['as' z=NAME { z.string }] { ast.alias(name=a, asname=b, LOCATIONS) }
dotted_name[str]:
| a=dotted_name '.' b=NAME { a + "." + b.string }
| a=NAME { a.string }
# COMPOUND STATEMENTS
# ===================
# Common elements
# ---------------
block[list] (memo):
| NEWLINE INDENT a=statements DEDENT { a }
| simple_stmts
| invalid_block
decorators: decorator+
decorator:
| a=('@' f=dec_maybe_call NEWLINE { f }) { a }
| a=('@' f=named_expression NEWLINE { f }) {
self.check_version((3, 9), "Generic decorator are", a)
}
dec_maybe_call:
| dn=dec_primary '(' z=[arguments] ')' {
ast.Call(func=dn, args=z[0] if z else [], keywords=z[1] if z else [], LOCATIONS)
}
| dec_primary
dec_primary:
| a=dec_primary '.' b=NAME { ast.Attribute(value=a, attr=b.string, ctx=Load, LOCATIONS) }
| a=NAME { ast.Name(id=a.string, ctx=Load, LOCATIONS) }
# Class definitions
# -----------------
class_def[ast.ClassDef]:
| a=decorators b=class_def_raw { self.set_decorators(b, a) }
| class_def_raw
class_def_raw[ast.ClassDef]:
| invalid_class_def_raw
| 'class' a=NAME t=[type_params] b=['(' z=[arguments] ')' { z }] &&':' c=block {
(
ast.ClassDef(
a.string,
bases=b[0] if b else [],
keywords=b[1] if b else [],
body=c,
decorator_list=[],
type_params=t or [],
LOCATIONS,
)
if sys.version_info >= (3, 12) else
ast.ClassDef(
a.string,
bases=b[0] if b else [],
keywords=b[1] if b else [],
body=c,
decorator_list=[],
LOCATIONS,
)
)
}
# Function definitions
# --------------------
function_def[Union[ast.FunctionDef, ast.AsyncFunctionDef]]:
| d=decorators f=function_def_raw { self.set_decorators(f, d) }
| f=function_def_raw {self.set_decorators(f, [])}
function_def_raw[Union[ast.FunctionDef, ast.AsyncFunctionDef]]:
| invalid_def_raw
| 'def' n=NAME t=[type_params] &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
(
ast.FunctionDef(
name=n.string,
args=params or self.make_arguments(None, [], None, [], None),
returns=a,
body=b,
type_comment=tc,
type_params=t or [],
LOCATIONS,
) if sys.version_info >= (3, 12) else
ast.FunctionDef(
name=n.string,
args=params or self.make_arguments(None, [], None, [], None),
returns=a,
body=b,
type_comment=tc,
LOCATIONS,
)
)
}
| 'async' 'def' n=NAME t=[type_params] &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
(
self.check_version(
(3, 5),
"Async functions are",
ast.AsyncFunctionDef(
name=n.string,
args=params or self.make_arguments(None, [], None, [], None),
returns=a,
body=b,
type_comment=tc,
type_params=t or [],
LOCATIONS,
)
) if sys.version_info >= (3, 12) else
self.check_version(
(3, 5),
"Async functions are",
ast.AsyncFunctionDef(
name=n.string,
args=params or self.make_arguments(None, [], None, [], None),
returns=a,
body=b,
type_comment=tc,
LOCATIONS,
)
)
)
}
# Function parameters
# -------------------
params:
| invalid_parameters
| parameters
parameters[ast.arguments]:
| a=slash_no_default b=param_no_default* c=param_with_default* d=[star_etc] {
self.check_version(
(3, 8), "Positional only arguments are", self.make_arguments(a, [], b, c, d)
)
}
| a=slash_with_default b=param_with_default* c=[star_etc] {
self.check_version(
(3, 8),
"Positional only arguments are",
self.make_arguments(None, a, None, b, c),
)
}
| a=param_no_default+ b=param_with_default* c=[star_etc] {
self.make_arguments(None, [], a, b, c)
}
| a=param_with_default+ b=[star_etc] {
self.make_arguments(None, [], None, a, b)
}
| a=star_etc { self.make_arguments(None, [], None, None, a) }
# Some duplication here because we can't write (',' | &')'),
# which is because we don't support empty alternatives (yet).
#
slash_no_default[List[Tuple[ast.arg, None]]]:
| a=param_no_default+ '/' ',' { [(p, None) for p in a] }
| a=param_no_default+ '/' &')' { [(p, None) for p in a] }
slash_with_default[List[Tuple[ast.arg, Any]]]:
| a=param_no_default* b=param_with_default+ '/' ',' { ([(p, None) for p in a] if a else []) + b }
| a=param_no_default* b=param_with_default+ '/' &')' { ([(p, None) for p in a] if a else []) + b }
star_etc[Tuple[Optional[ast.arg], List[Tuple[ast.arg, Any]], Optional[ast.arg]]]:
| invalid_star_etc
| '*' a=param_no_default b=param_maybe_default* c=[kwds] { (a, b, c) }
| '*' a=param_no_default_star_annotation b=param_maybe_default* c=[kwds] { (a, b, c) }
| '*' ',' b=param_maybe_default+ c=[kwds] { (None, b, c) }
| a=kwds { (None, [], a) }
kwds[ast.arg]:
| invalid_kwds
| '**' a=param_no_default { a }
# One parameter. This *includes* a following comma and type comment.
#
# There are three styles:
# - No default
# - With default
# - Maybe with default
#
# There are two alternative forms of each, to deal with type comments:
# - Ends in a comma followed by an optional type comment
# - No comma, optional type comment, must be followed by close paren
# The latter form is for a final parameter without trailing comma.
#
param_no_default[ast.arg]:
| a=param ',' tc=TYPE_COMMENT? { self.set_arg_type_comment(a, tc) }
| a=param tc=TYPE_COMMENT? &')' { self.set_arg_type_comment(a, tc) }
param_no_default_star_annotation[ast.arg]:
| a=param_star_annotation ',' tc=TYPE_COMMENT? { self.set_arg_type_comment(a, tc) }
| a=param_star_annotation tc=TYPE_COMMENT? &')' { self.set_arg_type_comment(a, tc) }
param_with_default[Tuple[ast.arg, Any]]:
| a=param c=default ',' tc=TYPE_COMMENT? { (self.set_arg_type_comment(a, tc), c) }
| a=param c=default tc=TYPE_COMMENT? &')' { (self.set_arg_type_comment(a, tc), c) }
param_maybe_default[Tuple[ast.arg, Any]]:
| a=param c=default? ',' tc=TYPE_COMMENT? { (self.set_arg_type_comment(a, tc), c) }
| a=param c=default? tc=TYPE_COMMENT? &')' { (self.set_arg_type_comment(a, tc), c) }
param: a=NAME b=annotation? { ast.arg(arg=a.string, annotation=b, LOCATIONS) }
param_star_annotation: a=NAME b=star_annotation {
ast.arg(arg=a.string, annotations=b, LOCATIONS)
}
annotation: ':' a=expression { a }
star_annotation: ':' a=star_expression { a }
default: '=' a=expression { a } | invalid_default
# If statement
# ------------
if_stmt[ast.If]:
| invalid_if_stmt
| 'if' a=named_expression ':' b=block c=elif_stmt { ast.If(test=a, body=b, orelse=c or [], LOCATIONS) }
| 'if' a=named_expression ':' b=block c=[else_block] { ast.If(test=a, body=b, orelse=c or [], LOCATIONS) }
elif_stmt[List[ast.If]]:
| invalid_elif_stmt
| 'elif' a=named_expression ':' b=block c=elif_stmt { [ast.If(test=a, body=b, orelse=c, LOCATIONS)] }
| 'elif' a=named_expression ':' b=block c=[else_block] { [ast.If(test=a, body=b, orelse=c or [], LOCATIONS)] }
else_block[list]:
| invalid_else_stmt
| 'else' &&':' b=block { b }
# While statement
# ---------------
while_stmt[ast.While]:
| invalid_while_stmt
| 'while' a=named_expression ':' b=block c=[else_block] {
ast.While(test=a, body=b, orelse=c or [], LOCATIONS)
}
# For statement
# -------------
for_stmt[Union[ast.For, ast.AsyncFor]]:
| invalid_for_stmt
| 'for' t=star_targets 'in' ~ ex=star_expressions &&':' tc=[TYPE_COMMENT] b=block el=[else_block] {
ast.For(target=t, iter=ex, body=b, orelse=el or [], type_comment=tc, LOCATIONS) }
| 'async' 'for' t=star_targets 'in' ~ ex=star_expressions ':' tc=[TYPE_COMMENT] b=block el=[else_block] {
self.check_version(
(3, 5),
"Async for loops are",
ast.AsyncFor(target=t, iter=ex, body=b, orelse=el or [], type_comment=tc, LOCATIONS)) }
| invalid_for_target
# With statement
# --------------
with_stmt[Union[ast.With, ast.AsyncWith]]:
| invalid_with_stmt_indent
| 'with' '(' a=','.with_item+ ','? ')' ':' b=block {
self.check_version(
(3, 9),
"Parenthesized with items",
ast.With(items=a, body=b, LOCATIONS)
)
}
| 'with' a=','.with_item+ ':' tc=[TYPE_COMMENT] b=block {
ast.With(items=a, body=b, type_comment=tc, LOCATIONS)
}
| 'async' 'with' '(' a=','.with_item+ ','? ')' ':' b=block {
self.check_version(