-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparse.js
More file actions
57 lines (48 loc) · 1.17 KB
/
parse.js
File metadata and controls
57 lines (48 loc) · 1.17 KB
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
class Stack extends Array {
peek() {
return this[this.length - 1];
}
}
class Obj {
constructor(token, type) {
this.token = token;
this.type = type;
}
}
function parse(tokens) {
const root = new Obj('', 'root');
const ast = [root];
const stack = new Stack(ast);
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
switch (token) {
case ')_DOT':
case ')':
const popped = stack.pop();
stack.peek().push(popped);
break;
case '(_DOT':
case '(':
stack.push([]);
break;
default:
let obj = undefined;
// string
if (token[0] === '"' && token[token.length - 1] === '"')
obj = new Obj(token.slice(1,-1), 'string');
// number
else if (!isNaN(token))
obj = new Obj(Number(token), 'number');
// special
else if (['fun', 'let', 'if', 'when', 'global', 'f'].includes(token) || token.slice(0,2) == 'f.')
obj = new Obj(token, 'special');
// name
else
obj = new Obj(token, 'name');
stack.peek().push(obj);
}
}
return ast;
}
// exports
export const parser = parse;