static void ts_subtree__compress()

in lib/src/subtree.c [281:321]


static void ts_subtree__compress(MutableSubtree self, unsigned count, const TSLanguage *language,
                                 MutableSubtreeArray *stack) {
  unsigned initial_stack_size = stack->size;

  MutableSubtree tree = self;
  TSSymbol symbol = tree.ptr->symbol;
  for (unsigned i = 0; i < count; i++) {
    if (tree.ptr->ref_count > 1 || tree.ptr->child_count < 2) break;

    MutableSubtree child = ts_subtree_to_mut_unsafe(tree.ptr->children[0]);
    if (
      child.data.is_inline ||
      child.ptr->child_count < 2 ||
      child.ptr->ref_count > 1 ||
      child.ptr->symbol != symbol
    ) break;

    MutableSubtree grandchild = ts_subtree_to_mut_unsafe(child.ptr->children[0]);
    if (
      grandchild.data.is_inline ||
      grandchild.ptr->child_count < 2 ||
      grandchild.ptr->ref_count > 1 ||
      grandchild.ptr->symbol != symbol
    ) break;

    tree.ptr->children[0] = ts_subtree_from_mut(grandchild);
    child.ptr->children[0] = grandchild.ptr->children[grandchild.ptr->child_count - 1];
    grandchild.ptr->children[grandchild.ptr->child_count - 1] = ts_subtree_from_mut(child);
    array_push(stack, tree);
    tree = grandchild;
  }

  while (stack->size > initial_stack_size) {
    tree = array_pop(stack);
    MutableSubtree child = ts_subtree_to_mut_unsafe(tree.ptr->children[0]);
    MutableSubtree grandchild = ts_subtree_to_mut_unsafe(child.ptr->children[child.ptr->child_count - 1]);
    ts_subtree_set_children(grandchild, grandchild.ptr->children, grandchild.ptr->child_count, language);
    ts_subtree_set_children(child, child.ptr->children, child.ptr->child_count, language);
    ts_subtree_set_children(tree, tree.ptr->children, tree.ptr->child_count, language);
  }
}