cpp-peglib/example/calc.cc

54 lines
1.3 KiB
C++
Raw Normal View History

2020-02-07 16:55:21 +00:00
#include <assert.h>
2015-02-08 01:52:26 +00:00
#include <iostream>
2020-10-02 01:26:04 +00:00
#include <peglib.h>
2015-02-08 01:52:26 +00:00
2015-08-10 20:37:56 +00:00
using namespace peg;
2020-02-07 16:55:21 +00:00
using namespace std;
2015-02-08 01:52:26 +00:00
2020-02-07 16:55:21 +00:00
int main(void) {
2020-10-02 01:26:04 +00:00
// (2) Make a parser
parser parser(R"(
2020-02-07 16:55:21 +00:00
# Grammar for Calculator...
Additive <- Multitive '+' Additive / Multitive
2022-09-03 11:09:31 +00:00
Multitive <- Primary '*' Multitive^cond / Primary
2020-02-07 16:55:21 +00:00
Primary <- '(' Additive ')' / Number
Number <- < [0-9]+ >
%whitespace <- [ \t]*
2022-09-03 11:09:31 +00:00
cond <- '' { error_message "missing multitative" }
2020-02-07 16:55:21 +00:00
)");
2015-02-08 01:52:26 +00:00
2020-10-02 01:26:04 +00:00
assert(static_cast<bool>(parser) == true);
// (3) Setup actions
parser["Additive"] = [](const SemanticValues &vs) {
switch (vs.choice()) {
case 0: // "Multitive '+' Additive"
return any_cast<int>(vs[0]) + any_cast<int>(vs[1]);
default: // "Multitive"
return any_cast<int>(vs[0]);
}
};
parser["Multitive"] = [](const SemanticValues &vs) {
switch (vs.choice()) {
case 0: // "Primary '*' Multitive"
return any_cast<int>(vs[0]) * any_cast<int>(vs[1]);
default: // "Primary"
return any_cast<int>(vs[0]);
}
};
parser["Number"] = [](const SemanticValues &vs) {
return vs.token_to_number<int>();
};
// (4) Parse
parser.enable_packrat_parsing(); // Enable packrat parsing.
2022-09-03 11:09:31 +00:00
int val = 0;
parser.parse(" (1 + 2) * ", val);
2020-10-02 01:26:04 +00:00
2022-09-03 11:09:31 +00:00
// assert(val == 9);
assert(val == 0);
2015-02-08 01:52:26 +00:00
}