-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.yalr
59 lines (49 loc) · 1.63 KB
/
calculator.yalr
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
option code.main true;
// This will be inserted close to the top of the file
verbatim file.top <%{
#include <map>
}%>
verbatim namespace.top <%{
std::map<std::string, float> variables;
}%>
skip WS r:\s+ ;
// basically here so that it is prefered to VARIABLE
// But, it also gives a chance to show case folding.
// This will accept print or PRINT or PrInT, etc.
//
term PRINT 'print' @cfold ;
//
// zero to many underbar followed by a letter followed by as many digits,
// letters, underbars you want.
// allowed __a___
// not allowed __3
//
term <@lexeme> VARIABLE rm:_*[a-zA-Z][_a-zA-Z0-9]* ;
term <float> NUMBER r:-?\d*\.?\d+([eE][-+]?\d+)? <%{ return atof(lexeme.data()); }%>
//
// associativity will define the terminals for us.
//
associativity left '+' '-' '*' '/';
precedence 100 '+' '-';
precedence 200 '*' '/';
goal rule statement_list {
=> statement;
=> statement_list statement ;
}
rule statement {
=> expression <%{ std::cout << "(e)answer = " << _v1 << "\n"; }%>
=> PRINT expression <%{ std::cout << "(p)answer = " << _v2 << "\n"; }%>
=> var:VARIABLE ':=' expr:expression <%{
std::cout << "assigning " << expr << " to '" << var << "'\n";
variables[var] = expr;
}%>
}
rule <float> expression {
=> l:expression '+' r:expression <%{ return l + r; }%>
=> l:expression '-' r:expression <%{ return l - r; }%>
=> l:expression '*' r:expression <%{ return l * r; }%>
=> l:expression '/' r:expression <%{ return l / r; }%>
=> NUMBER <%{ return _v1; }%>
=> VARIABLE <%{ return variables[_v1]; }%>
=> '(' expression ')' <%{ return _v2; }%>
}