Class: TreeHaver::Backends::FFI::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/tree_haver/backends/ffi.rb

Overview

FFI-based tree-sitter tree

Wraps a TSTree pointer and manages its lifecycle with a finalizer.

Note: Tree objects DO use finalizers (unlike Parser objects) because:

  1. Trees are typically short-lived and numerous (one per parse)

  2. ts_tree_delete is safer than ts_parser_delete during GC

  3. Memory leaks from accumulated trees are more problematic

  4. The finalizer silently ignores errors for safety

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ptr) ⇒ Tree

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Tree.



534
535
536
537
# File 'lib/tree_haver/backends/ffi.rb', line 534

def initialize(ptr)
  @ptr = ptr
  ObjectSpace.define_finalizer(self, self.class.finalizer(@ptr))
end

Class Method Details

.finalizer(ptr) ⇒ Proc

Returns a finalizer proc that deletes the tree

This is public API for testing purposes, but not intended for direct use. The finalizer is automatically registered when creating a Tree object.



549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/tree_haver/backends/ffi.rb', line 549

def finalizer(ptr)
  proc {
    begin
      Native.ts_tree_delete(ptr)
    rescue StandardError
      # Silently ignore errors during finalization to prevent crashes
      # during GC. If the library is unloaded or ptr is invalid, we
      # don't want to crash the entire process.
      nil
    end
  }
end

Instance Method Details

#root_nodeNode

Get the root node of the syntax tree



566
567
568
569
# File 'lib/tree_haver/backends/ffi.rb', line 566

def root_node
  node_val = Native.ts_tree_root_node(@ptr)
  Node.new(node_val)
end