-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.js
195 lines (166 loc) · 4.56 KB
/
compiler.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
const { join } = require('path');
const { readFileSync } = require('fs');
const TOKEN_TYPES = {
def: /\bdef\b/,
end: /\bend\b/,
identifier: /\b[a-zA-Z]+\b/,
integer: /\b[0-9]+\b/,
oparen: /\(/,
cparen: /\)/,
comma: /,/
};
class Tokenizer {
/** @param {string} code */
constructor(code) {
this.code = code;
/** @type string */
this.buffer = code;
}
tokenizeOneToken() {
for (let [type, re] of Object.entries(TOKEN_TYPES)) {
re = new RegExp(`^(${re.source})[\\s\\S]*$`);
const match = this.buffer.match(re);
if (match) {
const [, value] = match;
this.buffer = this.buffer.slice(value.length);
return new Token(type, value);
}
}
throw new Error(`Couldn't match token on\n${this.buffer}`);
}
tokenize() {
const tokens = [];
while (this.buffer.length) {
tokens.push(this.tokenizeOneToken());
this.buffer = this.buffer.trim();
}
return tokens;
}
}
class Token {
/**
* @param {string} type
* @param {string} value
*/
constructor(type, value) {
this.type = type;
this.value = value;
}
}
class Parser {
constructor(tokens) {
this.tokens = tokens;
}
parse() {
return this.parseDef();
}
parseDef() {
this.consume('def');
const name = this.consume('identifier').value;
const argNames = this.parseArgNames();
const body = this.parseExpr();
this.consume('end');
return DefNode({ name, argNames, body });
}
parseExpr() {
if (this.peek('integer')) {
return this.parseInteger();
}
if (this.peek('identifier') && this.peek('oparen', 1)) {
return this.parseCall();
}
return this.parseVarRef();
}
parseVarRef() {
return VarRefNode(this.consume('identifier').value);
}
parseCall() {
const name = this.consume('identifier').value;
const argExprs = this.parseArgExprs();
return CallNode({ name, argExprs });
}
parseArgExprs() {
const argExprs = [];
this.consume('oparen');
if (!this.peek('cparen')) {
argExprs.push(this.parseExpr());
while (this.peek('comma')) {
this.consume('comma');
argExprs.push(this.parseExpr());
}
}
this.consume('cparen');
return argExprs;
}
parseInteger() {
return IntegerNode(
Number(this.consume('integer').value)
);
}
parseArgNames() {
const argNames = [];
this.consume('oparen');
if (this.peek('identifier')) {
argNames.push(this.consume('identifier').value);
while (this.peek('comma')) {
this.consume('comma');
argNames.push(this.consume('identifier').value);
}
}
this.consume('cparen');
return argNames;
}
peek(expectedType, offset = 0) {
return this.tokens[offset].type === expectedType;
}
consume(expectedType) {
const token = this.tokens.shift();
if (token.type === expectedType) {
return token;
}
throw new Error(
`Expected token type ${expectedType}, but got ${token.type}`
);
}
}
const DefNode = ({ name, argNames, body }) => ({
type:'DefNode',
name,
argNames,
body
});
const IntegerNode = value => ({
type: 'IntegerNode',
value
});
const CallNode = ({ name, argExprs }) => ({
type: 'CallNode',
name,
argExprs
});
const VarRefNode = value => ({
type: 'VarRefNode',
value
});
function generate(node) {
switch(node.type) {
case 'DefNode':
return `function ${node.name}(${node.argNames.join(', ')}) { return ${generate(node.body)} }`;
case 'CallNode':
return `${node.name}(${node.argExprs.map(generate).join(', ')})`;
case 'VarRefNode':
return node.value;
case 'IntegerNode':
return node.value;
default:
throw new Error(`Unexpected node type: ${node.constructor.name}`)
}
}
const tokens = new Tokenizer(
readFileSync(join(__dirname, 'test.src'), 'utf8')
).tokenize();
const tree = new Parser(tokens).parse();
const generated = generate(tree);
const RUNTIME = 'function add(x, y) { return x + y };';
const TEST = `console.log(f(1, 2));`;
console.log([RUNTIME, generated, TEST].join('\n'));