-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathunpyc3.py
executable file
·2020 lines (1640 loc) · 60.8 KB
/
unpyc3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Decompiler for Python3.3.
Decompile a module or a function using the decompile() function
>>> from unpyc3 import decompile
>>> def foo(x, y, z=3, *args):
... global g
... for i, j in zip(x, y):
... if z == i + j or args[i] == j:
... g = i, j
... return
...
>>> print(decompile(foo))
def foo(x, y, z=3, *args):
global g
for i, j in zip(x, y):
if z == i + j or args[i] == j:
g = i, j
return
>>>
"""
__all__ = ['decompile']
# TODO:
# - Support for keyword-only arguments
# - Handle assert statements better
# - (Partly done) Nice spacing between function/class declarations
import dis
from array import array
from opcode import opname, opmap, HAVE_ARGUMENT, cmp_op
import imp
import inspect
# Masks for code object's co_flag attribute
VARARGS = 4
VARKEYWORDS = 8
# Put opcode names in the global namespace
for name, val in opmap.items():
globals()[name] = val
# These opcodes will generate a statement. This is used in the first
# pass (in Code.find_else) to find which POP_JUMP_IF_* instructions
# are jumps to the else clause of an if statement
stmt_opcodes = {
SETUP_LOOP, BREAK_LOOP, CONTINUE_LOOP,
SETUP_FINALLY, END_FINALLY,
SETUP_EXCEPT, POP_EXCEPT,
SETUP_WITH,
POP_BLOCK,
STORE_FAST, DELETE_FAST,
STORE_DEREF, DELETE_DEREF,
STORE_GLOBAL, DELETE_GLOBAL,
STORE_NAME, DELETE_NAME,
STORE_ATTR, DELETE_ATTR,
IMPORT_NAME, IMPORT_FROM,
RETURN_VALUE, YIELD_VALUE,
RAISE_VARARGS,
POP_TOP,
}
# Conditional branching opcode that make up if statements and and/or
# expressions
pop_jump_if_opcodes = (POP_JUMP_IF_TRUE, POP_JUMP_IF_FALSE)
# These opcodes indicate that a pop_jump_if_x to the address just
# after them is an else-jump
else_jump_opcodes = (
JUMP_FORWARD, RETURN_VALUE, JUMP_ABSOLUTE,
SETUP_LOOP, RAISE_VARARGS
)
# These opcodes indicate for loop rather than while loop
for_jump_opcodes = (
GET_ITER, FOR_ITER
)
def read_code(stream):
# This helper is needed in order for the PEP 302 emulation to
# correctly handle compiled files
# Note: stream must be opened in "rb" mode
import marshal
magic = stream.read(4)
if magic != imp.get_magic():
print("*** Warning: file has wrong magic number ***")
stream.read(4) # Skip timestamp
stream.read(4) # Skip rawsize
return marshal.load(stream)
def dec_module(path):
if path.endswith(".py"):
path = imp.cache_from_source(path)
elif not path.endswith(".pyc") and not path.endswith(".pyo"):
raise ValueError("path must point to a .py or .pyc file")
stream = open(path, "rb")
code_obj = read_code(stream)
code = Code(code_obj)
return code.get_suite(include_declarations=False, look_for_docstring=True)
def decompile(obj):
"""
Decompile obj if it is a module object, a function or a
code object. If obj is a string, it is assumed to be the path
to a python module.
"""
if isinstance(obj, str):
return dec_module(obj)
if inspect.iscode(obj):
code = Code(obj)
return code.get_suite()
if inspect.isfunction(obj):
code = Code(obj.__code__)
defaults = obj.__defaults__
kwdefaults = obj.__kwdefaults__
return DefStatement(code, defaults, kwdefaults, obj.__closure__)
elif inspect.ismodule(obj):
return dec_module(obj.__file__)
else:
msg = "Object must be string, module, function or code object"
raise TypeError(msg)
class Indent:
def __init__(self, indent_level=0, indent_step=4):
self.level = indent_level
self.step = indent_step
def write(self, pattern, *args, **kwargs):
if args or kwargs:
pattern = pattern.format(*args, **kwargs)
return self.indent(pattern)
def __add__(self, indent_increase):
return type(self)(self.level + indent_increase, self.step)
class IndentPrint(Indent):
def indent(self, string):
print(" " * self.step * self.level + string)
class IndentString(Indent):
def __init__(self, indent_level=0, indent_step=4, lines=None):
Indent.__init__(self, indent_level, indent_step)
if lines is None:
self.lines = []
else:
self.lines = lines
def __add__(self, indent_increase):
return type(self)(self.level + indent_increase, self.step, self.lines)
def sep(self):
if not self.lines or self.lines[-1]:
self.lines.append("")
def indent(self, string):
self.lines.append(" " * self.step * self.level + string)
def __str__(self):
return "\n".join(self.lines)
class Stack:
def __init__(self):
self._stack = []
self._counts = {}
def __bool__(self):
return bool(self._stack)
def __len__(self):
return len(self._stack)
def __contains__(self, val):
return self.get_count(val) > 0
def get_count(self, obj):
return self._counts.get(id(obj), 0)
def set_count(self, obj, val):
if val:
self._counts[id(obj)] = val
else:
del self._counts[id(obj)]
def pop1(self):
val = self._stack.pop() if self._stack else PyConst('ERROR')
self.set_count(val, self.get_count(val) - 1)
return val
def pop(self, count=None):
if count is None:
return self.pop1()
else:
vals = [self.pop1() for i in range(count)]
vals.reverse()
return vals
def push(self, *args):
for val in args:
self.set_count(val, self.get_count(val) + 1)
self._stack.append(val)
def peek(self, count=None):
if count is None:
return self._stack[-1]
else:
return self._stack[-count:]
def code_walker(code):
l = len(code)
code = array('B', code)
i = 0
extended_arg = 0
while i < l:
op = code[i]
if op >= HAVE_ARGUMENT:
oparg = code[i + 1] + code[i + 2] * 256 + extended_arg
extended_arg = 0
if op == EXTENDED_ARG:
extended_arg = oparg * 65536
yield i, (op, oparg)
i += 3
else:
yield i, (op, None)
i += 1
class Code:
def __init__(self, code_obj, parent=None):
self.code_obj = code_obj
self.parent = parent
self.derefnames = [PyName(v)
for v in code_obj.co_cellvars + code_obj.co_freevars]
self.consts = list(map(PyConst, code_obj.co_consts))
self.names = list(map(PyName, code_obj.co_names))
self.varnames = list(map(PyName, code_obj.co_varnames))
self.instr_seq = list(code_walker(code_obj.co_code))
self.instr_map = {addr: i for i, (addr, _) in enumerate(self.instr_seq)}
self.name = code_obj.co_name
self.globals = []
self.nonlocals = []
self.find_else()
def __getitem__(self, instr_index):
if 0 <= instr_index < len(self.instr_seq):
return Address(self, instr_index)
def __iter__(self):
for i in range(len(self.instr_seq)):
yield Address(self, i)
def show(self):
for addr in self:
print(addr)
def address(self, addr):
return self[self.instr_map[addr]]
def iscellvar(self, i):
return i < len(self.code_obj.co_cellvars)
def find_else(self):
jumps = {}
last_jump = None
for addr in self:
opcode, arg = addr
if opcode in pop_jump_if_opcodes:
jump_addr = self.address(arg)
if (jump_addr[-1].opcode in else_jump_opcodes
or jump_addr.opcode == FOR_ITER):
last_jump = addr
jumps[jump_addr] = addr
elif opcode == JUMP_ABSOLUTE:
# This case is to deal with some nested ifs such as:
# if a:
# if b:
# f()
# elif c:
# g()
jump_addr = self.address(arg)
if jump_addr in jumps:
jumps[addr] = jumps[jump_addr]
elif opcode in stmt_opcodes and last_jump is not None:
# This opcode will generate a statement, so it means
# that the last POP_JUMP_IF_x was an else-jump
jumps[addr] = last_jump
self.else_jumps = set(jumps.values())
def get_suite(self, include_declarations=True, look_for_docstring=False):
dec = SuiteDecompiler(self[0])
dec.run()
first_stmt = dec.suite and dec.suite[0]
# Change __doc__ = "docstring" to "docstring"
if look_for_docstring and isinstance(first_stmt, AssignStatement):
chain = first_stmt.chain
if len(chain) == 2 and str(chain[0]) == "__doc__":
dec.suite[0] = DocString(first_stmt.chain[1].val)
if include_declarations and (self.globals or self.nonlocals):
suite = Suite()
if self.globals:
stmt = "global " + ", ".join(map(str, self.globals))
suite.add_statement(SimpleStatement(stmt))
if self.nonlocals:
stmt = "nonlocal " + ", ".join(map(str, self.nonlocals))
suite.add_statement(SimpleStatement(stmt))
for stmt in dec.suite:
suite.add_statement(stmt)
return suite
else:
return dec.suite
def declare_global(self, name):
"""
Declare name as a global. Called by STORE_GLOBAL and
DELETE_GLOBAL
"""
if name not in self.globals:
self.globals.append(name)
def ensure_global(self, name):
"""
Declare name as global only if it is also a local variable
name in one of the surrounding code objects. This is called
by LOAD_GLOBAL
"""
parent = self.parent
while parent:
if name in parent.varnames:
return self.declare_global(name)
parent = parent.parent
def declare_nonlocal(self, name):
"""
Declare name as nonlocal. Called by STORE_DEREF and
DELETE_DEREF (but only when the name denotes a free variable,
not a cell one).
"""
if name not in self.nonlocals:
self.nonlocals.append(name)
class Address:
def __init__(self, code, instr_index):
self.code = code
self.index = instr_index
self.addr, (self.opcode, self.arg) = code.instr_seq[instr_index]
def __eq__(self, other):
return (isinstance(other, type(self))
and self.code == other.code and self.index == other.index)
def __lt__(self, other):
return other is None or (isinstance(other, type(self))
and self.code == other.code and self.index < other.index)
def __str__(self):
mark = "*" if self in self.code.else_jumps else " "
return "{} {} {} {}".format(
mark, self.addr,
opname[self.opcode], self.arg or ""
)
def __add__(self, delta):
return self.code.address(self.addr + delta)
def __getitem__(self, index):
return self.code[self.index + index]
def __iter__(self):
yield self.opcode
yield self.arg
def __hash__(self):
return hash((self.code, self.index))
def is_else_jump(self):
return self in self.code.else_jumps
def change_instr(self, opcode, arg=None):
self.code.instr_seq[self.index] = (self.addr, (opcode, arg))
def jump(self):
opcode = self.opcode
if opcode in dis.hasjrel:
return self[1] + self.arg
elif opcode in dis.hasjabs:
return self.code.address(self.arg)
class PyExpr:
def wrap(self, condition=True):
if condition:
return "({})".format(self)
else:
return str(self)
def store(self, dec, dest):
chain = dec.assignment_chain
chain.append(dest)
if self not in dec.stack:
chain.append(self)
dec.suite.add_statement(AssignStatement(chain))
dec.assignment_chain = []
def on_pop(self, dec):
dec.write(str(self))
class PyConst(PyExpr):
precedence = 100
def __init__(self, val):
self.val = val
def __str__(self):
return repr(self.val)
def __iter__(self):
return iter(self.val)
def __eq__(self, other):
return isinstance(other, PyConst) and self.val == other.val
class PyTuple(PyExpr):
precedence = 0
def __init__(self, values):
self.values = values
def __str__(self):
if not self.values:
return "()"
valstr = [val.wrap(val.precedence <= self.precedence)
for val in self.values]
if len(valstr) == 1:
return '(' + valstr[0] + "," + ')'
else:
return '(' + ", ".join(valstr) + ')'
def __iter__(self):
return iter(self.values)
def wrap(self, condition=True):
return str(self)
class PyList(PyExpr):
precedence = 16
def __init__(self, values):
self.values = values
def __str__(self):
valstr = ", ".join(val.wrap(val.precedence <= 0)
for val in self.values)
return "[{}]".format(valstr)
def __iter__(self):
return iter(self.values)
class PySet(PyExpr):
precedence = 16
def __init__(self, values):
self.values = values
def __str__(self):
valstr = ", ".join(val.wrap(val.precedence <= 0)
for val in self.values)
return "{{{}}}".format(valstr)
def __iter__(self):
return iter(self.values)
class PyDict(PyExpr):
precedence = 16
def __init__(self):
self.items = []
def set_item(self, key, val):
self.items.append((key, val))
def __str__(self):
itemstr = ", ".join("{}: {}".format(*kv) for kv in self.items)
return "{{{}}}".format(itemstr)
class PyName(PyExpr):
precedence = 100
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __eq__(self, other):
return isinstance(other, type(self)) and self.name == other.name
class PyUnaryOp(PyExpr):
def __init__(self, operand):
self.operand = operand
def __str__(self):
opstr = self.operand.wrap(self.operand.precedence < self.precedence)
return self.pattern.format(opstr)
@classmethod
def instr(cls, stack):
stack.push(cls(stack.pop()))
class PyBinaryOp(PyExpr):
def __init__(self, left, right):
self.left = left
self.right = right
def wrap_left(self):
return self.left.wrap(self.left.precedence < self.precedence)
def wrap_right(self):
return self.right.wrap(self.right.precedence <= self.precedence)
def __str__(self):
return self.pattern.format(self.wrap_left(), self.wrap_right())
@classmethod
def instr(cls, stack):
right = stack.pop()
left = stack.pop()
stack.push(cls(left, right))
class PySubscript(PyBinaryOp):
precedence = 15
pattern = "{}[{}]"
def wrap_right(self):
return str(self.right)
class PySlice(PyExpr):
precedence = 1
def __init__(self, args):
assert len(args) in (2, 3)
if len(args) == 2:
self.start, self.stop = args
self.step = None
else:
self.start, self.stop, self.step = args
if self.start == PyConst(None):
self.start = ""
if self.stop == PyConst(None):
self.stop = ""
def __str__(self):
if self.step is None:
return "{}:{}".format(self.start, self.stop)
else:
return "{}:{}:{}".format(self.start, self.stop, self.step)
class PyCompare(PyExpr):
precedence = 6
def __init__(self, complist):
self.complist = complist
def __str__(self):
return " ".join(x if i % 2 else x.wrap(x.precedence <= 0)
for i, x in enumerate(self.complist))
def extends(self, other):
if not isinstance(other, PyCompare):
return False
else:
return self.complist[0] == other.complist[-1]
def chain(self, other):
return PyCompare(self.complist + other.complist[1:])
class PyBooleanAnd(PyBinaryOp):
precedence = 4
pattern = "{} and {}"
class PyBooleanOr(PyBinaryOp):
precedence = 3
pattern = "{} or {}"
class PyIfElse(PyExpr):
precedence = 2
def __init__(self, cond, true_expr, false_expr):
self.cond = cond
self.true_expr = true_expr
self.false_expr = false_expr
def __str__(self):
p = self.precedence
cond_str = self.cond.wrap(self.cond.precedence <= p)
true_str = self.true_expr.wrap(self.cond.precedence <= p)
false_str = self.false_expr.wrap(self.cond.precedence < p)
return "{} if {} else {}".format(true_str, cond_str, false_str)
class PyAttribute(PyExpr):
precedence = 15
def __init__(self, expr, attrname):
self.expr = expr
self.attrname = attrname
def __str__(self):
expr_str = self.expr.wrap(self.expr.precedence < self.precedence)
return "{}.{}".format(expr_str, self.attrname)
class PyCallFunction(PyExpr):
precedence = 15
def __init__(self, func, args, kwargs, varargs=None, varkw=None):
self.func = func
self.args = args
self.kwargs = kwargs
self.varargs = varargs
self.varkw = varkw
def __str__(self):
funcstr = self.func.wrap(self.func.precedence < self.precedence)
if len(self.args) == 1 and not (self.kwargs or self.varargs
or self.varkw):
arg = self.args[0]
if isinstance(arg, PyGenExpr):
# Only one pair of brackets arount a single arg genexpr
return "{}{}".format(funcstr, arg)
args = [x.wrap(x.precedence <= 0) for x in self.args]
args.extend("{}={}".format(k.val, v.wrap(v.precedence <= 0))
for k, v in self.kwargs)
if self.varargs is not None:
args.append("*{}".format(self.varargs))
if self.varkw is not None:
args.append("**{}".format(self.varkw))
return "{}({})".format(funcstr, ", ".join(args))
class FunctionDefinition:
def __init__(self, code, defaults, kwdefaults, closure, paramobjs={}):
self.code = code
self.defaults = defaults
self.kwdefaults = kwdefaults
self.closure = closure
self.paramobjs = paramobjs
def getparams(self):
code_obj = self.code.code_obj
l = code_obj.co_argcount
params = list(code_obj.co_varnames[:l])
if self.defaults:
for i, arg in enumerate(reversed(self.defaults)):
name = params[-i - 1]
if name in self.paramobjs:
params[-i - 1] = "{}:{}={}".format(name, self.paramobjs[name], arg)
else:
params[-i - 1] = "{}={}".format(name, arg)
kwcount = code_obj.co_kwonlyargcount
kwparams = []
if kwcount:
for i in range(kwcount):
name = code_obj.co_varnames[l + i]
if name in self.kwdefaults and name in self.paramobjs:
kwparams.append("{}:{}={}".format(name, self.paramobjs[name], self.kwdefaults[name]))
elif name in self.kwdefaults:
kwparams.append("{}={}".format(name, self.kwdefaults[name]))
else:
kwparams.append(name)
l += kwcount
if code_obj.co_flags & VARARGS:
params.append("*" + code_obj.co_varnames[l])
l += 1
elif kwparams:
params.append("*")
params.extend(kwparams)
if code_obj.co_flags & VARKEYWORDS:
params.append("**" + code_obj.co_varnames[l])
return params
def getreturn(self):
if self.paramobjs and 'return' in self.paramobjs:
return self.paramobjs['return']
return None
class PyLambda(PyExpr, FunctionDefinition):
precedence = 1
def __str__(self):
suite = self.code.get_suite()
params = ", ".join(self.getparams())
if len(suite.statements) > 0:
def strip_return(val):
return val[len("return "):] if val.startswith('return') else val
if isinstance(suite[0], IfStatement) and len(suite.statements) == 2:
expr = "return {} if {} else {}".format(
strip_return(str(suite[0].true_suite)),
str(suite[0].cond),
strip_return(str(suite[1]))
)
else:
expr = strip_return(str(suite[0]))
else:
expr = "None"
return "lambda {}: {}".format(params, expr)
class PyComp(PyExpr):
"""
Abstraction for list, set, dict comprehensions and generator expressions
"""
precedence = 16
def __init__(self, code, defaults, kwdefaults, closure, paramobjs={}):
assert not defaults and not kwdefaults
self.code = code
code[0].change_instr(NOP)
last_i = len(code.instr_seq) - 1
code[last_i].change_instr(NOP)
def set_iterable(self, iterable):
self.code.varnames[0] = iterable
def __str__(self):
suite = self.code.get_suite()
return self.pattern.format(suite.gen_display())
class PyListComp(PyComp):
pattern = "[{}]"
class PySetComp(PyComp):
pattern = "{{{}}}"
class PyKeyValue(PyBinaryOp):
"""This is only to create dict comprehensions"""
precedence = 1
pattern = "{}: {}"
class PyDictComp(PyComp):
pattern = "{{{}}}"
class PyGenExpr(PyComp):
precedence = 16
pattern = "({})"
def __init__(self, code, defaults, kwdefaults, closure, paramobjs={}):
self.code = code
class PyYield(PyExpr):
precedence = 1
def __init__(self, value):
self.value = value
def __str__(self):
return "yield {}".format(self.value)
class PyYieldFrom(PyExpr):
precedence = 1
def __init__(self, value):
self.value = value
def __str__(self):
return "yield from {}".format(self.value)
class PyStarred(PyExpr):
"""Used in unpacking assigments"""
precedence = 15
def __init__(self, expr):
self.expr = expr
def __str__(self):
es = self.expr.wrap(self.expr.precedence < self.precedence)
return "*{}".format(es)
code_map = {
'<lambda>': PyLambda,
'<listcomp>': PyListComp,
'<setcomp>': PySetComp,
'<dictcomp>': PyDictComp,
'<genexpr>': PyGenExpr,
}
unary_ops = [
('UNARY_POSITIVE', 'Positive', '+{}', 13),
('UNARY_NEGATIVE', 'Negative', '-{}', 13),
('UNARY_NOT', 'Not', 'not {}', 5),
('UNARY_INVERT', 'Invert', '~{}', 13),
]
binary_ops = [
('POWER', 'Power', '{}**{}', 14, '{} **= {}'),
('MULTIPLY', 'Multiply', '{}*{}', 12, '{} *= {}'),
('FLOOR_DIVIDE', 'FloorDivide', '{}//{}', 12, '{} //= {}'),
('TRUE_DIVIDE', 'TrueDivide', '{}/{}', 12, '{} /= {}'),
('MODULO', 'Modulo', '{} % {}', 12, '{} %= {}'),
('ADD', 'Add', '{} + {}', 11, '{} += {}'),
('SUBTRACT', 'Subtract', '{} - {}', 11, '{} -= {}'),
('SUBSCR', 'Subscript', '{}[{}]', 15, None),
('LSHIFT', 'LeftShift', '{} << {}', 10, '{} <<= {}'),
('RSHIFT', 'RightShift', '{} >> {}', 10, '{} >>= {}'),
('AND', 'And', '{} & {}', 9, '{} &= {}'),
('XOR', 'Xor', '{} ^ {}', 8, '{} ^= {}'),
('OR', 'Or', '{} | {}', 7, '{} |= {}'),
]
class PyStatement:
def __str__(self):
istr = IndentString()
self.display(istr)
return str(istr)
def wrap(self, condition=True):
if condition:
assert not condition
return "({})".format(self)
else:
return str(self)
def on_pop(self, dec):
# dec.write("#ERROR: Unexpected context 'on_pop': pop on statement: ")
pass
class DocString(PyStatement):
def __init__(self, string):
self.string = string
def display(self, indent):
if '\n' not in self.string:
indent.write(repr(self.string))
else:
if "'''" not in self.string:
fence = "'''"
elif '"""' not in self.string:
fence = '"""'
else:
raise NotImplemented
lines = self.string.split('\n')
text = '\n'.join(l.encode('unicode_escape').decode()
for l in lines)
docstring = "{0}{1}{0}".format(fence, text)
indent.write(docstring)
class AssignStatement(PyStatement):
def __init__(self, chain):
self.chain = chain
def display(self, indent):
indent.write(" = ".join(map(str, self.chain)))
class InPlaceOp(PyStatement):
def __init__(self, left, right):
self.right = right
self.left = left
def store(self, dec, dest):
# assert dest is self.left
dec.suite.add_statement(self)
def display(self, indent):
indent.write(self.pattern, self.left, self.right)
class Unpack:
precedence = 50
def __init__(self, val, length, star_index=None):
self.val = val
self.length = length
self.star_index = star_index
self.dests = []
def store(self, dec, dest):
if len(self.dests) == self.star_index:
dest = PyStarred(dest)
self.dests.append(dest)
if len(self.dests) == self.length:
dec.stack.push(self.val)
dec.store(PyTuple(self.dests))
class ImportStatement(PyStatement):
alias = ""
precedence = 100
def __init__(self, name, level, fromlist):
self.name = name
self.alias = name
self.level = level
self.fromlist = fromlist
self.aslist = []
def store(self, dec, dest):
self.alias = dest
dec.suite.add_statement(self)
def on_pop(self, dec):
dec.suite.add_statement(self)
def display(self, indent):
if self.fromlist == PyConst(None):
name = self.name.name
alias = self.alias.name
if name == alias or name.startswith(alias + "."):
indent.write("import {}", name)
else:
indent.write("import {} as {}", name, alias)
elif self.fromlist == PyConst(('*',)):
indent.write("from {} import *", self.name.name)
else:
names = []
for name, alias in zip(self.fromlist, self.aslist):
if name == alias:
names.append(name)
else:
names.append("{} as {}".format(name, alias))
indent.write("from {} import {}", self.name, ", ".join(names))
class ImportFrom:
def __init__(self, name):
self.name = name
def store(self, dec, dest):
imp = dec.stack.peek()
assert isinstance(imp, ImportStatement)
imp.aslist.append(dest.name)
class SimpleStatement(PyStatement):
def __init__(self, val):
assert val is not None
self.val = val
def display(self, indent):
indent.write(self.val)
def gen_display(self, seq=()):
return " ".join((self.val,) + seq)
class IfStatement(PyStatement):
def __init__(self, cond, true_suite, false_suite):
self.cond = cond
self.true_suite = true_suite
self.false_suite = false_suite
def display(self, indent, is_elif=False):
ptn = "elif {}:" if is_elif else "if {}:"
indent.write(ptn, self.cond)
self.true_suite.display(indent + 1)
if not self.false_suite:
return
if len(self.false_suite) == 1:
stmt = self.false_suite[0]
if isinstance(stmt, IfStatement):
stmt.display(indent, is_elif=True)
return
indent.write("else:")