-
Notifications
You must be signed in to change notification settings - Fork 89
/
linearize.js
73 lines (64 loc) · 2.07 KB
/
linearize.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
'use strict';
var Syntax = require('estraverse').Syntax;
var build = require('ast-types').builders;
var types = require('ast-types').namedTypes;
var match = require('../syntaxUtils').match;
var clause = require('../syntaxUtils').clause;
var fail = require('../syntaxUtils').fail;
function hasReturn(node) {
return match(node, [
clause(Syntax.BlockStatement, function(body) {
return body.some(hasReturn);
}),
clause(Syntax.IfStatement, function(test, consequent, alternate) {
return hasReturn(consequent) || hasReturn(alternate);
}),
clause(Syntax.Program, function(body) {
return body.some(hasReturn);
}),
clause(Syntax.ReturnStatement, function(argument) {
return true;
})], function() {
return false;
});
}
function linearizeSequence(ss, i, ks) {
if (i === ss.length) {
return ks;
}
else {
ks = linearizeSequence(ss, i + 1, ks);
return match(ss[i], [
clause(Syntax.BlockStatement, function(body) {
return linearizeSequence(body, 0, ks);
}),
clause(Syntax.IfStatement, function(test, consequent, alternate) {
if (alternate === null) {
alternate = build.emptyStatement();
}
if (hasReturn(consequent) || hasReturn(alternate)) {
return [build.ifStatement(
test,
build.blockStatement(linearizeSequence([consequent], 0, ks)),
build.blockStatement(linearizeSequence([alternate], 0, ks)))];
}
else {
return [build.ifStatement(test, consequent, alternate)].concat(ks);
}
}),
clause(Syntax.ReturnStatement, function(argument) {
return [build.expressionStatement(argument)];
})], function() {
if (types.EmptyStatement.check(ss[i]) ||
types.ExpressionStatement.check(ss[i]) ||
types.VariableDeclaration.check(ss[i])) {
return [ss[i]].concat(ks);
}
else return fail('linearize: unrecognized node', ss[i])();
});
}
}
function linearize(nodes) {
return linearizeSequence(nodes, 0, []);
}
exports.linearize = linearize;