Skip to content

Commit 578eec7

Browse files
committed
Fix #187
1 parent 4d67d96 commit 578eec7

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

peglib.h

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3904,13 +3904,17 @@ struct AstOptimizer {
39043904
std::shared_ptr<T> parent = nullptr) {
39053905
auto found =
39063906
std::find(rules_.begin(), rules_.end(), original->name) != rules_.end();
3907-
bool opt = mode_ ? !found : found;
3907+
auto opt = mode_ ? !found : found;
39083908

39093909
if (opt && original->nodes.size() == 1) {
39103910
auto child = optimize(original->nodes[0], parent);
3911-
return std::make_shared<T>(*child, original->name.data(),
3912-
original->choice_count, original->position,
3913-
original->length, original->choice);
3911+
auto ast = std::make_shared<T>(*child, original->name.data(),
3912+
original->choice_count, original->position,
3913+
original->length, original->choice);
3914+
for (auto node : ast->nodes) {
3915+
node->parent = ast;
3916+
}
3917+
return ast;
39143918
}
39153919

39163920
auto ast = std::make_shared<T>(*original);

test/test1.cc

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -967,3 +967,18 @@ TEST(GeneralTest, token_to_number_float_test) {
967967
EXPECT_TRUE(ast->nodes.empty());
968968
}
969969

970+
TEST(GeneralTest, ParentReferencesShouldNotBeExpired) {
971+
auto parser = peg::parser(R"(
972+
ROOT <- OPTIMIZES_AWAY
973+
OPTIMIZES_AWAY <- ITEM+
974+
ITEM <- 'a'
975+
)");
976+
parser.enable_ast<peg::Ast>();
977+
978+
std::shared_ptr<peg::Ast> ast;
979+
parser.parse("aaa", ast);
980+
ast = parser.optimize_ast(ast);
981+
982+
EXPECT_FALSE(ast->nodes[0]->parent.expired());
983+
}
984+

0 commit comments

Comments
 (0)