-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastest_parse.peg
74 lines (66 loc) · 1.37 KB
/
fastest_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
67
68
69
70
71
72
73
74
/*
Slow parse
expression:
(1+2*3)*(4+5*6)
output:
{
"expr": 237,
"matches": {
"integer": 7,
"primary": 8,
"multiplicative": 8,
"additive": 5,
"start": 1
},
"total": 28
}
*/
{
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
= head:multiplicative tail:("+" right:additive)*
{ matches['additive']++;
var result = head;
for (var i = 0, ilen = tail.length; i < ilen; ++i) {
result += tail[i][1];
}
return result;
}
multiplicative
= head:primary tail:("*" right:multiplicative)*
{ matches['multiplicative']++;
var result = head;
for (var i = 0, ilen = tail.length; i < ilen; ++i) {
result *= tail[i][1];
}
return result;
}
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); }