This commit is contained in:
yhirose 2022-01-03 11:23:41 -05:00
parent 4d67d96d7a
commit 578eec705c
2 changed files with 23 additions and 4 deletions

View File

@ -3904,13 +3904,17 @@ struct AstOptimizer {
std::shared_ptr<T> parent = nullptr) { std::shared_ptr<T> parent = nullptr) {
auto found = auto found =
std::find(rules_.begin(), rules_.end(), original->name) != rules_.end(); 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) { if (opt && original->nodes.size() == 1) {
auto child = optimize(original->nodes[0], parent); auto child = optimize(original->nodes[0], parent);
return std::make_shared<T>(*child, original->name.data(), auto ast = std::make_shared<T>(*child, original->name.data(),
original->choice_count, original->position, original->choice_count, original->position,
original->length, original->choice); original->length, original->choice);
for (auto node : ast->nodes) {
node->parent = ast;
}
return ast;
} }
auto ast = std::make_shared<T>(*original); auto ast = std::make_shared<T>(*original);

View File

@ -967,3 +967,18 @@ TEST(GeneralTest, token_to_number_float_test) {
EXPECT_TRUE(ast->nodes.empty()); 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());
}