-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.py
5446 lines (5097 loc) · 201 KB
/
parser.py
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
from __future__ import annotations
import ast
import itertools
import sys
from typing import TYPE_CHECKING, Any, cast
from peg_parser.subheader import Del, Load, Node, Parser, Store, Target, logger, memoize, memoize_left_rec
if TYPE_CHECKING:
from peg_parser.tokenize import TokenInfo
# Keywords and soft keywords are listed at the end of the parser definition.
class XonshParser(Parser):
@memoize
def file(self) -> ast.Module | None:
# file: statements? $
mark = self._mark()
if (a := self.statements(),) and (self.token("ENDMARKER")):
return ast.Module(body=a or [], type_ignores=[])
self._reset(mark)
return None
@memoize
def interactive(self) -> ast.Interactive | None:
# interactive: statement_newline
mark = self._mark()
if a := self.statement_newline():
return ast.Interactive(body=a)
self._reset(mark)
return None
@memoize
def eval(self) -> ast.Expression | None:
# eval: expressions NEWLINE* $
mark = self._mark()
if (
(a := self.expressions())
and (self.repeated(self.token, "NEWLINE"),)
and (self.token("ENDMARKER"))
):
return ast.Expression(body=a)
self._reset(mark)
return None
@memoize
def fstring(self) -> ast.JoinedStr | None:
# fstring: FSTRING_START fstring_mid* FSTRING_END
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (
(a := self.token("FSTRING_START"))
and (b := self.repeated(self.fstring_mid),)
and (self.token("FSTRING_END"))
):
return self.handle_fstring(a, b, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def statements(self) -> list[Any] | None:
# statements: statement+
mark = self._mark()
if a := self.repeated(self.statement):
return list(itertools.chain.from_iterable(a))
self._reset(mark)
return None
@memoize
def statement(self) -> list[Any] | None:
# statement: compound_stmt | simple_stmts
mark = self._mark()
if a := self.compound_stmt():
return [a]
self._reset(mark)
if a := self.simple_stmts():
return a
self._reset(mark)
return None
@memoize
def statement_newline(self) -> list[Any] | None:
# statement_newline: compound_stmt NEWLINE | simple_stmts | NEWLINE | $
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (a := self.compound_stmt()) and (self.token("NEWLINE")):
return [a]
self._reset(mark)
if simple_stmts := self.simple_stmts():
return simple_stmts
self._reset(mark)
if self.token("NEWLINE"):
return [ast.Pass(**self.span(_lnum, _col))]
self._reset(mark)
if self.token("ENDMARKER"):
return None
self._reset(mark)
return None
@memoize
def simple_stmts(self) -> list[Any] | None:
# simple_stmts: simple_stmt !';' NEWLINE | ';'.simple_stmt+ ';'? NEWLINE
mark = self._mark()
if (
(a := self.simple_stmt())
and (self.negative_lookahead(self.expect, ";"))
and (self.token("NEWLINE"))
):
return [a]
self._reset(mark)
if (
(a1 := self.gathered(self.simple_stmt, self.expect, ";"))
and (self.expect(";"),)
and (self.token("NEWLINE"))
):
return a1
self._reset(mark)
return None
@memoize
def simple_stmt(self) -> ast.stmt | None:
# simple_stmt: assignment | &"type" type_alias | star_expressions | &'return' return_stmt | &('import' | 'from') import_stmt | &'raise' raise_stmt | 'pass' | &'del' del_stmt | &'yield' yield_stmt | &'assert' assert_stmt | 'break' | 'continue' | &'global' global_stmt | &'nonlocal' nonlocal_stmt
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if assignment := self.assignment():
return assignment
self._reset(mark)
if (self.positive_lookahead(self.expect, "type")) and (type_alias := self.type_alias()):
return type_alias
self._reset(mark)
if e := self.star_expressions():
return ast.Expr(value=e, **self.span(_lnum, _col))
self._reset(mark)
if (self.positive_lookahead(self.expect, "return")) and (return_stmt := self.return_stmt()):
return return_stmt
self._reset(mark)
if (self.positive_lookahead(self._tmp_1)) and (import_stmt := self.import_stmt()):
return import_stmt
self._reset(mark)
if (self.positive_lookahead(self.expect, "raise")) and (raise_stmt := self.raise_stmt()):
return raise_stmt
self._reset(mark)
if self.expect("pass"):
return ast.Pass(**self.span(_lnum, _col))
self._reset(mark)
if (self.positive_lookahead(self.expect, "del")) and (del_stmt := self.del_stmt()):
return del_stmt
self._reset(mark)
if (self.positive_lookahead(self.expect, "yield")) and (yield_stmt := self.yield_stmt()):
return yield_stmt
self._reset(mark)
if (self.positive_lookahead(self.expect, "assert")) and (assert_stmt := self.assert_stmt()):
return assert_stmt
self._reset(mark)
if self.expect("break"):
return ast.Break(**self.span(_lnum, _col))
self._reset(mark)
if self.expect("continue"):
return ast.Continue(**self.span(_lnum, _col))
self._reset(mark)
if (self.positive_lookahead(self.expect, "global")) and (global_stmt := self.global_stmt()):
return global_stmt
self._reset(mark)
if (self.positive_lookahead(self.expect, "nonlocal")) and (nonlocal_stmt := self.nonlocal_stmt()):
return nonlocal_stmt
self._reset(mark)
return None
@memoize
def compound_stmt(self) -> Any | None:
# 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
mark = self._mark()
if (self.positive_lookahead(self._tmp_2)) and (function_def := self.function_def()):
return function_def
self._reset(mark)
if (self.positive_lookahead(self.expect, "if")) and (if_stmt := self.if_stmt()):
return if_stmt
self._reset(mark)
if (self.positive_lookahead(self._tmp_3)) and (class_def := self.class_def()):
return class_def
self._reset(mark)
if (self.positive_lookahead(self._tmp_4)) and (with_stmt := self.with_stmt()):
return with_stmt
self._reset(mark)
if (self.positive_lookahead(self._tmp_5)) and (for_stmt := self.for_stmt()):
return for_stmt
self._reset(mark)
if (self.positive_lookahead(self.expect, "try")) and (try_stmt := self.try_stmt()):
return try_stmt
self._reset(mark)
if (self.positive_lookahead(self.expect, "while")) and (while_stmt := self.while_stmt()):
return while_stmt
self._reset(mark)
if match_stmt := self.match_stmt():
return match_stmt
self._reset(mark)
return None
@memoize
def assignment(self) -> ast.stmt | None:
# assignment: NAME ':' expression ['=' annotated_rhs] | ('(' single_target ')' | single_subscript_attribute_target) ':' expression ['=' annotated_rhs] | (assignment_lhs)+ annotated_rhs !'=' type_comment_str? | single_target augassign ~ annotated_rhs | invalid_assignment
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (a := self.name()) and (self.expect(":")) and (b := self.expression()) and (c := self._tmp_6(),):
return 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,
**self.span(_lnum, _col),
)
self._reset(mark)
if (
(a1 := self._tmp_7())
and (self.expect(":"))
and (b1 := self.expression())
and (c1 := self._tmp_8(),)
):
return ast.AnnAssign(target=a1, annotation=b1, value=c1, simple=0, **self.span(_lnum, _col))
self._reset(mark)
if (
(a2 := self.repeated(self.assignment_lhs))
and (b2 := self.annotated_rhs())
and (self.negative_lookahead(self.expect, "="))
and (tc := self.type_comment_str(),)
):
return ast.Assign(targets=a2, value=b2, type_comment=tc, **self.span(_lnum, _col))
self._reset(mark)
cut = False
if (
(a3 := self.single_target())
and (b3 := self.augassign())
and (cut := True)
and (c3 := self.annotated_rhs())
):
return ast.AugAssign(target=a3, op=b3, value=c3, **self.span(_lnum, _col))
self._reset(mark)
if cut:
return None
if self.call_invalid_rules and (self.invalid_assignment()):
return None
self._reset(mark)
return None
@memoize
def assignment_lhs(self) -> ast.expr | None:
# assignment_lhs: star_targets '='
mark = self._mark()
if (z := self.star_targets()) and (self.expect("=")):
return z
self._reset(mark)
return None
@memoize
def annotated_rhs(self) -> Any | None:
# annotated_rhs: yield_expr | star_expressions
return self.seq_alts(
self.yield_expr,
self.star_expressions,
)
@memoize
def augassign(self) -> Any | None:
# augassign: '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//='
mark = self._mark()
if self.expect("+="):
return ast.Add()
self._reset(mark)
if self.expect("-="):
return ast.Sub()
self._reset(mark)
if self.expect("*="):
return ast.Mult()
self._reset(mark)
if self.expect("@="):
return ast.MatMult()
self._reset(mark)
if self.expect("/="):
return ast.Div()
self._reset(mark)
if self.expect("%="):
return ast.Mod()
self._reset(mark)
if self.expect("&="):
return ast.BitAnd()
self._reset(mark)
if self.expect("|="):
return ast.BitOr()
self._reset(mark)
if self.expect("^="):
return ast.BitXor()
self._reset(mark)
if self.expect("<<="):
return ast.LShift()
self._reset(mark)
if self.expect(">>="):
return ast.RShift()
self._reset(mark)
if self.expect("**="):
return ast.Pow()
self._reset(mark)
if self.expect("//="):
return ast.FloorDiv()
self._reset(mark)
return None
@memoize
def return_stmt(self) -> ast.Return | None:
# return_stmt: 'return' star_expressions?
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (self.expect("return")) and (a := self.star_expressions(),):
return ast.Return(value=a, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def raise_stmt(self) -> ast.Raise | None:
# raise_stmt: 'raise' expression ['from' expression] | 'raise'
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (self.expect("raise")) and (a := self.expression()) and (b := self._tmp_9(),):
return ast.Raise(exc=a, cause=b, **self.span(_lnum, _col))
self._reset(mark)
if self.expect("raise"):
return ast.Raise(exc=None, cause=None, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def global_stmt(self) -> ast.Global | None:
# global_stmt: 'global' ','.NAME+
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (self.expect("global")) and (a := self.gathered(self.name, self.expect, ",")):
return ast.Global(names=[n.string for n in a], **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def nonlocal_stmt(self) -> ast.Nonlocal | None:
# nonlocal_stmt: 'nonlocal' ','.NAME+
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (self.expect("nonlocal")) and (a := self.gathered(self.name, self.expect, ",")):
return ast.Nonlocal(names=[n.string for n in a], **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def del_stmt(self) -> ast.Delete | None:
# del_stmt: 'del' del_targets &(';' | NEWLINE) | invalid_del_stmt
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (self.expect("del")) and (a := self.del_targets()) and (self.positive_lookahead(self._tmp_10)):
return ast.Delete(targets=a, **self.span(_lnum, _col))
self._reset(mark)
if self.call_invalid_rules and (self.invalid_del_stmt()):
return None
self._reset(mark)
return None
@memoize
def yield_stmt(self) -> ast.Expr | None:
# yield_stmt: yield_expr
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if y := self.yield_expr():
return ast.Expr(value=y, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def assert_stmt(self) -> ast.Assert | None:
# assert_stmt: 'assert' expression [',' expression]
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (self.expect("assert")) and (a := self.expression()) and (b := self._tmp_11(),):
return ast.Assert(test=a, msg=b, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def import_stmt(self) -> ast.Import | ast.ImportFrom | None:
# import_stmt: invalid_import | import_name | import_from
return self.seq_alts(
self.invalid_import,
self.import_name,
self.import_from,
)
@memoize
def import_name(self) -> ast.Import | None:
# import_name: 'import' dotted_as_names
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (self.expect("import")) and (a := self.dotted_as_names()):
return ast.Import(names=a, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def import_from(self) -> ast.ImportFrom | Any | None:
# import_from: 'from' dot_or_ellipsis* dotted_name 'import' import_from_targets | 'from' dot_or_ellipsis+ 'import' import_from_targets
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (
(self.expect("from"))
and (a := self.repeated(self.dot_or_ellipsis),)
and (b := self.dotted_name())
and (self.expect("import"))
and (c := self.import_from_targets())
):
return ast.ImportFrom(
module=b, names=c, level=self.extract_import_level(a), **self.span(_lnum, _col)
)
self._reset(mark)
if (
(self.expect("from"))
and (a1 := self.repeated(self.dot_or_ellipsis))
and (self.expect("import"))
and (b1 := self.import_from_targets())
):
return ast.ImportFrom(names=b1, level=self.extract_import_level(a1), **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def dot_or_ellipsis(self) -> TokenInfo | None:
# dot_or_ellipsis: '.' | '...'
return self.seq_alts(
(self.expect, "."),
(self.expect, "..."),
)
@memoize
def import_from_targets(self) -> list[ast.alias] | None:
# import_from_targets: '(' import_from_as_names ','? ')' | import_from_as_names !',' | '*' | invalid_import_from_targets
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (
(self.expect("("))
and (a := self.import_from_as_names())
and (self.expect(","),)
and (self.expect(")"))
):
return a
self._reset(mark)
if (import_from_as_names := self.import_from_as_names()) and (
self.negative_lookahead(self.expect, ",")
):
return import_from_as_names
self._reset(mark)
if self.expect("*"):
return [ast.alias(name="*", asname=None, **self.span(_lnum, _col))]
self._reset(mark)
if self.call_invalid_rules and (self.invalid_import_from_targets()):
return None
self._reset(mark)
return None
@memoize
def import_from_as_names(self) -> list[ast.alias] | None:
# import_from_as_names: ','.import_from_as_name+
mark = self._mark()
if a := self.gathered(self.import_from_as_name, self.expect, ","):
return a
self._reset(mark)
return None
@memoize
def import_from_as_name(self) -> ast.alias | None:
# import_from_as_name: NAME ['as' NAME]
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (a := self.name()) and (b := self._tmp_12(),):
return ast.alias(name=a.string, asname=b, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def dotted_as_names(self) -> list[ast.alias] | None:
# dotted_as_names: ','.dotted_as_name+
mark = self._mark()
if a := self.gathered(self.dotted_as_name, self.expect, ","):
return a
self._reset(mark)
return None
@memoize
def dotted_as_name(self) -> ast.alias | None:
# dotted_as_name: dotted_name ['as' NAME]
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (a := self.dotted_name()) and (b := self._tmp_12(),):
return ast.alias(name=a, asname=b, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize_left_rec
def dotted_name(self) -> str | None:
# dotted_name: dotted_name '.' NAME | NAME
mark = self._mark()
if (a := self.dotted_name()) and (self.expect(".")) and (b := self.name()):
return a + "." + b.string
self._reset(mark)
if a1 := self.name():
return a1.string
self._reset(mark)
return None
@memoize
def block(self) -> list[Any] | None:
# block: NEWLINE INDENT statements DEDENT | simple_stmts | invalid_block
mark = self._mark()
if (
(self.token("NEWLINE"))
and (self.token("INDENT"))
and (a := self.statements())
and (self.token("DEDENT"))
):
return a
self._reset(mark)
if simple_stmts := self.simple_stmts():
return simple_stmts
self._reset(mark)
if self.call_invalid_rules and (self.invalid_block()):
return None
self._reset(mark)
return None
@memoize
def decorators(self) -> Any | None:
# decorators: decorator+
mark = self._mark()
if one_or_more := self.repeated(self.decorator):
return one_or_more
self._reset(mark)
return None
@memoize
def decorator(self) -> ast.expr | None:
# decorator: '@' named_expression NEWLINE
mark = self._mark()
if (self.expect("@")) and (f := self.named_expression()) and (self.token("NEWLINE")):
return f
self._reset(mark)
return None
@memoize
def class_def(self) -> ast.ClassDef | None:
# class_def: decorators class_def_raw | class_def_raw
mark = self._mark()
if (a := self.decorators()) and (b := self.class_def_raw()):
return self.set_decorators(b, a)
self._reset(mark)
if class_def_raw := self.class_def_raw():
return class_def_raw
self._reset(mark)
return None
@memoize
def class_def_raw(self) -> ast.ClassDef | None:
# class_def_raw: invalid_class_def_raw | 'class' NAME type_params? ['(' arguments? ')'] &&':' block
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if self.call_invalid_rules and (self.invalid_class_def_raw()):
return None
self._reset(mark)
if (
(self.expect("class"))
and (a := self.name())
and (t := self.type_params(),)
and (b := self._tmp_14(),)
and (self.expect_forced(self.expect(":"), "':'"))
and (c := self.block())
):
return ast.ClassDef(
a.string,
bases=b[0] if b else [],
keywords=b[1] if b else [],
body=c,
decorator_list=[],
**{"type_params": t or []} if sys.version_info >= (3, 12) else {},
**self.span(_lnum, _col),
)
self._reset(mark)
return None
@memoize
def function_def(self) -> ast.FunctionDef | ast.AsyncFunctionDef | None:
# function_def: decorators function_def_raw | function_def_raw
mark = self._mark()
if (d := self.decorators()) and (f := self.function_def_raw()):
return self.set_decorators(f, d)
self._reset(mark)
if f := self.function_def_raw():
return self.set_decorators(f, [])
self._reset(mark)
return None
@memoize
def function_def_raw(self) -> ast.FunctionDef | ast.AsyncFunctionDef | Any | None:
# function_def_raw: invalid_def_raw | 'def' NAME type_params? &&'(' params? ')' return_expr? &&':' func_type_comment? block | 'async' 'def' NAME type_params? &&'(' params? ')' return_expr? &&':' func_type_comment? block
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if self.call_invalid_rules and (self.invalid_def_raw()):
return None
self._reset(mark)
if (
(self.expect("def"))
and (n := self.name())
and (t := self.type_params(),)
and (self.expect_forced(self.expect("("), "'('"))
and (params := self.params(),)
and (self.expect(")"))
and (a := self.return_expr(),)
and (self.expect_forced(self.expect(":"), "':'"))
and (tc := self.func_type_comment(),)
and (b := self.block())
):
return 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 []} if sys.version_info >= (3, 12) else {},
**self.span(_lnum, _col),
)
self._reset(mark)
if (
(self.expect("async"))
and (self.expect("def"))
and (n := self.name())
and (t := self.type_params(),)
and (self.expect_forced(self.expect("("), "'('"))
and (params := self.params(),)
and (self.expect(")"))
and (a := self.return_expr(),)
and (self.expect_forced(self.expect(":"), "':'"))
and (tc := self.func_type_comment(),)
and (b := self.block())
):
return 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 []} if sys.version_info >= (3, 12) else {},
**self.span(_lnum, _col),
)
self._reset(mark)
return None
@memoize
def return_expr(self) -> ast.expr | None:
# return_expr: '->' expression
mark = self._mark()
if (self.expect("->")) and (z := self.expression()):
return z
self._reset(mark)
return None
@memoize
def params(self) -> ast.arguments | None:
# params: invalid_parameters | parameters
return self.seq_alts(
self.invalid_parameters,
self.parameters,
)
@memoize
def parameters(self) -> ast.arguments | None:
# parameters: slash_no_default param_no_default* param_with_default* star_etc? | slash_with_default param_with_default* star_etc? | param_no_default+ param_with_default* star_etc? | param_with_default+ star_etc? | star_etc
mark = self._mark()
if (
(a := self.slash_no_default())
and (b := self.repeated(self.param_no_default),)
and (c := self.repeated(self.param_with_default),)
and (d := self.star_etc(),)
):
return self.make_arguments(a, [], b, c, d)
self._reset(mark)
if (
(a1 := self.slash_with_default())
and (b1 := self.repeated(self.param_with_default),)
and (c1 := self.star_etc(),)
):
return self.make_arguments(None, a1, None, b1, c1)
self._reset(mark)
if (
(a2 := self.repeated(self.param_no_default))
and (b2 := self.repeated(self.param_with_default),)
and (c2 := self.star_etc(),)
):
return self.make_arguments(None, [], a2, b2, c2)
self._reset(mark)
if (a3 := self.repeated(self.param_with_default)) and (b3 := self.star_etc(),):
return self.make_arguments(None, [], None, a3, b3)
self._reset(mark)
if a4 := self.star_etc():
return self.make_arguments(None, [], None, None, a4)
self._reset(mark)
return None
@memoize
def slash_no_default(self) -> list[tuple[ast.arg, None]] | None:
# slash_no_default: param_no_default+ '/' ',' | param_no_default+ '/' &')'
mark = self._mark()
if (a := self.repeated(self.param_no_default)) and (self.expect("/")) and (self.expect(",")):
return [(p, None) for p in a]
self._reset(mark)
if (
(a := self.repeated(self.param_no_default))
and (self.expect("/"))
and (self.positive_lookahead(self.expect, ")"))
):
return [(p, None) for p in a]
self._reset(mark)
return None
@memoize
def slash_with_default(self) -> list[tuple[ast.arg, Any]] | None:
# slash_with_default: param_no_default* param_with_default+ '/' ',' | param_no_default* param_with_default+ '/' &')'
mark = self._mark()
if (
(a := self.repeated(self.param_no_default),)
and (b := self.repeated(self.param_with_default))
and (self.expect("/"))
and (self.expect(","))
):
return ([(p, None) for p in a] if a else []) + b
self._reset(mark)
if (
(a := self.repeated(self.param_no_default),)
and (b := self.repeated(self.param_with_default))
and (self.expect("/"))
and (self.positive_lookahead(self.expect, ")"))
):
return ([(p, None) for p in a] if a else []) + b
self._reset(mark)
return None
@memoize
def star_etc(self) -> tuple[ast.arg | None, list[tuple[ast.arg, Any]], ast.arg | None] | None:
# star_etc: invalid_star_etc | '*' param_no_default param_maybe_default* kwds? | '*' param_no_default_star_annotation param_maybe_default* kwds? | '*' ',' param_maybe_default+ kwds? | kwds
mark = self._mark()
if self.call_invalid_rules and (self.invalid_star_etc()):
return None
self._reset(mark)
if (
(self.expect("*"))
and (a := self.param_no_default())
and (b := self.repeated(self.param_maybe_default),)
and (c := self.kwds(),)
):
return (a, b, c)
self._reset(mark)
if (
(self.expect("*"))
and (a := self.param_no_default_star_annotation())
and (b := self.repeated(self.param_maybe_default),)
and (c := self.kwds(),)
):
return (a, b, c)
self._reset(mark)
if (
(self.expect("*"))
and (self.expect(","))
and (b := self.repeated(self.param_maybe_default))
and (c := self.kwds(),)
):
return (None, b, c)
self._reset(mark)
if a := self.kwds():
return (None, [], a)
self._reset(mark)
return None
@memoize
def kwds(self) -> ast.arg | None:
# kwds: invalid_kwds | '**' param_no_default
mark = self._mark()
if self.call_invalid_rules and (self.invalid_kwds()):
return None
self._reset(mark)
if (self.expect("**")) and (a := self.param_no_default()):
return a
self._reset(mark)
return None
@memoize
def param_no_default(self) -> ast.arg | None:
# param_no_default: param ',' TYPE_COMMENT? | param TYPE_COMMENT? &')'
mark = self._mark()
if (a := self.param()) and (self.expect(",")) and (self.token("TYPE_COMMENT"),):
return a
self._reset(mark)
if (
(a := self.param())
and (self.token("TYPE_COMMENT"),)
and (self.positive_lookahead(self.expect, ")"))
):
return a
self._reset(mark)
return None
@memoize
def param_no_default_star_annotation(self) -> ast.arg | None:
# param_no_default_star_annotation: param_star_annotation ',' TYPE_COMMENT? | param_star_annotation TYPE_COMMENT? &')'
mark = self._mark()
if (a := self.param_star_annotation()) and (self.expect(",")) and (self.token("TYPE_COMMENT"),):
return a
self._reset(mark)
if (
(a := self.param_star_annotation())
and (self.token("TYPE_COMMENT"),)
and (self.positive_lookahead(self.expect, ")"))
):
return a
self._reset(mark)
return None
@memoize
def param_with_default(self) -> tuple[ast.arg, Any] | None:
# param_with_default: param default ',' TYPE_COMMENT? | param default TYPE_COMMENT? &')'
mark = self._mark()
if (
(a := self.param())
and (c := self.default())
and (self.expect(","))
and (self.token("TYPE_COMMENT"),)
):
return (a, c)
self._reset(mark)
if (
(a := self.param())
and (c := self.default())
and (self.token("TYPE_COMMENT"),)
and (self.positive_lookahead(self.expect, ")"))
):
return (a, c)
self._reset(mark)
return None
@memoize
def param_maybe_default(self) -> tuple[ast.arg, Any] | None:
# param_maybe_default: param default? ',' TYPE_COMMENT? | param default? TYPE_COMMENT? &')'
mark = self._mark()
if (
(a := self.param())
and (c := self.default(),)
and (self.expect(","))
and (self.token("TYPE_COMMENT"),)
):
return (a, c)
self._reset(mark)
if (
(a := self.param())
and (c := self.default(),)
and (self.token("TYPE_COMMENT"),)
and (self.positive_lookahead(self.expect, ")"))
):
return (a, c)
self._reset(mark)
return None
@memoize
def param(self) -> ast.arg | None:
# param: NAME annotation?
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (a := self.name()) and (b := self.annotation(),):
return ast.arg(arg=a.string, annotation=b, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def param_star_annotation(self) -> ast.arg | None:
# param_star_annotation: NAME star_annotation
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if (a := self.name()) and (b := self.star_annotation()):
return ast.arg(arg=a.string, annotation=b, **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def annotation(self) -> ast.expr | None:
# annotation: ':' expression
mark = self._mark()
if (self.expect(":")) and (a := self.expression()):
return a
self._reset(mark)
return None
@memoize
def star_annotation(self) -> Any | None:
# star_annotation: ':' star_expression
mark = self._mark()
if (self.expect(":")) and (a := self.star_expression()):
return a
self._reset(mark)
return None
@memoize
def default(self) -> ast.expr | None:
# default: '=' expression | invalid_default
mark = self._mark()
if (self.expect("=")) and (a := self.expression()):
return a
self._reset(mark)
if self.call_invalid_rules and (self.invalid_default()):
return None
self._reset(mark)
return None
@memoize
def if_stmt(self) -> ast.If | None:
# if_stmt: invalid_if_stmt | 'if' named_expression ':' block elif_stmt | 'if' named_expression ':' block else_block?
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if self.call_invalid_rules and (self.invalid_if_stmt()):
return None
self._reset(mark)
if (
(self.expect("if"))
and (a := self.named_expression())
and (self.expect(":"))
and (b := self.block())
and (c := self.elif_stmt())
):
return ast.If(test=a, body=b, orelse=c or [], **self.span(_lnum, _col))
self._reset(mark)
if (
(self.expect("if"))
and (a := self.named_expression())
and (self.expect(":"))
and (b := self.block())
and (c := self.else_block(),)
):
return ast.If(test=a, body=b, orelse=c or [], **self.span(_lnum, _col))
self._reset(mark)
return None
@memoize
def elif_stmt(self) -> list[ast.If] | None:
# elif_stmt: invalid_elif_stmt | 'elif' named_expression ':' block elif_stmt | 'elif' named_expression ':' block else_block?
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start
if self.call_invalid_rules and (self.invalid_elif_stmt()):
return None
self._reset(mark)
if (
(self.expect("elif"))
and (a := self.named_expression())
and (self.expect(":"))
and (b := self.block())
and (c := self.elif_stmt())
):
return [ast.If(test=a, body=b, orelse=c, **self.span(_lnum, _col))]
self._reset(mark)
if (
(self.expect("elif"))
and (a := self.named_expression())
and (self.expect(":"))
and (b := self.block())
and (c := self.else_block(),)
):
return [ast.If(test=a, body=b, orelse=c or [], **self.span(_lnum, _col))]
self._reset(mark)
return None
@memoize
def else_block(self) -> list[Any] | None:
# else_block: invalid_else_stmt | 'else' &&':' block
mark = self._mark()
if self.call_invalid_rules and (self.invalid_else_stmt()):
return None
self._reset(mark)
if (self.expect("else")) and (self.expect_forced(self.expect(":"), "':'")) and (b := self.block()):
return b
self._reset(mark)
return None
@memoize
def while_stmt(self) -> ast.While | None:
# while_stmt: invalid_while_stmt | 'while' named_expression ':' block else_block?
mark = self._mark()
_lnum, _col = self._tokenizer.peek().start