-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathcommonast.py
More file actions
1362 lines (1006 loc) · 37.3 KB
/
commonast.py
File metadata and controls
1362 lines (1006 loc) · 37.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
"""
Module that defines a common AST description, independent from Python
version and implementation. Also provides a function ``parse()`` to
generate this common AST by using the builtin ast module and converting
the result. Supports CPython 2.7, CPython 3.2+, Pypy.
https://github.com/almarklein/commonast
"""
from __future__ import print_function, absolute_import
import sys
import ast
import json
import base64
if hasattr(base64, "encodebytes"):
encodebytes = base64.encodebytes
decodebytes = base64.decodebytes
else:
encodebytes = base64.encodestring
decodebytes = base64.decodestring
NoneType = None.__class__
_Ellipsis = Ellipsis
# do some extra asserts when running tests, but not always, for speed
docheck = "pytest" in sys.modules
def parse(code, comments=False):
"""Parse Python code to produce a common AST tree.
Parameters:
code (str): the Python code to parse
comments (bool): if True, will include Comment nodes. Default False.
"""
converter = NativeAstConverter(code)
return converter.convert(comments)
class Node(object):
"""Abstract base class for all Nodes."""
__slots__ = ["lineno", "col_offset"]
class OPS:
"""Operator enums:"""
# Unary
UAdd = "UAdd"
USub = "USub"
Not = "Not"
Invert = "Invert"
# Binary
Add = "Add"
Sub = "Sub"
Mult = "Mult"
Div = "Div"
FloorDiv = "FloorDiv"
Mod = "Mod"
Pow = "Pow"
LShift = "LShift"
RShift = "RShift"
BitOr = "BitOr"
BitXor = "BitXor"
BitAnd = "BitAnd"
# Boolean
And = "And"
Or = "Or"
class COMP:
"""Comparison enums:"""
Eq = "Eq"
NotEq = "NotEq"
Lt = "Lt"
LtE = "LtE"
Gt = "Gt"
GtE = "GtE"
Is = "Is"
IsNot = "IsNot"
In = "In"
NotIn = "NotIn"
def __init__(self, *args):
names = self.__slots__
# Checks
assert len(args) == len(names) # check this always
if docheck:
assert not hasattr(self, "__dict__"), "Nodes must have __slots__"
assert self.__class__ is not Node, "Node is an abstract class"
for name, val in zip(names, args):
assert not isinstance(val, ast.AST)
if name == "name":
assert isinstance(val, (str, NoneType)), "name not a string"
elif name == "op":
assert val in Node.OPS.__dict__ or val in Node.COMP.__dict__
elif name.endswith("_node"):
assert isinstance(val, (Node, NoneType)), "%r is not a Node" % name
elif name.endswith("_nodes"):
islistofnodes = isinstance(val, list) and all(
isinstance(n, Node) for n in val
)
assert islistofnodes, "%r is not a list of nodes" % name
else:
assert not isinstance(val, Node), "%r should not be a Node" % name
assert not (
isinstance(val, list) and all(isinstance(n, Node) for n in val)
)
# Assign
for name, val in zip(names, args):
setattr(self, name, val)
def tojson(self, indent=2):
"""Return a string with the JSON representatiom of this AST.
Set indent to None for a more compact representation.
"""
return json.dumps(self._todict(), indent=indent, sort_keys=True)
@classmethod
def fromjson(cls, text):
"""Classmethod to create an AST tree from JSON."""
return Node._fromdict(json.loads(text))
@classmethod
def _fromdict(cls, d):
assert "_type" in d
Cls = globals()[d["_type"]]
args = []
for name in Cls.__slots__:
val = d[name]
if val is None:
pass
elif name.endswith("_node"):
val = Node._fromdict(val)
elif name.endswith("_nodes"):
val = [Node._fromdict(x) for x in val]
elif isinstance(val, str):
if val.startswith("BYTES:"):
val = decodebytes(val[6:].encode("utf-8"))
elif val.startswith("COMPLEX:"):
val = complex(val[8:])
args.append(val)
return Cls(*args)
def _todict(self):
"""Get a dict representing this AST. This is the basis for
creating JSON, but can be used to compare AST trees as well.
"""
d = {}
d["_type"] = self.__class__.__name__
for name in self.__slots__:
val = getattr(self, name)
if val is None:
pass
elif name.endswith("_node"):
val = val._todict()
elif name.endswith("_nodes"):
val = [x._todict() for x in val]
elif isinstance(self, Bytes) and isinstance(val, bytes):
val = "BYTES:" + encodebytes(val).decode("utf-8").rstrip()
elif isinstance(self, Num) and isinstance(val, complex):
val = "COMPLEX:" + repr(val)
d[name] = val
return d
def __eq__(self, other):
if not isinstance(other, Node):
raise ValueError("Can only compare nodes to other nodes.")
return self._todict() == other._todict()
def __repr__(self):
names = ", ".join([repr(x) for x in self.__slots__])
return "<%s with %s at 0x%x>" % (self.__class__.__name__, names, id(self))
def __str__(self):
return self.tojson()
try:
Node.OPS.__doc__ += ", ".join(
[x for x in sorted(Node.OPS.__dict__) if not x.startswith("_")]
)
Node.COMP.__doc__ += ", ".join(
[x for x in sorted(Node.COMP.__dict__) if not x.startswith("_")]
)
except AttributeError: # pragma: no cover
pass # Py < 3.3
## -- (start marker for doc generator)
## General
class Comment(Node):
"""
Attributes:
value: the comment string.
"""
__slots__ = ("value",)
class Module(Node):
"""Each code that an AST is created for gets wrapped in a Module node.
Attributes:
body_nodes: a list of nodes.
"""
__slots__ = ("body_nodes",)
## Literals
class Num(Node):
"""
Attributes:
value: the number as a native Python object (int, float, or complex).
"""
__slots__ = ("value",)
class Str(Node):
"""
Attributes:
value: the native Python str object.
"""
__slots__ = ("value",)
class FormattedValue(Node):
"""Node representing a single formatting field in an f-string. If the
string contains a single formatting field and nothing else the node can be
isolated, otherwise it appears in JoinedStr.
Attributes:
value_node: an expression (can be anything).
conversion: a string, '' means no formatting, 's' means !s string
formatting, 'r' means !r repr formatting, 'a' means !a ascii
formatting.
format_node: a JoinedStr node reprensenting the formatting, or None
if no format was specified. Both conversion and format_node can be
set at the same time.
"""
__slots__ = "value_node", "conversion", "format_node"
class JoinedStr(Node):
"""An f-string, comprising a series of FormattedValue and Str nodes.
Attributes:
value_nodes: list of Str and FormattedValue nodes.
"""
__slots__ = ("value_nodes",)
class Bytes(Node):
"""
Attributes:
value: the native Python bytes object.
"""
__slots__ = ("value",)
class List(Node):
"""
Attributes:
element_nodes: the items in the list.
"""
__slots__ = ("element_nodes",)
class Tuple(Node):
"""
Attributes:
element_nodes: the items in the tuple.
"""
__slots__ = ("element_nodes",)
class Set(Node):
"""
Attributes:
element_nodes: the items in the set.
"""
__slots__ = ("element_nodes",)
class Dict(Node):
"""
Attributes:
key_nodes: the keys of the dict.
value_nodes: the corresponding values.
"""
__slots__ = "key_nodes", "value_nodes"
class Ellipsis(Node):
"""Represents the ``...`` syntax for the Ellipsis singleton."""
__slots__ = ()
class NameConstant(Node):
"""
Attributes:
value: the corresponding native Python object like True, False or None.
"""
__slots__ = ("value",)
## Variables, attributes, indexing and slicing
class Name(Node):
"""
Attributes:
name: the string name of this variable.
"""
__slots__ = ("name",)
class Starred(Node):
"""A starred variable name, e.g. ``*foo``. Note that this isn't
used to define a function with ``*args`` - FunctionDef nodes have
special fields for that.
Attributes:
value_node: the value that is starred, typically a Name node.
"""
__slots__ = ("value_node",)
class Attribute(Node):
"""Attribute access, e.g. ``foo.bar``.
Attributes:
value_node: The node to get/set an attribute of. Typically a Name node.
attr: a string with the name of the attribute.
"""
__slots__ = "value_node", "attr"
class Subscript(Node):
"""Subscript access, e.g. ``foo[3]``.
Attributes:
value_node: The node to get/set a subscript of. Typically a Name node.
slice_node: An Index, Slice or ExtSlice node.
"""
__slots__ = "value_node", "slice_node"
class Index(Node):
"""
Attributes:
value_node: Single index.
"""
__slots__ = ("value_node",)
class Slice(Node):
"""
Attributes:
lower_node: start slice.
upper_node: end slice.
step_node: slice step.
"""
__slots__ = "lower_node", "upper_node", "step_node"
class ExtSlice(Node):
"""
Attributes:
dim_nodes: list of Index and Slice nodes (of for each dimension).
"""
__slots__ = ("dim_nodes",)
## Expressions
class Expr(Node):
"""When an expression, such as a function call, appears as a
statement by itself (an expression statement), with its return value
not used or stored, it is wrapped in this container.
Attributes:
value_node: holds one of the other nodes in this section, or a
literal, a Name, a Lambda, or a Yield or YieldFrom node.
"""
__slots__ = ("value_node",)
class UnaryOp(Node):
"""A unary operation (e.g. ``-x``, ``not x``).
Attributes:
op: the operator (an enum from ``Node.OPS``).
right_node: the operand at the right of the operator.
"""
__slots__ = "op", "right_node"
class BinOp(Node):
"""A binary operation (e.g. ``a / b``, ``a + b``).
Attributes:
op: the operator (an enum from ``Node.OPS``).
left_node: the node to the left of the operator.
right_node: the node to the right of the operator.
"""
__slots__ = "op", "left_node", "right_node"
class BoolOp(Node):
"""A boolean operator (``and``, ``or``, but not ``not``).
Attributes:
op: the operator (an enum from ``Node.OPS``).
value_nodes: a list of nodes. ``a``, ``b`` and ``c`` in
``a or b or c``.
"""
__slots__ = "op", "value_nodes"
class Compare(Node):
"""A comparison of two or more values.
Attributes:
op: the comparison operator (an enum from ``Node.COMP``).
left_node: the node to the left of the operator.
right_node: the node to the right of the operator.
"""
__slots__ = "op", "left_node", "right_node"
class Call(Node):
"""A function call.
Attributes:
func_node: Name, Attribute or SubScript node that represents
the function.
arg_nodes: list of nodes representing positional arguments.
kwarg_nodes: list of Keyword nodes representing keyword arguments.
Note that an argument ``*x`` would be specified as a Starred node
in arg_nodes, and ``**y`` as a Keyword node with a name being ``None``.
"""
__slots__ = ("func_node", "arg_nodes", "kwarg_nodes")
class Keyword(Node):
"""Keyword argument used in a Call.
Attributes:
name: the (string) name of the argument. Is None for ``**kwargs``.
value_node: the value of the arg.
"""
__slots__ = ("name", "value_node")
class IfExp(Node):
"""An expression such as ``a if b else c``.
Attributes:
test_node: the ``b`` in the above.
body_node: the ``a`` in the above.
else_node: the ``c`` in the above.
"""
__slots__ = "test_node", "body_node", "else_node"
class ListComp(Node):
"""List comprehension.
Attributes:
element_node: the part being evaluated for each item.
comp_nodes: a list of Comprehension nodes.
"""
__slots__ = "element_node", "comp_nodes"
class SetComp(Node):
"""Set comprehension. See ListComp."""
__slots__ = "element_node", "comp_nodes"
class GeneratorExp(Node):
"""Generor expression. See ListComp."""
__slots__ = "element_node", "comp_nodes"
class DictComp(Node):
"""Dict comprehension.
Attributes:
key_node: the key of the item being evaluated.
value_node: the value of the item being evaluated.
comp_nodes: a list of Comprehension nodes.
"""
__slots__ = "key_node", "value_node", "comp_nodes"
class Comprehension(Node):
"""Represents a single for-clause in a comprehension.
Attributes:
target_node: reference to use for each element, typically a
Name or Tuple node.
iter_node: the object to iterate over.
if_nodes: a list of test expressions.
"""
__slots__ = "target_node", "iter_node", "if_nodes"
## Statements
class Assign(Node):
"""Assignment of a value to a variable.
Attributes:
target_nodes: variables to assign to, Name or SubScript.
value_node: the object to assign.
"""
__slots__ = "target_nodes", "value_node"
class AugAssign(Node):
"""Augmented assignment, such as ``a += 1``.
Attributes:
target_node: variable to assign to, Name or SubScript.
op: operator enum (e.g. ``Node.OPS.Add``)
value_node: the object to assign.
"""
__slots__ = "target_node", "op", "value_node"
class Raise(Node):
"""Raising an exception.
Attributes:
exc_node: the exception object to be raised, normally a Call
or Name, or None for a standalone raise.
cause_node: the optional part for y in raise x from y.
"""
__slots__ = "exc_node", "cause_node"
class Assert(Node):
"""An assertion.
Attributes:
test_node: the condition to test.
msg_node: the failure message (commonly a Str node)
"""
__slots__ = "test_node", "msg_node"
class Delete(Node):
"""A del statement.
Attributes:
target_nodes: the variables to delete, such as Name, Attribute
or Subscript nodes.
"""
__slots__ = ("target_nodes",)
class Pass(Node):
"""Do nothing."""
__slots__ = ()
class Import(Node):
"""An import statement.
Attributes:
root: the name of the module to import from. None if this is
not a from-import.
names: list of (name, alias) tuples, where alias can be None.
level: an integer indicating depth of import. Zero means
absolute import.
"""
__slots__ = "root", "names", "level"
## Control flow
class If(Node):
"""An if-statement.
Note that elif clauses don't have a special representation in the
AST, but rather appear as extra If nodes within the else section
of the previous one.
Attributes:
test_node: the test, e.g. a Compare node.
body_nodes: the body of the if-statement.
else_nodes: the body of the else-clause of the if-statement.
"""
__slots__ = "test_node", "body_nodes", "else_nodes"
class For(Node):
"""A for-loop.
Attributes:
target_node: the variable(s) the loop assigns to.
iter_node: the object to iterate over.
body_nodes: the body of the for-loop.
else_nodes: the body of the else-clause of the for-loop.
"""
__slots__ = "target_node", "iter_node", "body_nodes", "else_nodes"
class While(Node):
"""A while-loop.
Attributes:
test_node: the test to perform on each iteration.
body_nodes: the body of the for-loop.
else_nodes: the body of the else-clause of the for-loop.
"""
__slots__ = "test_node", "body_nodes", "else_nodes"
class Break(Node):
"""Break from a loop."""
__slots__ = ()
class Continue(Node):
"""Continue with next iteration of a loop."""
__slots__ = ()
class Try(Node):
"""Try-block.
Attributes:
body_nodes: the body of the try-block (i.e. the code to try).
handler_nodes: a list of ExceptHandler instances.
else_nodes: the body of the else-clause of the try-block.
finally_nodes: the body of the finally-clause of the try-block.
"""
__slots__ = "body_nodes", "handler_nodes", "else_nodes", "finally_nodes"
class ExceptHandler(Node):
"""Single except-clause.
Attributes:
type_node: the type of exception to catch. Often a Name node
or None to catch all.
name: the string name of the exception object in case of ``as err``.
None otherwise.
body_nodes: the body of the except-clause.
"""
__slots__ = "type_node", "name", "body_nodes"
class With(Node):
"""A with-block (i.e. a context manager).
Attributes:
item_nodes: a list of WithItem nodes (i.e. context managers).
body_nodes: the body of the with-block.
"""
__slots__ = "item_nodes", "body_nodes"
class WithItem(Node):
"""A single context manager in a with block.
Attributes:
expr_node: the expression for the context manager.
as_node: a Name, Tuple or List node representing the ``as foo`` part.
"""
__slots__ = "expr_node", "as_node"
## Function and class definitions
class FunctionDef(Node):
"""A function definition.
Attributes:
name: the (string) name of the function.
decorator_nodes: the list of decorators to be applied, stored
outermost first (i.e. the first in the list will be applied
last).
annotation_node: the return annotation (Python 3 only).
arg_nodes: list of Args nodes representing positional arguments.
These *may* have a default value.
kwarg_nodes: list of Arg nodes representing keyword-only arguments.
args_node: an Arg node representing ``*args``.
kwargs_node: an Arg node representing ``**kwargs``.
body_nodes: the body of the function.
"""
__slots__ = (
"name",
"decorator_nodes",
"annotation_node",
"arg_nodes",
"kwarg_nodes",
"args_node",
"kwargs_node",
"body_nodes",
)
class Lambda(Node):
"""Anonymous function definition.
Attributes:
arg_nodes: list of Args nodes representing positional arguments.
kwarg_nodes: list of Arg nodes representing keyword-only arguments.
args_node: an Arg node representing ``*args``.
kwargs_node: an Arg node representing ``**kwargs``.
body_node: the body of the function (a single node).
"""
__slots__ = ("arg_nodes", "kwarg_nodes", "args_node", "kwargs_node", "body_node")
class AsyncFunctionDef(Node):
"""Asynchronous function definition.
Same as FunctionDef, but async.
"""
__slots__ = (
"name",
"decorator_nodes",
"annotation_node",
"arg_nodes",
"kwarg_nodes",
"args_node",
"kwargs_node",
"body_nodes",
)
class Arg(Node):
"""Function argument for a FunctionDef.
Attributes:
name: the (string) name of the argument.
value_node: the default value of this argument. Can be None.
annotation_node: the annotation for this argument (Python3 only).
"""
__slots__ = ("name", "value_node", "annotation_node")
class Return(Node):
"""
Attributes:
value_node: the value to return.
"""
__slots__ = ("value_node",)
class Yield(Node):
"""
Attributes:
value_node: the value to yield.
"""
__slots__ = ("value_node",)
class YieldFrom(Node):
"""
Attributes:
value_node: the value to yield.
"""
__slots__ = ("value_node",)
class Await(Node):
"""
Attributes:
value_node: the value to return.
"""
__slots__ = ("value_node",)
class Global(Node):
"""
Attributes:
names: a list of string names to declare global.
"""
__slots__ = ("names",)
class Nonlocal(Node):
"""
Attributes:
names: a list of string names to declare nonlocal.
"""
__slots__ = ("names",)
class ClassDef(Node):
"""A class definition.
Attributes:
name: a string for the class name.
decorator_nodes: the list of decorators to be applied, as in FunctionDef.
arg_nodes: list of nodes representing base classes.
kwarg_nodes: list of Keyword nodes representing keyword-only arguments.
body_nodes: the body of the class.
Note that arg_nodes and kwarg_nodes are similar to those in the
Call node. An argument ``*x`` would be specified as a Starred node
in arg_nodes, and ``**y`` as a Keyword node with a name being
``None``. For more information on keyword arguments see
https://www.python.org/dev/peps/pep-3115/.
"""
__slots__ = ("name", "decorator_nodes", "arg_nodes", "kwarg_nodes", "body_nodes")
## -- (end marker for doc generator)
class NativeAstConverter:
"""Convert ast produced by Python's ast module to common ast."""
def __init__(self, code):
self._root = ast.parse(code)
self._lines = code.splitlines()
self._stack = [] # contains tuple elements: (list_obj, native_nodes)
def _add_comments(self, container, lineno):
"""Add comment nodes from the last point until the given line number."""
linenr1 = self._comment_pointer
linenr2 = lineno
self._comment_pointer = linenr2 + 1 # store for next time
for i in range(linenr1, linenr2):
line = self._lines[i - 1] # lineno's start from 1
if line.lstrip().startswith("#"):
before, _, comment = line.partition("#")
node = Comment(comment)
node.lineno = i
node.col_offset = len(before)
container.append(node)
def convert(self, comments=False):
assert not self._stack
self._comment_pointer = 1
result = self._convert(self._root)
while self._stack:
container, native_nodes = self._stack.pop(0)
for native_node in native_nodes:
node = self._convert(native_node)
if comments:
self._add_comments(container, node.lineno)
container.append(node)
return result
def _convert(self, n):
# n is the native node produced by the ast module
if n is None:
return None # but some node attributes can be None
assert isinstance(n, ast.AST)
# Get converter function
type = n.__class__.__name__
try:
converter = getattr(self, "_convert_" + type)
except AttributeError: # pragma: no cover
raise RuntimeError("Cannot convert %s nodes." % type) from None
# Convert node
val = converter(n)
assert isinstance(val, Node)
# Set its position
val.lineno = getattr(n, "lineno", 1)
val.col_offset = getattr(n, "col_offset", 0)
return val
def _convert_Module(self, n):
node = Module([])
# Add back the "docstring" that Python removed; this may actually be
# a code snippet and not a module.
self._stack.append((node.body_nodes, n.body))
return node
## Literals
def _convert_Constant(self, n):
val = n.value
if val is None or val is True or val is False:
return NameConstant(val)
if isinstance(val, (int, float, complex)):
return Num(val)
if isinstance(val, str):
return Str(val)
if isinstance(val, bytes):
return Bytes(val)
if val is _Ellipsis:
return Ellipsis()
raise RuntimeError("Cannot convert %s constants." % type(val).__name__)
def _convert_Num(self, n):
return Num(n.n)
def _convert_Str(self, n):
# We check the string prefix here. We only really need it in Python 2,
# because u is not needed in py3, and b and r are resolved by the lexer,
# and f as well (resulting in JoinedStr or FormattedValue).
# Note that the col_offset of the node seems 1 off when the string is
# a key in a dict :/ (PScript issue #15)
return Str(n.s)
def _convert_JoinedStr(self, n):
c = self._convert
return JoinedStr([c(x) for x in n.values])
def _convert_FormattedValue(self, n):
conversion = "" if n.conversion < 0 else chr(n.conversion)
return FormattedValue(
self._convert(n.value), conversion, self._convert(n.format_spec)
)
def _convert_Bytes(self, n):
return Bytes(n.s)
def _convert_List(self, n):
c = self._convert
return List([c(x) for x in n.elts])