Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
2505 lines (2275 loc) · 83.1 KB
/
Copy pathparser.py
File metadata and controls
2505 lines (2275 loc) · 83.1 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
"""Implements the xonsh parser"""
import os
import sys
from collections import Iterable, Sequence, Mapping
from ply import yacc
from xonsh import ast
from xonsh.lexer import Lexer
from xonsh.tools import VER_3_4, VER_3_5, VER_MAJOR_MINOR, V_MAJOR_MINOR, \
docstring_by_version
class Location(object):
"""Location in a file."""
def __init__(self, fname, lineno, column=None):
"""Takes a filename, line number, and optionally a column number."""
self.fname = fname
self.lineno = lineno
self.column = column
def __str__(self):
s = '{0}:{1}'.format(self.fname, self.lineno)
if self.column is not None:
s += ':{0}'.format(self.column)
return s
def has_elts(x):
"""Tests if x is an AST node with elements."""
return isinstance(x, ast.AST) and hasattr(x, 'elts')
def ensure_has_elts(x, lineno=1, col_offset=1):
"""Ensures that x is an AST node with elements."""
if not has_elts(x):
if not isinstance(x, Iterable):
x = [x]
x = ast.Tuple(elts=x,
ctx=ast.Load(),
lineno=lineno,
col_offset=col_offset)
return x
def empty_list(lineno=None, col=None):
"""Creates the AST node for an empty list."""
return ast.List(elts=[], ctx=ast.Load(), lineno=lineno, col_offset=col)
def binop(x, op, y, lineno=None, col=None):
"""Creates the AST node for a binary operation."""
return ast.BinOp(left=x, op=op, right=y, lineno=lineno, col_offset=col)
def call_split_lines(x, lineno=None, col=None):
"""Creates the AST node for calling the 'splitlines' attribute of an
object, nominally a string.
"""
return ast.Call(func=ast.Attribute(value=x,
attr='splitlines',
ctx=ast.Load(),
lineno=lineno,
col_offset=col),
args=[],
keywords=[],
starargs=None,
kwargs=None,
lineno=lineno,
col_offset=col)
def ensure_list_from_str_or_list(x, lineno=None, col=None):
"""Creates the AST node for the following expression::
[x] if isinstance(x, str) else x
Somewhat useful.
"""
return ast.IfExp(test=ast.Call(func=ast.Name(id='isinstance',
ctx=ast.Load(),
lineno=lineno,
col_offset=col),
args=[x, ast.Name(id='str',
ctx=ast.Load(),
lineno=lineno,
col_offset=col)],
keywords=[],
starargs=None,
kwargs=None,
lineno=lineno,
col_offset=col),
body=ast.List(elts=[x],
ctx=ast.Load(),
lineno=lineno,
col_offset=col),
orelse=x,
lineno=lineno,
col_offset=col)
def xonsh_call(name, args, lineno=None, col=None):
"""Creates the AST node for calling a function of a given name."""
return ast.Call(func=ast.Name(id=name,
ctx=ast.Load(),
lineno=lineno,
col_offset=col),
args=args,
keywords=[],
starargs=None,
kwargs=None,
lineno=lineno,
col_offset=col)
def xonsh_help(x, lineno=None, col=None):
"""Creates the AST node for calling the __xonsh_help__() function."""
return xonsh_call('__xonsh_help__', [x], lineno=lineno, col=col)
def xonsh_superhelp(x, lineno=None, col=None):
"""Creates the AST node for calling the __xonsh_superhelp__() function."""
return xonsh_call('__xonsh_superhelp__', [x], lineno=lineno, col=col)
def xonsh_regexpath(x, lineno=None, col=None):
"""Creates the AST node for calling the __xonsh_regexpath__() function."""
return xonsh_call('__xonsh_regexpath__', [x], lineno=lineno, col=col)
def load_ctx(x):
"""Recursively sets ctx to ast.Load()"""
if not hasattr(x, 'ctx'):
return
x.ctx = ast.Load()
if isinstance(x, (ast.Tuple, ast.List)):
for e in x.elts:
load_ctx(e)
elif isinstance(x, ast.Starred):
load_ctx(x.value)
def store_ctx(x):
"""Recursively sets ctx to ast.Store()"""
if not hasattr(x, 'ctx'):
return
x.ctx = ast.Store()
if isinstance(x, (ast.Tuple, ast.List)):
for e in x.elts:
store_ctx(e)
elif isinstance(x, ast.Starred):
store_ctx(x.value)
def empty_list_if_newline(x):
return [] if x == '\n' else x
class Parser(object):
"""A class that parses the xonsh language."""
def __init__(self,
lexer_optimize=True,
lexer_table='xonsh.lexer_table',
yacc_optimize=True,
yacc_table='xonsh.parser_table',
yacc_debug=False,
outputdir=None):
"""Parameters
----------
lexer_optimize : bool, optional
Set to false when unstable and true when lexer is stable.
lexer_table : str, optional
Lexer module used when optimized.
yacc_optimize : bool, optional
Set to false when unstable and true when parser is stable.
yacc_table : str, optional
Parser module used when optimized.
yacc_debug : debug, optional
Dumps extra debug info.
outputdir : str or None, optional
The directory to place generated tables within.
"""
self.lexer = lexer = Lexer()
self.tokens = lexer.tokens
opt_rules = [
'newlines', 'arglist', 'func_call', 'rarrow_test', 'typedargslist',
'equals_test', 'colon_test', 'tfpdef', 'comma_tfpdef_list',
'comma_pow_tfpdef', 'vfpdef', 'comma_vfpdef_list',
'comma_pow_vfpdef', 'equals_yield_expr_or_testlist_list',
'testlist', 'as_name', 'period_or_ellipsis_list',
'comma_import_as_name_list', 'comma_dotted_as_name_list',
'comma_name_list', 'comma_test', 'elif_part_list', 'finally_part',
'varargslist', 'or_and_test_list', 'and_not_test_list',
'comp_op_expr_list', 'xor_and_expr_list',
'ampersand_shift_expr_list', 'shift_arith_expr_list',
'op_factor_list', 'trailer_list', 'testlist_comp',
'yield_expr_or_testlist_comp', 'dictorsetmaker',
'comma_subscript_list', 'test', 'sliceop', 'comp_iter',
'yield_arg', 'test_comma_list',]
if VER_MAJOR_MINOR <= VER_3_4:
opt_rules += ['argument_comma_list', 'comma_argument_list',]
for rule in opt_rules:
self._opt_rule(rule)
list_rules = [
'comma_tfpdef', 'comma_vfpdef', 'semi_small_stmt',
'comma_test_or_star_expr', 'period_or_ellipsis',
'comma_import_as_name', 'comma_dotted_as_name', 'period_name',
'comma_name', 'elif_part', 'except_part', 'comma_with_item',
'or_and_test', 'and_not_test', 'comp_op_expr', 'pipe_xor_expr',
'xor_and_expr', 'ampersand_shift_expr', 'shift_arith_expr',
'pm_term', 'op_factor', 'trailer', 'comma_subscript',
'comma_expr_or_star_expr', 'comma_test', 'comma_argument', 'comma_item',
'attr_period_name', 'test_comma', 'equals_yield_expr_or_testlist',
'test_or_star_expr']
if VER_MAJOR_MINOR <= VER_3_4:
list_rules += ['argument_comma',]
for rule in list_rules:
self._list_rule(rule)
yacc_kwargs = dict(module=self,
debug=yacc_debug,
start='start_symbols',
optimize=yacc_optimize,
tabmodule=yacc_table)
if not yacc_debug:
yacc_kwargs['errorlog'] = yacc.NullLogger()
if outputdir is not None:
yacc_kwargs['outputdir'] = outputdir
self.parser = yacc.yacc(**yacc_kwargs)
# Keeps track of the last token given to yacc (the lookahead token)
self._last_yielded_token = None
def reset(self):
"""Resets for clean parsing."""
self.lexer.reset()
self._last_yielded_token = None
def parse(self, s, filename='<code>', mode='exec', debug_level=0):
"""Returns an abstract syntax tree of xonsh code.
Parameters
----------
s : str
The xonsh code.
filename : str, optional
Name of the file.
mode : str, optional
Execution mode, one of: exec, eval, or single.
debug_level : str, optional
Debugging level passed down to yacc.
Returns
-------
tree : AST
"""
self.reset()
self.lexer.fname = filename
tree = self.parser.parse(input=s, lexer=self.lexer, debug=debug_level)
# hack for getting modes right
if mode == 'single':
if isinstance(tree, ast.Expression):
tree = ast.Interactive(body=[self.expr(tree.body)])
elif isinstance(tree, ast.Module):
tree = ast.Interactive(body=tree.body)
return tree
def _lexer_errfunc(self, msg, line, column):
self._parse_error(msg, self.currloc(line, column))
def _yacc_lookahead_token(self):
"""Gets the last token seen by the lexer."""
return self.lexer.last
def _opt_rule(self, rulename):
"""For a rule name, creates an associated optional rule.
'_opt' is appended to the rule name.
"""
def optfunc(self, p):
p[0] = p[1]
optfunc.__doc__ = ('{0}_opt : empty\n'
' | {0}').format(rulename)
optfunc.__name__ = 'p_' + rulename + '_opt'
setattr(self.__class__, optfunc.__name__, optfunc)
def _list_rule(self, rulename):
"""For a rule name, creates an associated list rule.
'_list' is appended to the rule name.
"""
def listfunc(self, p):
p[0] = p[1] if len(p) == 2 else p[1] + p[2]
listfunc.__doc__ = ('{0}_list : {0}\n'
' | {0}_list {0}').format(rulename)
listfunc.__name__ = 'p_' + rulename + '_list'
setattr(self.__class__, listfunc.__name__, listfunc)
def currloc(self, lineno, column=None):
"""Returns the current location."""
return Location(fname=self.lexer.fname, lineno=lineno, column=column)
def expr(self, p):
"""Creates an expression for a token."""
return ast.Expr(value=p, lineno=p.lineno, col_offset=p.col_offset)
def token_col(self, t):
"""Gets ths token column"""
return t.lexpos
@property
def lineno(self):
if self.lexer.last is None:
return 0
else:
return self.lexer.last.lineno
@property
def col(self):
t = self._yacc_lookahead_token()
if t is not None:
return self.token_col(t)
return 1
def _parse_error(self, msg, loc):
err = SyntaxError('{0}: {1}'.format(loc, msg))
err.loc = loc
raise err
#
# Precedence of operators
#
precedence = (('left', 'PIPE'), ('left', 'XOR'), ('left', 'AMPERSAND'),
('left', 'EQ', 'NE'), ('left', 'GT', 'GE', 'LT', 'LE'),
('left', 'RSHIFT', 'LSHIFT'), ('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIVIDE', 'DOUBLEDIV', 'MOD'),
('left', 'POW'), )
#
# Grammar as defined by BNF
#
def p_start_symbols(self, p):
"""start_symbols : single_input
| file_input
| eval_input
| empty
"""
p[0] = p[1]
def p_single_input(self, p):
"""single_input : compound_stmt NEWLINE
"""
p1 = empty_list_if_newline(p[1])
p0 = ast.Interactive(body=p1)
p[0] = p0
def p_file_input(self, p):
"""file_input : file_stmts"""
p[0] = ast.Module(body=p[1])
def p_file_stmts(self, p):
"""file_stmts : newline_or_stmt
| file_stmts newline_or_stmt
"""
if len(p) == 2:
# newline_or_stmt ENDMARKER
p1 = empty_list_if_newline(p[1])
p[0] = p1
else:
# file_input newline_or_stmt ENDMARKER
p2 = empty_list_if_newline(p[2])
p[0] = p[1] + p2
def p_newline_or_stmt(self, p):
"""newline_or_stmt : NEWLINE
| stmt
"""
p[0] = p[1]
def p_newlines(self, p):
"""newlines : NEWLINE
| newlines NEWLINE
"""
p[0] = p[1] if len(p) == 2 else p[1] + p[2]
def p_eval_input(self, p):
"""eval_input : testlist newlines_opt
"""
p[0] = ast.Expression(body=p[1])
def p_func_call(self, p):
"""func_call : LPAREN arglist_opt RPAREN"""
p[0] = p[2]
def p_attr_period_name(self, p):
"""attr_period_name : PERIOD NAME"""
p[0] = [p[2]]
def p_attr_name(self, p):
"""attr_name : NAME
| NAME attr_period_name_list
"""
p1 = p[1]
name = ast.Name(id=p1,
ctx=ast.Load(),
lineno=self.lineno,
col_offset=self.col)
if len(p) == 2:
p0 = name
else:
p2 = p[2]
p0 = ast.Attribute(value=name,
attr=p2[0],
ctx=ast.Load(),
lineno=self.lineno,
col_offset=self.col)
for a in p2[1:]:
p0 = ast.Attribute(value=p0,
attr=a,
ctx=ast.Load(),
lineno=self.lineno,
col_offset=self.col)
p[0] = p0
def p_decorator(self, p):
"""decorator : AT attr_name NEWLINE
| AT attr_name func_call NEWLINE
"""
lenp = len(p)
name = p[2]
p3 = p[3] if lenp > 3 else None
if lenp == 4:
p0 = name
elif p3 is None:
p0 = ast.Call(func=name,
args=[],
keywords=[],
starargs=None,
kwargs=None,
lineno=self.lineno,
col_offset=self.col)
else:
p0 = ast.Call(func=name,
lineno=self.lineno,
col_offset=self.col, **p3)
p[0] = p0
def p_decorators(self, p):
"""decorators : decorator
| decorators decorator
"""
p[0] = [p[1]] if len(p) == 2 else p[1] + [p[2]]
@docstring_by_version(
v34=\
"""classdef_or_funcdef : classdef
| funcdef
""",
v35=\
"""classdef_or_funcdef : classdef
| funcdef
| async_funcdef
""",
)
def p_classdef_or_funcdef(self, p):
p[0] = p[1]
def p_decorated(self, p):
"""decorated : decorators classdef_or_funcdef"""
p1, p2 = p[1], p[2]
p2[0].decorator_list = p1
p[0] = p2
def p_rarrow_test(self, p):
"""rarrow_test : RARROW test"""
p[0] = p[2]
def p_funcdef(self, p):
"""funcdef : DEF NAME parameters rarrow_test_opt COLON suite"""
f = ast.FunctionDef(name=p[2],
args=p[3],
returns=p[4],
body=p[6],
decorator_list=[],
lineno=self.lineno,
col_offset=self.col)
p[0] = [f]
def p_async_funcdef(self, p):
"""async_funcdef : ASYNC funcdef"""
f = p[2][0]
p[0] = [ast.AsyncFunctionDef(**f.__dict__)]
def p_parameters(self, p):
"""parameters : LPAREN typedargslist_opt RPAREN"""
p2 = p[2]
if p2 is None:
p2 = ast.arguments(args=[],
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[])
p[0] = p2
def p_equals_test(self, p):
"""equals_test : EQUALS test"""
p[0] = p[2]
def p_typedargslist(self, p):
"""typedargslist : tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt
| tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt COMMA POW vfpdef
| tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt comma_tfpdef_list_opt
| tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt TIMES tfpdef_opt comma_tfpdef_list COMMA POW tfpdef
| tfpdef equals_test_opt comma_tfpdef_list_opt comma_opt POW tfpdef
| TIMES tfpdef_opt comma_tfpdef_list comma_pow_tfpdef_opt
| TIMES tfpdef_opt comma_pow_tfpdef_opt
| POW tfpdef
"""
lenp = len(p)
p1, p2 = p[1], p[2]
p3 = p[3] if lenp > 3 else None
p4 = p[4] if lenp > 4 else None
# skip p5
p6 = p[6] if lenp > 6 else None
p7 = p[7] if lenp > 7 else None
# skip p8
p9 = p[9] if lenp > 9 else None
p10 = p[10] if lenp > 10 else None
p0 = ast.arguments(args=[],
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[])
if lenp == 3:
p0.kwarg = p2
elif lenp == 4:
self._set_var_args(p0, p2, None)
p0.kwarg = p3
elif lenp == 5 and p1 != '*':
# x
self._set_regular_args(p0, p1, p2, p3, p4)
elif lenp == 5 and p1 == '*':
self._set_var_args(p0, p2, p3) # *args
if p4 is not None:
# *args, x, **kwargs
p0.kwarg = p4
elif lenp == 7:
# x, **kwargs
self._set_regular_args(p0, p1, p2, p3, p4)
p0.kwarg = p[6]
elif lenp == 8:
# x, *args
self._set_regular_args(p0, p1, p2, p3, p4)
self._set_var_args(p0, p6, p7)
elif lenp == 10:
# x, *args, **kwargs
self._set_regular_args(p0, p1, p2, p3, p4)
self._set_var_args(p0, p6, None)
p0.kwarg = p9
elif lenp == 11:
# x, *args, **kwargs
self._set_regular_args(p0, p1, p2, p3, p4)
self._set_var_args(p0, p6, p7)
p0.kwarg = p10
else:
assert False
p[0] = p0
def p_colon_test(self, p):
"""colon_test : COLON test"""
p[0] = p[2]
def p_tfpdef(self, p):
"""tfpdef : NAME colon_test_opt"""
p[0] = ast.arg(arg=p[1], annotation=p[2])
def p_comma_tfpdef(self, p):
"""comma_tfpdef : COMMA
| COMMA tfpdef equals_test_opt
"""
if len(p) == 2:
p[0] = []
else:
p[0] = [{'arg': p[2], 'default': p[3]}]
def p_comma_pow_tfpdef(self, p):
"""comma_pow_tfpdef : COMMA POW tfpdef"""
p[0] = p[3]
def _set_args_def(self, argmts, vals, kwargs=False):
args, defs = (argmts.kwonlyargs, argmts.kw_defaults) if kwargs else \
(argmts.args, argmts.defaults)
for v in vals:
args.append(v['arg'])
d = v['default']
if kwargs or (d is not None):
defs.append(d)
def _set_regular_args(self, p0, p1, p2, p3, p4):
if p2 is None and p3 is None:
# x
p0.args.append(p1)
elif p2 is not None and p3 is None:
# x=42
p0.args.append(p1)
p0.defaults.append(p2)
elif p2 is None and p3 is not None:
# x, y and x, y=42
p0.args.append(p1)
self._set_args_def(p0, p3)
else:
# x=42, y=42
p0.args.append(p1)
p0.defaults.append(p2)
self._set_args_def(p0, p3)
def _set_var_args(self, p0, vararg, kwargs):
if vararg is None:
self._set_args_def(p0, kwargs, kwargs=True)
elif vararg is not None and kwargs is None:
# *args
p0.vararg = vararg
elif vararg is not None and kwargs is not None:
# *args, x and *args, x, y and *args, x=10 and *args, x=10, y
# and *args, x, y=10, and *args, x=42, y=65
p0.vararg = vararg
self._set_args_def(p0, kwargs, kwargs=True)
else:
assert False
def p_varargslist(self, p):
"""varargslist : vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt
| vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt COMMA POW vfpdef
| vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt comma_vfpdef_list_opt
| vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt TIMES vfpdef_opt comma_vfpdef_list COMMA POW vfpdef
| vfpdef equals_test_opt comma_vfpdef_list_opt comma_opt POW vfpdef
| TIMES vfpdef_opt comma_vfpdef_list comma_pow_vfpdef_opt
| TIMES vfpdef_opt comma_pow_vfpdef_opt
| POW vfpdef
"""
lenp = len(p)
p1, p2 = p[1], p[2]
p3 = p[3] if lenp > 3 else None
p4 = p[4] if lenp > 4 else None
# skip p5
p6 = p[6] if lenp > 6 else None
p7 = p[7] if lenp > 7 else None
# skip p8
p9 = p[9] if lenp > 9 else None
p10 = p[10] if lenp > 10 else None
p0 = ast.arguments(args=[],
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[])
if lenp == 3:
p0.kwarg = p2
elif lenp == 4:
self._set_var_args(p0, p2, None)
p0.kwarg = p3
elif lenp == 5 and p1 != '*':
# x
self._set_regular_args(p0, p1, p2, p3, p4)
elif lenp == 5 and p1 == '*':
self._set_var_args(p0, p2, p3) # *args
if p4 is not None:
# *args, x, **kwargs
p0.kwarg = p4
elif lenp == 7:
# x, **kwargs
self._set_regular_args(p0, p1, p2, p3, p4)
p0.kwarg = p6
elif lenp == 8:
# x, *args
self._set_regular_args(p0, p1, p2, p3, p4)
self._set_var_args(p0, p6, p7)
elif lenp == 10:
# x, *args, **kwargs
self._set_regular_args(p0, p1, p2, p3, p4)
self._set_var_args(p0, p6, None)
p0.kwarg = p9
elif lenp == 11:
# x, *args, **kwargs
self._set_regular_args(p0, p1, p2, p3, p4)
self._set_var_args(p0, p6, p7)
p0.kwarg = p10
else:
assert False
p[0] = p0
def p_vfpdef(self, p):
"""vfpdef : NAME"""
p[0] = ast.arg(arg=p[1], annotation=None)
def p_comma_vfpdef(self, p):
"""comma_vfpdef : COMMA
| COMMA vfpdef equals_test_opt
"""
if len(p) == 2:
p[0] = []
else:
p[0] = [{'arg': p[2], 'default': p[3]}]
def p_comma_pow_vfpdef(self, p):
"""comma_pow_vfpdef : COMMA POW vfpdef"""
p[0] = p[3]
def p_stmt(self, p):
"""stmt : simple_stmt
| compound_stmt
"""
p[0] = p[1]
def p_stmt_list(self, p):
"""stmt_list : stmt
| stmt_list stmt"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = p[1] + p[2]
def p_semi_opt(self, p):
"""semi_opt : SEMI
| empty
"""
if len(p) == 2:
p[0] = p[1]
def p_semi_small_stmt(self, p):
"""semi_small_stmt : SEMI small_stmt"""
p[0] = [p[2]]
def p_simple_stmt(self, p):
"""simple_stmt : small_stmt semi_small_stmt_list semi_opt NEWLINE
| small_stmt semi_opt NEWLINE
"""
p1, p2 = p[1], p[2]
p0 = [p1]
if p2 is not None and p2 != ';':
p0 += p2
p[0] = p0
def p_small_stmt(self, p):
"""small_stmt : expr_stmt
| del_stmt
| pass_stmt
| flow_stmt
| import_stmt
| global_stmt
| nonlocal_stmt
| assert_stmt
"""
p[0] = p[1]
_augassign_op = {
'+=': ast.Add,
'-=': ast.Sub,
'*=': ast.Mult,
'@=': ast.MatMult,
'/=': ast.Div,
'%=': ast.Mod,
'//=': ast.FloorDiv,
'**=': ast.Pow,
'^=': ast.BitXor,
'&=': ast.BitAnd,
'|=': ast.BitOr,
'<<=': ast.LShift,
'>>=': ast.RShift
}
def p_expr_stmt(self, p):
"""expr_stmt : testlist_star_expr augassign yield_expr_or_testlist
| testlist_star_expr equals_yield_expr_or_testlist_list_opt
| testlist equals_yield_expr_or_testlist_list_opt
| test_comma_list_opt star_expr comma_test_list equals_yield_expr_or_testlist
| test_comma_list_opt star_expr comma_opt test_comma_list_opt equals_yield_expr_or_testlist
"""
lenp = len(p)
p1, p2 = p[1], p[2]
p1 = [] if p1 is None else p1
if isinstance(p1, ast.Tuple):
p1 = [p1]
for targ in p1:
store_ctx(targ)
if lenp == 3:
if p2 is None and len(p1) == 1:
load_ctx(p1[0])
p0 = self.expr(p1[0])
elif p2 is None:
assert False
else:
list(map(store_ctx, p2[:-1]))
p0 = ast.Assign(targets=p1 + p2[:-1],
value=p2[-1],
lineno=self.lineno,
col_offset=self.col)
elif lenp == 4:
op = self._augassign_op[p2]
if op is None:
self._parse_error('operation {0!r} not supported'.format(p2),
self.currloc(lineno=p.lineno, column=p.lexpos))
p0 = ast.AugAssign(target=p1[0], op=op(), value=p[3],
lineno=self.lineno, col_offset=self.col)
elif lenp == 5 or lenp == 6:
if lenp == 5:
targs, rhs = p[3], p[4][0]
else:
targs, rhs = (p[4] or []), p[5][0]
store_ctx(p2)
for targ in targs:
store_ctx(targ)
p1.append(p2)
p1.extend(targs)
p1 = [ast.Tuple(elts=p1,
ctx=ast.Store(),
lineno=self.lineno,
col_offset=self.col)]
p0 = ast.Assign(targets=p1,
value=rhs,
lineno=self.lineno,
col_offset=self.col)
else:
assert False
p[0] = p0
def p_test_comma(self, p):
"""test_comma : test COMMA"""
p[0] = [p[1]]
def p_comma_opt(self, p):
"""comma_opt : COMMA
| empty
"""
if len(p) == 2:
p[0] = p[1]
def p_test_or_star_expr(self, p):
"""test_or_star_expr : test
| star_expr
"""
p[0] = p[1]
def p_comma_test_or_star_expr(self, p):
"""comma_test_or_star_expr : COMMA test_or_star_expr"""
p[0] = [p[2]]
def p_testlist_star_expr(self, p):
"""testlist_star_expr : test_or_star_expr comma_test_or_star_expr_list comma_opt
| test_or_star_expr comma_opt
"""
p1, p2 = p[1], p[2]
if p2 is None:
p0 = [p1]
elif p2 == ',':
p0 = [ast.Tuple(elts=[p1],
ctx=ast.Load(),
lineno=self.lineno,
col_offset=self.col)]
else:
p0 = [ast.Tuple(elts=[p1] + p2,
ctx=ast.Load(),
lineno=self.lineno,
col_offset=self.col)]
p[0] = p0
def p_augassign(self, p):
"""augassign : PLUSEQUAL
| MINUSEQUAL
| TIMESEQUAL
| ATEQUAL
| DIVEQUAL
| MODEQUAL
| AMPERSANDEQUAL
| PIPEEQUAL
| XOREQUAL
| LSHIFTEQUAL
| RSHIFTEQUAL
| POWEQUAL
| DOUBLEDIVEQUAL
"""
p[0] = p[1]
def p_yield_expr_or_testlist(self, p):
"""yield_expr_or_testlist : yield_expr
| testlist
"""
p[0] = p[1]
def p_equals_yield_expr_or_testlist(self, p):
"""equals_yield_expr_or_testlist : EQUALS yield_expr_or_testlist"""
p[0] = [p[2]]
#
# For normal assignments, additional restrictions enforced
# by the interpreter
#
def p_del_stmt(self, p):
"""del_stmt : DEL exprlist"""
p2 = p[2]
for targ in p2:
targ.ctx = ast.Del()
p0 = ast.Delete(targets=p2, lineno=self.lineno, col_offset=self.col)
p[0] = p0
def p_pass_stmt(self, p):
"""pass_stmt : PASS"""
p[0] = ast.Pass(lineno=self.lineno, col_offset=self.col)
def p_flow_stmt(self, p):
"""flow_stmt : break_stmt
| continue_stmt
| return_stmt
| raise_stmt
| yield_stmt
"""
p[0] = p[1]
def p_break_stmt(self, p):
"""break_stmt : BREAK"""
p[0] = ast.Break(lineno=self.lineno, col_offset=self.col)
def p_continue_stmt(self, p):
"""continue_stmt : CONTINUE"""
p[0] = ast.Continue(lineno=self.lineno, col_offset=self.col)
def p_return_stmt(self, p):
"""return_stmt : RETURN testlist_opt"""
p[0] = ast.Return(value=p[2], lineno=self.lineno, col_offset=self.col)
def p_yield_stmt(self, p):
"""yield_stmt : yield_expr"""
p[0] = self.expr(p[1])
def p_raise_stmt(self, p):
"""raise_stmt : RAISE
| RAISE test
| RAISE test FROM test
"""
lenp = len(p)
cause = None
if lenp == 2:
exc = None
elif lenp == 3:
exc = p[2]
elif lenp == 5:
exc = p[2]
cause = p[4]
else:
assert False
p0 = ast.Raise(exc=exc,
cause=cause,
lineno=self.lineno,
col_offset=self.col)
p[0] = p0
def p_import_stmt(self, p):
"""import_stmt : import_name
| import_from
"""
p[0] = p[1]
def p_import_name(self, p):
"""import_name : IMPORT dotted_as_names
"""
p[0] = ast.Import(names=p[2], lineno=self.lineno, col_offset=self.col)
def p_import_from_pre(self, p):
"""import_from_pre : FROM period_or_ellipsis_list_opt dotted_name
| FROM period_or_ellipsis_list
"""
if len(p) == 3:
p0 = p[2]
elif len(p) == 4:
p2, p3 = p[2], p[3]
p0 = p3 if p2 is None else p2 + p3
else:
assert False
p[0] = p0
def p_import_from_post(self, p):
"""import_from_post : TIMES
| LPAREN import_as_names RPAREN
| import_as_names
"""
if len(p) == 2:
if p[1] == '*':
p[1] = [ast.alias(name='*', asname=None)]
p0 = p[1]
elif len(p) == 4:
p0 = p[2]