2015-02-08 01:52:26 +00:00
|
|
|
#include <peglib.h>
|
2020-02-07 16:55:21 +00:00
|
|
|
#include <assert.h>
|
2015-02-08 01:52:26 +00:00
|
|
|
#include <iostream>
|
|
|
|
|
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) {
|
|
|
|
// (2) Make a parser
|
|
|
|
parser parser(R"(
|
|
|
|
# Grammar for Calculator...
|
|
|
|
Additive <- Multitive '+' Additive / Multitive
|
|
|
|
Multitive <- Primary '*' Multitive / Primary
|
|
|
|
Primary <- '(' Additive ')' / Number
|
|
|
|
Number <- < [0-9]+ >
|
|
|
|
%whitespace <- [ \t]*
|
|
|
|
)");
|
2015-02-08 01:52:26 +00:00
|
|
|
|
2020-03-29 21:01:46 +00:00
|
|
|
assert(static_cast<bool>(parser) == true);
|
2020-02-07 16:55:21 +00:00
|
|
|
|
|
|
|
// (3) Setup actions
|
|
|
|
parser["Additive"] = [](const SemanticValues& sv) {
|
|
|
|
switch (sv.choice()) {
|
|
|
|
case 0: // "Multitive '+' Additive"
|
|
|
|
return any_cast<int>(sv[0]) + any_cast<int>(sv[1]);
|
|
|
|
default: // "Multitive"
|
|
|
|
return any_cast<int>(sv[0]);
|
2015-02-08 01:52:26 +00:00
|
|
|
}
|
2015-02-09 22:12:59 +00:00
|
|
|
};
|
2015-02-08 01:52:26 +00:00
|
|
|
|
2020-02-07 16:55:21 +00:00
|
|
|
parser["Multitive"] = [](const SemanticValues& sv) {
|
|
|
|
switch (sv.choice()) {
|
|
|
|
case 0: // "Primary '*' Multitive"
|
|
|
|
return any_cast<int>(sv[0]) * any_cast<int>(sv[1]);
|
|
|
|
default: // "Primary"
|
|
|
|
return any_cast<int>(sv[0]);
|
|
|
|
}
|
|
|
|
};
|
2015-02-08 01:52:26 +00:00
|
|
|
|
2020-02-07 16:55:21 +00:00
|
|
|
parser["Number"] = [](const SemanticValues& sv) {
|
|
|
|
return stoi(sv.token(), nullptr, 10);
|
|
|
|
};
|
2015-02-08 01:52:26 +00:00
|
|
|
|
2020-02-07 16:55:21 +00:00
|
|
|
// (4) Parse
|
|
|
|
parser.enable_packrat_parsing(); // Enable packrat parsing.
|
2015-02-08 01:52:26 +00:00
|
|
|
|
2020-02-07 16:55:21 +00:00
|
|
|
int val;
|
|
|
|
parser.parse(" (1 + 2) * 3 ", val);
|
2015-02-08 01:52:26 +00:00
|
|
|
|
2020-02-07 16:55:21 +00:00
|
|
|
assert(val == 9);
|
2015-02-08 01:52:26 +00:00
|
|
|
}
|