Skip to content

Commit

Permalink
Fix #187
Browse files Browse the repository at this point in the history
  • Loading branch information
yhirose committed Jan 3, 2022
1 parent 4d67d96 commit 578eec7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
12 changes: 8 additions & 4 deletions peglib.h
Original file line number Diff line number Diff line change
Expand Up @@ -3904,13 +3904,17 @@ struct AstOptimizer {
std::shared_ptr<T> parent = nullptr) {
auto found =
std::find(rules_.begin(), rules_.end(), original->name) != rules_.end();
bool opt = mode_ ? !found : found;
auto opt = mode_ ? !found : found;

if (opt && original->nodes.size() == 1) {
auto child = optimize(original->nodes[0], parent);
return std::make_shared<T>(*child, original->name.data(),
original->choice_count, original->position,
original->length, original->choice);
auto ast = std::make_shared<T>(*child, original->name.data(),
original->choice_count, original->position,
original->length, original->choice);
for (auto node : ast->nodes) {
node->parent = ast;
}
return ast;
}

auto ast = std::make_shared<T>(*original);
Expand Down
15 changes: 15 additions & 0 deletions test/test1.cc
Original file line number Diff line number Diff line change
Expand Up @@ -967,3 +967,18 @@ TEST(GeneralTest, token_to_number_float_test) {
EXPECT_TRUE(ast->nodes.empty());
}

TEST(GeneralTest, ParentReferencesShouldNotBeExpired) {
auto parser = peg::parser(R"(
ROOT <- OPTIMIZES_AWAY
OPTIMIZES_AWAY <- ITEM+
ITEM <- 'a'
)");
parser.enable_ast<peg::Ast>();

std::shared_ptr<peg::Ast> ast;
parser.parse("aaa", ast);
ast = parser.optimize_ast(ast);

EXPECT_FALSE(ast->nodes[0]->parent.expired());
}

0 comments on commit 578eec7

Please sign in to comment.