-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcode_transformers.py
1460 lines (1188 loc) · 58.8 KB
/
code_transformers.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
import random
import esprima
import re
import math
from abstract import JSPrimitive, JSRef, State, JSOr, JSNull, JSUndef
from config import regexp_rename, rename_length, simplify_expressions, simplify_function_calls, simplify_control_flow, max_unroll_ratio, remove_dead_code, Stats, inline_max_statements
from functools import reduce
from collections import namedtuple
from node_tools import get_ann, set_ann, del_ann, node_from_id, id_from_node, clear_ann, node_assign, node_copy, dump_ann
from typing import Set, List
from interpreter import LoopContext, START_ITER
EXPRESSIONS = ["Literal", "ArrayExpression", "ArrowFunctionExpression", "AssignmentExpression", "AwaitExpression", "BinaryExpression", "CallExpression", "ConditionalExpression", "FunctionExpression", "LogicalExpression", "MemberExpression", "NewExpression", "ObjectExpression", "SequenceExpression", "ThisExpression", "UnaryExpression", "UpdateExpression"]
def wrap_in_statement(expr : esprima.nodes.Node) -> esprima.nodes.Node:
"""
Helper function to wrap expressions (typically expressions that have side effects) in statements
:param esprima.nodes.Node expr: The expression to wrap
:rtype esprima.nodes.Node:
:return: The statement
"""
statement = esprima.nodes.ExpressionStatement(expr)
statement.range = expr.range
return statement
class LexicalScopedAbsInt(object):
"""
Helper class to perform "simple" abstract interpretation, without having to resolve function calls.
The on_XXX methods are meant to be overloaded by inheriting classes.
The do_XXX methods are meant to be used internally.
"""
def __init__(self, ast : esprima.nodes.Node, domain : State, name : str):
"""
Class constructor.
:param esprima.nodes.Node ast: The AST to process
:param State domain: The initial state
:param str name: The name of the analysis
"""
self.ast : esprima.nodes.Node = ast
self.name : str = name
self.domain : State = domain
def on_statement(self, state : State, statement : esprima.nodes.Node) -> None:
"""
Called when we encounter a statement
:param State state: The current abstract state
:param esprima.nodes.Node statement: The processed statement
"""
pass
#TODO define AbsExpr somewhere
def on_expression(self, state : State, expression: esprima.nodes.Node, test : bool = False) -> 'AbsExpr':
"""
Called when we encounter an expression
:param State state: The current abstract state
:param esprima.nodes.Node statement: The processed expression
:param bool test: Set to true if the expression is a test condition (if, while, ...)
"""
pass
def do_declaration(self, state : State, decl : esprima.nodes.Node) -> None:
"""
Process declaration AST node
:param State state: The current abstract state
:param esprima.nodes.Node decl: The declaration AST node
"""
if decl is None or decl.type != "VariableDeclaration":
return
self.do_statement( state, decl)
#TODO dégager ca et gérer le eval() ailleurs/autrement
def do_expression(self, state, expression, test=False):
if expression.type == "CallExpression":
if type(expression.arguments) is list and len(expression.arguments) == 1 and expression.arguments[0].type == "BlockStatement":
for st in expression.arguments[0].body:
self.do_statement( state, st)
return (self.on_expression(state, expression, test))
elif expression.type == "FunctionExpression" or expression.type == "ArrowFunctionExpression":
return (self.on_expression( state, expression, test))
else:
return (self.on_expression( state, expression, test))
def do_statement(self, state : State, statement : esprima.nodes.Node) -> None:
"""
Process statement AST node
:param State state: The current abstract state
:param esprima.nodes.Node statement: The statement AST node
"""
if statement.type == "VariableDeclaration":
self.on_statement( state, statement)
elif statement.type == "ExpressionStatement":
self.on_statement( state, statement)
self.on_expression( state, statement.expression, False)
elif statement.type == "IfStatement":
self.on_statement( state, statement)
self.on_expression( state, statement.test, True)
state_else = self.domain.clone_state(state)
self.do_statement( state, statement.consequent)
if statement.alternate is not None:
self.do_statement( state_else, statement.alternate)
self.domain.join_state(state, state_else)
elif statement.type == "FunctionDeclaration":
self.on_statement( state, statement)
elif statement.type == "ReturnStatement":
self.on_statement( state, statement)
elif statement.type == "WhileStatement":
self.on_statement( state, statement)
header_state = self.domain.bottom_state()
while True:
prev_header_state = self.domain.clone_state(header_state)
self.domain.join_state(header_state, state)
self.domain.assign_state(state, header_state)
if header_state == prev_header_state:
break
self.do_expression( state, statement.test, True)
self.do_statement( state, statement.body)
elif statement.type == "TryStatement":
self.do_statement( state, statement.block)
elif statement.type == "BlockStatement":
for st in statement.body:
self.do_statement( state, st)
elif statement.type == "ForStatement":
self.on_statement( state, statement)
if statement.init is not None:
self.do_expression( state, statement.init)
header_state = self.domain.bottom_state()
while True:
prev_header_state = self.domain.clone_state(header_state)
self.domain.join_state(header_state, state)
self.domain.assign_state(state, header_state)
if header_state == prev_header_state:
break
if statement.test is not None:
self.do_expression( state, statement.test, True)
if statement.body is not None:
self.do_statement( state, statement.body)
if statement.update is not None:
self.do_expression( state, statement.update)
elif statement.type == "ThrowStatement":
self.on_statement( state, statement)
elif statement.type == "SwitchStatement":
self.on_statement( state, statement)
self.on_expression( state, statement.discriminant)
case_states = []
for case in statement.cases:
current_case = self.domain.clone_state(state)
case_states.append(current_case)
for statement in case.consequent:
self.do_statement( current_case, statement)
for s in case_states:
self.domain.join_state(state, s)
elif statement.type == "ClassDeclaration":
self.on_statement( state, statement)
elif statement.type == "ClassBody":
self.on_statement( state, statement)
elif statement.type == "MethodDefinition":
self.on_statement( state, statement)
elif statement.type == "ForInStatement":
self.on_expression( state, statement.left)
self.on_expression( state, statement.right)
header_state = self.domain.bottom_state()
while True:
prev_header_state = self.domain.clone_state(header_state)
self.domain.join_state(header_state, state)
self.domain.assign_state(state, header_state)
if header_state == prev_header_state:
break
self.do_statement( state, statement.body)
def do_prog(self, prog : esprima.nodes.Node) -> None:
"""
Called to process the whole program
:param esprima.nodes.Node prog: The program to analyze
"""
state = self.domain.init_state()
for statement in prog:
self.do_statement( state, statement)
self.on_end(state)
def run(self):
"""
Run the analyzer
"""
self.do_prog(self.ast.body)
class CodeTransform(object):
"""
Helper class for any AST transformation. The methods before_XXXX and after_XXX are meant to be overloaded by subclasses.
"""
def __init__(self, ast : esprima.nodes.Node = None, name : str = None):
"""
Class constructor
"""
self.ast : esprima.nodes.Node = ast
"""The AST on which this transformation operates"""
self.name : name = name
"""The name of this transformation"""
self.pass_num : int = 1
"""The number of times this pass has been performed"""
def before_expression(self, expr : esprima.nodes.Node) -> bool:
"""
Called before an expression. If the method returns false, the expression is not processed.
:param esprima.nodes.Node expr: The expression node
:rtype bool:
:return: True to process the expression, False otherwise
"""
return True
def before_statement(self, statement : esprima.nodes.Node) -> bool:
"""
Called before a statement. If the method returns false, the statement is not processed.
:param esprima.nodes.Node statement: The statement node
:rtype bool:
:return: True to process the statement, False otherwise
"""
return True
def after_expression(self, expr, results):
return None
def after_statement(self, statement, results):
return None
def after_program(self, results):
return None
def do_expr_or_declaration(self, exprdecl):
if exprdecl is None:
return
if exprdecl.type == "VariableDeclaration":
self.do_statement( exprdecl)
else:
self.do_expr( exprdecl)
def do_expr(self, expr):
if expr is None:
return
if not self.before_expression(expr):
return
results = []
if expr.type == "NewExpression":
self.do_expr( expr.callee)
for argument in expr.arguments:
results.append((self.do_expr( argument)))
elif expr.type == "ConditionalExpression":
results.append((self.do_expr(expr.test)))
results.append((self.do_expr( expr.consequent)))
results.append((self.do_expr( expr.alternate)))
elif expr.type == "SequenceExpression":
for e in expr.expressions:
results.append((self.do_expr( e)))
elif expr.type == "AssignmentExpression":
if expr.left.type == "MemberExpression":
results.append((self.do_expr( expr.left.object)))
if expr.left.computed:
results.append((self.do_expr(expr.left.property)))
results.append((self.do_expr(expr.right)))
elif expr.type == "ObjectExpression":
for prop in expr.properties:
if prop.computed:
results.append((self.do_expr(prop.key)))
else:
if prop.type == "Property":
results.append((self.do_expr( prop.value)))
elif expr.type == "ArrayExpression":
for elem in expr.elements:
results.append((self.do_expr(elem)))
elif expr.type == "MemberExpression":
results.append((self.do_expr(expr.object)))
if expr.computed:
results.append((self.do_expr(expr.property)))
elif expr.type == "UnaryExpression":
results.append((self.do_expr(expr.argument)))
elif expr.type == "BinaryExpression":
results.append((self.do_expr(expr.left)))
results.append((self.do_expr(expr.right)))
elif expr.type == "LogicalExpression":
results.append((self.do_expr(expr.left)))
results.append((self.do_expr(expr.right)))
elif expr.type == "FunctionExpression":
results.append((self.do_statement(expr.body)))
elif expr.type == "ArrowFunctionExpression":
if expr.expression:
results.append((self.do_expr(expr.body)))
else:
results.append((self.do_statement(expr.body)))
elif expr.type == "CallExpression": #todo reduced
results.append((self.do_expr(expr.callee)))
for argument in expr.arguments:
if argument.type == "BlockStatement":
results.append((self.do_statement( argument))) #TODO hack
results.append((self.do_expr(argument)))
elif expr.type == "UpdateExpression":
results.append((self.do_expr(expr.argument)))
elif expr.type == "AwaitExpression":
results.append((self.do_expr( expr.argument)))
return self.after_expression(expr, results)
def do_statement(self, statement, end="\n"):
if not self.before_statement(statement):
return
results = []
if statement.type == "VariableDeclaration":
for decl in statement.declarations:
if decl.id.type == "ObjectPattern":
for prop in decl.id.properties:
if prop.computed:
results.append((self.do_expr(prop.key)))
else:
if prop.type == "Property":
results.append((self.do_expr(prop.value)))
if decl.init is not None:
results.append((self.do_expr( decl.init)))
elif statement.type == "ExpressionStatement":
results.append((self.do_expr( statement.expression)))
elif statement.type == "IfStatement":
results.append((self.do_expr(statement.test)))
results.append((self.do_statement( statement.consequent)))
if statement.alternate is not None:
results.append((self.do_statement( statement.alternate)))
elif statement.type == "FunctionDeclaration":
results.append((self.do_statement( statement.body)))
elif statement.type == "ReturnStatement":
if statement.argument is not None:
results.append((self.do_expr( statement.argument)))
elif statement.type == "WhileStatement":
results.append((self.do_expr(statement.test)))
results.append((self.do_statement(statement.body)))
elif statement.type == "TryStatement":
results.append((self.do_statement(statement.block)))
elif statement.type == "BlockStatement":
for st in statement.body:
results.append((self.do_statement( st)))
elif statement.type == "ForStatement":
if statement.init is not None:
results.append((self.do_expr_or_declaration(statement.init)))
if statement.test is not None:
results.append((self.do_expr(statement.test)))
if statement.update is not None:
results.append((self.do_expr_or_declaration(statement.update)))
results.append((self.do_statement(statement.body)))
elif statement.type == "ThrowStatement":
results.append((self.do_expr(statement.argument)))
elif statement.type == "SwitchStatement":
results.append((self.do_expr(statement.discriminant)))
for case in statement.cases:
results.append((self.do_expr(case.test)))
for statement in case.consequent:
results.append((self.do_statement(statement)))
elif statement.type == "ClassDeclaration":
results.append((self.do_statement(statement.body)))
elif statement.type == "ClassBody":
for item in statement.body:
results.append((self.do_statement(item)))
elif statement.type == "MethodDefinition":
if statement.key.type != "Identifier":
results.append((self.do_expr(statement.key)))
results.append((self.do_statement(statement.value.body)))
elif statement.type == "ForInStatement":
results.append((self.do_expr_or_declaration(statement.left)))
results.append((self.do_expr_or_declaration( statement.right)))
results.append((self.do_statement(statement.body)))
return self.after_statement(statement, results)
def do_prog(self, prog):
results = []
for statement in prog:
results.append((self.do_statement( statement)))
self.after_program(results)
def run(self):
if self.name is not None:
print("Applying code transform: " + str(self.name), end="")
if self.pass_num > 1:
print(" (pass " + str(self.pass_num) + ")")
else:
print("")
self.do_prog(self.ast.body)
self.pass_num += 1
class ExpressionSimplifier(CodeTransform):
def __init__(self, ast, pures, simplify_undefs):
super().__init__(ast, "Expression Simplifier")
self.pures = pures
self.simplify_undefs = simplify_undefs
self.id_pures = set()
def after_statement(self, st, results):
if st.type == "ExpressionStatement":
set_ann(st.expression, "static_value", None)
def before_expression(self, o):
if o.type == "UpdateExpression":
set_ann(o.argument, "is_updated", True)
return True
return True
def after_expression(self, o, side_effects): #TODO nettoyer
"""
Process expression.
:param o esprima.nodes.Node: An expression node
:param List[Union[bool, esprima.nodes.Node]] side_effects: For all subexpressions: True if has side effects not related to functions. False if has no side effects. List of function calls if only side-effects related to functions.
"""
#print("simplify expression", o.node_id)
if not get_ann(o, "stats_counted_ex"):
Stats.simplified_expressions_tot += 1
print("Count: ")
print(o)
print("")
set_ann(o, "stats_counted_ex", True)
calls = []
#Collect side-effects call for any sub-expression. If we encounter side effects not releted to function call, return True
for s in side_effects:
if s is True:
return True
elif s is False:
continue
elif type(s) is list:
for c in s:
calls.append(c)
#If we reach here, sub-expressions have either no side effects, or side effects related to function calls
if o.type == "AssignmentExpression" or o.type == "ConditionalExpression" or o.type == "LogicalExpression":
return True #Report side effects not related to function call
if o.type == "UpdateExpression" and isinstance(get_ann(o, "static_value"), JSPrimitive):
if (type(get_ann(o, "static_value").val) is int or type(get_ann(o, "static_value").val) is float) and get_ann(o, "static_value").val < 0:
return True
n = esprima.nodes.AssignmentExpression("=", o.argument, esprima.nodes.Literal(get_ann(o, "static_value").val, None))
o.__dict__ = n.__dict__
return True
#If we reach here, this expression either have either no side effects, or side effects related to function calls
#Find out if this expression references a function that has been declared as pure on the command line arguments
if o.type == "CallExpression" and o.callee.name in self.pures:
if isinstance(get_ann(o.callee, "static_value"), JSRef):
self.id_pures.add(get_ann(o.callee, "static_value").target())
#Find out if this is a call with side effects
if o.type == "CallExpression" and not get_ann(o, "callee_is_pure") and o.callee.name not in self.pures and (not isinstance(get_ann(o.callee, "static_value"), JSRef) or get_ann(o.callee, "static_value").target() not in self.id_pures):
c = esprima.nodes.CallExpression(o.callee, o.arguments)
calls.append(c)
#Find out if expression has a statically-known value
static_value = get_ann(o, "static_value")
if self.simplify_undefs and isinstance(static_value, JSOr):
for c in static_value.choices:
if isinstance(c, JSPrimitive):
static_value = c
break
set_ann(o, "static_value", static_value)
if isinstance(static_value, JSPrimitive):
if type(static_value.val) is int:
if static_value.val < 0:
return calls
if type(static_value.val) is float and (static_value.val < 0 or not math.isfinite(static_value.val)):
return calls
if (isinstance(static_value, JSPrimitive) or static_value == JSNull) and not get_ann(o, "is_updated"):
if o.value is None:
Stats.simplified_expressions += 1
o.type = "Literal"
if static_value == JSNull:
o.value = None
else:
o.value = static_value.val
if len(calls) > 0:
o_copy = esprima.nodes.Literal(o.value, o.raw)
sequence = calls.copy()
sequence.append(o_copy)
seq_node = esprima.nodes.SequenceExpression(sequence)
o.__dict__ = seq_node.__dict__
set_ann(o, "static_value", static_value)
set_ann(o, "impure", True)
return calls
class VariableRenamer(CodeTransform):
def __init__(self, ast):
random.seed(42)
self.first=['b','ch','d','f','g','l','k', 'm','n','p','r','t','v','x','z']
self.second=['a','e','o','u','i','au','ou']
self.renamed = {}
self.used_names = set()
super().__init__(ast, "Variable Renamer")
def generate(self, n):
name = ""
for i in range(n):
name += random.choice(self.first)
name += random.choice(self.second)
return name
def rename(self, name):
global rename_length
if name is None:
return name
for r in regexp_rename:
if re.match(r, name) is not None:
if name in self.renamed.keys():
return self.renamed[name]
newname = self.generate(rename_length)
t = 0
while newname in self.used_names:
if t > 10:
rename_length += 1
print("WARNING: increased variable rename length to:", rename_length)
newname = generate(rename_length)
t = t + 1
self.used_names.add(newname)
self.renamed[name] = newname
return newname
return name
def before_expression(self, o):
if o.type == "Identifier" and o.name != "uncreate_defd":
o.name = self.rename(o.name)
elif o.type == "AssignmentExpression":
o.left.name = self.rename(o.left.name)
elif o.type == "FunctionExpression" or o.type == "ArrowFunctionExpression":
for a in o.params:
a.name = self.rename(a.name)
return True
def before_statement(self, st):
if st.type == "VariableDeclaration":
for decl in st.declarations:
if decl.id.type == "Identifier":
decl.id.name = self.rename(decl.id.name)
elif st.type == "FunctionDeclaration":
for a in st.params:
a.name = self.rename(a.name)
st.id.name = self.rename(st.id.name)
elif st.type == "ClassDeclaration":
st.id.name = self.rename(st.id.name)
elif st.type == "MethodDefinition":
for a in st.value.params:
a.name = self.rename(a.name)
return True
class LoopContextSelector(CodeTransform):
def __init__(self):
super().__init__()
def set_args(self, loop_id, loop_iter):
self.loop_id = loop_id
self.loop_iter = loop_iter
def after_expression(self, expr, results):
csv = get_ann(expr, "contextual_static_value")
if csv is not None:
csv = csv.copy()
merged_value = None
bye=[]
add=[]
for context, contextual_value in csv.items():
if self.loop_id == context[-1][0]:
if self.loop_iter == context[-1][1]:
merged_value = State.value_join(merged_value, contextual_value)
if len(context) > 1:
add.append((context[0:-1], contextual_value))
bye.append(context)
for context, contextual_value in add:
csv[LoopContext(context)] = contextual_value
for b in bye:
del csv[b]
if csv == {}:
csv = None
set_ann(expr, "contextual_static_value", csv)
set_ann(expr, "static_value", merged_value)
return None
class IdentSubst(CodeTransform):
def __init__(self):
super().__init__()
def set_args(self, formal, effective):
self.formal = formal
self.effective = effective
def after_expression(self, expr, results):
if expr.type == "Identifier":
if expr.name in self.formal:
i = self.formal.index(expr.name)
node_assign(expr, self.effective[i])
return None
class FunctionInliner(CodeTransform):
def __init__(self, ast):
super().__init__(ast, "Function Inliner")
self.subst = IdentSubst()
self.count = 0
def set_count(self, count):
self.count = count
def get_count(self):
return self.count
def get_return_expression(self, body):
if body.type == "ReturnStatement":
return body.argument
if body.type == "BlockStatement" and len(body.body) > 0 and body.body[0].type == "ReturnStatement":
return body.body[0].argument
return None
def before_statement(self, o):
if o.type == "ExpressionStatement" and o.expression.type == "CallExpression" and get_ann(o.expression, "call_target.body"):
body = node_from_id(get_ann(o.expression, "call_target.body"))
if len(body.body) <= inline_max_statements:
body_copy = node_copy(body)
self.subst.formal = get_ann(o.expression, "call_target.params")
self.subst.effective = o.expression.arguments
self.subst.do_statement(body_copy)
node_assign(o, body_copy)
Stats.inlined_functions += 1
self.count += 1
return True
def before_expression(self, o):
if o.type == "CallExpression" and not get_ann(o, "call_target.body"):
#o.leadingComments = [{"type":"Block", "value":" Unresolved "}]
pass
if o.type == "CallExpression" and get_ann(o, "call_target.body"):
body = node_from_id(get_ann(o, "call_target.body"))
ret_expr = self.get_return_expression(body)
if not get_ann(o, "stats_counted_fct"):
set_ann(o, "stats_counted_fct", True)
Stats.inlined_functions_tot += 1
if ret_expr is not None:
ret_expr_copy = node_copy(ret_expr)
self.subst.formal = get_ann(o, "call_target.params")
self.subst.effective = o.arguments
self.subst.do_expr(ret_expr_copy)
node_assign(o, ret_expr_copy) #, ["static_value"])
Stats.inlined_functions += 1
#o.leadingComments = [{"type":"Block", "value":" Inlined "}]
self.count += 1
else:
pass
#o.leadingComments = [{"type":"Block", "value":" NotInlined "}]
return True
class DeadCodeRemover(CodeTransform):
def __init__(self, ast):
super().__init__(ast, "Dead Code Remover")
def before_statement(self, o):
if not get_ann(o, "stats_counted_dead"):
set_ann(o, "stats_counted_dead", True)
Stats.dead_code_tot += 1
if not o.live and o.type == "BlockStatement":
o.body = [esprima.nodes.EmptyStatement()]
o.body[0].leadingComments = [{"type":"Block", "value":" Dead Code "}]
Stats.dead_code += 1
return False
return True
class LoopUnroller(CodeTransform):
def __init__(self, ast, always_unroll = False):
super().__init__(ast, "Loop Unroller")
self.fixer = LoopContextSelector()
self.always_unroll = always_unroll
def after_statement(self, o, dummy):
if (o.type == "WhileStatement" or o.type == "ForStatement"):
Stats.loops_unrolled_tot += 1
if (o.type == "WhileStatement" or o.type == "ForStatement") and type(get_ann(o, "unrolled")) is list:
loop_id = id_from_node(o)
u = get_ann(o, "unrolled")
unrolled_size = 0
for i in u:
if i == START_ITER:
continue
st = node_from_id(i)
unrolled_size += st.range[1] - st.range[0]
if self.always_unroll or unrolled_size / (o.range[1] - o.range[0]) < max_unroll_ratio:
Stats.loops_unrolled += 1
o.type = "BlockStatement"
o.body = []
loop_iter = -1
for i in u:
if i == START_ITER:
loop_iter += 1
continue
st = node_copy(node_from_id(i))
if st.type in EXPRESSIONS:
st = wrap_in_statement(st)
self.fixer.set_args(loop_id, loop_iter)
self.fixer.do_statement(st)
o.body.append(st)
o.leadingComments = [{"type":"Block", "value":" Begin unrolled loop "}]
o.trailingComments = [{"type":"Block", "value":" End unrolled loop "}]
del_ann(o, "unrolled")
return True
class EvalReplacer(CodeTransform):
def __init__(self, ast):
super().__init__(ast, "Eval Handler")
def before_statement(self, st):
if st is None:
return False
if st.type == "ExpressionStatement":
o = st.expression
if get_ann(o, "eval") is not None:
if get_ann(o, "eval_value_unused"):
block = esprima.nodes.BlockStatement(get_ann(o, "eval").body)
block.live = True
st.__dict__ = block.__dict__
return True
def before_expression(self, o):
if o is None:
return False
if get_ann(o, "is_eval") is not None:
Stats.eval_processed_tot += 1
if get_ann(o, "eval") is not None:
if not get_ann(o, "eval_value_unused"):
block = esprima.nodes.BlockStatement(get_ann(o, "eval").body)
block.live = True
o.arguments = [block] #TODO not valid JS
set_ann(o, "eval", None)
Stats.eval_processed += 1
#print(block)
#print(o)
if get_ann(o, "fn_cons") is not None:
Stats.eval_processed += 1
o.__dict__ = get_ann(o, "fn_cons")[0].expression.__dict__
return True
class ConstantMemberSimplifier(CodeTransform):
def __init__(self, ast):
super().__init__(ast, "Constant Member Simplifier")
def before_expression(self, expr):
if expr.type == "AssignmentExpression":
if expr.left.type == "MemberExpression":
if expr.left.computed and isinstance(get_ann(expr.left.property, "static_value"), JSPrimitive) and type(get_ann(expr.left.property, "static_value").val) is str:
expr.left.computed = False
expr.left.property.name = get_ann(expr.left.property, "static_value").val
if get_ann(expr.left.property, "impure"):
expr_copy = esprima.nodes.AssignmentExpression(expr.operator, expr.left, expr.right)
sequence = expr.left.property.expressions[:-1]
sequence.append(expr_copy)
result = esprima.nodes.SequenceExpression(sequence)
expr.__dict__ = result.__dict__
elif expr.type == "MemberExpression":
if expr.computed and isinstance(get_ann(expr.property, "static_value"), JSPrimitive) and type(get_ann(expr.property, "static_value").val) is str:
expr.computed = False
expr.property.name = get_ann(expr.property, "static_value").val
if get_ann(expr.property, "impure"):
expr_copy = esprima.nodes.StaticMemberExpression(expr.object, expr.property)
sequence = expr.property.expressions[:-1]
sequence.append(expr_copy)
result = esprima.nodes.SequenceExpression(sequence)
expr.__dict__ = result.__dict__
return True
class VarDefInterpreter(LexicalScopedAbsInt):
ExprDesc = namedtuple("ExprDesc", "def_set has_side_effects")
Def = namedtuple("Def", "name def_id")
class Domain(object):
class State(set):
pass
def init_state(self) -> State:
"""
Creates a new initial state
:return: new initial state
"""
return self.State({})
def bottom_state(self) -> State:
"""
Creates a new bottom state
:return: new bottom state
"""
return self.State({None})
def is_bottom(self, state : State) -> bool:
"""
Tells the state is bottom
:param State state: the state to check
:rtype: bool
:return: True if the passed state is bottom
"""
return state == self.State({None})
def clone_state(self, state : State) -> State:
"""
Copy a state, returning the copy
:param State state: the source state
:rtype: State
:return: the copied state
"""
return state.copy()
def join_state(self, state_dest : State, state_source : State) -> None:
"""
Join two states, store result in state_dest
:param State state_dest: the dest state
:param State state_source: the source state
"""
if self.is_bottom(state_source):
return
elif self.is_bottom(state_dest):
self.assign_state(state_dest, state_source)
else:
state_dest.update(state_source)
def assign_state(self, state_dest : State, state_source : State) -> None:
"""
Assign source state to destination state
:param State state_dest: the dest state
:param State state_source: the source state
"""
state_dest.clear()
state_dest.update(state_source)
def __init__(self, ast : esprima.nodes.Node) -> None:
"""
Class constructor
:param esprima.nodes.Node ast: The AST to process.
"""
self.defs = set()
self.free_vars = set()
self.inner_free_vars = set()
self.state_stack = []
self.func_stack = []
self.current_func = None
super().__init__(ast, self.Domain(), "Variable Definition")
def handle_function_body(self, state: Domain.State, body: esprima.nodes.Node) -> None:
"""
Called whenever we enter a function
:param State state: The current state
:param esprima.nodes.Node body: The function body
"""
self.free_vars = set()
self.func_stack.append(self.current_func)
self.current_func = body
self.state_stack.append(self.domain.clone_state(state))
self.domain.assign_state(state, self.domain.init_state())
self.do_statement( state, body)
set_ann(body, "inner_free_vars", self.inner_free_vars.copy())
self.current_func = self.func_stack.pop()
self.inner_free_vars.difference_update(set([x.name for x in state]))
self.domain.assign_state(state, self.state_stack.pop())
self.free_vars.update(self.inner_free_vars)
self.inner_free_vars = self.free_vars
self.free_vars = set()
def link_def_set_to_use(self, def_set : Set[int], use : int) -> None:
"""
Create a link from a set of definitions to an use
:param Set[int] def_set: the set of definitions (set of ids)
:param int use: the use (by id)
"""
for used_assignment_id in def_set:
used_assignment = node_from_id(used_assignment_id)
get_ann(used_assignment, "used_by").add(use)
def get_def_set_by_name(self, state : Domain.State, name : str) -> Set[int]:
"""
Get a set of definitions matching a variable name
:param Domain.State state: the current state
:param str name: the variable name
:rtype: Set[int]
:return: the set of definitions (set of ids)
"""
return set([x.def_id for x in state if x.name == name])
def kill_def_set_by_name(self, state : Domain.State, name : str) -> None:
"""
Removes definitions from state matching some variable name