You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cpp-peglib/example/calc4.cc

43 lines
1.1 KiB

#include <assert.h>
#include <iostream>
4 years ago
#include <peglib.h>
using namespace peg;
using namespace std;
int main(void) {
4 years ago
parser parser(R"(
EXPRESSION <- ATOM (OPERATOR ATOM)* {
precedence
L - +
L / *
}
ATOM <- NUMBER / '(' EXPRESSION ')'
OPERATOR <- < [-+/*] >
NUMBER <- < '-'? [0-9]+ >
%whitespace <- [ \t\r\n]*
)");
4 years ago
parser["EXPRESSION"] = [](const SemanticValues &vs) {
auto result = any_cast<long>(vs[0]);
if (vs.size() > 1) {
auto ope = any_cast<char>(vs[1]);
auto num = any_cast<long>(vs[2]);
switch (ope) {
case '+': result += num; break;
case '-': result -= num; break;
case '*': result *= num; break;
case '/': result /= num; break;
}
}
return result;
};
parser["OPERATOR"] = [](const SemanticValues &vs) { return *vs.sv().data(); };
parser["NUMBER"] = [](const SemanticValues &vs) { return atol(vs.sv().data()); };
4 years ago
long val;
parser.parse(" -1 + (1 + 2) * 3 - -1", val);
4 years ago
assert(val == 9);
}