-
Notifications
You must be signed in to change notification settings - Fork 2
/
astraverse.js
78 lines (63 loc) · 2.36 KB
/
astraverse.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
'use strict';
var patchSource = require('./source_replacer').patchSource;
function isLiteral(element) {
return Object(element) !== element;
}
function performOnParallellTraverse(action) {
var parallelTraverse = function parallellTraverse(actual, expected, actualLastFunctionScope, expectedLastFunctionScope) {
var attr;
function shouldBeChecked(attr) {
return attr !== 'type' && attr !== 'loc' && attr !== 'raw' && actual.hasOwnProperty(attr) && expected.hasOwnProperty(attr);
}
if (isLiteral(actual)) {
if (actual !== expected) {
action(actualLastFunctionScope, expectedLastFunctionScope);
}
return;
}
if (actual.type === "BlockStatement") {
actualLastFunctionScope = actual;
expectedLastFunctionScope = expected;
}
if (Array.isArray(actual)) {
if (actual.length !== expected.length) {
action(actualLastFunctionScope, expectedLastFunctionScope);
} else {
actual.forEach(function (_, i) {
parallellTraverse(actual[i], expected[i], actualLastFunctionScope, expectedLastFunctionScope);
});
return;
}
}
for (attr in actual) {
if (shouldBeChecked(attr)) {
if (expected && attr in expected) {
parallellTraverse(actual[attr], expected[attr], actualLastFunctionScope, expectedLastFunctionScope);
}
}
}
};
return parallelTraverse;
}
function equalizeTrees(patchedTree, sourceCode, createAst) {
var treesAreDifferent = true,
originalTree = createAst(sourceCode);
function replaceOriginalSourceWithPatch(a, b) {
var sourceToBePatched = b.loc.source,
sourceCode = patchSource(a.loc, b.loc, sourceToBePatched),
patchedAST = createAst(sourceCode);
throw patchedAST;
}
while (treesAreDifferent) {
try {
performOnParallellTraverse(replaceOriginalSourceWithPatch)(patchedTree, originalTree, patchedTree, originalTree);
treesAreDifferent = false;
} catch (replacedTree) {
originalTree = replacedTree;
}
}
return originalTree.loc.source;
}
module.exports = {
equalizeTrees: equalizeTrees
};