in lib/src/subtree.c [323:356]
void ts_subtree_balance(Subtree self, SubtreePool *pool, const TSLanguage *language) {
array_clear(&pool->tree_stack);
if (ts_subtree_child_count(self) > 0 && self.ptr->ref_count == 1) {
array_push(&pool->tree_stack, ts_subtree_to_mut_unsafe(self));
}
while (pool->tree_stack.size > 0) {
MutableSubtree tree = array_pop(&pool->tree_stack);
if (tree.ptr->repeat_depth > 0) {
Subtree child1 = tree.ptr->children[0];
Subtree child2 = tree.ptr->children[tree.ptr->child_count - 1];
if (
ts_subtree_child_count(child1) > 0 &&
ts_subtree_child_count(child2) > 0 &&
child1.ptr->repeat_depth > child2.ptr->repeat_depth
) {
unsigned n = child1.ptr->repeat_depth - child2.ptr->repeat_depth;
for (unsigned i = n / 2; i > 0; i /= 2) {
ts_subtree__compress(tree, i, language, &pool->tree_stack);
n -= i;
}
}
}
for (uint32_t i = 0; i < tree.ptr->child_count; i++) {
Subtree child = tree.ptr->children[i];
if (ts_subtree_child_count(child) > 0 && child.ptr->ref_count == 1) {
array_push(&pool->tree_stack, ts_subtree_to_mut_unsafe(child));
}
}
}
}