treesitter

package module
v0.0.0-...-7e94837 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

treesitter

Go bindings for the tree-sitter parsing library, loaded at run time with purego. No cgo.

tree, err := treesitter.ParseFile("main.c")
defer tree.Close()

q, err := treesitter.NewQuery(tree.Language(), `
    (call_expression function: (identifier) @callee
      (#match? @callee "^str"))`)
defer q.Close()

for m := range q.Matches(tree.RootNode()) {
	fmt.Printf("%s at %v\n", m.Text("callee"), m.Node("callee").StartPoint())
}

The API is shaped for Go rather than translated from C:

  • A tree remembers its source, so Node.Text() takes no argument.
  • Children, descendants, errors, matches, captures, and lookahead symbols are range-over-func iterators.
  • Counts and byte offsets are int, not uint32.
  • Node is a value type and every method accepts a null node, so n.ChildByFieldName("x").Text() is safe.
  • Query.Matches names captures and applies text predicates; a malformed predicate is a compile error. QueryCursor still exposes the raw tree-sitter behaviour.
  • ParseFile picks a grammar from the file name; Parse is a one-call parser for a language you already have.
  • Streaming input is io.ReaderAt, because tree-sitter reads by byte offset and revisits earlier offsets; a forward-only io.Reader cannot serve it.

The package covers parsing (whole-buffer, chunked, random-access, incremental, and context-cancellable), tree and node inspection, tree cursors, queries with named captures and predicate evaluation, lookahead iteration, and language introspection. The WebAssembly grammar loader and the custom allocator are not bound.

Libraries

libtree-sitter is located through TREE_SITTER_LIB_PATH, then the platform default search path, then the common Homebrew paths on macOS. Load sets the path explicitly. Grammars are separate shared libraries exporting tree_sitter_<name>. FindLanguage looks one up by name in TREE_SITTER_GRAMMAR_PATH, the tree-sitter CLI's library directory, the parser directories of Neovim and Emacs, and the system library directories (GrammarDirs lists them); LoadLanguage opens one by path.

If no grammar is installed, treesitter/grammars builds one:

if _, err := grammars.Install(ctx, "go"); err != nil {
	log.Fatal(err)
}
tree, err := treesitter.ParseFile("main.go")

Install downloads a pinned source archive, checks it against a recorded SHA-256, compiles it, and writes the library where FindLanguage looks. Upstream publishes C source rather than binaries, so this needs a C compiler at install time; parsing still needs none. grammars.All lists what is pinned, and Grammar.Build installs a grammar that is not. The pins cover the common languages plus cuda, ptx, glsl, hlsl, swift, objc, starlark, and tree-sitter's own query language. The package is separate so that a program which only parses links no HTTP client and no parse can reach the network.

tree-sitter has no notion of which language a file is written in. DetectLanguage maps a file name to a grammar name using the extensions the common grammars declare, which is what the tree-sitter CLI does with its file-types lists.

A grammar's ABI version must lie within the range this library supports (MinCompatibleLanguageVersion through LanguageVersion). Grammars built by the tree-sitter CLI, and the parsers Neovim installs, satisfy this.

Platforms

Linux and macOS on amd64 and arm64, the targets on which purego passes structs by value. Load fails elsewhere.

Layout

internal/ts is generated by gen-treesitter from github.com/tmc/libgen and binds tree_sitter/api.h one function to one Go function. The public package is written by hand on top of it. To regenerate:

gen-treesitter -header $PREFIX/include/tree_sitter/api.h -output treesitter/internal/ts

grammars/pins.gen.go is generated by grammars/mkmanifest.go, which resolves each grammar repository's latest release and records the archive's digest:

go generate ./grammars

Testing

The generated layout tests run everywhere. The remaining tests need the library and a C grammar and skip otherwise.

Documentation

Overview

Package treesitter provides Go bindings for the tree-sitter parsing library.

It does the same job as the established cgo bindings, with two differences: it loads libtree-sitter and its grammars at run time with purego, so building it needs no C toolchain, and its API is shaped for Go rather than translated from C.

Grammars are shared libraries, each exporting a function named tree_sitter_<name>. FindLanguage locates one by name in the directories GrammarDirs lists and LoadLanguage opens one by path; DetectLanguage guesses the name from a file name, and ParseFile puts the two together. Package github.com/tmc/lib/treesitter/grammars builds a grammar from a pinned source archive when none is installed.

Typical use:

tree, err := treesitter.ParseFile("hello.c")
if err != nil {
	log.Fatal(err)
}
defer tree.Close()
for n := range tree.Errors() {
	fmt.Println("syntax error at", n.StartPoint())
}

A tree remembers the source it was parsed from, so Node.Text takes no argument. Children, descendants, errors, query matches and captures, and lookahead symbols are iterators for use with range. Counts and byte offsets are int.

Queries return named captures and have their text predicates applied:

q, err := treesitter.NewQuery(lang, `
    (call_expression function: (identifier) @callee
      (#match? @callee "^str"))`)
if err != nil {
	log.Fatal(err)
}
defer q.Close()
for m := range q.Matches(tree.RootNode()) {
	fmt.Printf("%s at %v\n", m.Text("callee"), m.Node("callee").StartPoint())
}

Query.Matches evaluates #eq?, #match?, and #any-of? with their not-, any-, and any-not- forms, and rejects a malformed one when the query is compiled. Predicates it does not evaluate, such as #set! and #is?, are reported by Query.Predicates and Query.Properties for the caller to interpret. QueryCursor runs a query without any of that.

Parsers, trees, queries, and cursors own C memory and must be released with Close. Their zero values are not usable; obtain them from the New functions and from Parse. Close is idempotent. A Node is a value that refers into its tree and is valid only while that tree is open; its zero value is the null node, which IsNull reports and on which every method returns its zero result.

tree-sitter reads its input by byte offset and revisits earlier offsets, so streaming input is io.ReaderAt, not io.Reader; see Parser.ParseReaderAt.

The library is found through TREE_SITTER_LIB_PATH, then the platform's default search path, then common Homebrew locations. Load directs the search explicitly.

The package builds on the platforms purego supports for calling C with struct arguments: Linux and macOS on amd64 and arm64. Other systems have no library search names and Load fails on them.

Example

Example parses a C source file and prints the name of each function it defines. It needs libtree-sitter and a C grammar, so it has no fixed output.

package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/treesitter"
)

func main() {
	lang, err := treesitter.FindLanguage("c")
	if err != nil {
		log.Fatal(err)
	}
	src := []byte("int add(int a, int b) { return a + b; }\nint main() { return add(1, 2); }\n")
	tree, err := treesitter.Parse(lang, src)
	if err != nil {
		log.Fatal(err)
	}
	defer tree.Close()

	q, err := treesitter.NewQuery(lang, `(function_definition
	  declarator: (function_declarator declarator: (identifier) @name))`)
	if err != nil {
		log.Fatal(err)
	}
	defer q.Close()
	for m := range q.Matches(tree.RootNode()) {
		fmt.Printf("%s\n", m.Text("name"))
	}
}

Index

Examples

Constants

View Source
const (
	LanguageVersion              = 15
	MinCompatibleLanguageVersion = 13
)

LanguageVersion is the latest grammar ABI version this library understands, and MinCompatibleLanguageVersion the earliest.

View Source
const GrammarPathEnv = "TREE_SITTER_GRAMMAR_PATH"

GrammarPathEnv names the environment variable holding extra directories for FindLanguage, separated by the OS path list separator.

Variables

View Source
var ErrNoLanguage = errors.New("treesitter: parser has no language")

ErrNoLanguage is returned by Parse when the parser has no language.

View Source
var ErrParseFailed = errors.New("treesitter: parse failed")

ErrParseFailed is returned when tree-sitter produces no tree for reasons other than a missing language or a cancelled context.

Functions

func DetectLanguage

func DetectLanguage(filename string) string

DetectLanguage guesses the grammar name for a file from its name, using the extensions and well-known file names the common grammars declare. It returns "" when the name is not recognized. tree-sitter itself does not identify languages; this table mirrors the file-types lists of the grammars' tree-sitter.json files, so a hit is a name FindLanguage can look up, not a promise that the grammar is installed.

Ambiguous extensions resolve to the most common grammar: .h is c, .m is objc, .scm is scheme, .v is verilog.

func FindGrammar

func FindGrammar(name string) (string, error)

FindGrammar returns the path of the shared library for the named language in the first directory of GrammarDirs that has one. It accepts the file names used by the tree-sitter CLI and Neovim (<name>.so or .dylib), by Emacs and Linux distributions (libtree-sitter-<name>), and their hyphenated variants.

func GrammarDirs

func GrammarDirs() []string

GrammarDirs returns the directories FindLanguage searches, in order: the entries of TREE_SITTER_GRAMMAR_PATH, TREE_SITTER_LIBDIR (the tree-sitter CLI's setting) or the CLI's default cache directory, the parser directories of Neovim and Emacs installations, and the common system library directories. Directories that do not exist are omitted.

func LibraryPath

func LibraryPath() string

LibraryPath returns the path libtree-sitter was opened from, or "" if it is not loaded.

func Load

func Load(path string) error

Load opens libtree-sitter from path, or from the default search list when path is empty. Calling Load is optional: the first operation that needs the library loads it from the default search list.

func Loaded

func Loaded() bool

Loaded reports whether libtree-sitter is loaded.

func SlogLogger

func SlogLogger(l *slog.Logger) func(LogType, string)

SlogLogger adapts a slog.Logger to Parser.SetLogger:

p.SetLogger(treesitter.SlogLogger(logger))

Messages are logged at debug level with a kind attribute of "parse" or "lex"; tree-sitter emits one per parse step, so this is verbose.

Types

type Capture

type Capture struct {
	Name  string
	Node  Node
	Index int // capture id; see [Query.CaptureName]
}

Capture is a node matched by a named capture, with the name resolved.

type FieldID

type FieldID uint16

FieldID identifies a field within a language.

type GrammarNotFoundError

type GrammarNotFoundError struct {
	Name string   // the language name
	Dirs []string // the directories searched
}

GrammarNotFoundError is returned by FindLanguage when no directory holds a grammar for the language.

func (*GrammarNotFoundError) Error

func (e *GrammarNotFoundError) Error() string

type IncludedRangesError

type IncludedRangesError struct {
	Index int
}

IncludedRangesError is returned by SetIncludedRanges when a range is inverted or begins before the previous range ends. Index is the position of the offending range in the slice passed in.

func (*IncludedRangesError) Error

func (e *IncludedRangesError) Error() string

type InputEdit

type InputEdit struct {
	StartByte   int
	OldEndByte  int
	NewEndByte  int
	StartPoint  Point
	OldEndPoint Point
	NewEndPoint Point
}

InputEdit describes a change to a source text. StartByte and StartPoint must not exceed the old end byte and point.

type InputEncoding

type InputEncoding int32

InputEncoding is the text encoding of parser input.

Input encodings. Custom requires a decode function and is not supported by this package.

type Language

type Language struct {
	// contains filtered or unexported fields
}

Language is a grammar: the set of node types, fields, and parse states a Parser uses. Languages live for the life of the process and need not be closed.

func FindLanguage

func FindLanguage(name string) (*Language, error)

FindLanguage locates and loads the grammar for the named language. The name is the grammar's own, as in tree_sitter_<name>: "c", "cpp", "c_sharp", "typescript". Set TREE_SITTER_GRAMMAR_PATH to search extra directories; see GrammarDirs for the full list. Loaded languages are cached, so repeated calls with the same name return the same *Language.

Example

ExampleFindLanguage parses a Swift file that uses MLX and lists the types it declares, the functions and methods with their parameter types, and every call into the MLX namespace. The Swift grammar is found through the usual grammar directories or TREE_SITTER_GRAMMAR_PATH.

package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/treesitter"
)

func main() {
	src := []byte(`import MLX
import MLXNN
import MLXRandom

class MLP: Module {
    @ModuleInfo var up: Linear
    @ModuleInfo var down: Linear

    init(dimensions: Int, hidden: Int) {
        up = Linear(dimensions, hidden)
        down = Linear(hidden, dimensions)
    }

    func callAsFunction(_ x: MLXArray) -> MLXArray {
        down(gelu(up(x)))
    }
}

func loss(model: MLP, x: MLXArray, y: MLXArray) -> MLXArray {
    MLX.mean(MLX.square(model(x) - y))
}

let model = MLP(dimensions: 8, hidden: 32)
let x = MLXRandom.normal([16, 8])
let grads = MLX.grad(loss)(model, x, x)
eval(grads)
`)

	lang, err := treesitter.FindLanguage("swift")
	if err != nil {
		log.Fatal(err)
	}
	tree, err := treesitter.Parse(lang, src)
	if err != nil {
		log.Fatal(err)
	}
	defer tree.Close()
	if tree.HasError() {
		log.Fatal("parse error")
	}

	// Declarations: a class or struct, each function with its parameters'
	// types, and calls into the MLX namespace. The #eq? predicate on the
	// last pattern is applied by Matches.
	q, err := treesitter.NewQuery(lang, `
(class_declaration name: (type_identifier) @class)
(function_declaration name: (simple_identifier) @func)
(function_declaration
  (parameter (simple_identifier) @param . (user_type) @param.type))
(navigation_expression
  target: (simple_identifier) @module
  suffix: (navigation_suffix (simple_identifier) @member)
  (#eq? @module "MLX"))`)
	if err != nil {
		log.Fatal(err)
	}
	defer q.Close()

	for m := range q.Matches(tree.RootNode()) {
		for _, c := range m.Captures {
			if c.Name == "module" {
				continue // reported through @member
			}
			fmt.Printf("%s %s at %v\n", c.Name, c.Node.Text(), c.Node.StartPoint())
		}
	}

	// Walk the tree directly for the imports.
	for n := range tree.RootNode().Children() {
		if n.Type() == "import_declaration" {
			fmt.Printf("import %s\n", n.NamedChild(0).Text())
		}
	}
}

func LoadLanguage

func LoadLanguage(path, name string) (*Language, error)

LoadLanguage opens the grammar shared library at path and returns the language exported by its tree_sitter_<name> function. The library stays open for the life of the process.

LoadLanguage rejects a grammar whose ABI version this library cannot parse with.

func NewLanguage

func NewLanguage(ptr uintptr) *Language

NewLanguage wraps a TSLanguage pointer obtained elsewhere, such as from a grammar linked into the program. It returns nil for a zero pointer. The library must already be loaded or loadable; use Load to check.

func (*Language) ABIVersion

func (l *Language) ABIVersion() int

ABIVersion returns the ABI version the grammar was generated with.

func (*Language) FieldCount

func (l *Language) FieldCount() int

FieldCount returns the number of distinct field names.

func (*Language) FieldID

func (l *Language) FieldID(name string) FieldID

FieldID returns the id of a field name, or 0 when the language has no such field.

func (*Language) FieldName

func (l *Language) FieldName(id FieldID) string

FieldName returns the name of a field, or "" for an unknown id.

func (*Language) Name

func (l *Language) Name() string

Name returns the language's name, or "" for a grammar generated before names were recorded.

func (*Language) NextState

func (l *Language) NextState(state StateID, symbol Symbol) StateID

NextState returns the parse state reached from state by shifting symbol. Together with LookaheadIterator it drives error recovery and completion.

func (*Language) Pointer

func (l *Language) Pointer() uintptr

Pointer returns the underlying TSLanguage pointer.

func (*Language) StateCount

func (l *Language) StateCount() int

StateCount returns the number of valid parse states.

func (*Language) Subtypes

func (l *Language) Subtypes(supertype Symbol) []Symbol

Subtypes returns the symbols a supertype can expand to.

func (*Language) Supertypes

func (l *Language) Supertypes() []Symbol

Supertypes returns the language's supertype symbols.

func (*Language) SymbolCount

func (l *Language) SymbolCount() int

SymbolCount returns the number of distinct node types.

func (*Language) SymbolForName

func (l *Language) SymbolForName(name string, named bool) Symbol

SymbolForName returns the symbol for a node type name. Named selects between named and anonymous node types of the same spelling. It returns 0 when the language has no such type.

func (*Language) SymbolName

func (l *Language) SymbolName(s Symbol) string

SymbolName returns the name of a node type.

func (*Language) SymbolType

func (l *Language) SymbolType(s Symbol) SymbolType

SymbolType classifies a node type.

func (*Language) Version

func (l *Language) Version() (major, minor, patch uint8, ok bool)

Version returns the grammar's semantic version. ok is false when the grammar records no version.

type LogType

type LogType int32

LogType classifies parser log messages.

const (
	LogParse LogType = LogType(ts.LogParse)
	LogLex   LogType = LogType(ts.LogLex)
)

Log types.

func (LogType) String

func (t LogType) String() string

String returns the name of the log type.

type LookaheadIterator

type LookaheadIterator struct {
	// contains filtered or unexported fields
}

LookaheadIterator enumerates the symbols valid in a parse state, which is the basis of syntax-aware completion and error messages. It owns C memory and must be closed.

func NewLookaheadIterator

func NewLookaheadIterator(lang *Language, state StateID) (*LookaheadIterator, error)

NewLookaheadIterator returns an iterator over the symbols valid in state. It fails for a state the language does not have.

func (*LookaheadIterator) Close

func (it *LookaheadIterator) Close()

Close frees the iterator.

func (*LookaheadIterator) CurrentSymbol

func (it *LookaheadIterator) CurrentSymbol() Symbol

CurrentSymbol returns the symbol the iterator is on.

func (*LookaheadIterator) CurrentSymbolName

func (it *LookaheadIterator) CurrentSymbolName() string

CurrentSymbolName returns the name of the symbol the iterator is on.

func (*LookaheadIterator) Language

func (it *LookaheadIterator) Language() *Language

Language returns the iterator's language.

func (*LookaheadIterator) Next

func (it *LookaheadIterator) Next() bool

Next advances to the next symbol and reports whether there was one.

func (*LookaheadIterator) Reset

func (it *LookaheadIterator) Reset(lang *Language, state StateID) bool

Reset restarts the iterator at a state of another language. It reports false for an invalid state.

func (*LookaheadIterator) ResetState

func (it *LookaheadIterator) ResetState(state StateID) bool

ResetState restarts the iterator at another state of the same language. It reports false for an invalid state.

func (*LookaheadIterator) Symbols

func (it *LookaheadIterator) Symbols() iter.Seq[Symbol]

Symbols returns an iterator over the remaining valid symbols.

type Match

type Match struct {
	ID       int
	Pattern  int
	Captures []Capture
}

Match is one match of one query pattern, with its captures named and copied out of the cursor. It is the result of Query.Matches.

func (Match) Node

func (m Match) Node(name string) Node

Node returns the node of the first capture with the given name, or a null node when the match has none.

func (Match) Nodes

func (m Match) Nodes(name string) []Node

Nodes returns the nodes of every capture with the given name, in match order. A capture inside a repetition can match more than once.

func (Match) Text

func (m Match) Text(name string) []byte

Text returns the source text of the first capture with the given name, or nil when the match has none.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node is a node in a Tree. It is a small value that refers into the tree and is valid only while the tree is open. The zero Node is null; every method accepts a null node and returns its zero result, so a missing child or field can be used without checking first.

func (Node) Child

func (n Node) Child(i int) Node

Child returns the i'th child, or a null node when out of range.

func (Node) ChildByFieldID

func (n Node) ChildByFieldID(id FieldID) Node

ChildByFieldID returns the child with the given field id, or a null node.

func (Node) ChildByFieldName

func (n Node) ChildByFieldName(name string) Node

ChildByFieldName returns the child with the given field name, or a null node.

func (Node) ChildCount

func (n Node) ChildCount() int

ChildCount returns the number of children, named and anonymous.

func (Node) ChildWithDescendant

func (n Node) ChildWithDescendant(descendant Node) Node

ChildWithDescendant returns the child that contains descendant.

func (Node) Children

func (n Node) Children() iter.Seq[Node]

Children returns an iterator over all children in order.

func (Node) DescendantCount

func (n Node) DescendantCount() int

DescendantCount returns the number of descendants, including the node itself.

func (Node) DescendantForByteRange

func (n Node) DescendantForByteRange(start, end int) Node

DescendantForByteRange returns the smallest descendant spanning the byte range.

func (Node) DescendantForPointRange

func (n Node) DescendantForPointRange(start, end Point) Node

DescendantForPointRange returns the smallest descendant spanning the point range.

func (Node) Descendants

func (n Node) Descendants() iter.Seq[Node]

Descendants returns an iterator over every node below n in document (pre-order) order. n itself is not included.

func (*Node) Edit

func (n *Node) Edit(edit InputEdit)

Edit adjusts the node's position for an edit already applied to its tree with Tree.Edit. It is needed only for nodes retained across the edit; nodes fetched afterwards are already correct.

func (Node) EndByte

func (n Node) EndByte() int

EndByte returns the byte offset just past the node's end.

func (Node) EndPoint

func (n Node) EndPoint() Point

EndPoint returns the position just past the node's end.

func (Node) Equal

func (n Node) Equal(other Node) bool

Equal reports whether two nodes are the same node of the same tree.

func (Node) FieldNameForChild

func (n Node) FieldNameForChild(i int) string

FieldNameForChild returns the field name of the i'th child, or "" if the child has none.

func (Node) FieldNameForNamedChild

func (n Node) FieldNameForNamedChild(i int) string

FieldNameForNamedChild returns the field name of the i'th named child, or "" if it has none.

func (Node) FirstChildForByte

func (n Node) FirstChildForByte(b int) Node

FirstChildForByte returns the first child that extends past the byte offset.

func (Node) FirstNamedChildForByte

func (n Node) FirstNamedChildForByte(b int) Node

FirstNamedChildForByte returns the first named child that extends past the byte offset.

func (Node) GrammarSymbol

func (n Node) GrammarSymbol() Symbol

GrammarSymbol returns the symbol as written in the grammar, before any alias is applied.

func (Node) GrammarType

func (n Node) GrammarType() string

GrammarType returns the type name as written in the grammar, before any alias is applied.

func (Node) HasChanges

func (n Node) HasChanges() bool

HasChanges reports whether the node was edited since the tree was parsed.

func (Node) HasError

func (n Node) HasError() bool

HasError reports whether the node or any descendant is a syntax error.

func (Node) IsError

func (n Node) IsError() bool

IsError reports whether the node itself is a syntax error.

func (Node) IsExtra

func (n Node) IsExtra() bool

IsExtra reports whether the node is an extra, such as a comment, that the grammar allows anywhere.

func (Node) IsMissing

func (n Node) IsMissing() bool

IsMissing reports whether the parser inserted the node to recover from an error.

func (Node) IsNamed

func (n Node) IsNamed() bool

IsNamed reports whether the node is a named node rather than an anonymous one such as punctuation.

func (Node) IsNull

func (n Node) IsNull() bool

IsNull reports whether the node is null, which is how absent parents, children, and siblings are reported.

func (Node) Language

func (n Node) Language() *Language

Language returns the language of the node's tree.

func (Node) NamedChild

func (n Node) NamedChild(i int) Node

NamedChild returns the i'th named child.

func (Node) NamedChildCount

func (n Node) NamedChildCount() int

NamedChildCount returns the number of named children.

func (Node) NamedChildren

func (n Node) NamedChildren() iter.Seq[Node]

NamedChildren returns an iterator over the named children in order.

func (Node) NamedDescendantForByteRange

func (n Node) NamedDescendantForByteRange(start, end int) Node

NamedDescendantForByteRange returns the smallest named descendant spanning the byte range.

func (Node) NamedDescendantForPointRange

func (n Node) NamedDescendantForPointRange(start, end Point) Node

NamedDescendantForPointRange returns the smallest named descendant spanning the point range.

func (Node) NextNamedSibling

func (n Node) NextNamedSibling() Node

NextNamedSibling returns the following named sibling, or a null node.

func (Node) NextParseState

func (n Node) NextParseState() StateID

NextParseState returns the parse state after the node.

func (Node) NextSibling

func (n Node) NextSibling() Node

NextSibling returns the following sibling, or a null node.

func (Node) Parent

func (n Node) Parent() Node

Parent returns the node's parent, or a null node at the root.

func (Node) ParseState

func (n Node) ParseState() StateID

ParseState returns the parse state the node was created in.

func (Node) PrevNamedSibling

func (n Node) PrevNamedSibling() Node

PrevNamedSibling returns the preceding named sibling, or a null node.

func (Node) PrevSibling

func (n Node) PrevSibling() Node

PrevSibling returns the preceding sibling, or a null node.

func (Node) Range

func (n Node) Range() Range

Range returns the node's extent in bytes and points.

func (Node) StartByte

func (n Node) StartByte() int

StartByte returns the byte offset where the node begins.

func (Node) StartPoint

func (n Node) StartPoint() Point

StartPoint returns the position where the node begins.

func (Node) String

func (n Node) String() string

String returns the node's subtree as an S-expression.

func (Node) Symbol

func (n Node) Symbol() Symbol

Symbol returns the node's type as a symbol.

func (Node) Text

func (n Node) Text() []byte

Text returns the node's source text, taken from the source its tree was parsed from. It returns nil for a null node, for a tree with no source, and for a node that lies outside the source, which happens when the text has been edited since the parse.

func (Node) Tree

func (n Node) Tree() *Tree

Tree returns the tree the node belongs to, or nil for a null node.

func (Node) Type

func (n Node) Type() string

Type returns the node's type name.

func (Node) Walk

func (n Node) Walk() *TreeCursor

Walk returns a cursor positioned at the node.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser turns source text into a Tree. A Parser is not safe for concurrent use.

func NewParser

func NewParser() (*Parser, error)

NewParser returns a parser with no language set.

func (*Parser) Close

func (p *Parser) Close()

Close frees the parser. Trees it produced remain valid.

func (*Parser) IncludedRanges

func (p *Parser) IncludedRanges() []Range

IncludedRanges returns the ranges the parser is restricted to. With no restriction it returns one range covering the whole document.

func (*Parser) Language

func (p *Parser) Language() *Language

Language returns the parser's language, or nil if none is set.

func (*Parser) Parse

func (p *Parser) Parse(src []byte, old *Tree) (*Tree, error)

Parse parses UTF-8 source. old, if non-nil, is a tree from a previous parse of the same document, already updated with Tree.Edit; passing it makes the parse incremental. The source is read only during the call.

func (*Parser) ParseContext

func (p *Parser) ParseContext(ctx context.Context, src []byte, old *Tree) (*Tree, error)

ParseContext is like Parse but stops when ctx is done, returning ctx's error. Cancellation is checked as parsing progresses, so a very small input may finish before the context is observed.

func (*Parser) ParseEncoding

func (p *Parser) ParseEncoding(src []byte, enc InputEncoding, old *Tree) (*Tree, error)

ParseEncoding is like Parse for UTF-8 or UTF-16 source.

func (*Parser) ParseInput

func (p *Parser) ParseInput(read func(byteIndex int, pos Point) []byte, enc InputEncoding, old *Tree) (*Tree, error)

ParseInput parses text supplied by read, which returns the text starting at byteIndex, or nil at the end of the document. pos is the same position as a point. read may return the text in chunks of any size; returned slices are copied before tree-sitter sees them.

tree-sitter reads by byte offset and revisits earlier offsets, so read must serve any offset it has already been asked for, not only advancing ones. The resulting tree has no source, so Node.Text returns nil for its nodes.

func (*Parser) ParseReaderAt

func (p *Parser) ParseReaderAt(r io.ReaderAt, size int64, old *Tree) (*Tree, error)

ParseReaderAt parses the first size bytes of r.

tree-sitter reads its input by byte offset and revisits earlier offsets, so the input must support random access; that is why this takes an io.ReaderAt rather than an io.Reader. A *bytes.Reader, *strings.Reader, *os.File, or *io.SectionReader satisfies it directly.

Only a window of the document is held in memory, so the tree has no source and Node.Text returns nil for its nodes. Read the file into memory and use Parser.Parse when the text is wanted afterwards.

func (*Parser) PrintDotGraphs

func (p *Parser) PrintDotGraphs(f *os.File) error

PrintDotGraphs makes the parser write a Graphviz graph of its state to f after each parse step until StopPrintingDotGraphs or Close. The parser writes through its own duplicate of f's descriptor, so f may be closed once PrintDotGraphs returns.

func (*Parser) Reset

func (p *Parser) Reset()

Reset discards the state of an interrupted parse so that the next Parse starts from the beginning.

func (*Parser) SetIncludedRanges

func (p *Parser) SetIncludedRanges(ranges []Range) error

SetIncludedRanges restricts parsing to the given byte ranges of the document, for example the code blocks of a template. Ranges must be ordered and non-overlapping; a violation is reported as an *IncludedRangesError. An empty slice parses the whole document.

func (*Parser) SetLanguage

func (p *Parser) SetLanguage(lang *Language) error

SetLanguage selects the grammar to parse with. It fails when the grammar's ABI version is incompatible with the library.

func (*Parser) SetLogger

func (p *Parser) SetLogger(fn func(kind LogType, msg string))

SetLogger installs a function that receives the parser's log messages, or removes it when fn is nil.

func (*Parser) StopPrintingDotGraphs

func (p *Parser) StopPrintingDotGraphs()

StopPrintingDotGraphs stops the output started by PrintDotGraphs and closes the parser's duplicate descriptor. Close calls it.

type Point

type Point struct {
	Row    int
	Column int
}

Point is a position in source text: a zero-based row and a zero-based byte column within that row.

func (Point) String

func (p Point) String() string

String returns the point as row:column.

type Predicate

type Predicate struct {
	Operator string
	Args     []PredicateArg
}

Predicate is a query predicate such as (#eq? @a "b"). Operator is the name without its leading #, so it ends in ? for a predicate and ! for a directive: "eq?", "match?", "any-of?", "set!".

Query.Satisfies evaluates the text predicates tree-sitter defines. Every other predicate, including #set! and #is?, is reported here for the caller to interpret and does not affect matching.

func (Predicate) String

func (p Predicate) String() string

String returns the predicate in query syntax.

type PredicateArg

type PredicateArg struct {
	Capture string // capture name; "" when the argument is a literal
	Literal string // literal text; meaningful when Capture is ""
}

PredicateArg is one argument of a Predicate: either a capture, named without its leading @, or a string literal.

func (PredicateArg) IsCapture

func (a PredicateArg) IsCapture() bool

IsCapture reports whether the argument names a capture.

func (PredicateArg) String

func (a PredicateArg) String() string

String returns the argument in query syntax.

type Property

type Property struct {
	Key     string
	Value   string
	Capture string // "" when the property applies to the whole pattern
	Negate  bool   // true for #is-not?
}

Property is a (#set! key value) directive, or an (#is? key value) assertion, attached either to a capture or to the pattern as a whole. Value is empty for a key with no value.

type Quantifier

type Quantifier int32

Quantifier describes how many times a query capture may occur.

const (
	QuantifierZero       Quantifier = Quantifier(ts.QuantifierZero)
	QuantifierZeroOrOne  Quantifier = Quantifier(ts.QuantifierZeroOrOne)
	QuantifierZeroOrMore Quantifier = Quantifier(ts.QuantifierZeroOrMore)
	QuantifierOne        Quantifier = Quantifier(ts.QuantifierOne)
	QuantifierOneOrMore  Quantifier = Quantifier(ts.QuantifierOneOrMore)
)

Quantifiers.

func (Quantifier) String

func (q Quantifier) String() string

String returns the quantifier in query syntax.

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query is a compiled set of tree patterns. A query owns C memory and must be closed.

func NewQuery

func NewQuery(lang *Language, source string) (*Query, error)

NewQuery compiles source, in tree-sitter's query language, for lang. A compile failure is reported as a *QueryError.

func NewQueryFS

func NewQueryFS(lang *Language, fsys fs.FS, name string) (*Query, error)

NewQueryFS compiles the query stored at name in fsys. Queries are ordinary text, so a query set can be kept in files and embedded with go:embed.

func (*Query) CaptureCount

func (q *Query) CaptureCount() int

CaptureCount returns the number of distinct capture names.

func (*Query) CaptureName

func (q *Query) CaptureName(id int) string

CaptureName returns the name of capture id.

func (*Query) CaptureNames

func (q *Query) CaptureNames() []string

CaptureNames returns the query's capture names, indexed by capture id.

func (*Query) CaptureQuantifier

func (q *Query) CaptureQuantifier(pattern, id int) Quantifier

CaptureQuantifier returns how many times capture id may occur in pattern.

func (*Query) Captures

func (q *Query) Captures(root Node) iter.Seq2[Match, Capture]

Captures runs the query over root's subtree and yields every capture in document order, each with the match it belongs to. Highlighting wants this order; Query.Matches groups by match instead.

func (*Query) Close

func (q *Query) Close()

Close frees the query.

func (*Query) DisableCapture

func (q *Query) DisableCapture(name string)

DisableCapture stops the query from reporting the named capture.

func (*Query) DisablePattern

func (q *Query) DisablePattern(i int)

DisablePattern stops the query from matching pattern i.

func (*Query) EndByteForPattern

func (q *Query) EndByteForPattern(i int) int

EndByteForPattern returns where pattern i ends in the query source.

func (*Query) IsPatternGuaranteedAtStep

func (q *Query) IsPatternGuaranteedAtStep(byteOffset int) bool

IsPatternGuaranteedAtStep reports whether a pattern is certain to match once the query has reached the given byte offset of its source.

func (*Query) IsPatternNonLocal

func (q *Query) IsPatternNonLocal(i int) bool

IsPatternNonLocal reports whether pattern i can match nodes that are not direct descendants of a single node.

func (*Query) IsPatternRooted

func (q *Query) IsPatternRooted(i int) bool

IsPatternRooted reports whether pattern i has a single root node.

func (*Query) Matches

func (q *Query) Matches(root Node) iter.Seq[Match]

Matches runs the query over root's subtree and yields the matches whose text predicates hold. It manages its own cursor, which is released when the loop ends, including on an early break.

Use QueryCursor directly to reuse a cursor, to restrict the search to a byte or point range, or to see matches that predicates reject.

func (*Query) MatchesContext

func (q *Query) MatchesContext(ctx context.Context, root Node) iter.Seq2[Match, error]

MatchesContext is like Query.Matches but stops when ctx is done. It yields each match with a nil error, then a single zero match with ctx's error if the search was cancelled. When cancellation happens as the last match is produced, the error may follow a complete set of results.

func (*Query) PatternCount

func (q *Query) PatternCount() int

PatternCount returns the number of patterns.

func (*Query) Predicates

func (q *Query) Predicates(i int) []Predicate

Predicates returns the predicates of pattern i, in source order, including those the package does not evaluate.

func (*Query) Properties

func (q *Query) Properties(i int) []Property

Properties returns the #set!, #is?, and #is-not? properties of pattern i. They carry information for the caller, such as a highlight name, and do not affect matching.

func (*Query) Satisfies

func (q *Query) Satisfies(m QueryMatch) bool

Satisfies reports whether m meets the text predicates of its pattern: #eq?, #match?, and #any-of?, with their not-, any-, and any-not- forms. Other predicates are ignored.

Evaluation reads the source text of captured nodes. When the tree has no source, as after Parser.ParseInput, there is nothing to compare and Satisfies reports true.

func (*Query) StartByteForPattern

func (q *Query) StartByteForPattern(i int) int

StartByteForPattern returns where pattern i begins in the query source.

func (*Query) StringCount

func (q *Query) StringCount() int

StringCount returns the number of distinct string literals.

func (*Query) StringValue

func (q *Query) StringValue(id int) string

StringValue returns the string literal with the given id.

type QueryCapture

type QueryCapture struct {
	Node  Node
	Index int // capture id; see Query.CaptureName
}

QueryCapture is a node matched by a named capture.

type QueryCursor

type QueryCursor struct {
	// contains filtered or unexported fields
}

QueryCursor runs a Query over a subtree. A cursor owns C memory and must be closed. It may be reused for many queries.

func NewQueryCursor

func NewQueryCursor() (*QueryCursor, error)

NewQueryCursor returns a cursor with no query executing.

func (*QueryCursor) Captures

func (c *QueryCursor) Captures() iter.Seq2[QueryMatch, QueryCapture]

Captures returns an iterator over the remaining captures of the current execution in document order, each paired with the match it belongs to.

func (*QueryCursor) Close

func (c *QueryCursor) Close()

Close frees the cursor.

func (*QueryCursor) DidExceedMatchLimit

func (c *QueryCursor) DidExceedMatchLimit() bool

DidExceedMatchLimit reports whether matches were dropped because the limit was reached.

func (*QueryCursor) Exec

func (c *QueryCursor) Exec(q *Query, node Node)

Exec starts running q over node's subtree. Results come from NextMatch or NextCapture.

func (*QueryCursor) ExecContext

func (c *QueryCursor) ExecContext(ctx context.Context, q *Query, node Node)

ExecContext is like Exec but stops producing results once ctx is done. tree-sitter polls the context as it advances, so NextMatch and NextCapture return ok false soon after cancellation; callers that need to tell cancellation from exhaustion check ctx.Err. The context is released by the next Exec, ExecContext, or Close.

func (*QueryCursor) MatchLimit

func (c *QueryCursor) MatchLimit() int

MatchLimit returns the cap on in-progress matches.

func (*QueryCursor) Matches

func (c *QueryCursor) Matches() iter.Seq[QueryMatch]

Matches returns an iterator over the remaining matches of the current execution, started by Exec or ExecContext. Ranging over it consumes the matches; a later NextMatch continues where the loop stopped.

func (*QueryCursor) NextCapture

func (c *QueryCursor) NextCapture() (m QueryMatch, captureIndex int, ok bool)

NextCapture returns the next capture in document order along with the match it belongs to, or ok false when there are no more.

func (*QueryCursor) NextMatch

func (c *QueryCursor) NextMatch() (m QueryMatch, ok bool)

NextMatch returns the next match, or ok false when there are no more.

func (*QueryCursor) RemoveMatch

func (c *QueryCursor) RemoveMatch(id int)

RemoveMatch discards an in-progress match by id, freeing its resources.

func (*QueryCursor) SetByteRange

func (c *QueryCursor) SetByteRange(start, end int) bool

SetByteRange restricts results to nodes within the byte range. It reports false if the range is invalid.

func (*QueryCursor) SetContainingByteRange

func (c *QueryCursor) SetContainingByteRange(start, end int) bool

SetContainingByteRange restricts results to nodes that contain the byte range. It reports false if the range is invalid.

func (*QueryCursor) SetContainingPointRange

func (c *QueryCursor) SetContainingPointRange(start, end Point) bool

SetContainingPointRange restricts results to nodes that contain the point range. It reports false if the range is invalid.

func (*QueryCursor) SetMatchLimit

func (c *QueryCursor) SetMatchLimit(limit int)

SetMatchLimit caps the number of in-progress matches. The default is unlimited.

func (*QueryCursor) SetMaxStartDepth

func (c *QueryCursor) SetMaxStartDepth(depth int)

SetMaxStartDepth limits how far below the node passed to Exec a pattern may start matching. Zero matches only that node.

func (*QueryCursor) SetPointRange

func (c *QueryCursor) SetPointRange(start, end Point) bool

SetPointRange restricts results to nodes within the point range. It reports false if the range is invalid.

type QueryError

type QueryError struct {
	Kind    QueryErrorKind
	Offset  int
	Row     int
	Column  int
	Message string
}

QueryError reports why a query failed to compile and where. Offset is the byte offset into the query source; Row and Column locate the same byte as a zero-based line and column. Message, when set, says what was wrong with a predicate.

func (*QueryError) Error

func (e *QueryError) Error() string

type QueryErrorKind

type QueryErrorKind int32

QueryErrorKind classifies a query compilation error.

func (QueryErrorKind) String

func (k QueryErrorKind) String() string

String returns the name of the error kind.

type QueryMatch

type QueryMatch struct {
	ID           int
	PatternIndex int
	Captures     []QueryCapture
}

QueryMatch is one match of one pattern.

type Range

type Range struct {
	StartPoint Point
	EndPoint   Point
	StartByte  int
	EndByte    int
}

Range is a span of source text, in both bytes and points.

type StateID

type StateID uint16

StateID identifies a parse state within a language.

type Symbol

type Symbol uint16

Symbol identifies a node type within a language.

type SymbolType

type SymbolType int32

SymbolType classifies a language's symbols.

const (
	SymbolRegular   SymbolType = SymbolType(ts.SymbolRegular)
	SymbolAnonymous SymbolType = SymbolType(ts.SymbolAnonymous)
	SymbolSupertype SymbolType = SymbolType(ts.SymbolSupertype)
	SymbolAuxiliary SymbolType = SymbolType(ts.SymbolAuxiliary)
)

Symbol types.

func (SymbolType) String

func (t SymbolType) String() string

String returns the name of the symbol type.

type Tree

type Tree struct {
	// contains filtered or unexported fields
}

Tree is a syntax tree. Trees own C memory and must be closed.

A tree keeps a reference to the source text it was parsed from, so Node.Text needs no argument. The source must not be modified while the tree is open. A tree parsed by Parser.ParseInput has no source.

func Parse

func Parse(lang *Language, src []byte) (*Tree, error)

Parse parses src with lang. It is shorthand for creating a parser, setting its language, and closing it; use a Parser directly to parse more than once, to parse incrementally, or to set options.

func ParseFile

func ParseFile(path string) (*Tree, error)

ParseFile reads the file at path, chooses a grammar from its name with DetectLanguage, finds it with FindLanguage, and parses it. The resulting tree carries the file's contents as its source.

Example

ExampleParseFile parses a file chosen by its name and reports any syntax errors it contains.

package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/treesitter"
)

func main() {
	tree, err := treesitter.ParseFile("main.go")
	if err != nil {
		log.Fatal(err)
	}
	defer tree.Close()
	for n := range tree.Errors() {
		fmt.Printf("%v: %s\n", n.StartPoint(), n.Type())
	}
}

func (*Tree) ChangedRanges

func (t *Tree) ChangedRanges(newTree *Tree) []Range

ChangedRanges returns the ranges whose syntax differs between t and newTree, where newTree came from an incremental parse using t.

func (*Tree) Close

func (t *Tree) Close()

Close frees the tree. Nodes obtained from it become invalid.

func (*Tree) Copy

func (t *Tree) Copy() *Tree

Copy returns a shallow copy that can be closed and edited independently, for use from another goroutine. The copy shares the original's source.

func (*Tree) Edit

func (t *Tree) Edit(edit InputEdit)

Edit records a change to the source text so that the tree's node positions stay correct and a following incremental parse can reuse unchanged nodes. It does not update Tree.Source; pass the new text to the next parse.

Example

ExampleTree_Edit re-parses a document incrementally after a change.

package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/treesitter"
)

func main() {
	lang, err := treesitter.FindLanguage("c")
	if err != nil {
		log.Fatal(err)
	}
	p, err := treesitter.NewParser()
	if err != nil {
		log.Fatal(err)
	}
	defer p.Close()
	if err := p.SetLanguage(lang); err != nil {
		log.Fatal(err)
	}

	old, err := p.Parse([]byte("int x;"), nil)
	if err != nil {
		log.Fatal(err)
	}
	defer old.Close()

	// Replace "x" with "count".
	old.Edit(treesitter.InputEdit{
		StartByte: 4, OldEndByte: 5, NewEndByte: 9,
		StartPoint:  treesitter.Point{Row: 0, Column: 4},
		OldEndPoint: treesitter.Point{Row: 0, Column: 5},
		NewEndPoint: treesitter.Point{Row: 0, Column: 9},
	})
	tree, err := p.Parse([]byte("int count;"), old)
	if err != nil {
		log.Fatal(err)
	}
	defer tree.Close()
	for _, r := range old.ChangedRanges(tree) {
		fmt.Printf("changed bytes %d-%d\n", r.StartByte, r.EndByte)
	}
}

func (*Tree) Errors

func (t *Tree) Errors() iter.Seq[Node]

Errors returns an iterator over the tree's error and missing nodes, in document order. It descends only into subtrees that contain an error, so a tree that parsed cleanly costs one check.

func (*Tree) HasError

func (t *Tree) HasError() bool

HasError reports whether the parse found any syntax error. tree-sitter always produces a tree, so this is how a failed parse is detected.

func (*Tree) IncludedRanges

func (t *Tree) IncludedRanges() []Range

IncludedRanges returns the ranges of the document the tree covers.

func (*Tree) Language

func (t *Tree) Language() *Language

Language returns the language the tree was parsed with.

func (*Tree) PrintDotGraph

func (t *Tree) PrintDotGraph(fd int)

PrintDotGraph writes a Graphviz graph of the tree to fd.

func (*Tree) RootNode

func (t *Tree) RootNode() Node

RootNode returns the tree's root.

func (*Tree) RootNodeWithOffset

func (t *Tree) RootNodeWithOffset(offsetBytes int, offsetExtent Point) Node

RootNodeWithOffset returns the root with its position shifted by the given byte offset and point, for a tree that describes part of a larger document.

func (*Tree) Source

func (t *Tree) Source() []byte

Source returns the text the tree was parsed from, or nil if it is not known. The result aliases the caller's slice and must not be modified.

type TreeCursor

type TreeCursor struct {
	// contains filtered or unexported fields
}

TreeCursor walks a tree more efficiently than repeated Node calls. A cursor owns C memory and must be closed.

func NewTreeCursor

func NewTreeCursor(node Node) *TreeCursor

NewTreeCursor returns a cursor positioned at node.

func (*TreeCursor) Close

func (c *TreeCursor) Close()

Close frees the cursor.

func (*TreeCursor) Copy

func (c *TreeCursor) Copy() *TreeCursor

Copy returns a cursor at the same position.

func (*TreeCursor) CurrentDepth

func (c *TreeCursor) CurrentDepth() int

CurrentDepth returns the depth of the current node below the node the cursor was created at.

func (*TreeCursor) CurrentDescendantIndex

func (c *TreeCursor) CurrentDescendantIndex() int

CurrentDescendantIndex returns the index of the current node among the descendants of the node the cursor was created at, in pre-order.

func (*TreeCursor) CurrentFieldID

func (c *TreeCursor) CurrentFieldID() FieldID

CurrentFieldID returns the field id of the current node, or 0.

func (*TreeCursor) CurrentFieldName

func (c *TreeCursor) CurrentFieldName() string

CurrentFieldName returns the field name of the current node, or "".

func (*TreeCursor) CurrentNode

func (c *TreeCursor) CurrentNode() Node

CurrentNode returns the node the cursor is on.

func (*TreeCursor) GotoDescendant

func (c *TreeCursor) GotoDescendant(index int)

GotoDescendant moves to the descendant with the given pre-order index.

func (*TreeCursor) GotoFirstChild

func (c *TreeCursor) GotoFirstChild() bool

GotoFirstChild moves to the first child and reports whether there was one.

func (*TreeCursor) GotoFirstChildForByte

func (c *TreeCursor) GotoFirstChildForByte(b int) (index int, ok bool)

GotoFirstChildForByte moves to the first child that extends past the byte offset and returns its index, or ok false if there is none.

func (*TreeCursor) GotoFirstChildForPoint

func (c *TreeCursor) GotoFirstChildForPoint(p Point) (index int, ok bool)

GotoFirstChildForPoint moves to the first child that extends past the point and returns its index, or ok false if there is none.

func (*TreeCursor) GotoLastChild

func (c *TreeCursor) GotoLastChild() bool

GotoLastChild moves to the last child and reports whether there was one.

func (*TreeCursor) GotoNextSibling

func (c *TreeCursor) GotoNextSibling() bool

GotoNextSibling moves to the next sibling and reports whether there was one.

func (*TreeCursor) GotoParent

func (c *TreeCursor) GotoParent() bool

GotoParent moves to the parent and reports whether there was one.

func (*TreeCursor) GotoPreviousSibling

func (c *TreeCursor) GotoPreviousSibling() bool

GotoPreviousSibling moves to the previous sibling and reports whether there was one.

func (*TreeCursor) Reset

func (c *TreeCursor) Reset(node Node)

Reset repositions the cursor at node, which may be in another tree.

func (*TreeCursor) ResetTo

func (c *TreeCursor) ResetTo(src *TreeCursor)

ResetTo repositions the cursor at src's position.

Directories

Path Synopsis
Package grammars builds tree-sitter grammars from pinned source archives and installs them where treesitter.FindLanguage looks.
Package grammars builds tree-sitter grammars from pinned source archives and installs them where treesitter.FindLanguage looks.
internal
ts
Package ts provides low-level Go bindings for the tree-sitter C API.
Package ts provides low-level Go bindings for the tree-sitter C API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL