-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.js
111 lines (89 loc) · 2.3 KB
/
parser.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
var Lexer = require('./lexer.js');
module.exports = function Parser() {
var lexer;
this.parse = function (input) {
lexer = new Lexer(input);
return parse_expression();
};
this.throw = function (message) {
if (lexer) {
lexer.throw(message);
}
};
function parse_bracket() {
var token = lexer.read();
if (token.value !== '(') {
lexer.throw('Unexpected token');
}
var expression = parse_expression();
token = lexer.peek();
if (token.value !== ')') {
lexer.throw('Expected token is )');
}
lexer.read();
return expression;
}
function parse_unary() {
var token = lexer.peek();
if (token.type === 'OPERATOR' && '+-'.indexOf(token.value) >= 0) {
lexer.read();
var expression = parse_low_level_expression();
return {
operation: token.value,
right: expression
}
}
lexer.throw('Unexpected token');
}
function parse_low_level_expression() {
if (lexer.eol()) {
return null;
}
var token = lexer.peek();
switch (token.type) {
case 'BRACKET':
return parse_bracket();
case 'NUMBER':
token = lexer.read();
return token;
default:
return parse_unary();
}
}
function parse_second_level_expression() {
var expression = parse_low_level_expression();
var other_expression;
var token = lexer.peek();
while (!lexer.eol() && '*/'.indexOf(token.value) >= 0) {
token = lexer.read();
other_expression = parse_low_level_expression();
expression = {
operation: token.value,
left: expression,
right: other_expression
};
token = lexer.peek();
}
return expression;
}
function parse_first_level_expression() {
var expression = parse_second_level_expression();
var other_expression;
var token = lexer.peek();
while (!lexer.eol() && '+-'.indexOf(token.value) >= 0) {
token = lexer.read();
other_expression = parse_second_level_expression();
expression = {
operation: token.value,
left: expression,
right: other_expression
};
token = lexer.peek();
}
return expression;
}
function parse_expression() {
var expression = parse_first_level_expression();
return expression;
}
};