defmodule Localize.Mf2.TreeSitter.Tree do @moduledoc """ A tree-sitter parse tree for an MF2 source binary. A `Tree` wraps the opaque NIF resource returned by the tree-sitter parser together with the original source so that byte ranges on any descendant node can be resolved back to the text they span. Trees are immutable. Pass one to `Localize.Mf2.TreeSitter.root/1` to obtain the root `Localize.Mf2.TreeSitter.Node` and walk from there. """ alias Localize.Mf2.TreeSitter.Nif @enforce_keys [:ref, :source] defstruct [:ref, :source] @typedoc """ A parse tree. Opaque — the `:ref` field is a NIF resource handle whose internal representation is unspecified. Always interact with a tree via the functions on `Localize.Mf2.TreeSitter` rather than pattern-matching on its fields. """ @opaque t :: %__MODULE__{ref: Nif.tree(), source: binary()} @doc """ Return the tree's S-expression form. Equivalent to the output of `tree-sitter parse --sexp` for the same source. Intended for debugging and for corpus-parity tests. ### Arguments * `tree` is a `#{inspect(__MODULE__)}` struct. ### Returns * A binary containing the Lisp-style S-expression. ### Examples iex> {:ok, tree} = Localize.Mf2.TreeSitter.parse("hello {$name}") iex> sexp = Localize.Mf2.TreeSitter.Tree.to_sexp(tree) iex> String.starts_with?(sexp, "(source_file") true """ @spec to_sexp(t()) :: binary() def to_sexp(%__MODULE__{ref: ref}), do: Nif.tree_to_sexp(ref) end