forked from pissang/dfatool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfatool.js
executable file
·2838 lines (2523 loc) · 85.6 KB
/
dfatool.js
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
//====================================
// dfatool.js
// JavaScript Data Flow Analyze Tool
//
// author Yi Shen([email protected])
// TODO: repetitive statement
// object type value binding with snapshot(update synchronously)
//====================================
(function(factory) {
// CommonJS or Node
if (typeof require == "function" && typeof exports == "object" && typeof module == "object") {
factory(require("escodegen"), exports);
}
// AMD
else if (typeof define !== "undefined" && define["amd"]) {
// harded-coded dependency on escodegen
define(["escodegen", "exports"], factory);
// No module loader
} else {
factory(escodegen, window["dfatool"] = {});
}
})(function(codegen, exports) {
// in the Node
if (typeof require != "undefined" && typeof exports == "object" && typeof module=="object") {
var fs = require("fs");
}
var TEMPLATE_BLOCK = function(body) {
return {
"type" : "BlockStatement",
"body" : body || []
}
}
var TEMPLATE_IDENTIFIER = function(name) {
return {
"type": "Identifier",
"name": name || "__anoymous__"
}
}
var TEMPLATE_FUNCTION_DECLARATION = function(id, params, body) {
return {
"type": "FunctionDeclaration",
"id": TEMPLATE_IDENTIFIER(id),
"params" : params || [],
"defaults" : [],
"body" : body || TEMPLATE_BLOCK(),
"rest" : null,
"generator" : false,
"expression" : false
}
}
var TEMPLATE_ASSIGNMENT_EXPRESSION = function(left, right, operator) {
return {
"type" : "AssignmentExpression",
"left" : left || TEMPLATE_IDENTIFIER(),
"right" : right || TEMPLATE_IDENTIFIER(),
"operator" : operator || "="
}
}
var TEMPLATE_EXPRESSION_STATEMENT = function(expression) {
return {
"type" : "ExpressionStatement",
"expression" : expression
}
}
var TEMPLATE_VARIABLE_DECLARATOR = function(id) {
return {
"type" : "VariableDeclarator",
"id" : TEMPLATE_IDENTIFIER(id),
"init" : null
}
}
var TEMPLATE_OBJECT_EXPRESSION = function(properties) {
return {
"type" : "ObjectExpression",
"properties" : properties || []
}
}
var TEMPLATE_LITERAL_EXPRESSION = function(val) {
return {
"type" : "Literal",
"value" : val,
"raw" : val.toString()
}
}
var TEMPLATE_ARRAY_EXPRESSION = function() {
return {
"type" : "ArrayExpression",
"elements" : []
}
}
var TEMPLATE_BINARY_EXPRESSION = function(operator, left, right) {
return {
"type" : "BinaryExpression",
"operator" : operator,
"left" : left,
"right" : right
}
}
var TEMPLATE_UNARY_EXPRESSION = function(operator, argument) {
return {
"type" : "UnaryExpression",
"operator" : operator,
"argument" : argument
}
}
var TEMPLATE_IF_STATEMENT = function(test, consequent, alternate) {
return {
"type" : "IfStatement",
"test" : test,
"consequent" : consequent,
"alternate" : alternate
}
}
var TEMPLATE_MEMBER_EXPRESSION = function(object, property, computed) {
computed = isUndefined(computed) ? true : computed;
return {
"type" : "MemberExpression",
"object" : object,
"property" : property,
"computed" : computed
}
}
//=====================================
// Abstract syntax tree traverse (none-recursive)
// it is easily to have stack overflow if traverse the ast recursively
// -before is for pre-order traverse
// -after is for post-order traverse
// -isReplaceReference {Boolean|Function}
//=====================================
function walk(root, before, after, isReplaceReference) {
if (! root) {
return;
}
var _stack = [];
if (Array.isArray(root)) {
root.forEach(function(child) {
walk(child, before, after, isReplaceReference);
})
return ;
}
var node = root;
// Save the node which has been replaced by its reference
// in case of Circular Reference
var _expanded = [];
if (! isFunction(isReplaceReference)) {
var _isReplaceReference = isReplaceReference;
isReplaceReference = function() {
return _isReplaceReference;
}
}
while (node) {
if (! node.__visited__) {
if (isReplaceReference(node)) {
node = replaceReference(node);
// return false when has a circular reference
if (! node) {
next();
continue;
}
}
// call before visiting any of its children
// return false to skip the children
// return an ast if you wan't to replace it
var res = before(node);
// skip its chilren when return false
if (! res) {
res = after && after(node);
if (res && res.type) {
replaceNode(res);
}
next();
continue;
} else if (res.type) { //replace the node if res is an new ast node
replaceNode(res);
//change the walking node
node = res;
}
var tmp = inferenceChildren(node);
var children = tmp.children;
var map = tmp.map;
// push parent node to stack
if (children && children.length) {
_stack.push(node);
node.__childidx__ = -1;
node.__children__ = children;
node.__map__ = map;
node.__visited__ = true;
next();
} else { //leaf
var res = after && after(node);
if (res && res.type) {
replaceNode(res);
}
next();
}
} else {
// clean the ast node;
delete node.__visited__;
delete node.__childidx__;
delete node.__children__;
delete node.__map__;
if (after) {
// call after all its children visited
res = after(node);
if (res && res.type) {
replaceNode(res);
}
}
delete node.origin;
next();
continue;
}
}
function replaceReference(_node) {
if (_node.reference) {
// solve circular reference
if (_expanded.indexOf(_node)>=0) {
log("Circular Reference:", _node);
return false;
}
var ref = getReference(_node);
if (_stack.indexOf(ref.ast)>=0) {
log("Circular Reference AST:", _node);
return false;
}
_expanded.push(_node);
var origin = _node;
// replace the reference ast node
if (ref.type == "array") {
_node = rebuildArray(ref, origin);
} else if (ref.type == "object") {
_node = rebuildObject(ref, origin);
} else {
_node = ref.ast;
}
_node.origin = origin;
}
return _node;
}
function rebuildArray(ref, origin) {
var _node = TEMPLATE_ARRAY_EXPRESSION();
ref.elements.forEach(function(value) {
if (value.type == "array") {
var elem = rebuildArray(value, origin);
} else if (value.type == "object") {
var elem = rebuildObject(value, origin);
} else {
var elem = value.ast;
}
_node.elements.push(elem);
})
_node.loc = deepCloneAst(origin.loc);
_node.scope = ref.scopeSvForRebuild;
return _node;
}
function rebuildObject(ref, origin) {
var _node = TEMPLATE_OBJECT_EXPRESSION();
for (var key in ref.props) {
var prop = ref.props[key];
if (prop) {
if (prop.type == "array") {
var propAst = rebuildArray(prop, origin);
} else if (prop.type == "object") {
var propAst = rebuildObject(prop, origin);
} else {
var propAst = prop.ast;
}
var item = {
"type" : "Property",
"key" : TEMPLATE_LITERAL_EXPRESSION(ref.withoutPrefix(key)),
"value" : propAst,
"kind" : "init", //other kinds?
"loc" : null
}
_node["properties"].push(item);
}
}
_node.loc = deepCloneAst(origin.loc);
_node.scope = ref.scopeSvForRebuild;
return _node;
}
function replaceNode(_node) {
//replace
if (_stack.length == 0) {
root = _node;
return
}
var parent = _stack[_stack.length-1];
var idx = parent.__childidx__;
var value = parent.__map__[idx];
var tmp = value.split("__");
var propName = tmp[0];
var index = tmp[1];
if (index) {
parent[propName][index] = _node;
} else {
parent[propName] = _node;
}
}
function next() {
var parent = _stack[_stack.length-1];
if (parent) {
var sibling = parent.__children__[++parent.__childidx__];
if (! sibling) {
// back to parent
node = _stack.pop();
} else {
if (sibling.__visited__) {
log("Circular AST:", sibling);
next();
return;
}
node = sibling;
}
} else {
node = null;
}
}
function inferenceChildren(node) {
var children = [];
var map = []; //map is for reconstruct the ast
//the impletation is ugly
for (var propName in node) {
var prop = node[propName];
//flatten
if (prop &&
prop.type &&
(propName!="reference") &&
(propName!="origin")) {
children.push(prop);
map.push(propName);
} else if (Array.isArray(prop) &&
propName != "__children__" &&
propName != "__map__") {
for (var i = 0; i < prop.length; i++) {
children.push(prop[i]);
map.push(propName+"__"+i);
}
}
}
return {
children : children,
map : map
}
}
return root;
}
function deepCloneAst(ast) {
if (! ast) {
return ast;
}
if (ast.constructor == Array) {
var ret = [];
for (var i = 0; i < ast.length; i++) {
ret[i] = deepCloneAst(ast[i]);
}
return ret;
}
else if (ast.constructor == Object) {
var ret = {};
for (var propName in ast) {
if (propName == "__map__" ||
propName == "origin" ||
propName == "__children__" ||
propName == "__childidx__") {
continue;
}
ret[propName] = deepCloneAst(ast[propName]);
}
if (ast.scope) {
ret.scope = ast.scope;
}
if (ast.reference) {
ret.reference = ast.reference;
}
return ret;
}
else {
return ast;
}
}
//==============================================
// Scope Object of Function
//==============================================
var Scope = function(parent) {
this.id = Scope.generateID();
if (parent) {
this.parent = parent;
parent.children.push(this);
}
this.children = [];
// variables and functions defined in this scope;
this._defines = {};
// arguments and this object;
this._closure = {};
// varialbles modified in this scope and define in parent scope;
this._modified = {};
// program location where the function is implement
this._baseLoc = 0;
// pending statement
// when variable in the lhs of assignstatement can't find in the scope
// it will be added to pendinglist
this._pending = [];
// _caller scope;
this._caller = null;
// location in caller scope when called
this._callloc = 9999999;
// statement using anoymous function for solving
// like (function(g) {
// g['method'] = someMethod()
// })(window)
this._anoymousStatements = [];
// UseStatement with unkown variable, maybe some object in a library or native function,
// but we cant find it in the scope chain, in this case, we will put the statement
// in this pendingStatments;
this._pendingStatements = [];
this._return = new ReturnedVariable("return", this);
}
Scope.generateID = createIDGenerator();
// add a prefix to avoid override to native method
Scope.prototype._prefix = "v_";
Scope.prototype.withPrefix = withPrefix;
Scope.prototype.withoutPrefix = withoutPrefix;
// define a variable
Scope.prototype.define = function(identifier) {
if (isUndefined(this.getDefine(identifier))) {
this._defines[this.withPrefix(identifier)] = new Variable(identifier, this);
}
return this.getDefine(identifier);
}
Scope.prototype.setDefine = function(identifier, variable) {
this._defines[this.withPrefix(identifier)] = variable;
return variable;
}
Scope.prototype.getDefine = function(identifier) {
return this._defines[this.withPrefix(identifier)];
}
Scope.prototype.setClosure = function(identifier, variable) {
this._closure[this.withPrefix(identifier)] = variable;
return variable;
}
Scope.prototype.getClosure = function(identifier) {
return this._closure[this.withPrefix(identifier)];
}
Scope.prototype.modify = function(identifier, modified) {
this._modified[this.withPrefix(identifier)] = modified;
return modified
}
Scope.prototype.getModified = function(identifier) {
return this._modified[this.withPrefix(identifier)];
}
Scope.prototype.getReturn = function() {
return this._return;
}
//-return {AssignStatement}
Scope.prototype.assign = function(lhs, rhs, loc) {
var res = this.inferenceVariable(lhs);
if (res && res.variable) {
var variable = res.variable;
var identifier = variable.name;
if (variable.scope == this) { //in scope
if (! (res.accessPath && res.accessPath.length)) {
return variable.assign(rhs, loc);
} else {
return variable.assignProperty(res.accessPath, rhs, loc);
}
} else if (this.inScope(variable.scope)) {
// keep the scope clean
// soft update of the value in the parent scope
// it will convert to an strong update when the function is called
var modified = this.getModified(identifier);
if (! modified) {
modified = this.modify(identifier, new Modified(identifier, variable.scope, this));
}
if (! res.accessPath) {
return modified.assign(rhs, loc);
} else {
return modified.assignProperty(res.accessPath, rhs, loc);
}
} else {
// may be have an invalid access to the variable in the other scope?
// or anoymous function or object
}
}
// bad case
else if (lhs.type == "Identifier") {
var globalScope = this.getGlobalScope();
var variable = globalScope.define(lhs.name);
if (globalScope == this) {
variable.assign(rhs, loc);
} else {
log("Warning, maybe forget define ", lhs)
}
}
else {
// here loc is correspond to an id
if (! this._pending.filter(function(item) {
return item.loc == loc;
}).length) {
this._pending.push({
lhs : lhs,
rhs : rhs,
loc : loc
})
}
return null;
}
}
// for call expression module.foo(), accessExpr is module.foo, useExpr is whole module.foo()
Scope.prototype.use = function(accessExpr, useExpr, loc) {
var res = this.inferenceVariable(accessExpr);
if (! (res && res.variable)) {
// put the use statement of a unkown variable in the _pendingStatements
var anoymousStatement = new UseStatement(useExpr, this);
this._pendingStatements.push(anoymousStatement);
}
else {
var variable = res.variable;
var identifier = variable.name;
if (variable.name == "__anoymous__") {
var anoymousStatement = new UseStatement(useExpr, this);
this._anoymousStatements.push(anoymousStatement);
} else if (variable.scope == this) { // in scope
return variable.use(useExpr, loc);
} else if (this.inScope(variable.scope)) {
var modified = this.getModified(identifier);
if (! modified) {
var modified = this.modify(identifier, new Modified(identifier, variable.scope, this));
}
return modified.use(useExpr, loc);
} else {
// todo:what about this?
}
}
}
Scope.prototype.inScope = function(scope) {
var parent = this.parent;
while (parent && parent != scope) {
parent = parent.parent;
}
return parent;
}
// expression can be ast of object.key, object["key1"], getObject().key....
// or the identifier string of variable
// -return [accessPath, variable]
Scope.prototype.inferenceVariable = function(expression) {
// use the scope where the ast is created to simulate closure when the ast is transferrd by function call
var closureScope = expression.scope || this;
if (expression.type == "ThisExpression") {
if (expression.reference) {
return {
ret : null,
variable : getReference(expression).targetVariable
}
}
var identifier = "this";
var definedScope = closureScope.findDefinedScope(identifier);
var ret = {
accessPath : null,
variable : definedScope.getDefine(identifier) || definedScope.getClosure(identifier)
}
return ret;
}
else if (expression.type == "Identifier") {
// use the reference directly if the expression has already been expanded
if (expression.reference) {
return {
ret : null,
variable : getReference(expression).targetVariable
}
}
var identifier = expression.name;
var definedScope = closureScope.findDefinedScope(identifier);
var ret = {
accessPath : null,
variable : definedScope.getDefine(identifier) || definedScope.getClosure(identifier)
}
return ret;
} else if (expression.type == "MemberExpression") {
var root = expression.object;
var accessPath = [expression.property];
while (root.type == "MemberExpression") {
accessPath.unshift(root.property);
root = root.object;
}
// root must be an variable point to an object target
// or an anoymous object
if (root.type == "Identifier") {
var ret = closureScope.inferenceVariable(root);
if (ret) {
ret.accessPath = accessPath;
return ret;
}
}
else if (root.type == "ThisExpression") {
return {
variable : closureScope.getClosure("this"),
accessPath : accessPath
}
}
else if (root.type == "CallExpression") {
var func = this.inferenceValue(root["callee"], this.offsetLoc(root["callee"].loc.start));
if (func && func.type == "function") {
var res = func.execute(root, this);
if (! res) {
return;
}
if (! res.inference()) {
log("Function Return Undefined Value", root);
} else {
var ret = {
variable : res,
accessPath : accessPath
}
return ret;
}
}
}
else if (root.type == "ObjectExpression" ||
root.type == "ArrayExpression") {
return {
variable : Variable.createAnoymous(root),
accessPath : accessPath
}
} else if (root) {
// log("Unkown Expr Type: "+root.type, origin);
} else {
log("Undefined Root", expression);
}
}
//here object expression, array expression and function expression is mainly from the derivation result from other expression
//in use statement
else if (expression.type == "FunctionExpression" ||
expression.type == "ObjectExpression" ||
expression.type == "ArrayExpression") {
return {
variable : Variable.createAnoymous(expression),
accessPath : accessPath
}
}
}
// -loc will be used when the expression is created in this scope
// -return {AssignStatement}
Scope.prototype.inferenceValue = function(expression, loc) {
var closureScope = expression.scope || this; //defined scope
//this.scope is the used scope
var res = closureScope.inferenceVariable(expression);
// pending while res will be undefined
if (! (res && res.variable)) {
log("InvalidReference", expression);
return;
}
var variable = res.variable;
// anoymous variable return the value instantly
if (variable.name == "__anoymous__") {
var value = variable.inference(res.accessPath);
}
else if (variable.scope == this) {
var value = variable.inference(loc, res.accessPath);
}
else {
// is called in the ancestor's scope
// and the variable is defined in one scope of the caller chain
// in this situation we will need to guess the value based on the call statement location;
// walk through the call chain and find the scope where the variable is defined
var caller = this._caller, //todo: this._caller or scope._caller ?
callerLoc = this._callloc
while (caller && caller != res.scope) {
if (! this.inScope(caller)) {
caller = null;
break;
}
callerLoc = caller._callloc;
caller = caller._caller;
}
if (caller) {
var value = variable.inference(callerLoc, res.accessPath);
} else {
// get the latest value
var value = variable.inference(res.accessPath);
}
}
if (! value) {
log("Warning:"+gencode(expression)+" is undefined");
}
return value;
}
// find the scope where the given variable is defined;
Scope.prototype.findDefinedScope = function(identifier) {
var scope = this;
while (scope) {
if (scope.getDefine(identifier) || scope.getClosure(identifier)) {
return scope;
}
else if (! scope.parent) {
// suppose the value is in the global scope
return scope;
} else {
scope = scope.parent;
}
}
}
Scope.prototype.clear = function() {
for (var name in this._defines) {
this._defines[name].clear();
}
for (var name in this._modified) {
this._modified[name].clear();
}
this._return.clear();
this._closure = [];
this._caller = null;
this._callloc = 0;
walk(this.ast, function(node) {
delete node.reference;
return true;
})
}
Scope.prototype.initialize = function() {
var scope = this;
function initializeInBranch(ast, currentBranch) {
walk(ast, function(node) {
var scope = node.scope;
switch(node.type) {
case "FunctionDeclaration":
// function declaration can be defined in anywhere so we set the loc 0;
var dfNode = scope.assign(node["id"], node, 0);
if (currentBranch && dfNode) {
dfNode.conditionalStatement = currentBranch;
}
return false;
case "VariableDeclarator":
if (node["init"]) {
// in the case "var a = b = c;"
if (node["init"].type == "AssignmentExpression") {
processChainedAssignment(node["init"], currentBranch, scope.offsetLoc(node.loc.start));
var dfNode = scope.assign(node["id"], node["init"]["left"], scope.offsetLoc(node.loc.end));
} else {
var dfNode = scope.assign(node["id"], node["init"], scope.offsetLoc(node.loc.end));
}
if (currentBranch && dfNode) {
dfNode.conditionalStatement = currentBranch;
}
}
return false;
case "AssignmentExpression":
processChainedAssignment(node, currentBranch, scope.offsetLoc(node.loc.start));
return false;
case "ExpressionStatement":
// if the statement is a single call expression
if (node["expression"]["type"] == "CallExpression") {
var expr = node["expression"];
var dfNode = scope.use(expr["callee"], expr, scope.offsetLoc(node.loc.end));
if (currentBranch && dfNode) {
dfNode.conditionalStatement = currentBranch;
}
return false;
}
break;
case "ReturnStatement":
if (! node["argument"]) { //statement is "return;"
return;
}
var dfNode = scope._return.assign(node["argument"], scope.offsetLoc(node.loc.end));
if (currentBranch && dfNode) {
dfNode.conditionalStatement = currentBranch;
}
return false;
case "IfStatement":
var consequent = new ConditionalStatement(currentBranch);
consequent.start = scope.offsetLoc(node["consequent"].loc.start);
consequent.end = scope.offsetLoc(node["consequent"].loc.end);
consequent.and(node["test"]);
initializeInBranch(node["consequent"], consequent);
if (node["alternate"]) {
var alternate = new ConditionalStatement(currentBranch);
alternate.consequent = consequent;
consequent.alternate = alternate;
alternate.start = scope.offsetLoc(node["alternate"].loc.start);
alternate.end = scope.offsetLoc(node["alternate"].loc.end);
initializeInBranch(node["alternate"], alternate);
}
return false;
case "SwitchStatement":
var discriminant = node["discriminant"];
// todo consider the situation of case without break statement;
node["cases"].forEach(function(_case) {
if (! _case.test) { // todo, when the case have no test expression
return;
}
test = TEMPLATE_BINARY_EXPRESSION("==", discriminant, _case.test);
test.loc = _case.test.loc;
test.scope = scope;
var consequent = new ConditionalStatement(currentBranch);
consequent.and(test);
consequent.start = scope.offsetLoc(_case.loc.start);
consequent.end = scope.offsetLoc(_case.loc.end);
initializeInBranch(_case["consequent"], consequent);
})
return false;
}
return true;
})
}
function processChainedAssignment(node, currentBranch, baseLoc) {
// support the chained assign statement like "module.q = module.Q = module.dom.q";
// will be convert to module.Q = module.dom.q; module.q = module.Q
var nodes = [];
var operators = [];
var current = node;
while (current.type == "AssignmentExpression") {
nodes.unshift(current.left);
operators.unshift(current.operator);
current = current.right;
}
nodes.unshift(current);
// location of each assign item need to be reverted;
// like a = b = c, statment b=c need to be put in the left most, and then a = b;
// TODO: here simple revert still has some problem, for example fooooooo = a = b;
// the location of a is behind the statement of a = b, so value of fooooooo is still
// equal to previous value of a;
var loc = baseLoc;
for (var i = 0; i < nodes.length-1; i++) {
var rightNode = nodes[i],
leftNode = nodes[i+1],
operator = operators[i];
loc += scope.offsetLoc(rightNode.loc.end) - scope.offsetLoc(leftNode.loc.start);
var dfNode = scope.assign(leftNode, rightNode, loc);
if (dfNode) {
dfNode.operator = operator;
if (currentBranch) {
dfNode.conditionalStatement = currentBranch;
}
}
}
}
initializeInBranch(this.ast, null);
}
// Spread the expression of each value to a fix point
// -worklist is an array of derivable items(which has a derivation method)
Scope.prototype.derivation = function(worklist /*optional*/, getWorkListFilter/*optional*/, order /*optional*/) {
if (isFunction(worklist)) {
order = getWorkListFilter;
getWorkListFilter = worklist;
worklist = this.getWorkList();
} else if (isNumber(worklist)) {
order = worklist;
getWorkListFilter = exports.getDefaultWorklistFilter;
worklist = this.getWorkList();
}
if (! worklist) {
worklist = this.getWorkList();
}
if (! getWorkListFilter) {
getWorkListFilter = exports.getDefaultWorklistFilter;
}
var order = order || 1; // default 1-order derivation
worklist.sort(function(a,b) {
return a.loc - b.loc;
})
var worklistFilter = getWorkListFilter(this, worklist);
// wrap the worklistfilter
var count = 0;
while (worklist.length && count < order) {
var passResult = [];
worklist.forEach(function(derivableItem) {
if (worklistFilter && worklistFilter(derivableItem)) {
passResult.push(derivableItem);
}
}, this)
this.solvePending();
worklist = passResult;
count++;
}
}
Scope.prototype.solvePending = function() {
this._pending.forEach(function(item) {
if (this.assign(item.lhs, item.rhs, item.loc)) {
// remove the item;
this._pending = this._pending.filter(function(a) {
return a != item;
})
}
}, this);
}
Scope.prototype.getWorkList = function() {
var worklist = [];
for (var name in this._defines) {
addVariable(this._defines[name]);
}
for (var name in this._closure) {
addVariable(this._closure[name] );
}
for (var name in this._modified) {
addVariable(this._modified[name]);
}
addVariable(this._return);
function addVariable(variable) {