-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfaster_parse.peg
66 lines (58 loc) · 1.25 KB
/
faster_parse.peg
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
/*
Slow parse
expression:
(1+2*3)*(4+5*6)
output:
{
"expr": 238,
"matches": {
"integer": 15,
"primary": 18,
"multiplicative": 14,
"additive": 7,
"start": 1
},
"total": 55
}
*/
{
var matches = {
integer: 0,
primary: 0,
multiplicative: 0,
additive: 0,
start: 0
};
}
start
= expr:additive
{
matches['start']++;
return {
expr:expr,
matches:matches,
total: matches['integer'] +
matches['primary'] +
matches['multiplicative'] +
matches['additive'] +
matches['start']
};
}
additive
= m:multiplicative !("+")
{ matches['additive']++; return m; }
/ left:multiplicative "+" right:additive
{ matches['additive']++; return left + right; }
multiplicative
= p:primary !("*")
{ matches['multiplicative']++; return p; }
/ left:primary "*" right:multiplicative
{ matches['multiplicative']++; return left * right; }
primary
= i:integer
{ matches['primary']++; return i; }
/ "(" additive:additive ")"
{ matches['primary']++; return additive; }
integer "integer"
= digits:[0-9]+
{ matches['integer']++; return parseInt(digits.join(""), 10); }