This repository was archived by the owner on Jan 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathparser.py
More file actions
2006 lines (1754 loc) · 81.6 KB
/
parser.py
File metadata and controls
2006 lines (1754 loc) · 81.6 KB
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
# encoding:utf-8
"""
The :mod:`parser` module concerns itself with parsing Python source.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from functools import reduce
from . import source, diagnostic, lexer, ast
# A few notes about our approach to parsing:
#
# Python uses an LL(1) parser generator. It's a bit weird, because
# the usual reason to choose LL(1) is to make a handwritten parser
# possible, however Python's grammar is formulated in a way that
# is much more easily recognized if you make an FSM rather than
# the usual "if accept(token)..." ladder. So in a way it is
# the worst of both worlds.
#
# We don't use a parser generator because we want to have an unified
# grammar for all Python versions, and also have grammar coverage
# analysis and nice error recovery. To make the grammar compact,
# we use combinators to compose it from predefined fragments,
# such as "sequence" or "alternation" or "Kleene star". This easily
# gives us one token of lookahead in most cases, but e.g. not
# in the following one:
#
# argument: test | test '=' test
#
# There are two issues with this. First, in an alternation, the first
# variant will be tried (and accepted) earlier. Second, if we reverse
# them, by the point it is clear ``'='`` will not be accepted, ``test``
# has already been consumed.
#
# The way we fix this is by reordering rules so that longest match
# comes first, and adding backtracking on alternations (as well as
# plus and star, since those have a hidden alternation inside).
#
# While backtracking can in principle make asymptotical complexity
# worse, it never makes parsing syntactically correct code supralinear
# with Python's LL(1) grammar, and we could not come up with any
# pathological incorrect input as well.
# Coverage data
_all_rules = []
_all_stmts = {}
# Generic LL parsing combinators
class Unmatched:
pass
unmatched = Unmatched()
def llrule(loc, expected, cases=1):
if loc is None:
def decorator(rule):
rule.expected = expected
return rule
else:
def decorator(inner_rule):
if cases == 1:
def rule(*args, **kwargs):
result = inner_rule(*args, **kwargs)
if result is not unmatched:
rule.covered[0] = True
return result
else:
rule = inner_rule
rule.loc, rule.expected, rule.covered = \
loc, expected, [False] * cases
_all_rules.append(rule)
return rule
return decorator
def action(inner_rule, loc=None):
"""
A decorator returning a function that first runs ``inner_rule`` and then, if its
return value is not None, maps that value using ``mapper``.
If the value being mapped is a tuple, it is expanded into multiple arguments.
Similar to attaching semantic actions to rules in traditional parser generators.
"""
def decorator(mapper):
@llrule(loc, inner_rule.expected)
def outer_rule(parser):
result = inner_rule(parser)
if result is unmatched:
return result
if isinstance(result, tuple):
return mapper(parser, *result)
else:
return mapper(parser, result)
return outer_rule
return decorator
def Eps(value=None, loc=None):
"""A rule that accepts no tokens (epsilon) and returns ``value``."""
@llrule(loc, lambda parser: [])
def rule(parser):
return value
return rule
def Tok(kind, loc=None):
"""A rule that accepts a token of kind ``kind`` and returns it, or returns None."""
@llrule(loc, lambda parser: [kind])
def rule(parser):
return parser._accept(kind)
return rule
def Loc(kind, loc=None):
"""A rule that accepts a token of kind ``kind`` and returns its location, or returns None."""
@llrule(loc, lambda parser: [kind])
def rule(parser):
result = parser._accept(kind)
if result is unmatched:
return result
return result.loc
return rule
def Rule(name, loc=None):
"""A proxy for a rule called ``name`` which may not be yet defined."""
@llrule(loc, lambda parser: getattr(parser, name).expected(parser))
def rule(parser):
return getattr(parser, name)()
return rule
def Expect(inner_rule, loc=None):
"""A rule that executes ``inner_rule`` and emits a diagnostic error if it returns None."""
@llrule(loc, inner_rule.expected)
def rule(parser):
result = inner_rule(parser)
if result is unmatched:
expected = reduce(list.__add__, [rule.expected(parser) for rule in parser._errrules])
expected = list(sorted(set(expected)))
if len(expected) > 1:
expected = " or ".join([", ".join(expected[0:-1]), expected[-1]])
elif len(expected) == 1:
expected = expected[0]
else:
expected = "(impossible)"
error_tok = parser._tokens[parser._errindex]
error = diagnostic.Diagnostic(
"fatal", "unexpected {actual}: expected {expected}",
{"actual": error_tok.kind, "expected": expected},
error_tok.loc)
parser.diagnostic_engine.process(error)
return result
return rule
def Seq(first_rule, *rest_of_rules, **kwargs):
"""
A rule that accepts a sequence of tokens satisfying ``rules`` and returns a tuple
containing their return values, or None if the first rule was not satisfied.
"""
@llrule(kwargs.get("loc", None), first_rule.expected)
def rule(parser):
result = first_rule(parser)
if result is unmatched:
return result
results = [result]
for rule in rest_of_rules:
result = rule(parser)
if result is unmatched:
return result
results.append(result)
return tuple(results)
return rule
def SeqN(n, *inner_rules, **kwargs):
"""
A rule that accepts a sequence of tokens satisfying ``rules`` and returns
the value returned by rule number ``n``, or None if the first rule was not satisfied.
"""
@action(Seq(*inner_rules), loc=kwargs.get("loc", None))
def rule(parser, *values):
return values[n]
return rule
def Alt(*inner_rules, **kwargs):
"""
A rule that expects a sequence of tokens satisfying one of ``rules`` in sequence
(a rule is satisfied when it returns anything but None) and returns the return
value of that rule, or None if no rules were satisfied.
"""
loc = kwargs.get("loc", None)
expected = lambda parser: reduce(list.__add__, map(lambda x: x.expected(parser), inner_rules))
if loc is not None:
@llrule(loc, expected, cases=len(inner_rules))
def rule(parser):
data = parser._save()
for idx, inner_rule in enumerate(inner_rules):
result = inner_rule(parser)
if result is unmatched:
parser._restore(data, rule=inner_rule)
else:
rule.covered[idx] = True
return result
return unmatched
else:
@llrule(loc, expected, cases=len(inner_rules))
def rule(parser):
data = parser._save()
for inner_rule in inner_rules:
result = inner_rule(parser)
if result is unmatched:
parser._restore(data, rule=inner_rule)
else:
return result
return unmatched
return rule
def Opt(inner_rule, loc=None):
"""Shorthand for ``Alt(inner_rule, Eps())``"""
return Alt(inner_rule, Eps(), loc=loc)
def Star(inner_rule, loc=None):
"""
A rule that accepts a sequence of tokens satisfying ``inner_rule`` zero or more times,
and returns the returned values in a :class:`list`.
"""
@llrule(loc, lambda parser: [])
def rule(parser):
results = []
while True:
data = parser._save()
result = inner_rule(parser)
if result is unmatched:
parser._restore(data, rule=inner_rule)
return results
results.append(result)
return rule
def Plus(inner_rule, loc=None):
"""
A rule that accepts a sequence of tokens satisfying ``inner_rule`` one or more times,
and returns the returned values in a :class:`list`.
"""
@llrule(loc, inner_rule.expected)
def rule(parser):
result = inner_rule(parser)
if result is unmatched:
return result
results = [result]
while True:
data = parser._save()
result = inner_rule(parser)
if result is unmatched:
parser._restore(data, rule=inner_rule)
return results
results.append(result)
return rule
class commalist(list):
__slots__ = ("trailing_comma",)
def List(inner_rule, separator_tok, trailing, leading=True, loc=None):
if not trailing:
@action(Seq(inner_rule, Star(SeqN(1, Tok(separator_tok), inner_rule))), loc=loc)
def outer_rule(parser, first, rest):
return [first] + rest
return outer_rule
else:
# A rule like this: stmt (';' stmt)* [';']
# This doesn't yield itself to combinators above, because disambiguating
# another iteration of the Kleene star and the trailing separator
# requires two lookahead tokens (naively).
separator_rule = Tok(separator_tok)
@llrule(loc, inner_rule.expected)
def rule(parser):
results = commalist()
if leading:
result = inner_rule(parser)
if result is unmatched:
return result
else:
results.append(result)
while True:
result = separator_rule(parser)
if result is unmatched:
results.trailing_comma = None
return results
result_1 = inner_rule(parser)
if result_1 is unmatched:
results.trailing_comma = result
return results
else:
results.append(result_1)
return rule
# Python AST specific parser combinators
def Newline(loc=None):
"""A rule that accepts token of kind ``newline`` and returns an empty list."""
@llrule(loc, lambda parser: ["newline"])
def rule(parser):
result = parser._accept("newline")
if result is unmatched:
return result
return []
return rule
def Oper(klass, *kinds, **kwargs):
"""
A rule that accepts a sequence of tokens of kinds ``kinds`` and returns
an instance of ``klass`` with ``loc`` encompassing the entire sequence
or None if the first token is not of ``kinds[0]``.
"""
@action(Seq(*map(Loc, kinds)), loc=kwargs.get("loc", None))
def rule(parser, *tokens):
return klass(loc=tokens[0].join(tokens[-1]))
return rule
def BinOper(expr_rulename, op_rule, node=ast.BinOp, loc=None):
@action(Seq(Rule(expr_rulename), Star(Seq(op_rule, Rule(expr_rulename)))), loc=loc)
def rule(parser, lhs, trailers):
for (op, rhs) in trailers:
lhs = node(left=lhs, op=op, right=rhs,
loc=lhs.loc.join(rhs.loc))
return lhs
return rule
def BeginEnd(begin_tok, inner_rule, end_tok, empty=None, loc=None):
@action(Seq(Loc(begin_tok), inner_rule, Loc(end_tok)), loc=loc)
def rule(parser, begin_loc, node, end_loc):
if node is None:
node = empty(parser)
# Collection nodes don't have loc yet. If a node has loc at this
# point, it means it's an expression passed in parentheses.
if node.loc is None and type(node) in [
ast.List, ast.ListComp,
ast.Dict, ast.DictComp,
ast.Set, ast.SetComp,
ast.GeneratorExp,
ast.Tuple, ast.Repr,
ast.Call, ast.Subscript,
ast.arguments]:
node.begin_loc, node.end_loc, node.loc = \
begin_loc, end_loc, begin_loc.join(end_loc)
return node
return rule
class Parser(object):
# Generic LL parsing methods
def __init__(self, lexer, version, diagnostic_engine):
self._init_version(version)
self.diagnostic_engine = diagnostic_engine
self.lexer = lexer
self._tokens = []
self._index = -1
self._errindex = -1
self._errrules = []
self._advance()
def _save(self):
return self._index
def _restore(self, data, rule):
self._index = data
self._token = self._tokens[self._index]
if self._index > self._errindex:
# We have advanced since last error
self._errindex = self._index
self._errrules = [rule]
elif self._index == self._errindex:
# We're at the same place as last error
self._errrules.append(rule)
else:
# We've backtracked far and are now just failing the
# whole parse
pass
def _advance(self):
self._index += 1
if self._index == len(self._tokens):
self._tokens.append(self.lexer.next(eof_token=True))
self._token = self._tokens[self._index]
def _accept(self, expected_kind):
if self._token.kind == expected_kind:
result = self._token
self._advance()
return result
return unmatched
# Python-specific methods
def _init_version(self, version):
if version in ((2, 6), (2, 7)):
if version == (2, 6):
self.with_stmt = self.with_stmt__26
self.atom_6 = self.atom_6__26
else:
self.with_stmt = self.with_stmt__27
self.atom_6 = self.atom_6__27
self.except_clause_1 = self.except_clause_1__26
self.classdef = self.classdef__26
self.subscript = self.subscript__26
self.raise_stmt = self.raise_stmt__26
self.comp_if = self.comp_if__26
self.atom = self.atom__26
self.funcdef = self.funcdef__26
self.parameters = self.parameters__26
self.varargslist = self.varargslist__26
self.comparison_1 = self.comparison_1__26
self.exprlist_1 = self.exprlist_1__26
self.testlist_comp_1 = self.testlist_comp_1__26
self.expr_stmt_1 = self.expr_stmt_1__26
self.yield_expr = self.yield_expr__26
return
elif version in ((3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6)):
if version == (3, 0):
self.with_stmt = self.with_stmt__26 # lol
else:
self.with_stmt = self.with_stmt__27
self.except_clause_1 = self.except_clause_1__30
self.classdef = self.classdef__30
self.subscript = self.subscript__30
self.raise_stmt = self.raise_stmt__30
self.comp_if = self.comp_if__30
self.atom = self.atom__30
self.funcdef = self.funcdef__30
self.parameters = self.parameters__30
if version < (3, 2):
self.varargslist = self.varargslist__30
self.typedargslist = self.typedargslist__30
self.comparison_1 = self.comparison_1__30
self.star_expr = self.star_expr__30
self.exprlist_1 = self.exprlist_1__30
self.testlist_comp_1 = self.testlist_comp_1__26
self.expr_stmt_1 = self.expr_stmt_1__26
else:
self.varargslist = self.varargslist__32
self.typedargslist = self.typedargslist__32
self.comparison_1 = self.comparison_1__32
self.star_expr = self.star_expr__32
self.exprlist_1 = self.exprlist_1__32
self.testlist_comp_1 = self.testlist_comp_1__32
self.expr_stmt_1 = self.expr_stmt_1__32
if version < (3, 3):
self.yield_expr = self.yield_expr__26
else:
self.yield_expr = self.yield_expr__33
return
raise NotImplementedError("pythonparser.parser.Parser cannot parse Python %s" %
str(version))
def _arguments(self, args=None, defaults=None, kwonlyargs=None, kw_defaults=None,
vararg=None, kwarg=None,
star_loc=None, dstar_loc=None, begin_loc=None, end_loc=None,
equals_locs=None, kw_equals_locs=None, loc=None):
if args is None:
args = []
if defaults is None:
defaults = []
if kwonlyargs is None:
kwonlyargs = []
if kw_defaults is None:
kw_defaults = []
if equals_locs is None:
equals_locs = []
if kw_equals_locs is None:
kw_equals_locs = []
return ast.arguments(args=args, defaults=defaults,
kwonlyargs=kwonlyargs, kw_defaults=kw_defaults,
vararg=vararg, kwarg=kwarg,
star_loc=star_loc, dstar_loc=dstar_loc,
begin_loc=begin_loc, end_loc=end_loc,
equals_locs=equals_locs, kw_equals_locs=kw_equals_locs,
loc=loc)
def _arg(self, tok, colon_loc=None, annotation=None):
loc = tok.loc
if annotation:
loc = loc.join(annotation.loc)
return ast.arg(arg=tok.value, annotation=annotation,
arg_loc=tok.loc, colon_loc=colon_loc, loc=loc)
def _empty_arglist(self):
return ast.Call(args=[], keywords=[], starargs=None, kwargs=None,
star_loc=None, dstar_loc=None, loc=None)
def _wrap_tuple(self, elts):
assert len(elts) > 0
if len(elts) > 1:
return ast.Tuple(ctx=None, elts=elts,
loc=elts[0].loc.join(elts[-1].loc), begin_loc=None, end_loc=None)
else:
return elts[0]
def _assignable(self, node, is_delete=False):
if isinstance(node, ast.Name) or isinstance(node, ast.Subscript) or \
isinstance(node, ast.Attribute) or isinstance(node, ast.Starred):
return node
elif (isinstance(node, ast.List) or isinstance(node, ast.Tuple)) and \
any(node.elts):
node.elts = [self._assignable(elt, is_delete) for elt in node.elts]
return node
else:
if is_delete:
error = diagnostic.Diagnostic(
"fatal", "cannot delete this expression", {}, node.loc)
else:
error = diagnostic.Diagnostic(
"fatal", "cannot assign to this expression", {}, node.loc)
self.diagnostic_engine.process(error)
def add_flags(self, flags):
if "print_function" in flags:
self.lexer.print_function = True
if "unicode_literals" in flags:
self.lexer.unicode_literals = True
# Grammar
@action(Expect(Alt(Newline(),
Rule("simple_stmt"),
SeqN(0, Rule("compound_stmt"), Newline()))))
def single_input(self, body):
"""single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE"""
loc = None
if body != []:
loc = body[0].loc
return ast.Interactive(body=body, loc=loc)
@action(Expect(SeqN(0, Star(Alt(Newline(), Rule("stmt"))), Tok("eof"))))
def file_input(parser, body):
"""file_input: (NEWLINE | stmt)* ENDMARKER"""
body = reduce(list.__add__, body, [])
loc = None
if body != []:
loc = body[0].loc
return ast.Module(body=body, loc=loc)
@action(Expect(SeqN(0, Rule("testlist"), Star(Tok("newline")), Tok("eof"))))
def eval_input(self, expr):
"""eval_input: testlist NEWLINE* ENDMARKER"""
return ast.Expression(body=[expr], loc=expr.loc)
@action(Seq(Loc("@"), List(Tok("ident"), ".", trailing=False),
Opt(BeginEnd("(", Opt(Rule("arglist")), ")",
empty=_empty_arglist)),
Loc("newline")))
def decorator(self, at_loc, idents, call_opt, newline_loc):
"""decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE"""
root = idents[0]
dec_loc = root.loc
expr = ast.Name(id=root.value, ctx=None, loc=root.loc)
for ident in idents[1:]:
dot_loc = ident.loc.begin()
dot_loc.begin_pos -= 1
dec_loc = dec_loc.join(ident.loc)
expr = ast.Attribute(value=expr, attr=ident.value, ctx=None,
loc=expr.loc.join(ident.loc),
attr_loc=ident.loc, dot_loc=dot_loc)
if call_opt:
call_opt.func = expr
call_opt.loc = dec_loc.join(call_opt.loc)
expr = call_opt
return at_loc, expr
decorators = Plus(Rule("decorator"))
"""decorators: decorator+"""
@action(Seq(Rule("decorators"), Alt(Rule("classdef"), Rule("funcdef"))))
def decorated(self, decorators, classfuncdef):
"""decorated: decorators (classdef | funcdef)"""
classfuncdef.at_locs = list(map(lambda x: x[0], decorators))
classfuncdef.decorator_list = list(map(lambda x: x[1], decorators))
classfuncdef.loc = classfuncdef.loc.join(decorators[0][0])
return classfuncdef
@action(Seq(Loc("def"), Tok("ident"), Rule("parameters"), Loc(":"), Rule("suite")))
def funcdef__26(self, def_loc, ident_tok, args, colon_loc, suite):
"""(2.6, 2.7) funcdef: 'def' NAME parameters ':' suite"""
return ast.FunctionDef(name=ident_tok.value, args=args, returns=None,
body=suite, decorator_list=[],
at_locs=[], keyword_loc=def_loc, name_loc=ident_tok.loc,
colon_loc=colon_loc, arrow_loc=None,
loc=def_loc.join(suite[-1].loc))
@action(Seq(Loc("def"), Tok("ident"), Rule("parameters"),
Opt(Seq(Loc("->"), Rule("test"))),
Loc(":"), Rule("suite")))
def funcdef__30(self, def_loc, ident_tok, args, returns_opt, colon_loc, suite):
"""(3.0-) funcdef: 'def' NAME parameters ['->' test] ':' suite"""
arrow_loc = returns = None
if returns_opt:
arrow_loc, returns = returns_opt
return ast.FunctionDef(name=ident_tok.value, args=args, returns=returns,
body=suite, decorator_list=[],
at_locs=[], keyword_loc=def_loc, name_loc=ident_tok.loc,
colon_loc=colon_loc, arrow_loc=arrow_loc,
loc=def_loc.join(suite[-1].loc))
parameters__26 = BeginEnd("(", Opt(Rule("varargslist")), ")", empty=_arguments)
"""(2.6, 2.7) parameters: '(' [varargslist] ')'"""
parameters__30 = BeginEnd("(", Opt(Rule("typedargslist")), ")", empty=_arguments)
"""(3.0) parameters: '(' [typedargslist] ')'"""
varargslist__26_1 = Seq(Rule("fpdef"), Opt(Seq(Loc("="), Rule("test"))))
@action(Seq(Loc("**"), Tok("ident")))
def varargslist__26_2(self, dstar_loc, kwarg_tok):
return self._arguments(kwarg=self._arg(kwarg_tok),
dstar_loc=dstar_loc, loc=dstar_loc.join(kwarg_tok.loc))
@action(Seq(Loc("*"), Tok("ident"),
Opt(Seq(Tok(","), Loc("**"), Tok("ident")))))
def varargslist__26_3(self, star_loc, vararg_tok, kwarg_opt):
dstar_loc = kwarg = None
loc = star_loc.join(vararg_tok.loc)
vararg = self._arg(vararg_tok)
if kwarg_opt:
_, dstar_loc, kwarg_tok = kwarg_opt
kwarg = self._arg(kwarg_tok)
loc = star_loc.join(kwarg_tok.loc)
return self._arguments(vararg=vararg, kwarg=kwarg,
star_loc=star_loc, dstar_loc=dstar_loc, loc=loc)
@action(Eps(value=()))
def varargslist__26_4(self):
return self._arguments()
@action(Alt(Seq(Star(SeqN(0, varargslist__26_1, Tok(","))),
Alt(varargslist__26_2, varargslist__26_3)),
Seq(List(varargslist__26_1, ",", trailing=True),
varargslist__26_4)))
def varargslist__26(self, fparams, args):
"""
(2.6, 2.7)
varargslist: ((fpdef ['=' test] ',')*
('*' NAME [',' '**' NAME] | '**' NAME) |
fpdef ['=' test] (',' fpdef ['=' test])* [','])
"""
for fparam, default_opt in fparams:
if default_opt:
equals_loc, default = default_opt
args.equals_locs.append(equals_loc)
args.defaults.append(default)
elif len(args.defaults) > 0:
error = diagnostic.Diagnostic(
"fatal", "non-default argument follows default argument", {},
fparam.loc, [args.args[-1].loc.join(args.defaults[-1].loc)])
self.diagnostic_engine.process(error)
args.args.append(fparam)
def fparam_loc(fparam, default_opt):
if default_opt:
equals_loc, default = default_opt
return fparam.loc.join(default.loc)
else:
return fparam.loc
if args.loc is None:
args.loc = fparam_loc(*fparams[0]).join(fparam_loc(*fparams[-1]))
elif len(fparams) > 0:
args.loc = args.loc.join(fparam_loc(*fparams[0]))
return args
@action(Tok("ident"))
def fpdef_1(self, ident_tok):
return ast.arg(arg=ident_tok.value, annotation=None,
arg_loc=ident_tok.loc, colon_loc=None,
loc=ident_tok.loc)
fpdef = Alt(fpdef_1, BeginEnd("(", Rule("fplist"), ")",
empty=lambda self: ast.Tuple(elts=[], ctx=None, loc=None)))
"""fpdef: NAME | '(' fplist ')'"""
def _argslist(fpdef_rule, old_style=False):
argslist_1 = Seq(fpdef_rule, Opt(Seq(Loc("="), Rule("test"))))
@action(Seq(Loc("**"), Tok("ident")))
def argslist_2(self, dstar_loc, kwarg_tok):
return self._arguments(kwarg=self._arg(kwarg_tok),
dstar_loc=dstar_loc, loc=dstar_loc.join(kwarg_tok.loc))
@action(Seq(Loc("*"), Tok("ident"),
Star(SeqN(1, Tok(","), argslist_1)),
Opt(Seq(Tok(","), Loc("**"), Tok("ident")))))
def argslist_3(self, star_loc, vararg_tok, fparams, kwarg_opt):
dstar_loc = kwarg = None
loc = star_loc.join(vararg_tok.loc)
vararg = self._arg(vararg_tok)
if kwarg_opt:
_, dstar_loc, kwarg_tok = kwarg_opt
kwarg = self._arg(kwarg_tok)
loc = star_loc.join(kwarg_tok.loc)
kwonlyargs, kw_defaults, kw_equals_locs = [], [], []
for fparam, default_opt in fparams:
if default_opt:
equals_loc, default = default_opt
kw_equals_locs.append(equals_loc)
kw_defaults.append(default)
else:
kw_defaults.append(None)
kwonlyargs.append(fparam)
if any(kw_defaults):
loc = loc.join(kw_defaults[-1].loc)
elif any(kwonlyargs):
loc = loc.join(kwonlyargs[-1].loc)
return self._arguments(vararg=vararg, kwarg=kwarg,
kwonlyargs=kwonlyargs, kw_defaults=kw_defaults,
star_loc=star_loc, dstar_loc=dstar_loc,
kw_equals_locs=kw_equals_locs, loc=loc)
argslist_4 = Alt(argslist_2, argslist_3)
@action(Eps(value=()))
def argslist_5(self):
return self._arguments()
if old_style:
argslist = Alt(Seq(Star(SeqN(0, argslist_1, Tok(","))),
argslist_4),
Seq(List(argslist_1, ",", trailing=True),
argslist_5))
else:
argslist = Alt(Seq(Eps(value=[]), argslist_4),
Seq(List(argslist_1, ",", trailing=False),
Alt(SeqN(1, Tok(","), Alt(argslist_4, argslist_5)),
argslist_5)))
def argslist_action(self, fparams, args):
for fparam, default_opt in fparams:
if default_opt:
equals_loc, default = default_opt
args.equals_locs.append(equals_loc)
args.defaults.append(default)
elif len(args.defaults) > 0:
error = diagnostic.Diagnostic(
"fatal", "non-default argument follows default argument", {},
fparam.loc, [args.args[-1].loc.join(args.defaults[-1].loc)])
self.diagnostic_engine.process(error)
args.args.append(fparam)
def fparam_loc(fparam, default_opt):
if default_opt:
equals_loc, default = default_opt
return fparam.loc.join(default.loc)
else:
return fparam.loc
if args.loc is None:
args.loc = fparam_loc(*fparams[0]).join(fparam_loc(*fparams[-1]))
elif len(fparams) > 0:
args.loc = args.loc.join(fparam_loc(*fparams[0]))
return args
return action(argslist)(argslist_action)
typedargslist__30 = _argslist(Rule("tfpdef"), old_style=True)
"""
(3.0, 3.1)
typedargslist: ((tfpdef ['=' test] ',')*
('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
| tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
"""
typedargslist__32 = _argslist(Rule("tfpdef"))
"""
(3.2-)
typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','
['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]]
| '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
"""
varargslist__30 = _argslist(Rule("vfpdef"), old_style=True)
"""
(3.0, 3.1)
varargslist: ((vfpdef ['=' test] ',')*
('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
| vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
"""
varargslist__32 = _argslist(Rule("vfpdef"))
"""
(3.2-)
varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [','
['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]]
| '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
"""
@action(Seq(Tok("ident"), Opt(Seq(Loc(":"), Rule("test")))))
def tfpdef(self, ident_tok, annotation_opt):
"""(3.0-) tfpdef: NAME [':' test]"""
if annotation_opt:
colon_loc, annotation = annotation_opt
return self._arg(ident_tok, colon_loc, annotation)
return self._arg(ident_tok)
vfpdef = fpdef_1
"""(3.0-) vfpdef: NAME"""
@action(List(Rule("fpdef"), ",", trailing=True))
def fplist(self, elts):
"""fplist: fpdef (',' fpdef)* [',']"""
return ast.Tuple(elts=elts, ctx=None, loc=None)
stmt = Alt(Rule("simple_stmt"), Rule("compound_stmt"))
"""stmt: simple_stmt | compound_stmt"""
simple_stmt = SeqN(0, List(Rule("small_stmt"), ";", trailing=True), Tok("newline"))
"""simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE"""
small_stmt = Alt(Rule("expr_stmt"), Rule("print_stmt"), Rule("del_stmt"),
Rule("pass_stmt"), Rule("flow_stmt"), Rule("import_stmt"),
Rule("global_stmt"), Rule("nonlocal_stmt"), Rule("exec_stmt"),
Rule("assert_stmt"))
"""
(2.6, 2.7)
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
(3.0-)
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
"""
expr_stmt_1__26 = Rule("testlist")
expr_stmt_1__32 = Rule("testlist_star_expr")
@action(Seq(Rule("augassign"), Alt(Rule("yield_expr"), Rule("testlist"))))
def expr_stmt_2(self, augassign, rhs_expr):
return ast.AugAssign(op=augassign, value=rhs_expr)
@action(Star(Seq(Loc("="), Alt(Rule("yield_expr"), Rule("expr_stmt_1")))))
def expr_stmt_3(self, seq):
if len(seq) > 0:
return ast.Assign(targets=list(map(lambda x: x[1], seq[:-1])), value=seq[-1][1],
op_locs=list(map(lambda x: x[0], seq)))
else:
return None
@action(Seq(Rule("expr_stmt_1"), Alt(expr_stmt_2, expr_stmt_3)))
def expr_stmt(self, lhs, rhs):
"""
(2.6, 2.7, 3.0, 3.1)
expr_stmt: testlist (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist))*)
(3.2-)
expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist_star_expr))*)
"""
if isinstance(rhs, ast.AugAssign):
if isinstance(lhs, ast.Tuple) or isinstance(lhs, ast.List):
error = diagnostic.Diagnostic(
"fatal", "illegal expression for augmented assignment", {},
rhs.op.loc, [lhs.loc])
self.diagnostic_engine.process(error)
else:
rhs.target = self._assignable(lhs)
rhs.loc = rhs.target.loc.join(rhs.value.loc)
return rhs
elif rhs is not None:
rhs.targets = list(map(self._assignable, [lhs] + rhs.targets))
rhs.loc = lhs.loc.join(rhs.value.loc)
return rhs
else:
return ast.Expr(value=lhs, loc=lhs.loc)
testlist_star_expr = action(
List(Alt(Rule("test"), Rule("star_expr")), ",", trailing=True)) \
(_wrap_tuple)
"""(3.2-) testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']"""
augassign = Alt(Oper(ast.Add, "+="), Oper(ast.Sub, "-="), Oper(ast.MatMult, "@="),
Oper(ast.Mult, "*="), Oper(ast.Div, "/="), Oper(ast.Mod, "%="),
Oper(ast.BitAnd, "&="), Oper(ast.BitOr, "|="), Oper(ast.BitXor, "^="),
Oper(ast.LShift, "<<="), Oper(ast.RShift, ">>="),
Oper(ast.Pow, "**="), Oper(ast.FloorDiv, "//="))
"""augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')"""
@action(List(Rule("test"), ",", trailing=True))
def print_stmt_1(self, values):
nl, loc = True, values[-1].loc
if values.trailing_comma:
nl, loc = False, values.trailing_comma.loc
return ast.Print(dest=None, values=values, nl=nl,
dest_loc=None, loc=loc)
@action(Seq(Loc(">>"), Rule("test"), Tok(","), List(Rule("test"), ",", trailing=True)))
def print_stmt_2(self, dest_loc, dest, comma_tok, values):
nl, loc = True, values[-1].loc
if values.trailing_comma:
nl, loc = False, values.trailing_comma.loc
return ast.Print(dest=dest, values=values, nl=nl,
dest_loc=dest_loc, loc=loc)
@action(Seq(Loc(">>"), Rule("test")))
def print_stmt_3(self, dest_loc, dest):
return ast.Print(dest=dest, values=[], nl=True,
dest_loc=dest_loc, loc=dest_loc)
@action(Eps())
def print_stmt_4(self, eps):
return ast.Print(dest=None, values=[], nl=True,
dest_loc=None, loc=None)
@action(Seq(Loc("print"), Alt(print_stmt_1, print_stmt_2, print_stmt_3, print_stmt_4)))
def print_stmt(self, print_loc, stmt):
"""
(2.6-2.7)
print_stmt: 'print' ( [ test (',' test)* [','] ] |
'>>' test [ (',' test)+ [','] ] )
"""
stmt.keyword_loc = print_loc
if stmt.loc is None:
stmt.loc = print_loc
else:
stmt.loc = print_loc.join(stmt.loc)
return stmt
@action(Seq(Loc("del"), List(Rule("expr"), ",", trailing=True)))
def del_stmt(self, stmt_loc, exprs):
# Python uses exprlist here, but does *not* obey the usual
# tuple-wrapping semantics, so we embed the rule directly.
"""del_stmt: 'del' exprlist"""
return ast.Delete(targets=[self._assignable(expr, is_delete=True) for expr in exprs],
loc=stmt_loc.join(exprs[-1].loc), keyword_loc=stmt_loc)
@action(Loc("pass"))
def pass_stmt(self, stmt_loc):
"""pass_stmt: 'pass'"""
return ast.Pass(loc=stmt_loc, keyword_loc=stmt_loc)
flow_stmt = Alt(Rule("break_stmt"), Rule("continue_stmt"), Rule("return_stmt"),
Rule("raise_stmt"), Rule("yield_stmt"))
"""flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt"""
@action(Loc("break"))
def break_stmt(self, stmt_loc):
"""break_stmt: 'break'"""
return ast.Break(loc=stmt_loc, keyword_loc=stmt_loc)
@action(Loc("continue"))
def continue_stmt(self, stmt_loc):
"""continue_stmt: 'continue'"""
return ast.Continue(loc=stmt_loc, keyword_loc=stmt_loc)
@action(Seq(Loc("return"), Opt(Rule("testlist"))))
def return_stmt(self, stmt_loc, values):
"""return_stmt: 'return' [testlist]"""
loc = stmt_loc
if values:
loc = loc.join(values.loc)
return ast.Return(value=values,
loc=loc, keyword_loc=stmt_loc)
@action(Rule("yield_expr"))
def yield_stmt(self, expr):
"""yield_stmt: yield_expr"""
return ast.Expr(value=expr, loc=expr.loc)
@action(Seq(Loc("raise"), Opt(Seq(Rule("test"),
Opt(Seq(Tok(","), Rule("test"),
Opt(SeqN(1, Tok(","), Rule("test")))))))))
def raise_stmt__26(self, raise_loc, type_opt):
"""(2.6, 2.7) raise_stmt: 'raise' [test [',' test [',' test]]]"""
type_ = inst = tback = None
loc = raise_loc
if type_opt:
type_, inst_opt = type_opt
loc = loc.join(type_.loc)
if inst_opt:
_, inst, tback = inst_opt
loc = loc.join(inst.loc)
if tback:
loc = loc.join(tback.loc)
return ast.Raise(exc=type_, inst=inst, tback=tback, cause=None,
keyword_loc=raise_loc, from_loc=None, loc=loc)
@action(Seq(Loc("raise"), Opt(Seq(Rule("test"), Opt(Seq(Loc("from"), Rule("test")))))))
def raise_stmt__30(self, raise_loc, exc_opt):
"""(3.0-) raise_stmt: 'raise' [test ['from' test]]"""
exc = from_loc = cause = None
loc = raise_loc
if exc_opt:
exc, cause_opt = exc_opt
loc = loc.join(exc.loc)
if cause_opt:
from_loc, cause = cause_opt