-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcalc.peg
101 lines (83 loc) · 1.28 KB
/
calc.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
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
%{
//ignore_for_file: prefer_conditional_assignment, prefer_final_locals
import 'package:source_span/source_span.dart';
void main() {
const source = ' 1 + 2 * 3 + x ';
final result = calc(source, {'x': 5});
print(result);
}
int calc(String source, Map<String, int> vars) {
final parser = CalcParser(vars);
final state = State(source);
final result = parser.parseStart(state);
if (result == null) {
final file = SourceFile.fromString(source);
throw FormatException(state
.getErrors()
.map((e) => file.span(e.start, e.end).message(e.message))
.join('\n'));
}
return result.$1;
}
}%
%%
Map<String, int> vars = {};
CalcParser(this.vars);
%%
`int`
Start =>
S
$ = Expr
EOF
`int`
Expr('expression') =>
Sum
`int`
Sum =>
$ = Product
@while (*) {
[+] S
r = Product
{ $ += r; }
----
[-] S
r = Product
{ $ -= r; }
}
`int`
Product =>
$ = Value
@while (*) {
[*] S
r = Value
{ $ *= r; }
----
[/] S
r = Value
{ $ ~/= r; }
}
`int`
Value('expression') => (
NUMBER
----
i = ID
$ = { vars[i]! }
----
'(' S
$ = Expr
')' S
)
`int`
NUMBER =>
n = <[0-9]+>
S
$ = { int.parse(n) }
`String`
ID =>
$ = <[a-zA-Z]>
S
`void`
EOF('end of file') =>
! .
`void`
S => [ \t\r\n]*