-
Notifications
You must be signed in to change notification settings - Fork 5
/
unreachableBranchTransformer.js
97 lines (81 loc) · 2.19 KB
/
unreachableBranchTransformer.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
var Evaluator = require('esmangle-evaluator');
var recast = require('recast');
var types = recast.types;
var b = types.builders;
var VISITOR_METHODS = {
visitLogicalExpression: visitLogicalExp,
visitIfStatement: visitCondition,
visitConditionalExpression: visitCondition
};
module.exports = function(branch) {
recast.visit(branch, VISITOR_METHODS);
return branch;
};
/**
* "||" and "&&"
*/
function visitLogicalExp(path) {
var leftEval = Evaluator.booleanCondition(path.node.left);
if (typeof leftEval !== 'boolean') {
// console.log('___ %s ___', path.node.operator);
this.traverse(path);
return;
}
var leftSideEffect = Evaluator.hasSideEffect(path.node.left);
if (leftSideEffect) {
this.traverse(path);
return;
}
if (leftEval === true && path.node.operator === '||') {
// console.log('true || ___');
path.replace(path.node.left);
recast.visit(path, VISITOR_METHODS);
return false;
}
if (leftEval === true && path.node.operator === '&&') {
// console.log('true && ___');
path.replace(path.node.right);
recast.visit(path, VISITOR_METHODS);
return false;
}
if (leftEval === false && path.node.operator === '&&') {
// console.log('false && ___');
path.replace(path.node.left);
recast.visit(path, VISITOR_METHODS);
return false;
}
if (leftEval === false && path.node.operator === '||') {
// console.log('false || ___');
path.replace(path.node.right);
recast.visit(path, VISITOR_METHODS);
return false;
}
}
/**
* "if" and ternary "?"
*/
function visitCondition(path) {
var testEval = Evaluator.booleanCondition(path.node.test);
if (typeof testEval !== 'boolean') {
// console.log('if/? ___');
this.traverse(path);
return;
}
var testSideEffect = Evaluator.hasSideEffect(path.node.test);
if (testSideEffect) {
this.traverse(path);
return;
}
if (testEval === true) {
// console.log('if/? (true)');
path.replace(path.value.consequent);
recast.visit(path, VISITOR_METHODS);
return false;
}
if (testEval === false) {
// console.log('if/? (false)');
path.replace(path.value.alternate);
recast.visit(path, VISITOR_METHODS);
return false;
}
}