Skip to content

Tree Reuse โ€‹

What you'll learn โ€‹

  • How old trees stay valid during incremental parsing and how to duplicate a tree.

Complete example โ€‹

zig
var old_tree = try parser.parseString("alpha + beta");
defer old_tree.deinit();

var dup = try old_tree.copy();
defer dup.deinit();

// old_tree is untouched by incremental parsing and still fully usable.
var new_tree = try parser.parse(&old_tree, edit, "alpha + gamma");
defer new_tree.deinit();

How it works โ€‹

  • Old trees are immutable from the parser's perspective: reuse clones subtrees (translating positions through the edit) into the new pool. The old pool is only ever read.
  • copy() duplicates source bytes, nodes, and child indices with the tree's own allocator โ€” a snapshot you can edit or compare later.
  • Reused subtrees keep their recorded LR start states, which is what makes splicing sound: identical state plus identical bytes implies an identical subtree.

API used โ€‹

  • Tree โ€” copy, getChangedRanges; Parser โ€” parse, reused_node_count.

Released under the MIT License.