Skip to content

Commit

Permalink
Add subscript operator to Expression to access sub-expressions by name (
Browse files Browse the repository at this point in the history
#60)

* Add another subscript operator to expression to access sub-expressions by name.

* explicitly include optional for windows.

* clang-format run.

* Add test for subscript operators.

* Forgot the clang-format run again ...

* Simplify subscript test
  • Loading branch information
jteuber authored Feb 5, 2021
1 parent dcec3a0 commit 99ea226
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
9 changes: 9 additions & 0 deletions include/peg_parser/interpreter.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#pragma once

#include <iterator>
#include <optional>
#include <type_traits>

#include "parser.h"
Expand Down Expand Up @@ -58,6 +59,14 @@ namespace peg_parser {
Expression operator[](size_t idx) const {
return interpreter.interpret(syntaxTree->inner[idx]);
}
std::optional<Expression> operator[](std::string_view name) const {
auto it = std::find_if(syntaxTree->inner.begin(), syntaxTree->inner.end(),
[name](auto st) { return st->rule->name == name; });
if (it != syntaxTree->inner.end()) {
return interpreter.interpret(*it);
}
return {};
}
iterator begin() const { return iterator(*this, 0); }
iterator end() const { return iterator(*this, size()); }

Expand Down
11 changes: 11 additions & 0 deletions test/source/parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,14 @@ TEST_CASE("Documentation Example") {
REQUIRE(g.run("1 - 2*3/2 + 4") == Approx(2));
REQUIRE(g.run("1 + 2 * (3+4)/ 2 - 3") == Approx(5));
}

TEST_CASE("Subscript Operators") {
ParserGenerator<bool> program;
program["Word"] << "[a-z]+";
program["Yell"] << "[A-Z]+";
program["Start"] << "Word | Yell" >> [](auto e) { return bool(e["Yell"]); };
program.setStart(program["Start"]);

REQUIRE(!program.run("hello"));
REQUIRE(program.run("HELLO"));
}

0 comments on commit 99ea226

Please sign in to comment.