-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc_grammar.peg
38 lines (37 loc) · 1.38 KB
/
calc_grammar.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
start-symbol: start
code: {{
static Value add(const Value & a, const Value & b){
return Value((void*)((int) a.getValue() + (int) b.getValue()));
}
static Value sub(const Value & a, const Value & b){
return Value((void*)((int) a.getValue() - (int) b.getValue()));
}
static Value multiply(const Value & a, const Value & b){
return Value((void*)((int) a.getValue() * (int) b.getValue()));
}
static Value divide(const Value & a, const Value & b){
return Value((void*)((int) a.getValue() / (int) b.getValue()));
}
}}
rules:
start = expression sw <eof> {{ value = $1; }}
expression = expression2 expression1_rest($1)
expression1_rest(a) = "+" expression2 e:{{value = add(a,$2);}} expression1_rest(e) | "-" expression2 e:{{value =sub(a,$2);}} expression1_rest(e)| <void> {{ value = a; }}
expression2 = expression3 expression2_rest($1)
expression2_rest(a) = "*" expression3 e:{{value = multiply(a,$2);}} expression2_rest(e)
| "/" expression3 e:{{value = divide(a,$2);}} expression2_rest(e)
| <void> {{ value = a; }}
expression3 = number
| "(" expression ")" {{ value = $2; }}
inline number = digit+ {{
int total = 0;
for (Value::iterator it = $1.getValues().begin(); it !=
$1.getValues().end(); it++){
const Value & v = *it;
char letter = (char) (int) v.getValue();
total = (total * 10) + letter - '0';
}
value = (void*) total;
}}
inline sw = "\\n"*
inline digit = [0123456789]