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"))
}
}
Output:
Index ¶
- Constants
- Variables
- func DetectLanguage(filename string) string
- func FindGrammar(name string) (string, error)
- func GrammarDirs() []string
- func LibraryPath() string
- func Load(path string) error
- func Loaded() bool
- func SlogLogger(l *slog.Logger) func(LogType, string)
- type Capture
- type FieldID
- type GrammarNotFoundError
- type IncludedRangesError
- type InputEdit
- type InputEncoding
- type Language
- func (l *Language) ABIVersion() int
- func (l *Language) FieldCount() int
- func (l *Language) FieldID(name string) FieldID
- func (l *Language) FieldName(id FieldID) string
- func (l *Language) Name() string
- func (l *Language) NextState(state StateID, symbol Symbol) StateID
- func (l *Language) Pointer() uintptr
- func (l *Language) StateCount() int
- func (l *Language) Subtypes(supertype Symbol) []Symbol
- func (l *Language) Supertypes() []Symbol
- func (l *Language) SymbolCount() int
- func (l *Language) SymbolForName(name string, named bool) Symbol
- func (l *Language) SymbolName(s Symbol) string
- func (l *Language) SymbolType(s Symbol) SymbolType
- func (l *Language) Version() (major, minor, patch uint8, ok bool)
- type LogType
- type LookaheadIterator
- func (it *LookaheadIterator) Close()
- func (it *LookaheadIterator) CurrentSymbol() Symbol
- func (it *LookaheadIterator) CurrentSymbolName() string
- func (it *LookaheadIterator) Language() *Language
- func (it *LookaheadIterator) Next() bool
- func (it *LookaheadIterator) Reset(lang *Language, state StateID) bool
- func (it *LookaheadIterator) ResetState(state StateID) bool
- func (it *LookaheadIterator) Symbols() iter.Seq[Symbol]
- type Match
- type Node
- func (n Node) Child(i int) Node
- func (n Node) ChildByFieldID(id FieldID) Node
- func (n Node) ChildByFieldName(name string) Node
- func (n Node) ChildCount() int
- func (n Node) ChildWithDescendant(descendant Node) Node
- func (n Node) Children() iter.Seq[Node]
- func (n Node) DescendantCount() int
- func (n Node) DescendantForByteRange(start, end int) Node
- func (n Node) DescendantForPointRange(start, end Point) Node
- func (n Node) Descendants() iter.Seq[Node]
- func (n *Node) Edit(edit InputEdit)
- func (n Node) EndByte() int
- func (n Node) EndPoint() Point
- func (n Node) Equal(other Node) bool
- func (n Node) FieldNameForChild(i int) string
- func (n Node) FieldNameForNamedChild(i int) string
- func (n Node) FirstChildForByte(b int) Node
- func (n Node) FirstNamedChildForByte(b int) Node
- func (n Node) GrammarSymbol() Symbol
- func (n Node) GrammarType() string
- func (n Node) HasChanges() bool
- func (n Node) HasError() bool
- func (n Node) IsError() bool
- func (n Node) IsExtra() bool
- func (n Node) IsMissing() bool
- func (n Node) IsNamed() bool
- func (n Node) IsNull() bool
- func (n Node) Language() *Language
- func (n Node) NamedChild(i int) Node
- func (n Node) NamedChildCount() int
- func (n Node) NamedChildren() iter.Seq[Node]
- func (n Node) NamedDescendantForByteRange(start, end int) Node
- func (n Node) NamedDescendantForPointRange(start, end Point) Node
- func (n Node) NextNamedSibling() Node
- func (n Node) NextParseState() StateID
- func (n Node) NextSibling() Node
- func (n Node) Parent() Node
- func (n Node) ParseState() StateID
- func (n Node) PrevNamedSibling() Node
- func (n Node) PrevSibling() Node
- func (n Node) Range() Range
- func (n Node) StartByte() int
- func (n Node) StartPoint() Point
- func (n Node) String() string
- func (n Node) Symbol() Symbol
- func (n Node) Text() []byte
- func (n Node) Tree() *Tree
- func (n Node) Type() string
- func (n Node) Walk() *TreeCursor
- type Parser
- func (p *Parser) Close()
- func (p *Parser) IncludedRanges() []Range
- func (p *Parser) Language() *Language
- func (p *Parser) Parse(src []byte, old *Tree) (*Tree, error)
- func (p *Parser) ParseContext(ctx context.Context, src []byte, old *Tree) (*Tree, error)
- func (p *Parser) ParseEncoding(src []byte, enc InputEncoding, old *Tree) (*Tree, error)
- func (p *Parser) ParseInput(read func(byteIndex int, pos Point) []byte, enc InputEncoding, old *Tree) (*Tree, error)
- func (p *Parser) ParseReaderAt(r io.ReaderAt, size int64, old *Tree) (*Tree, error)
- func (p *Parser) PrintDotGraphs(f *os.File) error
- func (p *Parser) Reset()
- func (p *Parser) SetIncludedRanges(ranges []Range) error
- func (p *Parser) SetLanguage(lang *Language) error
- func (p *Parser) SetLogger(fn func(kind LogType, msg string))
- func (p *Parser) StopPrintingDotGraphs()
- type Point
- type Predicate
- type PredicateArg
- type Property
- type Quantifier
- type Query
- func (q *Query) CaptureCount() int
- func (q *Query) CaptureName(id int) string
- func (q *Query) CaptureNames() []string
- func (q *Query) CaptureQuantifier(pattern, id int) Quantifier
- func (q *Query) Captures(root Node) iter.Seq2[Match, Capture]
- func (q *Query) Close()
- func (q *Query) DisableCapture(name string)
- func (q *Query) DisablePattern(i int)
- func (q *Query) EndByteForPattern(i int) int
- func (q *Query) IsPatternGuaranteedAtStep(byteOffset int) bool
- func (q *Query) IsPatternNonLocal(i int) bool
- func (q *Query) IsPatternRooted(i int) bool
- func (q *Query) Matches(root Node) iter.Seq[Match]
- func (q *Query) MatchesContext(ctx context.Context, root Node) iter.Seq2[Match, error]
- func (q *Query) PatternCount() int
- func (q *Query) Predicates(i int) []Predicate
- func (q *Query) Properties(i int) []Property
- func (q *Query) Satisfies(m QueryMatch) bool
- func (q *Query) StartByteForPattern(i int) int
- func (q *Query) StringCount() int
- func (q *Query) StringValue(id int) string
- type QueryCapture
- type QueryCursor
- func (c *QueryCursor) Captures() iter.Seq2[QueryMatch, QueryCapture]
- func (c *QueryCursor) Close()
- func (c *QueryCursor) DidExceedMatchLimit() bool
- func (c *QueryCursor) Exec(q *Query, node Node)
- func (c *QueryCursor) ExecContext(ctx context.Context, q *Query, node Node)
- func (c *QueryCursor) MatchLimit() int
- func (c *QueryCursor) Matches() iter.Seq[QueryMatch]
- func (c *QueryCursor) NextCapture() (m QueryMatch, captureIndex int, ok bool)
- func (c *QueryCursor) NextMatch() (m QueryMatch, ok bool)
- func (c *QueryCursor) RemoveMatch(id int)
- func (c *QueryCursor) SetByteRange(start, end int) bool
- func (c *QueryCursor) SetContainingByteRange(start, end int) bool
- func (c *QueryCursor) SetContainingPointRange(start, end Point) bool
- func (c *QueryCursor) SetMatchLimit(limit int)
- func (c *QueryCursor) SetMaxStartDepth(depth int)
- func (c *QueryCursor) SetPointRange(start, end Point) bool
- type QueryError
- type QueryErrorKind
- type QueryMatch
- type Range
- type StateID
- type Symbol
- type SymbolType
- type Tree
- func (t *Tree) ChangedRanges(newTree *Tree) []Range
- func (t *Tree) Close()
- func (t *Tree) Copy() *Tree
- func (t *Tree) Edit(edit InputEdit)
- func (t *Tree) Errors() iter.Seq[Node]
- func (t *Tree) HasError() bool
- func (t *Tree) IncludedRanges() []Range
- func (t *Tree) Language() *Language
- func (t *Tree) PrintDotGraph(fd int)
- func (t *Tree) RootNode() Node
- func (t *Tree) RootNodeWithOffset(offsetBytes int, offsetExtent Point) Node
- func (t *Tree) Source() []byte
- type TreeCursor
- func (c *TreeCursor) Close()
- func (c *TreeCursor) Copy() *TreeCursor
- func (c *TreeCursor) CurrentDepth() int
- func (c *TreeCursor) CurrentDescendantIndex() int
- func (c *TreeCursor) CurrentFieldID() FieldID
- func (c *TreeCursor) CurrentFieldName() string
- func (c *TreeCursor) CurrentNode() Node
- func (c *TreeCursor) GotoDescendant(index int)
- func (c *TreeCursor) GotoFirstChild() bool
- func (c *TreeCursor) GotoFirstChildForByte(b int) (index int, ok bool)
- func (c *TreeCursor) GotoFirstChildForPoint(p Point) (index int, ok bool)
- func (c *TreeCursor) GotoLastChild() bool
- func (c *TreeCursor) GotoNextSibling() bool
- func (c *TreeCursor) GotoParent() bool
- func (c *TreeCursor) GotoPreviousSibling() bool
- func (c *TreeCursor) Reset(node Node)
- func (c *TreeCursor) ResetTo(src *TreeCursor)
Examples ¶
Constants ¶
const ( LanguageVersion = 15 MinCompatibleLanguageVersion = 13 )
LanguageVersion is the latest grammar ABI version this library understands, and MinCompatibleLanguageVersion the earliest.
const GrammarPathEnv = "TREE_SITTER_GRAMMAR_PATH"
GrammarPathEnv names the environment variable holding extra directories for FindLanguage, separated by the OS path list separator.
Variables ¶
var ErrNoLanguage = errors.New("treesitter: parser has no language")
ErrNoLanguage is returned by Parse when the parser has no language.
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 ¶
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 ¶
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 ¶
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 SlogLogger ¶
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 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.
const ( UTF8 InputEncoding = InputEncoding(ts.InputEncodingUTF8) UTF16LE InputEncoding = InputEncoding(ts.InputEncodingUTF16LE) UTF16BE InputEncoding = InputEncoding(ts.InputEncodingUTF16BE) )
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 ¶
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())
}
}
}
Output:
func LoadLanguage ¶
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 ¶
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 ¶
ABIVersion returns the ABI version the grammar was generated with.
func (*Language) FieldCount ¶
FieldCount returns the number of distinct field names.
func (*Language) FieldID ¶
FieldID returns the id of a field name, or 0 when the language has no such field.
func (*Language) Name ¶
Name returns the language's name, or "" for a grammar generated before names were recorded.
func (*Language) NextState ¶
NextState returns the parse state reached from state by shifting symbol. Together with LookaheadIterator it drives error recovery and completion.
func (*Language) StateCount ¶
StateCount returns the number of valid parse states.
func (*Language) Supertypes ¶
Supertypes returns the language's supertype symbols.
func (*Language) SymbolCount ¶
SymbolCount returns the number of distinct node types.
func (*Language) SymbolForName ¶
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 ¶
SymbolName returns the name of a node type.
func (*Language) SymbolType ¶
func (l *Language) SymbolType(s Symbol) SymbolType
SymbolType classifies a node 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) 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.
type Match ¶
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 ¶
Node returns the node of the first capture with the given name, or a null node 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) ChildByFieldID ¶
ChildByFieldID returns the child with the given field id, or a null node.
func (Node) ChildByFieldName ¶
ChildByFieldName returns the child with the given field name, or a null node.
func (Node) ChildCount ¶
ChildCount returns the number of children, named and anonymous.
func (Node) ChildWithDescendant ¶
ChildWithDescendant returns the child that contains descendant.
func (Node) DescendantCount ¶
DescendantCount returns the number of descendants, including the node itself.
func (Node) DescendantForByteRange ¶
DescendantForByteRange returns the smallest descendant spanning the byte range.
func (Node) DescendantForPointRange ¶
DescendantForPointRange returns the smallest descendant spanning the point range.
func (Node) Descendants ¶
Descendants returns an iterator over every node below n in document (pre-order) order. n itself is not included.
func (*Node) Edit ¶
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) FieldNameForChild ¶
FieldNameForChild returns the field name of the i'th child, or "" if the child has none.
func (Node) FieldNameForNamedChild ¶
FieldNameForNamedChild returns the field name of the i'th named child, or "" if it has none.
func (Node) FirstChildForByte ¶
FirstChildForByte returns the first child that extends past the byte offset.
func (Node) FirstNamedChildForByte ¶
FirstNamedChildForByte returns the first named child that extends past the byte offset.
func (Node) GrammarSymbol ¶
GrammarSymbol returns the symbol as written in the grammar, before any alias is applied.
func (Node) GrammarType ¶
GrammarType returns the type name as written in the grammar, before any alias is applied.
func (Node) HasChanges ¶
HasChanges reports whether the node was edited since the tree was parsed.
func (Node) IsExtra ¶
IsExtra reports whether the node is an extra, such as a comment, that the grammar allows anywhere.
func (Node) IsMissing ¶
IsMissing reports whether the parser inserted the node to recover from an error.
func (Node) IsNamed ¶
IsNamed reports whether the node is a named node rather than an anonymous one such as punctuation.
func (Node) IsNull ¶
IsNull reports whether the node is null, which is how absent parents, children, and siblings are reported.
func (Node) NamedChild ¶
NamedChild returns the i'th named child.
func (Node) NamedChildCount ¶
NamedChildCount returns the number of named children.
func (Node) NamedChildren ¶
NamedChildren returns an iterator over the named children in order.
func (Node) NamedDescendantForByteRange ¶
NamedDescendantForByteRange returns the smallest named descendant spanning the byte range.
func (Node) NamedDescendantForPointRange ¶
NamedDescendantForPointRange returns the smallest named descendant spanning the point range.
func (Node) NextNamedSibling ¶
NextNamedSibling returns the following named sibling, or a null node.
func (Node) NextParseState ¶
NextParseState returns the parse state after the node.
func (Node) NextSibling ¶
NextSibling returns the following sibling, or a null node.
func (Node) ParseState ¶
ParseState returns the parse state the node was created in.
func (Node) PrevNamedSibling ¶
PrevNamedSibling returns the preceding named sibling, or a null node.
func (Node) PrevSibling ¶
PrevSibling returns the preceding sibling, or a null node.
func (Node) StartPoint ¶
StartPoint returns the position where the node begins.
func (Node) Text ¶
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.
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 (*Parser) Close ¶
func (p *Parser) Close()
Close frees the parser. Trees it produced remain valid.
func (*Parser) IncludedRanges ¶
IncludedRanges returns the ranges the parser is restricted to. With no restriction it returns one range covering the whole document.
func (*Parser) Parse ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetLanguage selects the grammar to parse with. It fails when the grammar's ABI version is incompatible with the library.
func (*Parser) SetLogger ¶
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 ¶
Point is a position in source text: a zero-based row and a zero-based byte column within that row.
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.
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 ¶
NewQuery compiles source, in tree-sitter's query language, for lang. A compile failure is reported as a *QueryError.
func NewQueryFS ¶
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 ¶
CaptureCount returns the number of distinct capture names.
func (*Query) CaptureName ¶
CaptureName returns the name of capture id.
func (*Query) CaptureNames ¶
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 ¶
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) DisableCapture ¶
DisableCapture stops the query from reporting the named capture.
func (*Query) DisablePattern ¶
DisablePattern stops the query from matching pattern i.
func (*Query) EndByteForPattern ¶
EndByteForPattern returns where pattern i ends in the query source.
func (*Query) IsPatternGuaranteedAtStep ¶
IsPatternGuaranteedAtStep reports whether a pattern is certain to match once the query has reached the given byte offset of its source.
func (*Query) IsPatternNonLocal ¶
IsPatternNonLocal reports whether pattern i can match nodes that are not direct descendants of a single node.
func (*Query) IsPatternRooted ¶
IsPatternRooted reports whether pattern i has a single root node.
func (*Query) Matches ¶
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 ¶
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 ¶
PatternCount returns the number of patterns.
func (*Query) Predicates ¶
Predicates returns the predicates of pattern i, in source order, including those the package does not evaluate.
func (*Query) Properties ¶
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 ¶
StartByteForPattern returns where pattern i begins in the query source.
func (*Query) StringCount ¶
StringCount returns the number of distinct string literals.
func (*Query) StringValue ¶
StringValue returns the string literal with the given id.
type QueryCapture ¶
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) 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.
const ( QueryErrorSyntax QueryErrorKind = QueryErrorKind(ts.QueryErrorSyntax) QueryErrorNodeType QueryErrorKind = QueryErrorKind(ts.QueryErrorNodeType) QueryErrorField QueryErrorKind = QueryErrorKind(ts.QueryErrorField) QueryErrorCapture QueryErrorKind = QueryErrorKind(ts.QueryErrorCapture) QueryErrorStructure QueryErrorKind = QueryErrorKind(ts.QueryErrorStructure) QueryErrorLanguage QueryErrorKind = QueryErrorKind(ts.QueryErrorLanguage) )
Query error kinds.
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 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 ¶
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 ¶
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())
}
}
Output:
func (*Tree) ChangedRanges ¶
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 ¶
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 ¶
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)
}
}
Output:
func (*Tree) Errors ¶
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 ¶
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 ¶
IncludedRanges returns the ranges of the document the tree covers.
func (*Tree) PrintDotGraph ¶
PrintDotGraph writes a Graphviz graph of the tree to fd.
func (*Tree) RootNodeWithOffset ¶
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.
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) 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.
Source Files
¶
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. |