-
Notifications
You must be signed in to change notification settings - Fork 7
/
fupy
executable file
·2472 lines (2224 loc) · 85.2 KB
/
fupy
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
#!/usr/bin/env python
"""
Decompiles a .pyc or .pyo file into a human-readable .py source file.
fupy is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
fupy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with fupy. If not, see <http:https://www.gnu.org/licenses/>.
Contact: Guillaume Delugre <guillaume (at) security-labs (dot) org>
"""
import sys
import imp, dis, opcode, marshal
import types
import __builtin__
class Statement:
""" Python generic statement. """
def __init__(self, indent_level = 0):
self.indent_level = indent_level
def set_indent_level(self, level):
self.indent_level = level
def make_indent(self, indent):
return indent * self.indent_level
def __eq__(self, s):
if isinstance(s, Statement):
saved_indent_levels = self.indent_level, s.indent_level
self.set_indent_level(0)
s.set_indent_level(0)
if hasattr(self, 'parenthesize'):
saved_self_parenthesize = self.parenthesize
self.parenthesize = True
if hasattr(s, 'parenthesize'):
saved_other_parenthesize = s.parenthesize
s.parenthesize = True
equals = self.write(' ') == s.write(' ')
self.set_indent_level(saved_indent_levels[0])
s.set_indent_level(saved_indent_levels[1])
if hasattr(self, 'parenthesize'):
self.parenthesize = saved_self_parenthesize
if hasattr(s, 'parenthesize'):
self.parenthesize = saved_other_parenthesize
return equals
else:
return False
def __ne__(self, s):
return not (self == s)
@staticmethod
def auto_indent(writer):
def do_indent(self, indent = ''):
return indent * self.indent_level + writer(self, indent)
return do_indent
class Block(Statement):
""" Python compound statement. Contains one or more indented block of statements.
Can be
- if/elif/else
- for in..else
- while..else
- try..except..else..finally
- with
- def
- class
"""
def __init__(self, statements = [], indent_level = 0):
Statement.__init__(self, indent_level)
self.statements = statements
for statement in statements:
statement.set_indent_level(self.indent_level + 1)
def append_statement(self, statement):
self.statements.append(statement)
statement.set_indent_level(self.indent_level + 1)
def set_indent_level(self, level):
Statement.set_indent_level(self, level)
for statement in self.statements:
statement.set_indent_level(level + 1)
def replace_statements(self, match, new, rec = False):
for i, statement in enumerate(self.statements):
if rec and isinstance(statement, Block):
statement.replace_statements(match, new, rec)
if match(statement):
self.statements[i] = new(statement)
self.statements[i].set_indent_level(self.indent_level + 1)
def delete_statements(self, match, rec = False):
pos = []
for i, statement in enumerate(self.statements):
if rec and isinstance(statement, Block):
statement.delete_statements(cond)
if match(statement):
pos.insert(0, i)
for i in pos:
self.statements.pop(i)
if len(self.statements) == 0:
self.append_statement(Pass())
def write(self, indent = ''):
# Reduce conditional blocks to assert statements when possible
i = 0
while i < len(self.statements):
s = self.statements[i]
next = i < len(self.statements) - 1 and self.statements[i + 1]
if isinstance(s, If) and not isinstance(next, Elif):
if len(s.statements) == 1 and isinstance(s.statements[0], Raise) and s.statements[0].exception == Variable('AssertionError'):
self.statements[i] = Assert(s.expr.expr if isinstance(s.expr, UnaryOp) and s.expr.op == 'not ' else UnaryOp('not ', s.expr), s.statements[0].param)
self.statements[i].set_indent_level(self.indent_level + 1)
if isinstance(next, Else):
self.statements.pop(i + 1)
self.statements[i+1:i+2] = next.statements
for statement in next.statements:
statement.set_indent_level(self.indent_level + 1)
elif isinstance(next, Else) and len(next.statements) == 1 and isinstance(next.statements[0], Raise) and next.statements[0].exception == Variable('AssertionError'):
self.statements[i] = Assert(s.expr, next.statements[0].param)
self.statements[i].set_indent_level(self.indent_level + 1)
self.statements.pop(i + 1)
self.statements[i+1:i+2] = s.statements
for statement in s.statements:
statement.set_indent_level(self.indent_level + 1)
i = i + 1
if len(self.statements) == 0:
self.append_statement(Pass())
return "\n".join([statement.write(indent) for statement in self.statements])
class Expression(Statement):
""" Python generic expression. """
def __hash__(self):
return hash(id(self))
class ExpressionList(Expression):
""" List of expressions : expr1, expr2, ... """
def __init__(self, exprs = None):
Expression.__init__(self)
if exprs:
self.exprs = exprs
else:
self.exprs = []
def append(self, expr):
self.exprs.append(expr)
@Statement.auto_indent
def write(self, indent = ''):
return ", ".join([expr.write() for expr in self.exprs])
class ConditionalExpression(Expression):
""" Conditional expression : expr1 if cond else expr2 """
def __init__(self, if_expr, cond_expr, else_expr):
Expression.__init__(self)
self.if_expr = if_expr
self.cond_expr = cond_expr
self.else_expr = else_expr
@Statement.auto_indent
def write(self, indent = ''):
return self.if_expr.write() + " if " + self.cond_expr.write() + " else " + self.else_expr.write()
class Assignment(Expression):
""" Assignement expr1 = expr2 """
def __init__(self, left, right):
Expression.__init__(self)
self.left = left
self.right = right
@Statement.auto_indent
def write(self, indent = ''):
return self.left.write() + " = " + self.right.write()
class GetAttr(Expression):
""" Expression attribute expr.attr """
def __init__(self, expr, attr):
Expression.__init__(self)
self.base = expr
if isinstance(self.base, BinaryOp):
self.base.parenthesize = True
self.attr = attr
@Statement.auto_indent
def write(self, indent = ''):
return self.base.write() + "." + self.attr
class Variable(Expression):
""" Expression as variable name """
def __init__(self, name):
Expression.__init__(self)
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return isinstance(other, Variable) and (self.name == other.name)
def __ne__(self, other):
return not (self == other)
@Statement.auto_indent
def write(self, indent = ''):
return self.name
class Constant(Expression):
""" Expression as constant (e.g "foo", (1,2,x)) """
def __init__(self, value):
Expression.__init__(self)
self.value = value
def __hash__(self):
return hash(self.value)
def __eq__(self, other):
return isinstance(other, Constant) and (self.value == other.value)
def __ne__(self, other):
return not (self == other)
@Statement.auto_indent
def write(self, indent = ''):
if isinstance(self.value, types.ListType):
values = [ value.write() if isinstance(value, Expression) else repr(value) for value in self.value ]
out = "[" + ", ".join(values) + "]"
elif isinstance(self.value, types.TupleType):
values = [ value.write() if isinstance(value, Expression) else repr(value) for value in self.value ]
out = "(" + ", ".join(values)
if len(values) == 1:
out += ","
out += ")"
elif isinstance(self.value, types.DictType):
couples = []
for key, value in self.value.iteritems():
key = key.write() if isinstance(key, Expression) else repr(key)
value = value.write() if isinstance(value, Expression) else repr(value)
couples.append(key + ": " + value)
out = "{" + ", ".join(couples) + "}"
elif isinstance(self.value, set):
values = [ value.write() if isinstance(value, Expression) else repr(value) for value in self.value ]
out = "{" + ", ".join(values) + "}"
else:
out = repr(self.value)
return out
class Comprehension(Expression):
""" Comprehension expression : expr1 for vars in expr2 """
def __init__(self, expr, variables, iterable, if_expr = None):
Expression.__init__(self)
self.expr = expr
self.variables = variables
self.iterable = iterable
self.if_expr = if_expr
@Statement.auto_indent
def write(self, indent = ''):
var_list = ", ".join([var.write() for var in self.variables])
out = self.expr.write() + " for " + var_list + " in " + self.iterable.write()
if self.if_expr:
out += " if " + self.if_expr.write()
return out
class TypedComprehension(Expression):
""" List/set/dict comprehensions """
def __init__(self, comp):
Expression.__init__(self)
self.comp = comp
class ListComprehension(TypedComprehension):
""" List comprehension : [expr1 for vars in expr2] """
@Statement.auto_indent
def write(self, indent = ''):
return '[' + self.comp.write() + ']'
class SetComprehension(TypedComprehension):
""" Set comprehension : {expr1 for vars in expr2} """
@Statement.auto_indent
def write(self, indent = ''):
return '{' + self.comp.write() + '}'
class DictComprehensionEntry:
""" Entry in dict comprehension : key_expr : value_expr """
def __init__(self, key_expr, value_expr):
self.key_expr = key_expr
self.value_expr = value_expr
def write(self, indent = ''):
return self.key_expr.write() + ' : ' + self.value_expr.write()
class DictComprehension(TypedComprehension):
""" Dict comprehension : { key_expr : value_expr for vars in expr } """
@Statement.auto_indent
def write(self, indent = ''):
return '{' + self.comp.write() + '}'
class Generator(Expression):
""" Generator expression : (expr1 for vars in expr2) """
def __init__(self, comp):
Expression.__init__(self)
self.comp = comp
self.parenthesize = True
@Statement.auto_indent
def write(self, indent = ''):
out = ''
if self.parenthesize:
out += '('
out += self.comp.write()
if self.parenthesize:
out += ')'
return out
class UnaryOp(Expression):
""" Expression with unary operator (e.g ~expr) """
def __init__(self, op, expr):
Expression.__init__(self)
self.op = op
self.expr = expr
self.parenthesize = False
if isinstance(self.expr, BinaryOp) or isinstance(self.expr, UnaryOp):
if self.expr.precedence() < self.precedence():
self.expr.parenthesize = True
def precedence(self):
return PythonDecompiler.unary_operator_precedences[self.op]
@Statement.auto_indent
def write(self, indent = ''):
out = ''
if self.parenthesize:
out += '('
out += self.op + self.expr.write()
if self.parenthesize:
out += ')'
return out
class UnaryConvert(Expression):
""" Expression with convert operator (`expr`) """
def __init__(self, expr):
Expression.__init__(self)
self.expr = expr
@Statement.auto_indent
def write(self, indent = ''):
return '`' + self.expr.write() + '`'
class BinaryOp(Expression):
""" Expression with binary operator (e.g expr1 == expr2) """
def __init__(self, left, op, right):
Expression.__init__(self)
self.op = op
self.left = left
self.right = right
self.parenthesize = False
logical_ops = ( 'and', 'or' )
if self.op in logical_ops:
neg_op = logical_ops[1-logical_ops.index(self.op)]
if isinstance(self.left, BinaryOp) and self.left.op == neg_op:
self.left.parenthesize = True
if isinstance(self.right, BinaryOp) and self.right.op == neg_op:
self.right.parenthesize = True
else:
if isinstance(self.left, BinaryOp) or isinstance(self.left, UnaryOp):
if self.left.precedence() < self.precedence():
self.left.parenthesize = True
if isinstance(self.right, BinaryOp) or isinstance(self.right, UnaryOp):
if self.precedence() == self.right.precedence() and not self.commutative():
self.right.parenthesize = True
elif self.right.precedence() < self.precedence():
self.right.parenthesize = True
def commutative(self):
return self.op in PythonDecompiler.commutative_operators
def precedence(self):
return PythonDecompiler.binary_operator_precedences[self.op]
def first(self):
if isinstance(self.left, BinaryOp):
return self.left.first
else:
return self.left
def last(self):
if isinstance(self.right, BinaryOp):
return self.right.last
else:
return self.right
@Statement.auto_indent
def write(self, indent = ''):
out = ''
if self.parenthesize:
out += '('
out += self.left.write() + " " + self.op + " " + self.right.write()
if self.parenthesize:
out += ')'
return out
class BinarySubscr(Expression):
""" Expression expr1[expr2]. """
def __init__(self, base_expr, index_expr):
Expression.__init__(self)
self.base_expr = base_expr
if isinstance(self.base_expr, BinaryOp):
self.base_expr.parenthesize = True
self.index_expr = index_expr
@Statement.auto_indent
def write(self, indent = ''):
return self.base_expr.write() + "[" + self.index_expr.write() + "]"
class FunctionCall(Expression):
""" Function call expression : expr(expr1, expr2, param = expr3) """
def __init__(self, expr, pos_args = [], key_args = {}, var_args = None, kwvar_args = None):
Expression.__init__(self)
self.function = expr
self.pos_args = pos_args
self.key_args = key_args
self.var_args = var_args
self.kwvar_args = kwvar_args
# rare case where generator does not need parenthesises
if len(self.key_args) == 0 and len(self.pos_args) == 1 and isinstance(self.pos_args[0], Generator):
self.pos_args[0].parenthesize = False
@Statement.auto_indent
def write(self, indent = ''):
args = ", ".join([arg.write() for arg in self.pos_args ])
if len(self.key_args) > 0:
if len(args) > 0:
args += ", "
keys = self.key_args.keys()
keys.sort()
args += ", ".join([key + " = " + self.key_args[key].write() for key in keys])
if self.var_args:
if len(args) > 0:
args += ", "
args += '*' + self.var_args.write()
if self.kwvar_args:
if len(args) > 0:
args += ", "
args += '**' + self.kwvar_args.write()
return self.function.write() + "(" + args + ")"
class Slice(Expression):
""" Slice expression : start:stop:step """
def __init__(self, start = None, stop = None, step = None):
Expression.__init__(self)
self.start = start
self.stop = stop
self.step = step
@Statement.auto_indent
def write(self, indent = ''):
out = ''
if self.start != None and self.start != Constant(None):
out += self.start.write()
out += ':'
if self.stop != None and self.stop != Constant(None):
out += self.stop.write()
if self.step != None and self.step != Constant(None):
out += ':' + self.step.write()
return out
class Yield(Expression):
""" Yield expression. """
def __init__(self, expr):
Statement.__init__(self)
self.expr = expr
@Statement.auto_indent
def write(self, indent = ''):
return "yield " + self.expr.write()
class Lambda(Expression):
""" Lambda expression: lambda args: expr """
def __init__(self, args, default_args, statements):
Expression.__init__(self)
self.args = args
self.default_values = default_args
self.statements = statements
self.__remove_returns()
def __remove_returns(self):
for i, statement in enumerate(self.statements):
if isinstance(statement, Return):
self.statements[i] = statement.expr
elif isinstance(statement, Block):
statement.replace_statements(match = (lambda s: isinstance(s, Return)), new = (lambda s: s.expr), rec = True)
@Statement.auto_indent
def write(self, indent = ''):
args = []
first_default = len(self.args) - len(self.default_values)
for i in range(0, first_default):
args.append(self.args[i])
for i in range(first_default, len(self.args)):
args.append(self.args[i] + " = " + self.default_values[i - first_default].write())
out = "(lambda " + ", ".join([str(arg) for arg in args]) + ": "
out += "; ".join([ statement.write() for statement in self.statements ]) + ")"
return out
class With(Block):
""" With block : with expr as var: statements """
def __init__(self, expr, var, statements):
Block.__init__(self, statements)
self.expr = expr
self.var = var
@Statement.auto_indent
def write(self, indent):
out = "with " + self.expr.write()
if self.var:
out += " as " + self.var.write()
out += ":\n"
out += Block.write(self, indent)
return out
class For(Block):
""" For block : for variables in expr: statements """
def __init__(self, variables, expr, statements):
Block.__init__(self, statements)
self.variables = variables
self.expr = expr
@Statement.auto_indent
def write(self, indent):
var_list = ", ".join([ var.write() for var in self.variables ])
return "for " + var_list + " in " + self.expr.write() + ":\n" + Block.write(self, indent)
class While(Block):
""" While block: while expr: statements """
def __init__(self, expr, statements):
Block.__init__(self, statements)
self.expr = expr
@Statement.auto_indent
def write(self, indent):
return "while " + self.expr.write() + ":\n" + Block.write(self, indent)
class If(Block):
""" If block: if expr: statements """
def __init__(self, expr, statements):
Block.__init__(self, statements)
self.expr = expr
@Statement.auto_indent
def write(self, indent):
return "if " + self.expr.write() + ":\n" + Block.write(self, indent)
class Elif(Block):
""" Elif block: elif expr: statements
Can appear after an If statement or another Elif statement.
"""
def __init__(self, expr, statements):
Block.__init__(self, statements)
self.expr = expr
@Statement.auto_indent
def write(self, indent):
return "elif " + self.expr.write() + ":\n" + Block.write(self, indent)
class Else(Block):
""" Else block: else: statements
Can appear after If, Elif, For, While, Try statements.
"""
@Statement.auto_indent
def write(self, indent):
return "else:\n" + Block.write(self, indent)
class Try(Block):
""" Try block """
def __init__(self, statements):
Block.__init__(self, statements)
@Statement.auto_indent
def write(self, indent):
return "try:\n" + Block.write(self, indent)
class Except(Block):
""" Except block: except exc as name: statements """
def __init__(self, statements, exc = None, as_name = None):
Block.__init__(self, statements)
self.exc = exc
self.as_name = as_name
@Statement.auto_indent
def write(self, indent):
out = "except"
if self.exc:
out += ' ' + self.exc.write()
if self.as_name:
out += " as " + self.as_name.write()
out += ":\n"
out += Block.write(self, indent)
return out
class Finally(Block):
""" Finally block """
@Statement.auto_indent
def write(self, indent):
return "finally:\n" + Block.write(self, indent)
class DocString(Statement):
""" Docstring comment. """
def __init__(self, comment):
Statement.__init__(self)
self.comment = comment
@Statement.auto_indent
def write(self, indent):
lines = self.comment.split("\n")
indented_lines = [ self.make_indent(indent) + line.lstrip() for line in lines[1:] ]
return '"""' + "\n".join(lines[0:1] + indented_lines) + '"""'
class ClassDefinition(Block):
""" Class definition block: class name(superclasses): statements """
def __init__(self, name, supers, statements):
Block.__init__(self, statements)
self.name = name
self.supers = supers
self.docstring = None
docstrings = filter(
lambda s: isinstance(s, Assignment) and s.left == Variable('__doc__'),
self.statements
)
if len(docstrings) > 0:
self.docstring = DocString(docstrings[0].right.value)
self.docstring.set_indent_level(self.indent_level + 1)
self.delete_statements(
match = lambda s: isinstance(s, Return) or isinstance(s, Assignment) and (s.left == Variable('__module__') or s.left == Variable('__doc__')),
rec = False
)
methods = filter(
lambda s: isinstance(s, FunctionDefinition),
self.statements
)
for method in methods:
self.unmangle(method)
def unmangle(self, method):
if method.name[0:1] == '_' and method.name[1:len(self.name)+1] == self.name:
method.name = method.name[len(self.name)+1:]
def set_indent_level(self, level):
Block.set_indent_level(self, level)
if self.docstring:
self.docstring.set_indent_level(level + 1)
@Statement.auto_indent
def write(self, indent):
out = "class " + self.name
if len(self.supers) > 0:
supers = ", ".join([superclass.write() for superclass in self.supers])
out += "(" + supers + ")"
out += ":\n"
if self.docstring:
out += self.docstring.write(indent) + "\n"
out += Block.write(self, indent)
if len(self.statements) > 0 and not isinstance(self.statements[-1], FunctionDefinition) and not isinstance(self.statements[-1], ClassDefinition):
out += "\n"
return out
class FunctionDefinition(Block):
""" Function definition block:
def func(args, arg_n = default_arg_1, arg_n+1 = default_arg_2): statements
"""
def __init__(self, name, args, default_args, varargs, kwvarargs, statements):
Block.__init__(self, statements)
self.name = name
self.args = args
self.default_values = default_args
self.varargs = varargs
self.kwvarargs = kwvarargs
self.docstring = None
if len(statements) > 0 and statements[-1].write('') == 'return':
statements.pop()
def set_docstring(self, string):
self.docstring = DocString(string)
self.docstring.set_indent_level(self.indent_level + 1)
def set_indent_level(self, level):
Block.set_indent_level(self, level)
if self.docstring:
self.docstring.set_indent_level(level + 1)
@Statement.auto_indent
def write(self, indent):
args = []
first_default = len(self.args) - len(self.default_values)
for i in range(0, first_default):
args.append(self.args[i])
for i in range(first_default, len(self.args)):
args.append(self.args[i] + " = " + self.default_values[i - first_default].write())
out = "def " + self.name + "(" + ", ".join(args)
if self.varargs:
if len(args) > 0:
out += ", "
out += "*" + self.varargs
if self.kwvarargs:
if len(args) > 0 or self.varargs:
out += ", "
out += "**" + self.kwvarargs
out += "):\n"
if self.docstring:
out += self.docstring.write(indent) + "\n"
out += Block.write(self, indent) + "\n"
return out
class Import(Statement):
""" Import statement.
Equivalent to
module = __import__('module', fromlist = None, level = -1).
"""
def __init__(self, module, as_name = None):
Statement.__init__(self)
self.module = module
self.as_name = as_name
@Statement.auto_indent
def write(self, indent = ''):
out = "import " + '.'.join(self.module.path)
if self.as_name:
out += " as " + self.as_name.write()
return out
class ImportFrom(Statement):
""" Import from statement.
Equivalent to
name = __import__('module', fromlist = None, level = -1).name.
"""
def __init__(self, module, name, as_name = None):
Statement.__init__(self)
self.module = module
self.name = name
self.as_name = as_name
@Statement.auto_indent
def write(self, indent = ''):
out = "from " + '.'.join(self.module.path) + " import " + self.name.write()
if self.as_name:
out += " as " + self.as_name.write()
return out
class Assert(Statement):
""" Assert statement.
Equivalent to
if not expr: raise AssertionError(message)
"""
def __init__(self, expr, message = None):
Statement.__init__(self)
self.expr = expr
self.message = message
@Statement.auto_indent
def write(self, indent = ''):
out = "assert " + self.expr.write()
if self.message:
out += ", " + self.message.write()
return out
class Print(Statement):
""" Print statement. """
def __init__(self, expr_list = None):
Statement.__init__(self)
if expr_list:
self.expr_list = expr_list
else:
self.expr_list = ExpressionList()
self.new_line = False
@Statement.auto_indent
def write(self, indent = ''):
out = "print " + self.expr_list.write()
if not self.new_line:
out += ","
return out
class ExtendedPrint(Statement):
""" Extended print statement. """
def __init__(self, filedesc, expr_list = None):
Statement.__init__(self)
self.filedesc = filedesc
if expr_list:
self.expr_list = expr_list
else:
self.expr_list = ExpressionList()
self.new_line = False
@Statement.auto_indent
def write(self, indent = ''):
out = "print >> " + self.filedesc.write() + ", " + self.expr_list.write()
if not self.new_line:
out += ","
return out
class Break(Statement):
""" break statement. """
@Statement.auto_indent
def write(self, indent = ''):
return "break"
class Continue(Statement):
""" continue statement. """
@Statement.auto_indent
def write(self, indent = ''):
return "continue"
class Return(Statement):
""" return statement. """
def __init__(self, expr = None):
Statement.__init__(self)
self.expr = expr
@Statement.auto_indent
def write(self, indent = ''):
out = "return"
if self.expr != None and self.expr != Constant(None):
out += " " + self.expr.write()
return out
class Global(Statement):
""" global statement """
def __init__(self, var):
Statement.__init__(self)
self.var = var
@Statement.auto_indent
def write(self, indent = ''):
return "global " + self.var.write()
class Del(Statement):
""" del statement. """
def __init__(self, expr):
Statement.__init__(self)
self.expr = expr
@Statement.auto_indent
def write(self, indent = ''):
return "del " + self.expr.write()
class Raise(Statement):
""" raise statement. """
def __init__(self, exception = None, param = None, trace = None):
Statement.__init__(self)
self.exception = exception
self.param = param
self.trace = trace
@Statement.auto_indent
def write(self, indent = ''):
out = "raise"
if self.exception != None:
out += " " + self.exception.write()
if self.param != None:
out += ", " + self.param.write()
if self.trace != None:
out += ", " + self.trace.write()
return out
class Decorator(Statement):
""" Function decorator. """
def __init__(self, expr):
Statement.__init__(self)
self.expr = expr
@Statement.auto_indent
def write(self, indent = ''):
return "@" + self.expr.write()
class Exec(Statement):
""" exec statement. """
def __init__(self, expr, global_vars, local_vars):
Statement.__init__(self)
self.expr = expr
self.global_vars = global_vars
self.local_vars = local_vars
@Statement.auto_indent
def write(self, indent = ''):
out = "exec " + self.expr.write()
if self.global_vars != Constant(None):
out += " in " + self.global_vars.write()
if self.local_vars != Constant(None):
out += ", " + self.local_vars.write()
return out
class Pass(Statement):
""" pass statement. """
@Statement.auto_indent
def write(self, indent = ''):
return "pass"
class PythonProgram(Block):
""" Python program. This is what we wish to reconstruct.
The python source is considered as a block of statements.
"""
def __init__(self, statements):
Block.__init__(self, statements, -1)
self.delete_statements(match = lambda s: isinstance(s, Return), rec = False)
docstrings = filter(
lambda s: isinstance(s, Assignment) and s.left == Variable('__doc__'),
self.statements
)
if len(docstrings) > 0:
statements.insert(0, DocString(docstrings[0].right.value))
self.delete_statements(
match = lambda s: isinstance(s, Assignment) and s.left == Variable('__doc__'),
rec = False
)
class PythonExceptionClass:
"""
Internally used by the decompiler to represent the current exception class.
"""
def write(self, indent = ''):
return '.CurrentExceptionClass'
class PythonExceptionInstance:
"""
Internally used by the decompiler to represent the current exception instance.
"""
def write(self, indent = ''):
return '.CurrentException'
class PythonImportedModule:
"""
Internally used by the decompiler to represent an imported module.
"""
def __init__(self, name):
self.path = name.split('.')
class PythonImportedModuleAttr:
"""
Internally used by the decompiler to represent an imported module name.
"""
def __init__(self, module, name):
self.module = module
self.name = name
class PythonCompiledFunction:
"""
Internally used by the decompiler to represent a function made out of a precompiled code object.
"""
def __init__(self, code, default_args):
self.code = code
self.default_args = default_args
class PythonCompiledGenerator:
"""
Internally used by the decompiler to represent a precompiled generator object.
"""
def __init__(self, code):
self.code = code
class PythonCompiledComprehension:
"""
Internally used by the decompiler to represent set and dict comprehensions.
"""
def __init__(self, code):
self.code = code
class PythonCompiledFunctionCall:
"""
Internally used by the decompiler to represent a call to a precompiled function.
"""
def __init__(self, compiled):
self.function = compiled
class PythonCompiledClass:
"""
Internally used by the decompiler to represent a compiled class object.
"""
def __init__(self, supers, code):
self.supers = supers
self.code = code
class PythonIterator:
"""
Internally used by the decompiler to represent a volatile iterator.
"""