forked from petehunt/c4.5-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codegen.js
58 lines (52 loc) · 1.28 KB
/
codegen.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
'use strict';
var recast = require("recast");
var types = recast.types;
var n = types.namedTypes;
var b = types.builders;
var FEATURES_NAME = 'features';
function getFeatureAst(featureName) {
return b.memberExpression(
b.identifier(FEATURES_NAME),
b.literal(featureName),
true
);
}
function _codegen(node) {
if (node.type === 'result') {
return b.returnStatement(b.literal(node.value));
} else if (node.type === 'feature_number') {
var test = b.binaryExpression(
'>',
getFeatureAst(node.name),
b.literal(node.cut)
);
return b.ifStatement(
test,
_codegen(node.values[0].child),
_codegen(node.values[1].child)
);
} else {
// category
return b.switchStatement(
getFeatureAst(node.name),
node.values.map(function(node) {
var body = [_codegen(node.child)];
if (node.child.type !== 'result') {
body.push(b.breakStatement());
}
return b.switchCase(
b.literal(node.name),
body
);
}) // TODO: concat a default case for error handling?
);
}
}
function codegen(node) {
return b.functionExpression(
b.identifier('classify'),
[b.identifier('features')],
b.blockStatement([_codegen(node)])
);
}
module.exports = codegen;