cpp-peglib/example/calc.cc
Josh Soref 65ccaaa7c3
Spelling (#287)
* spelling: bracket

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: build

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: commandline

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: debugging

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: definition

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: editing

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: editors

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: github

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: grammar

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: multiplicative

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: optimization

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: optimize

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: semicolon

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

* spelling: whitespace

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>

---------

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>
2024-01-02 08:44:45 -05:00

54 lines
1.4 KiB
C++

#include <assert.h>
#include <iostream>
#include <peglib.h>
using namespace peg;
using namespace std;
int main(void) {
// (2) Make a parser
parser parser(R"(
# Grammar for Calculator...
Additive <- Multiplicative '+' Additive / Multiplicative
Multiplicative <- Primary '*' Multiplicative^cond / Primary
Primary <- '(' Additive ')' / Number
Number <- < [0-9]+ >
%whitespace <- [ \t]*
cond <- '' { error_message "missing multiplicative" }
)");
assert(static_cast<bool>(parser) == true);
// (3) Setup actions
parser["Additive"] = [](const SemanticValues &vs) {
switch (vs.choice()) {
case 0: // "Multiplicative '+' Additive"
return any_cast<int>(vs[0]) + any_cast<int>(vs[1]);
default: // "Multiplicative"
return any_cast<int>(vs[0]);
}
};
parser["Multiplicative"] = [](const SemanticValues &vs) {
switch (vs.choice()) {
case 0: // "Primary '*' Multiplicative"
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.
int val = 0;
parser.parse(" (1 + 2) * ", val);
// assert(val == 9);
assert(val == 0);
}