Skip to content

Commit 99ea226

Browse files
authored
Add subscript operator to Expression to access sub-expressions by name (#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
1 parent dcec3a0 commit 99ea226

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

include/peg_parser/interpreter.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#pragma once
22

33
#include <iterator>
4+
#include <optional>
45
#include <type_traits>
56

67
#include "parser.h"
@@ -58,6 +59,14 @@ namespace peg_parser {
5859
Expression operator[](size_t idx) const {
5960
return interpreter.interpret(syntaxTree->inner[idx]);
6061
}
62+
std::optional<Expression> operator[](std::string_view name) const {
63+
auto it = std::find_if(syntaxTree->inner.begin(), syntaxTree->inner.end(),
64+
[name](auto st) { return st->rule->name == name; });
65+
if (it != syntaxTree->inner.end()) {
66+
return interpreter.interpret(*it);
67+
}
68+
return {};
69+
}
6170
iterator begin() const { return iterator(*this, 0); }
6271
iterator end() const { return iterator(*this, size()); }
6372

test/source/parser.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,3 +284,14 @@ TEST_CASE("Documentation Example") {
284284
REQUIRE(g.run("1 - 2*3/2 + 4") == Approx(2));
285285
REQUIRE(g.run("1 + 2 * (3+4)/ 2 - 3") == Approx(5));
286286
}
287+
288+
TEST_CASE("Subscript Operators") {
289+
ParserGenerator<bool> program;
290+
program["Word"] << "[a-z]+";
291+
program["Yell"] << "[A-Z]+";
292+
program["Start"] << "Word | Yell" >> [](auto e) { return bool(e["Yell"]); };
293+
program.setStart(program["Start"]);
294+
295+
REQUIRE(!program.run("hello"));
296+
REQUIRE(program.run("HELLO"));
297+
}

0 commit comments

Comments
 (0)