-
Notifications
You must be signed in to change notification settings - Fork 0
/
comp.js
executable file
·57 lines (41 loc) · 1.34 KB
/
comp.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
//creating the tokens
const lexer = str => {
return str.split(" ").map(item => {
return item.trim()
})
}
console.log(lexer("add 5 with 5"))
//making the abstract tree
const parser = tokens => {
let current_token_index = 0;
const parseNumber = () => ({
value: parseInt(tokens[current_token_index++]),
type: "number",
})
const parseOperator = () => {
const node = {
value: tokens[current_token_index++],
type: "operator",
expression: []
}
while (tokens[current_token_index]) {
node.expression.push(parseExpression())
}
return node;
}
const parseExpression = () => /\d/.test(tokens[current_token_index]) ? parseNumber() : parseOperator();
return parseExpression();
}
console.log(parser(lexer("add 5 with 6")))
let ast = parser(lexer("add 5 with 6"));
//the transpiler
const transpile = ast => {
const mapOperator = {
add: '+', sub: '-', mul: '*', div: '/'
};
const transpileNode = ast => ast.type === 'number' ? transpileNumber(ast) : transpileOperator(ast);
const transpileNumber = ast => ast.value;
const transpileOperator = ast => `${ast.expression.map(transpileNode).join(' ' + mapOperator[ast.value] + ' ')}`;
return transpileOperator(ast);
};
console.log(transpile(ast))