-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathast.py
More file actions
1491 lines (1340 loc) · 53.3 KB
/
ast.py
File metadata and controls
1491 lines (1340 loc) · 53.3 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
from blib2to3.pgen2 import token
from ast import literal_eval
from semmle.python import ast
from blib2to3.pgen2.parse import ParseError
import sys
LOAD = ast.Load()
STORE = ast.Store()
PARAM = ast.Param()
DEL = ast.Del()
POSITIONAL = 1
KEYWORD = 2
class ParseTreeVisitor(object):
'''Standard tree-walking visitor,
using `node.name` rather than `type(node).__name__`
'''
def visit(self, node, extra_arg=None):
method = 'visit_' + node.name
if extra_arg is None:
return getattr(self, method)(node)
else:
return getattr(self, method)(node, extra_arg)
class Convertor(ParseTreeVisitor):
''' Walk the conrete parse tree, returning an AST.
The CPT is specified by blib2to3/Grammar.txt.
The AST specified by semmle/python/master.py.
Each `visit_X` method takes a `X` node in the CFG and
produces some part of the AST, usually a single node.
'''
def __init__(self, logger):
self.logger = logger
# To handle f-strings nested inside other f-strings, we must keep track of the stack of
# surrounding prefixes while walking the tree. This is necessary because inside an f-string
# like `f"hello{f'to{you}dear'}world"`, the string part containing "world" has (in terms of
# the concrete parse tree) a prefix of `}`, which doesn't tell us how to interpret it (in
# particular, we can't tell if it's a raw string or not). So instead we look at the top of
# the prefix stack to figure out what the "current prefix" is. The nested f-string in the
# example above demonstrates why we must do this as a stack -- we must restore the outer
# `f"` prefix when we're done with the inner `f'`-prefix string.
#
# The stack manipulation itself takes place in the `visit_FSTRING_START` and
# `visit_FSTRING_END` methods. The text wrangling takes place in the `parse_string` helper
# function.
self.outer_prefix_stack = []
def visit_file_input(self, node):
body = []
for s in [self.visit(s) for s in node.children if s.name not in ("ENDMARKER", "NEWLINE")]:
if isinstance(s, list):
body.extend(s)
else:
body.append(s)
result = ast.Module(body)
set_location(result, node)
return result
def visit_import_from(self, node):
level = 0
index = 1
module_start = node.children[index].start
while is_token(node.children[index], "."):
level += 1
index += 1
if is_token(node.children[index], "import"):
module_end = node.children[index-1].end
index += 1
module_name = None
else:
module_end = node.children[index].end
module_name = self.visit(node.children[index])
index += 2
if is_token(node.children[index], "*"):
module = ast.ImportExpr(level, module_name, False)
set_location(module, module_start, module_end)
result = ast.ImportFrom(module)
set_location(result, node)
return result
if is_token(node.children[index], "("):
import_as_names = node.children[index+1]
else:
import_as_names = node.children[index]
aliases = []
for import_as_name in import_as_names.children[::2]:
module = ast.ImportExpr(level, module_name, False)
set_location(module, module_start, module_end)
aliases.append(self._import_as_name(import_as_name, module))
result = ast.Import(aliases)
set_location(result, node)
return result
#Helper for visit_import_from
def _import_as_name(self, node, module):
name = node.children[0].value
if len(node.children) == 3:
asname = node.children[2]
else:
asname = node.children[0]
expr = ast.ImportMember(module, name)
set_location(expr, node)
rhs = make_name(asname.value, STORE, asname.start, asname.end)
result = ast.alias(expr, rhs)
set_location(result, node)
return result
def visit_small_stmt(self, node):
return self.visit(node.children[0])
def visit_simple_stmt(self, node):
return [self.visit(s) for s in node.children if s.name not in ("SEMI", "NEWLINE")]
def visit_stmt(self, node):
return self.visit(node.children[0])
def visit_compound_stmt(self, node):
return self.visit(node.children[0])
def visit_pass_stmt(self, node):
p = ast.Pass()
set_location(p, node)
return p
def visit_classdef(self, node):
if len(node.children) == 4:
cls, name, colon, suite = node.children
args, keywords = [], []
elif len(node.children) == 7:
cls, name, _, args, _, colon, suite = node.children
args, keywords = self.visit(args)
else:
assert len(node.children) == 6
cls, name, _, _, colon, suite = node.children
args, keywords = [], []
start = cls.start
end = colon.end
suite = self.visit(suite)
inner = ast.Class(name.value, suite)
set_location(inner, start, end)
cls_expr = ast.ClassExpr(name.value, [], args, keywords, inner)
set_location(cls_expr, start, end)
name_expr = make_name(name.value, STORE, name.start, name.end)
result = ast.Assign(cls_expr, [name_expr])
set_location(result, start, end)
return result
def visit_arglist(self, node):
all_args = self._visit_list(node.children[::2])
args = [ arg for kind, arg in all_args if kind is POSITIONAL ]
keywords = [ arg for kind, arg in all_args if kind is KEYWORD ]
return args, keywords
def visit_argument(self, node):
child = node.children[0]
if is_token(child, "*"):
kind, arg = POSITIONAL, ast.Starred(self.visit(node.children[1], LOAD), LOAD)
elif is_token(child, "**"):
kind, arg = KEYWORD, ast.DictUnpacking(self.visit(node.children[1], LOAD))
elif len(node.children) == 3 and is_token(node.children[1], "="):
try:
name = get_node_value(child)
except Exception:
#Not a legal name
name = None
self.logger.warning("Illegal name for keyword on line %s", child.start[0])
kind, arg = KEYWORD, ast.keyword(name, self.visit(node.children[2], LOAD))
else:
arg = self.visit(child, LOAD)
if len(node.children) == 1:
return POSITIONAL, arg
elif len(node.children) == 3 and is_token(node.children[1], ":="):
return POSITIONAL, self.visit_namedexpr_test(node, LOAD)
generators = self.visit(node.children[1])
kind, arg = POSITIONAL, ast.GeneratorExp(arg, generators)
set_location(arg, node)
rewrite_comp(arg)
set_location(arg, node)
return kind, arg
def visit_namedexpr_test(self, node, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
target = self.visit(node.children[0], STORE)
value = self.visit(node.children[-1], LOAD)
result = ast.AssignExpr(value, target)
set_location(result, node)
return result
def visit_test(self, node, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
else:
if ctx is not LOAD:
context_error(node)
body = self.visit(node.children[0], ctx)
test = self.visit(node.children[2], ctx)
orelse = self.visit(node.children[4], ctx)
ifexp = ast.IfExp(test, body, orelse)
set_location(ifexp, node)
return ifexp
def visit_or_test(self, node, ctx):
return self._boolop(node, ast.Or, ctx)
def visit_and_test(self, node, ctx):
return self._boolop(node, ast.And, ctx)
def visit_not_test(self, node, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
if ctx is not LOAD:
context_error(node)
result = ast.UnaryOp(
ast.Not(),
self.visit(node.children[1], ctx)
)
set_location(result, node)
return result
# Helper for `or` and `and`.
def _boolop(self, node, opcls, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
values = [ self.visit(s, ctx) for s in node.children[::2] ]
result = ast.BoolOp(opcls(), values)
set_location(result, node)
return result
# Helper for various binary expression visitors.
def _binary(self, node, opfact, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
if ctx is not LOAD:
context_error(node)
children = iter(node.children)
result = self.visit(next(children), LOAD)
for op in children:
item = next(children)
rhs = self.visit(item, LOAD)
result = ast.BinOp(result, opfact(op), rhs)
set_location(result, node.start, item.end)
return result
def visit_suite(self, node):
if len(node.children) == 1:
return self.visit(node.children[0])
result = []
for s in [self.visit(s) for s in node.children[2:-1]]:
if isinstance(s, list):
result.extend(s)
else:
result.append(s)
return result
def visit_expr_stmt(self, node):
if len(node.children) == 1:
result = ast.Expr(self.visit(node.children[0], LOAD))
set_location(result, node)
return result
if len(node.children) > 1 and is_token(node.children[1], "="):
return self._assign(node)
if len(node.children) == 2:
# Annotated assignment
target = self.visit(node.children[0], STORE)
ann = node.children[1]
type_anno = self.visit(ann.children[1], LOAD)
if len(ann.children) > 2:
value = self.visit(ann.children[3], LOAD)
else:
value = None
result = ast.AnnAssign(value, type_anno, target)
else:
#Augmented assignment
lhs = self.visit(node.children[0], LOAD)
op = self.visit(node.children[1])
rhs = self.visit(node.children[2], LOAD)
expr = ast.BinOp(lhs, op, rhs)
set_location(expr, node)
result = ast.AugAssign(expr)
set_location(result, node)
return result
def visit_augassign(self, node):
return AUG_ASSIGN_OPS[node.children[0].value]()
#Helper for visit_expr_stmt (for assignment)
def _assign(self, node):
targets = [ self.visit(t, STORE) for t in node.children[:-1:2]]
result = ast.Assign(self.visit(node.children[-1], LOAD), targets)
set_location(result, node)
return result
def visit_testlist(self, node, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
elts = self._visit_list(node.children[::2], ctx)
result = ast.Tuple(elts, ctx)
set_location(result, node)
return result
visit_testlist_star_expr = visit_testlist
def visit_comparison(self, node, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
if ctx is not LOAD:
context_error(node)
left = self.visit(node.children[0], ctx)
ops = [ self.visit(op) for op in node.children[1::2]]
comps = [ self.visit(op, ctx) for op in node.children[2::2]]
result = ast.Compare(left, ops, comps)
set_location(result, node)
return result
def visit_comp_op(self, node):
if len(node.children) == 1:
return COMP_OP_CLASSES[node.children[0].value]()
else:
assert len(node.children) == 2
return ast.IsNot() if node.children[0].value == "is" else ast.NotIn()
def visit_expr(self, node, ctx):
return self._binary(node, lambda _: ast.BitOr(), ctx)
def visit_xor_expr(self, node, ctx):
return self._binary(node, lambda _: ast.BitXor(), ctx)
def visit_and_expr(self, node, ctx):
return self._binary(node, lambda _: ast.BitAnd(), ctx)
def visit_shift_expr(self, node, ctx):
return self._binary(
node,
lambda op: ast.LShift() if op.value == "<<" else ast.RShift(),
ctx
)
def visit_arith_expr(self, node, ctx):
return self._binary(
node,
lambda op: ast.Add() if op.value == "+" else ast.Sub(),
ctx
)
def visit_term(self, node, ctx):
return self._binary(
node,
lambda op: TERM_OP_CLASSES[op.value](),
ctx
)
def visit_factor(self, node, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
result = ast.UnaryOp(
FACTOR_OP_CLASSES[node.children[0].value](),
self.visit(node.children[1], ctx)
)
set_location(result, node)
return result
def visit_power(self, node, ctx):
'''This part of the Grammar is formulated in a slightly
awkward way, so we need to recursively handle the `await`
prefix, then the `** factor` suffix, then the atom and trailers.
'''
# Because `await` was a valid identifier in earlier versions of Python,
# we cannot assume it indicates an `await` expression. We therefore
# have to look at what follows in order to make a decision. The
# relevant part of the grammar is
#
# power: ['await'] atom trailer* ['**' factor]
#
# The case we wish to identify is when 'await' appears, but as an
# `atom`, and not an `await` token.
#
# Because `atom` nodes may no longer be present (see
# `SKIP_IF_SINGLE_CHILD_NAMES` in `__init__.py`) we instead look at the
# node following the (potentially) skipped `atom`. In particular, if
# the following node is a `trailer` or "**" token, we know that the
# given node cannot be an `await` token, and must be an `atom` instead.
try:
next_node = node.children[1]
next_is_atom = next_node.name != "trailer" and not is_token(next_node, "**")
except (IndexError, AttributeError):
# IndexError if `node` has at most one child.
# AttributeError if `next_node` is a `Leaf` instead of a `Node`.
next_is_atom = False
if is_token(node.children[0], "await") and next_is_atom:
if ctx is not LOAD:
context_error(node)
pow = self._power(node.children[1:], ctx)
result = ast.Await(pow)
set_location(result, node)
return result
else:
return self._power(node.children, ctx)
#Helper for visit_power
def _power(self, children, ctx):
start = children[0].start
if len(children) > 1 and is_token(children[-2], "**"):
if ctx is not LOAD:
context_error(children[0])
trailers = children[1:-2]
pow_expr = self.visit(children[-1], ctx)
else:
trailers = children[1:]
pow_expr = None
if trailers:
expr = self.visit(children[0], LOAD)
for trailer in trailers[:-1]:
expr = self._apply_trailer(expr, trailer, start, LOAD)
expr = self._apply_trailer(expr, trailers[-1], start, ctx)
else:
expr = self.visit(children[0], ctx)
if pow_expr:
expr = ast.BinOp(expr, ast.Pow(), pow_expr)
set_location(expr, children[0].start, children[-1].end)
return expr
#Helper for _power
def _atom(self, children, ctx):
start = children[0].start
if len(children) == 1:
return self.visit(children[0], ctx)
atom = self.visit(children[0], LOAD)
for trailer in children[1:-1]:
atom = self._apply_trailer(atom, trailer, start, LOAD)
atom = self._apply_trailer(atom, children[-1], start, ctx)
return atom
#Helper for _atom
def _apply_trailer(self, atom, trailer, start, ctx):
children = trailer.children
left = children[0]
if is_token(left, "("):
if is_token(children[1], ")"):
args, keywords = [], []
end = children[1].end
else:
args, keywords = self.visit(children[1])
end = children[2].end
result = ast.Call(atom, args, keywords)
elif is_token(left, "["):
result = ast.Subscript(atom, self.visit(children[1], LOAD), ctx)
end = children[2].end
else:
assert is_token(left, ".")
result = ast.Attribute(atom, children[1].value, ctx)
end = children[1].end
set_location(result, start, end)
return result
def visit_atom(self, node, ctx):
left = node.children[0]
if left.value in "[({":
n = node.children[1]
if hasattr(n, "value") and n.value in "])}":
if n.value == ")":
result = ast.Tuple([], ctx)
elif n.value == "]":
result = ast.List([], ctx)
else:
result = ast.Dict([])
set_location(result, node)
return result
else:
result = self.visit(node.children[1], ctx)
if left.value == "(":
result.parenthesised = True
else:
#Meaningful bracketing
set_location(result, node)
if isinstance(result, (ast.GeneratorExp, ast.ListComp, ast.SetComp, ast.DictComp)):
rewrite_comp(result)
return result
if left.type == token.NAME:
return make_name(left.value, ctx, left.start, left.end)
if ctx is not LOAD:
context_error(node)
if left.type == token.NUMBER:
val = get_numeric_value(left)
result = ast.Num(val, left.value)
set_location(result, left)
return result
if left.value == ".":
assert len(node.children) == 3 and node.children[2].value == "."
result = ast.Ellipsis()
set_location(result, node)
return result
assert left.type == token.BACKQUOTE
result = ast.Repr(self.visit(node.children[1], LOAD))
set_location(result, node)
return result
def visit_STRING(self, node, ctx):
if ctx is not LOAD:
context_error(node)
outer_prefix = self.outer_prefix_stack[-1] if self.outer_prefix_stack else None
prefix, s = parse_string(node.value, self.logger, outer_prefix)
text = get_text(node.value, outer_prefix)
result = ast.StringPart(prefix, text, s)
set_location(result, node)
return result
def visit_NUMBER(self, node, ctx):
if ctx is not LOAD:
context_error(node)
val = get_numeric_value(node)
result = ast.Num(val, node.value)
set_location(result, node)
return result
def visit_funcdef(self, node, is_async=False):
# funcdef: 'def' NAME parameters ['->' test] ':' suite
name = node.children[1].value
if node.children[3].value == "->":
return_type = self.visit(node.children[4], LOAD)
end = node.children[5].end
body = self.visit(node.children[6])
else:
return_type = None
end = node.children[3].end
body = self.visit(node.children[4])
start = node.children[0].start
params = node.children[2]
if len(params.children) == 2:
args, vararg, kwonlyargs, kwarg = [], None, [], None
else:
args, vararg, kwonlyargs, kwarg = self._get_parameters(params.children[1])
func = ast.Function(name, [], args, vararg, kwonlyargs, kwarg, body, is_async)
set_location(func, start, end)
if len(params.children) == 2:
args = ast.arguments([], [], [], None, None, [])
else:
args = self._get_defaults_and_annotations(params.children[1])
funcexpr = ast.FunctionExpr(name, args, return_type, func)
set_location(funcexpr, start, end)
name_expr = make_name(name, STORE, node.children[1].start, node.children[1].end)
result = ast.Assign(funcexpr, [name_expr])
set_location(result, start, end)
return result
#Helper for visit_funcdef and visit_lambdef
def _get_parameters(self, node):
'''Returns the quadruple: args, vararg, kwonlyargs, kwarg
'''
args = []
vararg = None
kwonlyargs = []
kwarg = None
children = iter(node.children)
arg = None
for child in children:
if is_token(child, "*"):
try:
child = next(children)
except StopIteration:
pass
else:
if not is_token(child, ","):
vararg = self.visit(child, PARAM)
break
if is_token(child, ","):
pass
elif is_token(child, "/"):
pass
elif is_token(child, "="):
next(children)
elif is_token(child, "**"):
child = next(children)
kwarg = self.visit(child, PARAM)
else:
arg = self.visit(child, PARAM)
args.append(arg)
#kwonly args
for child in children:
if is_token(child, ","):
pass
elif is_token(child, "="):
next(children)
elif is_token(child, "**"):
child = next(children)
kwarg = self.visit(child, PARAM)
else:
arg = self.visit(child, PARAM)
kwonlyargs.append(arg)
return args, vararg, kwonlyargs, kwarg
#Helper for visit_funcdef and visit_lambdef
def _get_defaults_and_annotations(self, node):
defaults = []
kw_defaults = []
annotations = []
varargannotation = None
kwargannotation = None
kw_annotations = []
children = iter(node.children)
# Because we want the i'th element of `kw_defaults` to be the default value for
# the i'th keyword-only argument, when encountering the combined token for the
# argument name and optional annotation, we add a `None` to `kw_defaults` assuming
# that there is no default value. If there turns out to be a default value, we
# remove the `None` and add the real default value. Like-wise for `defaults`.
# positional-only args and "normal" args
for child in children:
if is_token(child, "*"):
try:
child = next(children)
except StopIteration:
pass
else:
if not is_token(child, ","):
varargannotation = self.visit(child, LOAD)
break
if is_token(child, ","):
pass
elif is_token(child, "/"):
pass
elif is_token(child, "="):
child = next(children)
defaults.pop()
defaults.append(self.visit(child, LOAD))
elif is_token(child, "**"):
child = next(children)
kwargannotation = self.visit(child, LOAD)
arg = None
else:
# Preemptively assume there is no default argument (indicated by None)
defaults.append(None)
annotations.append(self.visit(child, LOAD))
#kwonly args
for child in children:
if is_token(child, ","):
pass
elif is_token(child, "="):
child = next(children)
kw_defaults.pop()
kw_defaults.append(self.visit(child, LOAD))
elif is_token(child, "**"):
child = next(children)
kwargannotation = self.visit(child, LOAD)
else:
# Preemptively assume there is no default argument (indicated by None)
kw_defaults.append(None)
kw_annotations.append(self.visit(child, LOAD))
result = ast.arguments(defaults, kw_defaults, annotations, varargannotation, kwargannotation, kw_annotations)
set_location(result, node)
return result
def visit_tfpdef(self, node, ctx):
# TO DO Support tuple parameters
# No one uses them any more, so this isn't super important.
child = node.children[0]
if is_token(child, "("):
return None
return self.visit(child, ctx)
def visit_tname(self, node, ctx):
if ctx is PARAM:
child = node.children[0]
return make_name(child.value, ctx, child.start, child.end)
elif len(node.children) > 1:
return self.visit(node.children[2], ctx)
else:
return None
def visit_decorated(self, node):
asgn = self.visit(node.children[1])
value = asgn.value
for deco in reversed(node.children[0].children):
defn = value
decorator = self.visit(deco)
value = ast.Call(decorator, [defn], [])
copy_location(decorator, value)
asgn.value = value
return asgn
def visit_decorators(self, node):
return self._visit_list(node.children)
def visit_decorator(self, node):
namedexpr_test = node.children[1]
result = self.visit_namedexpr_test(namedexpr_test, LOAD)
set_location(result, namedexpr_test)
return result
def _visit_list(self, items, ctx=None):
if ctx is None:
return [ self.visit(i) for i in items ]
else:
return [ self.visit(i, ctx) for i in items ]
def visit_dotted_name(self, node):
return ".".join(name.value for name in node.children[::2])
def visit_NAME(self, name, ctx):
return make_name(name.value, ctx, name.start, name.end)
def visit_listmaker(self, node, ctx):
if len(node.children) == 1 or is_token(node.children[1], ","):
items = [self.visit(c, ctx) for c in node.children[::2]]
result = ast.List(items, ctx)
else:
if ctx is not LOAD:
context_error(node)
elt = self.visit(node.children[0], ctx)
generators = self.visit(node.children[1])
result = ast.ListComp(elt, generators)
set_location(result, node)
return result
def visit_testlist_gexp(self, node, ctx):
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
if is_token(node.children[1], ","):
items = [self.visit(c, ctx) for c in node.children[::2]]
result = ast.Tuple(items, ctx)
else:
if ctx is not LOAD:
context_error(node)
elt = self.visit(node.children[0], ctx)
generators = self.visit(node.children[1])
result = ast.GeneratorExp(elt, generators)
set_location(result, node)
return result
def visit_comp_for(self, node):
is_async = is_token(node.children[0], "async")
target = self.visit(node.children[1+is_async], STORE)
iter = self.visit(node.children[3+is_async], LOAD)
if len(node.children) == 5+is_async:
ifs = []
end = iter._end
comp_iter = self.visit(node.children[4+is_async])
while comp_iter and not isinstance(comp_iter[0], ast.comprehension):
ifs.append(comp_iter[0])
end = comp_iter[0]._end
comp_iter = comp_iter[1:]
comp = ast.comprehension(target, iter, ifs)
comp.is_async = is_async
set_location(comp, node.children[0].start, end)
return [comp] + comp_iter
else:
comp = ast.comprehension(target, iter, [])
comp.is_async = is_async
set_location(comp, node)
return [comp]
visit_old_comp_for = visit_comp_for
def visit_comp_iter(self, node):
return self.visit(node.children[0])
def visit_comp_if(self, node):
cond = self.visit(node.children[1], LOAD)
if len(node.children) == 3:
comp_list = self.visit(node.children[2])
return [cond] + comp_list
else:
return [cond]
visit_old_comp_if = visit_comp_if
visit_old_comp_iter = visit_comp_iter
def visit_exprlist(self, node, ctx):
#Despite the name this returns a single expression
if len(node.children) == 1:
return self.visit(node.children[0], ctx)
else:
elts = self._visit_list(node.children[::2], ctx)
result = ast.Tuple(elts, ctx)
set_location(result, node)
return result
visit_testlist_safe = visit_exprlist
def visit_old_test(self, node, ctx):
return self.visit(node.children[0], ctx)
def visit_if_stmt(self, node):
endindex = len(node.children)
if is_token(node.children[-3], "else"):
orelse = self.visit(node.children[-1])
endindex -= 3
else:
orelse = None
while endindex:
test = self.visit(node.children[endindex-3], LOAD)
body = self.visit(node.children[endindex-1])
result = ast.If(test, body, orelse)
start = node.children[endindex-4].start
end = node.children[endindex-2].end
set_location(result, start, end)
orelse = [result]
endindex -= 4
return result
def visit_import_stmt(self, node):
return self.visit(node.children[0])
def visit_import_name(self, node):
aliases = self.visit(node.children[1])
result = ast.Import(aliases)
set_location(result, node)
return result
def visit_dotted_as_names(self, node):
return self._visit_list(node.children[::2])
def visit_dotted_as_name(self, node):
child0 = node.children[0]
dotted_name = self.visit(child0)
if len(node.children) == 3:
value = ast.ImportExpr(0, dotted_name, False)
child2 = node.children[2]
asname = make_name(child2.value, STORE, child2.start, child2.end)
else:
value = ast.ImportExpr(0, dotted_name, True)
topname = dotted_name.split(".")[0]
asname = make_name(topname, STORE, child0.start, child0.end)
set_location(value, child0)
result = ast.alias(value, asname)
set_location(result, node)
return result
def visit_dictsetmaker(self, node, ctx):
if ctx is not LOAD:
context_error(node)
if is_token(node.children[0], "**") or len(node.children) > 1 and is_token(node.children[1], ":"):
return self._dictmaker(node)
else:
return self._setmaker(node)
#Helper for visit_dictsetmaker (for dictionaries)
def _dictmaker(self, node):
if len(node.children) == 4 and is_token(node.children[1], ":") and not is_token(node.children[3], ","):
#Comprehension form
key = self.visit(node.children[0], LOAD)
value = self.visit(node.children[2], LOAD)
generators = self.visit(node.children[3])
result = ast.DictComp(key, value, generators)
set_location(result, node)
return result
index = 0
items = []
while len(node.children) > index:
if is_token(node.children[index], "**"):
d = self.visit(node.children[index+1], LOAD)
item = ast.DictUnpacking(d)
set_location(item, node.children[index].start, node.children[index+1].end)
index += 3
else:
key = self.visit(node.children[index], LOAD)
value = self.visit(node.children[index+2], LOAD)
item = ast.KeyValuePair(key, value)
set_location(item, node.children[index].start, node.children[index+2].end)
index += 4
items.append(item)
result = ast.Dict(items)
set_location(result, node)
return result
#Helper for visit_dictsetmaker (for sets)
def _setmaker(self, node):
if len(node.children) == 2 and not is_token(node.children[1], ","):
#Comprehension form
elt = self.visit(node.children[0], LOAD)
generators = self.visit(node.children[1])
result = ast.SetComp(elt, generators)
set_location(result, node)
return result
items = self._visit_list(node.children[::2], LOAD)
result = ast.Set(items)
set_location(result, node)
return result
def visit_while_stmt(self, node):
test = self.visit(node.children[1], LOAD)
body = self.visit(node.children[3])
if len(node.children) == 7:
orelse = self.visit(node.children[6])
else:
orelse = None
result = ast.While(test, body, orelse)
set_location(result, node.children[0].start, node.children[2].end)
return result
def visit_flow_stmt(self, node):
return self.visit(node.children[0])
def visit_break_stmt(self, node):
result = ast.Break()
set_location(result, node)
return result
def visit_continue_stmt(self, node):
result = ast.Continue()
set_location(result, node)
return result
def visit_return_stmt(self, node):
if len(node.children) == 2:
result = ast.Return(self.visit(node.children[1], LOAD))
else:
result = ast.Return(None)
set_location(result, node)
return result
def visit_raise_stmt(self, node):
result = ast.Raise()
set_location(result, node)
if len(node.children) == 1:
return result
result.exc = self.visit(node.children[1], LOAD)
if len(node.children) > 3:
if is_token(node.children[2], "from"):
result.cause = self.visit(node.children[3], LOAD)
else:
result.type = result.exc
del result.exc
result.inst = self.visit(node.children[3], LOAD)
if len(node.children) == 6:
result.tback = self.visit(node.children[5], LOAD)
return result
def visit_yield_stmt(self, node):
result = ast.Expr(self.visit(node.children[0], LOAD))
set_location(result, node)
return result
def visit_yield_expr(self, node, ctx):
if ctx is not LOAD:
context_error(node)
if len(node.children) == 1:
result = ast.Yield(None)
else:
if is_token(node.children[1].children[0], "from"):
result = ast.YieldFrom(self.visit(node.children[1].children[1], LOAD))
else:
result = ast.Yield(self.visit(node.children[1].children[0], LOAD))
set_location(result, node)
return result
def visit_try_stmt(self, node):
body = self.visit(node.children[2])
index = 3
handlers = []
while len(node.children) > index and not hasattr(node.children[index], "value"):
#Except block.
type, name = self.visit(node.children[index])
handler_body = self.visit(node.children[index+2])
handler = ast.ExceptStmt(type, name, handler_body)
set_location(handler, node.children[index].start , node.children[index+1].end)
handlers.append(handler)
index += 3
if len(node.children) > index and is_token(node.children[index], "else"):
orelse = self.visit(node.children[index+2])
else:
orelse = []
if is_token(node.children[-3], "finally"):
finalbody = self.visit(node.children[-1])
else:
finalbody = []
result = ast.Try(body, orelse, handlers, finalbody)
set_location(result, node.start, node.children[1].end)
return result
def visit_except_clause(self, node):
type, name = None, None
if len(node.children) > 1:
type = self.visit(node.children[1], LOAD)
if len(node.children) > 3:
name = self.visit(node.children[3], STORE)
return type, name
def visit_del_stmt(self, node):
if len(node.children) > 1:
result = ast.Delete(self._visit_list(node.children[1].children[::2], DEL))
else:
result = ast.Delete([])
set_location(result, node)
return result
visit_subscriptlist = visit_testlist
visit_testlist1 = visit_testlist
def visit_subscript(self, node, ctx):
if len(node.children) == 1 and not is_token(node.children[0], ":"):
return self.visit(node.children[0], ctx)