From 0b817a609f7cd3d7309a81dbfe96287c6945a085 Mon Sep 17 00:00:00 2001 From: Max Brunsfeld Date: Mon, 13 Feb 2023 13:45:12 -0800 Subject: [PATCH] Clear the parse stack when terminating parsing early due to error cost This fixes a bug where the parse tree would not be rebalanced if this code path was taken. --- lib/src/parser.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/src/parser.c b/lib/src/parser.c index f186ce33..f84b3c8d 100644 --- a/lib/src/parser.c +++ b/lib/src/parser.c @@ -1941,8 +1941,16 @@ TSTree *ts_parser_parse( } } + // After advancing each version of the stack, re-sort the versions by their cost, + // removing any versions that are no longer worth pursuing. unsigned min_error_cost = ts_parser__condense_stack(self); + + // If there's already a finished parse tree that's better than any in-progress version, + // then terminate parsing. Clear the parse stack to remove any extra references to subtrees + // within the finished tree, ensuring that these subtrees can be safely mutated in-place + // for rebalancing. if (self->finished_tree.ptr && ts_subtree_error_cost(self->finished_tree) < min_error_cost) { + ts_stack_clear(self->stack); break; }