-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathcalc.cpp.ast.g
89 lines (65 loc) · 1.21 KB
/
calc.cpp.ast.g
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
/**
* Generated parser in C++.
*
* ./bin/syntax -g examples/calc.cpp.g -m lalr1 -o CalcParser.h
*
* #include "CalcParser.h"
*
* CalcParser parser;
*
* std::cout << parser.parse("2 + 2 * 2"); // 6
*/
%lex
%%
\s+ %empty
\d+ NUMBER
/lex
%{
#include <iostream>
#include <memory>
/**
* Base class for AST nodes.
*/
class Node {};
/**
* Binary expressions.
*/
class BinaryExpression : public Node {
public:
BinaryExpression(std::string op, Node* left, Node* right)
: op(op), left(left), right(right) {}
std::string op;
Node* left;
Node* right;
};
/**
* AST node for numbers.
*/
class NumericLiteral : public Node {
public:
NumericLiteral(int value): value(value) {}
int value;
};
// Type of the parsing value.
using Value = Node*;
// On parser begin hook:
void onParseBegin(const std::string& str) {
std::cout << "Parsing: " << str << "\n";
}
// On parser end hook:
void onParseEnd(Node* result) {
std::cout << "Result: " << result << "\n";
}
%}
%left '+'
%left '*'
%%
E
: E '+' E
{ $$ = new BinaryExpression($2, $1, $3) }
| E '*' E
{ $$ = new BinaryExpression($2, $1, $3) }
| '(' E ')' { $$ = $2 }
| NUMBER
{ $$ = new NumericLiteral(std::stoi($1)) }
;