sitter

package module
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: May 24, 2025 License: MIT Imports: 14 Imported by: 8

README

Go Tree-Sitter bindings

Build Status

ONLY provides the Go bindings for tree-sitter. For grammars see go-sitter-forest.

Origins & Credits

This originally started as a "fork" of @smacker's go-tree-sitter, read below to find out Why and How? It also recently adopted the query.go from go-tree-sitter so that we can filter captures/matches implicitly (no more need to call FilterPredicates()).

Why

I needed strictly the sitter functionality without any of the parsers and I needed this dependency to be as light as possible and had no need for the parsers as I have created my own repo (also based on @smacker's work, but I needed a lot more parsers) and that repo is itself 1.4GB already, so I didn't need another 200MB dependency on sitter, when the actual code is less than 2MB.

Technically, the go-tree-sitter is now a viable alternative, in the sense that it does only offer the bindings alone. Still, at 20MB in size is 20x times larger than this repo. I may still keep my fork, we'll see...

How

I copied the files from the root of go-tree-sitter plus my PR, as it was at 1f283e24f56023537e6de2d542732445e505f901 commit. I kept the LICENSE so, although there is no git history, being a brand new repo and not a GitHub fork, everything points back to the original author.

So there it is, full transparency and giving credit where is due. I generally dislike deleting history, but simple git rming parsers from a clone, would've still kept them in git history and contribute to the repo size.

Differences
  • timely kept up to date with tree-sitter updates (including new API calls);
  • tiny, zero deps repo;
  • implemented all API calls from api.h with the exception of WASM;
  • reorganized code based on api.h sections and corresponding files (i.e. broken down bindings.go into language.go, parser.go, node.go, query.go, tree.go, tree_cursor.go and sitter.go, with each file having the code sorted the same way as in api.h);
  • synced Go funcs' comments with their counterparts from api.h;
  • added return types where they were missing (a few places, where the C counterpart would return a bool but the Go wrapper wouldn't);
  • some simplification related to types/params/etc. where it was possible;
  • made all Close() methods private (as they are not supposed to be called by end users) and replaced their isBool with a sync.Once;
  • added an automated check (and corresponding github action) to quickly check if we are falling behind api.h;
  • all tests run in parallel (so both faster and acting as an extra, indirect check that concurrency works as expected);
  • code cleanup (enabled lots of linters and cleaned up code accordingly).

Usage

Create a parser with a grammar:

import (
	"context"
	"fmt"

	sitter "github.com/alexaandru/go-tree-sitter-bare"
	"github.com/alexaandru/go-sitter-forest/javascript"
)

var parser = sitter.NewParser()

func init() {
    if ok := parser.SetLanguage(sitter.NewLanguage(javascript.GetLanguage())); !ok {
        panic("cannot set language")
    }
}

Parse some code:

sourceCode := []byte("let a = 1")
tree, err := parser.ParseString(context.Background(), nil, sourceCode)
if err != nil {
	panic(err)
}
defer tree.Close()

Inspect the syntax tree:

```go
n := tree.RootNode()

fmt.Println(n)
// (program (lexical_declaration (variable_declarator (identifier) (number))))

child := n.NamedChild(0)
fmt.Println(child.Type()) // lexical_declaration
fmt.Println(child.StartByte()) // 0
fmt.Println(child.EndByte()) // 9
Editing

If your source code changes, you can update the syntax tree. This will take less time than the first parse.

// change 1 -> true
newText := []byte("let a = true")
tree.Edit(sitter.EditInput{
    StartIndex: 8, OldEndIndex: 9, NewEndIndex: 12,
    StartPoint: sitter.Point{Row: 0, Column: 8},
    OldEndPoint: sitter.Point{Row: 0, Column: 9},
    NewEndPoint: sitter.Point{Row: 0, Column: 12},
})

// check that it changed tree
assert.True(n.HasChanges())
assert.True(n.Child(0).HasChanges())
assert.False(n.Child(0).Child(0).HasChanges()) // left side of the tree didn't change
assert.True(n.Child(0).Child(1).HasChanges())

// generate new tree
newTree, err := parser.ParseString(context.TODO(), tree, newText)
if err != nil {
	panic(err)
}
defer newTree.Close()
Predicates

You can filter AST by using predicate S-expressions.

Similar to Rust or WebAssembly bindings we support filtering on a few common predicates:

  • [any-][not-]eq?,
  • [any-][not-]match?,
  • [not-]any-of?,
  • set?,
  • is[-not]?,
  • and a default/catchall that simply saves the predicate op/args for later use, in Query.generalPredicates

Usage example:

package main

import (
	"context"
	"fmt"

	"github.com/alexaandru/go-sitter-forest/javascript"
	sitter "github.com/alexaandru/go-tree-sitter-bare"
)

func main() {
	// Javascript code
	sourceCode := []byte(`
		const camelCaseConst = 1;
		const SCREAMING_SNAKE_CASE_CONST = 2;
		const lower_snake_case_const = 3;`)
	// Query with predicates
	query := []byte(`(
		(identifier) @constant
		(#match? @constant "^[A-Z][A-Z_]+"))`)

	// Get language.
	langPtr := javascript.GetLanguage()
	lang := sitter.NewLanguage(langPtr)

	// Parse source code.
	tree, err := parser.ParseString(context.Background(), nil, sourceCode)
	if err != nil {
		panic(err)
	}
	defer tree.Close()

	n := tree.RootNode()

	// Execute the query.
	q, _ := sitter.NewQuery(lang, query)
	qc := sitter.NewQueryCursor()

	matches := qc.Matches(q, n, sourceCode) // or q.Captures()

	for {
		m := matches.Next()
		if m == nil {
			break
		}

		for _, c := range m.Captures {
			fmt.Println(c.Node.Content(sourceCode))
			// Output: SCREAMING_SNAKE_CASE_CONST
		}
	}
}

Resource Management and Tree Ownership

Explicit Cleanup Required for Trees

As of Go 1.24+, resource management for Tree-sitter bindings is modernized. Most objects (Parser, Query, QueryCursor, TreeCursor) are cleaned up automatically using Go's runtime.AddCleanup. However, Tree objects require explicit cleanup.

  • You must call tree.Close() when you are done with a Tree.
  • Failing to call Close() will result in memory leaks.
  • Using a Tree after calling Close() will panic or cause undefined behavior.
  • This is necessary because Tree ownership is ambiguous and automatic cleanup could cause double-free or use-after-free bugs.
Example
sourceCode := []byte("let a = 1")
tree, err := parser.ParseString(context.Background(), nil, sourceCode)
if err != nil {
	panic(err)
}
defer tree.Close() // Always close your trees!
Why not automatic cleanup for Tree?

Unlike other objects, Trees can be copied, edited, and passed around, making it impossible to safely determine ownership for automatic cleanup. Explicit Close() is the only safe approach.

Convenience Wrappers

If you want automatic cleanup, you can wrap Tree in your own type and use Go's runtime.SetFinalizer or similar, but this is not provided by default to avoid unsafe behavior.

Documentation

Index

Constants

View Source
const (
	InputEncodingUTF8  = C.TSInputEncodingUTF8
	InputEncodingUTF16 = C.TSInputEncodingUTF16
)

Input encoding types.

View Source
const (
	QuantifierZero       = C.TSQuantifierZero
	QuantifierZeroOrOne  = C.TSQuantifierZeroOrOne
	QuantifierZeroOrMore = C.TSQuantifierZeroOrMore
	QuantifierOne        = C.TSQuantifierOne
	QuantifierOneOrMore  = C.TSQuantifierOneOrMore
)

Possible quantifiers.

View Source
const (
	TREE_SITTER_LANGUAGE_VERSION                = int(C.TREE_SITTER_LANGUAGE_VERSION)
	TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION = int(C.TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION)
)
View Source
const (

	// UnlimitedMaxDepth is used for turning off max depth limit for query cursor.
	UnlimitedMaxDepth = maxUint32
)

Variables

View Source
var (
	ErrOperationLimit = errors.New("operation limit was hit")
	ErrNoLanguage     = errors.New("cannot parse without language")
)

Possible error types.

View Source
var (
	ErrPredicateBase           = errors.New("predicate error")
	ErrPredicateArgsWrongCount = fmt.Errorf("%w: wrong arguments #", ErrPredicateBase)
	ErrPredicateInvalidArg     = fmt.Errorf("%w: invalid argument", ErrPredicateBase)
	ErrPredicateWrongStart     = fmt.Errorf("%w: must begin with a literal value", ErrPredicateBase)
	ErrPredicateWrongType      = fmt.Errorf("%w: invalid type", ErrPredicateBase)
	ErrPredicateRegex          = fmt.Errorf("%w: invalid regex", ErrPredicateBase)

	ErrPredicateFnBase     = errors.New("predicate fn error")
	ErrPredicateFnWrongRet = fmt.Errorf("%w: invalid return type", ErrPredicateFnBase)
	ErrPredicateFnMissing  = fmt.Errorf("%w: none registered", ErrPredicateFnBase)
)

Query related errors.

Functions

This section is empty.

Types

type CaptureQuantifier added in v1.9.0

type CaptureQuantifier = C.TSQuantifier
const (
	CaptureQuantifierZero       CaptureQuantifier = C.TSQuantifierZero
	CaptureQuantifierZeroOrOne  CaptureQuantifier = C.TSQuantifierZeroOrOne
	CaptureQuantifierZeroOrMore CaptureQuantifier = C.TSQuantifierZeroOrMore
	CaptureQuantifierOne        CaptureQuantifier = C.TSQuantifierOne
	CaptureQuantifierOneOrMore  CaptureQuantifier = C.TSQuantifierOneOrMore
)

type FieldID added in v1.3.2

type FieldID = C.TSFieldId

FieldID is used for parser field ID.

type Input

type Input struct {
	// Payload an arbitrary pointer that will be passed to each invocation
	// of the Read function. NOTE: I do see it passed into ts_parser_parse()
	// however I don't see it used. Just keeping it here for documenting purposes.
	Payload unsafe.Pointer
	//  Read is a function to retrieve a chunk of text at a given byte offset
	//  and (row, column) position. The function should return a pointer to the
	//  text and write its length to the [`bytes_read`] pointer. The parser does
	//  not take ownership of this buffer; it just borrows it until it has
	//  finished reading it. The function should write a zero value to the
	//  [`bytes_read`] pointer to indicate the end of the document.
	Read ReadFunc
	// Encoding is an indication of how the text is encoded.
	// Either `TSInputEncodingUTF8` or `TSInputEncodingUTF16`.
	Encoding InputEncoding
}

Input type lets you specify how to read the text.

type InputEdit added in v1.3.3

type InputEdit struct {
	StartIndex  uint
	OldEndIndex uint
	NewEndIndex uint
	StartPoint  Point
	OldEndPoint Point
	NewEndPoint Point
}

InputEdit represents one edit in the input.

type InputEncoding

type InputEncoding = C.TSInputEncoding

InputEncoding indicates the encoding of the text to parse.

type IterMode

type IterMode int

IterMode indicates the iteration mode.

const (
	DFS IterMode = iota
	BFS
	DFSNamed
	BFSNamed
)

The possible iteration modes.

func (IterMode) String added in v1.4.3

func (i IterMode) String() string

type Iterator

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

Iterator for a tree of nodes.

func NewIterator

func NewIterator(n Node, opts ...IterMode) *Iterator

NewIterator takes a node and mode (DFS/BFS) and returns iterator over children of the node.

func (*Iterator) ForEach

func (iter *Iterator) ForEach(fn func(Node) error) (err error)

ForEach iterates over all nodes, until an error is enconuntered (or there are no more nodes).

func (*Iterator) Next

func (iter *Iterator) Next() (n Node, err error)

Next returns the next node in the current iteration.

type Language

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

Language defines how to parse a particular programming language.

func NewLanguage

func NewLanguage(ptr unsafe.Pointer) (l *Language)

NewLanguage initializes a new language from the provided pointer.

func (*Language) Copy added in v1.3.2

func (l *Language) Copy() *Language

Copy returns another reference to the language.

func (*Language) Delete added in v1.3.2

func (l *Language) Delete()

Delete frees any dynamically-allocated resources for this language, if this is the last reference.

func (*Language) FieldCount added in v1.3.2

func (l *Language) FieldCount() uint32

FieldCount returns the number of distinct field names in the language.

func (*Language) FieldID added in v1.3.2

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

FieldID returns the numerical id for the given field name string.

func (*Language) FieldName

func (l *Language) FieldName(idx int) string

FieldName returns the field name string for the given numerical id.

func (*Language) NextState added in v1.3.2

func (l *Language) NextState(curr StateID, sym Symbol) StateID

NextState returns the next parse state. Combine this with lookahead iterators to generate completion suggestions or valid symbols in error nodes. Use `ts_node_grammar_symbol` for valid symbols.

func (*Language) StateCount added in v1.3.2

func (l *Language) StateCount() uint32

StateCount returns the number of valid states in the language.

func (*Language) SymbolCount

func (l *Language) SymbolCount() uint32

SymbolCount returns the number of distinct field names in the language.

func (*Language) SymbolID added in v1.3.2

func (l *Language) SymbolID(name string, isNamed bool) Symbol

SymbolID returns the numerical id for the given node type string.

func (*Language) SymbolName

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

SymbolName returns a node type string for the given Symbol.

func (*Language) SymbolType

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

SymbolType returns named, anonymous, or a hidden type for a Symbol.

func (*Language) Version added in v1.3.2

func (l *Language) Version() int

Version returns the ABI version number for this language. This version number is used to ensure that languages were generated by a compatible version of Tree-sitter.

type LanguageError added in v1.9.0

type LanguageError int

LanguageError represents an error that occurred when trying to assign an incompatible [TSLanguage] to a [TSParser].

func (LanguageError) Error added in v1.9.0

func (e LanguageError) Error() string

type LookaheadIterator added in v1.5.0

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

LookaheadIterator holds the pointer to the corresponding C struct.

func NewLookaheadIterator added in v1.5.0

func NewLookaheadIterator(lang *Language, stateID StateID) *LookaheadIterator

NewLookaheadIterator creates a new lookahead iterator for the given language and parse state.

This returns `NULL` if state is invalid for the language.

Repeatedly using `ts_lookahead_iterator_next` and `ts_lookahead_iterator_current_symbol` will generate valid symbols in the given parse state. Newly created lookahead iterators will contain the `ERROR` symbol.

Lookahead iterators can be useful to generate suggestions and improve syntax error diagnostics. To get symbols valid in an ERROR node, use the lookahead iterator on its first leaf node state. For `MISSING` nodes, a lookahead iterator created on the previous non-extra leaf node may be appropriate.

func (*LookaheadIterator) CurrentSymbol added in v1.5.0

func (iter *LookaheadIterator) CurrentSymbol() Symbol

CurrentSymbol returns the current symbol of the lookahead iterator.

func (*LookaheadIterator) CurrentSymbolName added in v1.5.0

func (iter *LookaheadIterator) CurrentSymbolName() string

CurrentSymbolName returns the current symbol type of the lookahead iterator as a null terminated string.

func (*LookaheadIterator) Delete added in v1.5.0

func (iter *LookaheadIterator) Delete()

Delete deletes a lookahead iterator freeing all the memory used.

func (*LookaheadIterator) Language added in v1.5.0

func (iter *LookaheadIterator) Language() *Language

Language returns the current language of the lookahead iterator.

func (*LookaheadIterator) Next added in v1.5.0

func (iter *LookaheadIterator) Next() bool

Next advances the lookahead iterator to the next symbol.

This returns `true` if there is a new symbol and `false` otherwise.

func (*LookaheadIterator) Reset added in v1.5.0

func (iter *LookaheadIterator) Reset(lang *Language, stateID StateID) bool

Reset resets the lookahead iterator.

This returns `true` if the language was set successfully and `false` otherwise.

func (*LookaheadIterator) ResetState added in v1.5.0

func (iter *LookaheadIterator) ResetState(stateID StateID) bool

ResetState resets the lookahead iterator to another state.

This returns `true` if the iterator was reset to the given state and `false` otherwise.

type Node

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

Node represents a single node in the syntax tree It tracks its start and end positions in the source code, as well as its relation to other nodes like its parent, siblings and children.

func Parse

func Parse(ctx context.Context, content []byte, lang *Language) (n Node, err error)

Parse is a shortcut for parsing bytes of source code, returns root node.

func (Node) Child

func (n Node) Child(idx uint32) Node

Child returns the node's child at the given index, where zero represents the first child.

func (Node) ChildByFieldID added in v1.3.3

func (n Node) ChildByFieldID(id FieldID) Node

ChildByFieldID returns the node's child with the given numerical field id.

You can convert a field name to an id using the `ts_language_field_id_for_name` function.

func (Node) ChildByFieldName

func (n Node) ChildByFieldName(name string) Node

ChildByFieldName returns the node's child with the given field name.

func (Node) ChildContainingDescendant added in v1.3.0

func (n Node) ChildContainingDescendant(d Node) Node

ChildContainingDescendant returns the node's child that contains `descendant`. Deprecated: use [`ts_node_contains_descendant`] instead, this will be removed in 0.25

Get the node's child containing `descendant`. This will not return the descendant if it is a direct child of `self`, for that use `ts_node_contains_descendant`.

func (Node) ChildCount

func (n Node) ChildCount() uint32

ChildCount returns the node's number of children.

func (Node) ChildWithDescendant added in v1.7.0

func (n Node) ChildWithDescendant(d Node) Node

ChildWithDescendant returns the node that contains `descendant`.

NOTE: that this can return `descendant` itself, unlike the deprecated function [`ts_node_child_containing_descendant`].

func (Node) Content

func (n Node) Content(input []byte) string

Content returns node's source code from input as a string.

func (Node) DescendantCount added in v1.3.3

func (n Node) DescendantCount() uint32

DescendantCount returns the node's number of descendants, including one for the node itself.

func (Node) DescendantForByteRange added in v1.3.3

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

DescendantForByteRange returns the smallest node within this node that spans the given range of bytes.

func (Node) DescendantForPointRange added in v1.3.3

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

DescendantForPointRange returns the smallest node within this node that spans the given range of {row, column} positions.

func (Node) Edit

func (n Node) Edit(i InputEdit)

Edit the node to keep it in-sync with source code that has been edited.

This function is only rarely needed. When you edit a syntax tree with the `ts_tree_edit` function, all of the nodes that you retrieve from the tree afterward will already reflect the edit. You only need to use `ts_node_edit` when you have a `TSNode` instance that you want to keep and continue to use after an edit.

func (Node) EndByte

func (n Node) EndByte() uint

EndByte returns the node's end byte.

func (Node) EndPoint

func (n Node) EndPoint() Point

EndPoint returns the node's end position in terms of rows and columns.

func (Node) Equal

func (n Node) Equal(other Node) bool

Equal checks if two nodes are identical.

func (Node) FieldNameForChild

func (n Node) FieldNameForChild(idx int) string

FieldNameForChild returns the field name of the child at the given index, or "" if not named.

func (Node) FieldNameForNamedChild added in v1.7.0

func (n Node) FieldNameForNamedChild(idx uint32) string

FieldNameForNamedChild returns the field name for node's named child at the given index, where zero represents the first named child. Returns NULL, if no field is found.

func (Node) FirstChildForByte added in v1.3.3

func (n Node) FirstChildForByte(ofs uint32) Node

FirstChildForByte returns the node's first child that extends beyond the given byte offset.

func (Node) FirstNamedChildForByte added in v1.3.3

func (n Node) FirstNamedChildForByte(ofs uint32) Node

FirstNamedChildForByte returns the node's first named child that extends beyond the given byte offset.

func (Node) GrammarSymbol added in v1.3.2

func (n Node) GrammarSymbol() Symbol

GrammarSymbol returns the node's symbol as it appears in the grammar, ignoring aliases. This should be used in `ts_language_next_state` instead of `ts_node_symbol`.

func (Node) GrammarType added in v1.3.2

func (n Node) GrammarType() string

GrammarType returns the node's type as it appears in the grammar, ignoring aliases.

func (Node) HasChanges

func (n Node) HasChanges() bool

HasChanges checks if a syntax node has been edited.

func (Node) HasError

func (n Node) HasError() bool

HasError check if the node is a syntax error or contains any syntax errors.

func (Node) IsError

func (n Node) IsError() bool

IsError checks if the node is a syntax error.

Syntax errors represent parts of the code that could not be incorporated into a valid syntax tree.

func (Node) IsExtra

func (n Node) IsExtra() bool

IsExtra checks if the node is *extra*.

Extra nodes represent things like comments, which are not required the grammar, but can appear anywhere.

func (Node) IsMissing

func (n Node) IsMissing() bool

IsMissing checks if the node is *missing*.

Missing nodes are inserted by the parser in order to recover from certain kinds of syntax errors.

func (Node) IsNamed

func (n Node) IsNamed() bool

IsNamed checks if the node is *named*.

Named nodes correspond to named rules in the grammar, whereas *anonymous* nodes correspond to string literals in the grammar.

func (Node) IsNull

func (n Node) IsNull() bool

IsNull checks if the node is null.

Functions like `ts_node_child` and `ts_node_next_sibling` will return a null node to indicate that no such node was found.

func (Node) Language added in v1.3.2

func (n Node) Language() *Language

Language returns the node's language.

func (Node) NamedChild

func (n Node) NamedChild(idx uint32) Node

NamedChild returns the node's *named* child at the given index.

See also `ts_node_is_named`.

func (Node) NamedChildCount

func (n Node) NamedChildCount() uint32

NamedChildCount returns the node's number of *named* children.

See also `ts_node_is_named`.

func (Node) NamedDescendantForByteRange added in v1.3.0

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

NamedDescendantForByteRange returns the smallest named node within this node that spans the given range of bytes.

func (Node) NamedDescendantForPointRange

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

NamedDescendantForPointRange returns the smallest named node within this node that spans the given range of row/column positions.

func (Node) NextNamedSibling

func (n Node) NextNamedSibling() Node

NextNamedSibling returns the node's next *named* sibling.

func (Node) NextParseState added in v1.3.3

func (n Node) NextParseState() StateID

NextParseState returns the parse state after this node.

func (Node) NextSibling

func (n Node) NextSibling() Node

NextSibling returns the node's next sibling.

func (Node) Parent

func (n Node) Parent() Node

Parent returns the node's immediate parent.

Prefer `ts_node_child_containing_descendant` for iterating over the node's ancestors.

func (Node) ParseState added in v1.3.3

func (n Node) ParseState() StateID

ParseState returns this node's parse state.

func (Node) PrevNamedSibling

func (n Node) PrevNamedSibling() Node

PrevNamedSibling returns the node's previous *named* sibling.

func (Node) PrevSibling

func (n Node) PrevSibling() Node

PrevSibling returns the node's previous sibling.

func (Node) Range added in v1.2.0

func (n Node) Range() Range

Range returns the node range.

func (Node) StartByte

func (n Node) StartByte() uint

StartByte returns the node's start byte.

func (Node) StartPoint

func (n Node) StartPoint() Point

StartPoint returns the node's start position in terms of rows and columns.

func (Node) String

func (n Node) String() string

String returns an S-expression representing the node as a string.

This string is allocated with `malloc` and the caller is responsible for freeing it using `free`.

func (Node) Symbol

func (n Node) Symbol() Symbol

Symbol returns the node's type.

func (Node) Type

func (n Node) Type() string

Type returns the node's type.

type Parser

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

Parser produces concrete syntax tree based on source code using Language.

func NewParser

func NewParser() (p *Parser)

NewParser creates a new Parser.

func (*Parser) CancellationFlag added in v1.3.3

func (p *Parser) CancellationFlag() *uint64

CancellationFlag returns the parser's current cancellation flag pointer.

func (*Parser) Debug

func (p *Parser) Debug()

Debug enables debug output to stderr.

func (*Parser) IncludedRanges added in v1.3.2

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

IncludedRanges returns the ranges of text that the parser will include when parsing.

The returned pointer is owned by the parser. The caller should not free it or write to it.

func (*Parser) Language added in v1.3.2

func (p *Parser) Language() (_ *Language)

Language returns the parser's current language, if set.

func (*Parser) Logger added in v1.3.5

func (p *Parser) Logger() C.TSLogger

Logger returns the parser's current logger.

func (*Parser) Parse

func (p *Parser) Parse(ctx context.Context, oldTree *Tree, input Input) (*Tree, error)

Parse produces new Tree by reading from a callback defined in input it is useful if your data is stored in specialized data structure as it will avoid copying the data into []bytes and faster access to edited part of the data.

If you are parsing this document for the first time, pass `NULL` for the `old_tree` parameter. Otherwise, if you have already parsed an earlier version of this document and the document has since been edited, pass the previous syntax tree so that the unchanged parts of it can be reused. This will save time and memory. For this to work correctly, you must have already edited the old syntax tree using the [`ts_tree_edit`] function in a way that exactly matches the source code changes.

See Input for details about it.

This function returns a syntax tree on success, and `NULL` on failure. There are three possible reasons for failure:

  1. The parser does not have a language assigned. Check for this using the [`ts_parser_language`] function.
  2. Parsing was cancelled due to a timeout that was set by an earlier call to the [`ts_parser_set_timeout_micros`] function. You can resume parsing from where the parser left out by calling [`ts_parser_parse`] again with the same arguments. Or you can start parsing from scratch by first calling [`ts_parser_reset`].
  3. Parsing was cancelled using a cancellation flag that was set by an earlier call to [`ts_parser_set_cancellation_flag`]. You can resume parsing from where the parser left out by calling [`ts_parser_parse`] again with the same arguments.

func (*Parser) ParseString added in v1.3.3

func (p *Parser) ParseString(ctx context.Context, oldTree *Tree, content []byte, opts ...InputEncoding) (*Tree, error)

ParseString produces new Tree from content (optionally using old tree).

Uses the parser to parse some source code stored in one contiguous buffer. If the optional encoding is passed, it will be used for parsing. See `Parse()` for further details, as the behavior virtually the same.

func (*Parser) PrintDotGraphs added in v1.3.3

func (p *Parser) PrintDotGraphs(name string) (err error)

PrintDotGraphs can be used to write debugging graphs during parsing.

The graphs are formatted in the DOT language. You may want to pipe these graphs directly to a `dot(1)` process in order to generate SVG output. You can turn off this logging by passing a negative number.

func (*Parser) Reset

func (p *Parser) Reset()

Reset instructs the parser to start the next parse from the beginning.

If the parser previously failed because of a timeout or a cancellation, then by default, it will resume where it left off on the next call to `ts_parser_parse` or other parsing functions. If you don't want to resume, and instead intend to use this parser to parse some other document, you must call `ts_parser_reset` first.

func (*Parser) SetCancellationFlag added in v1.3.3

func (p *Parser) SetCancellationFlag(flag *uint64)

SetCancellationFlag sets the parser's current cancellation flag pointer.

If a non-null pointer is assigned, then the parser will periodically read from this pointer during parsing. If it reads a non-zero value, it will halt early, returning NULL. See [`ts_parser_parse`] for more information.

func (*Parser) SetIncludedRanges

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

SetIncludedRanges sets the ranges of text that the parser should include when parsing.

By default, the parser will always include entire documents. This function allows you to parse only a *portion* of a document but still return a syntax tree whose ranges match up with the document as a whole. You can also pass multiple disjoint ranges.

The second and third parameters specify the location and length of an array of ranges. The parser does *not* take ownership of these ranges; it copies the data, so it doesn't matter how these ranges are allocated.

If `count` is zero, then the entire document will be parsed. Otherwise, the given ranges must be ordered from earliest to latest in the document, and they must not overlap. That is, the following must hold for all:

`i < count - 1`: `ranges[i].end_byte <= ranges[i + 1].start_byte`

If this requirement is not satisfied, the operation will fail, the ranges will not be assigned, and this function will return `false`. On success, this function returns `true`.

func (*Parser) SetLanguage

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

SetLanguage sets the language that the parser should use for parsing.

Returns a boolean indicating whether or not the language was successfully assigned. True means assignment succeeded. False means there was a version mismatch: the language was generated with an incompatible version of the Tree-sitter CLI. Check the language's version using `ts_language_version` and compare it to this library's `TREE_SITTER_LANGUAGE_VERSION` and `TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION` constants.

func (*Parser) SetLogger added in v1.3.5

func (p *Parser) SetLogger(logger C.TSLogger)

SetLogger sets the logger that a parser should use during parsing.

The parser does not take ownership over the logger payload. If a logger was previously assigned, the caller is responsible for releasing any memory owned by the previous logger.

func (*Parser) SetTimeoutMicros added in v1.3.2

func (p *Parser) SetTimeoutMicros(limit int)

SetTimeoutMicros limits the maximum duration in microseconds that parsing should be allowed to take before halting.

If parsing takes longer than this, it will halt early, returning NULL. See `ts_parser_parse` for more information.

func (*Parser) TimeoutMicros added in v1.3.2

func (p *Parser) TimeoutMicros() int

TimeoutMicros returns the duration in microseconds that parsing is allowed to take.

type Point

type Point struct {
	Row    uint
	Column uint
}

Point represents one location in the input.

type Predicator added in v1.9.0

type Predicator func(_ *Query, _ QueryPredicateSteps, op string, row uint,
	strVal, cptVal func(int) func() string) (any, error)

type PropertyPredicate added in v1.9.0

type PropertyPredicate struct {
	Property QueryProperty
	Positive bool
}

type Query

type Query struct {
	TextPredicates [][]TextPredicateCapture
	// contains filtered or unexported fields
}

Query is a tree query, compiled from a string of S-expressions. The query itself is immutable. The mutable state used in the process of executing the query is stored in a `TSQueryCursor`.

func NewQuery

func NewQuery(lang *Language, pattern []byte) (q *Query, err error)

NewQuery creates a new query from a string containing one or more S-expression patterns. The query is associated with a particular language, and can only be run on syntax nodes parsed with that language.

If all of the given patterns are valid, this returns a `TSQuery`. If a pattern is invalid, it returns an error which provides two pieces of information about the problem:

  1. The byte offset of the error is written to the `error_offset` parameter.
  2. The type of error is written to the `error_type` parameter.

func (*Query) CaptureCount

func (q *Query) CaptureCount() uint32

CaptureCount returns the number of captures in the query.

func (*Query) CaptureIndexForName added in v1.9.0

func (q *Query) CaptureIndexForName(name string) (i int, ok bool)

CaptureIndexForName returns the index for a given capture name.

func (*Query) CaptureNameForID added in v1.3.0

func (q *Query) CaptureNameForID(id uint32) string

CaptureNameForID returns the name and length of one of the query's captures, or one of the query's string literals. Each capture and string is associated with a numeric id based on the order that it appeared in the query's source.

func (*Query) CaptureNames added in v1.9.0

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

CaptureNames returns the names of the captures used in the query.

func (*Query) CaptureQuantifierForID added in v1.3.0

func (q *Query) CaptureQuantifierForID(id, captureID uint32) C.TSQuantifier

CaptureQuantifierForID returns the quantifier of the query's captures. Each capture is associated with a numeric id based on the order that it appeared in the query's source.

func (*Query) CaptureQuantifiers added in v1.9.0

func (q *Query) CaptureQuantifiers(index uint) []CaptureQuantifier

CaptureQuantifiers returns the quantifiers of the captures used in the query.

func (*Query) DisableCapture added in v1.3.3

func (q *Query) DisableCapture(name string)

DisableCapture disables a certain capture within a query.

This prevents the capture from being returned in matches, and also avoids any resource usage associated with recording the capture. Currently, there is no way to undo this.

func (*Query) DisablePattern added in v1.3.3

func (q *Query) DisablePattern(patIdx uint32)

DisablePattern disables a certain pattern within a query.

This prevents the pattern from matching and removes most of the overhead associated with the pattern. Currently, there is no way to undo this.

func (*Query) EndByteForPattern added in v1.6.0

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

EndByteForPattern returns the byte offset where the given pattern ends in the query's source.

This can be useful when combining queries by concatenating their source code strings.

func (*Query) GeneralPredicates added in v1.9.0

func (q *Query) GeneralPredicates(index uint) []QueryPredicate

GeneralPredicates returns the other user-defined predicates associated with the given index.

This includes predicate with operators other than: * `match?` * `eq?` and `not-eq?` * `is?` and `is-not?` * `set!`

func (*Query) IsPatternGuaranteedAtStep added in v1.3.3

func (q *Query) IsPatternGuaranteedAtStep(byteOfs uint32) bool

IsPatternGuaranteedAtStep checks if a given pattern is guaranteed to match once a given step is reached. The step is specified by its byte offset in the query's source code.

func (*Query) IsPatternNonLocal added in v1.3.3

func (q *Query) IsPatternNonLocal(patIdx uint32) bool

IsPatternNonLocal checks if the given pattern in the query is 'non local'.

A non-local pattern has multiple root nodes and can match within a repeating sequence of nodes, as specified by the grammar. Non-local patterns disable certain optimizations that would otherwise be possible when executing a query on a specific range of a syntax tree.

func (*Query) IsPatternRooted added in v1.3.3

func (q *Query) IsPatternRooted(patIdx uint32) bool

IsPatternRooted checks if the given pattern in the query has a single root node.

func (*Query) PatternCount

func (q *Query) PatternCount() uint32

PatternCount returns the number of patterns in the query.

func (*Query) PredicatesForPattern

func (q *Query) PredicatesForPattern(patternIndex uint32) []QueryPredicateSteps

PredicatesForPattern returns all of the predicates for the given pattern in the query.

The predicates are represented as a single array of steps. There are three types of steps in this array, which correspond to the three legal values for the `type` field:

  • `TSQueryPredicateStepTypeCapture` - Steps with this type represent names of captures. Their `value_id` can be used with the `ts_query_capture_name_for_id` function to obtain the name of the capture.
  • `TSQueryPredicateStepTypeString` - Steps with this type represent literal strings. Their `value_id` can be used with the `ts_query_string_value_for_id` function to obtain their string value.
  • `TSQueryPredicateStepTypeDone` - Steps with this type are *sentinels* that represent the end of an individual predicate. If a pattern has two predicates, then there will be two steps with this `type` in the array.

func (*Query) PropertyPredicates added in v1.9.0

func (q *Query) PropertyPredicates(index uint) []PropertyPredicate

PropertyPredicates returns the properties that are checked for the given pattern index.

This includes predicates with the operators `is?` and `is-not?`.

func (*Query) PropertySettings added in v1.9.0

func (q *Query) PropertySettings(index uint) []QueryProperty

PropertySettings returns the properties that are set for the given pattern index.

This includes predicates with the operator `set!`.

func (*Query) StartByteForPattern added in v1.3.3

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

StartByteForPattern returns the byte offset where the given pattern starts in the query's source.

This can be useful when combining queries by concatenating their source code strings.

func (*Query) StringCount

func (q *Query) StringCount() uint32

StringCount returns the number of string literals in the query.

func (*Query) StringValueForID added in v1.3.0

func (q *Query) StringValueForID(id uint32) string

StringValueForID returns the string value associated with the given query id.

type QueryCapture

type QueryCapture struct {
	Node  Node
	Index uint32
}

QueryCapture is a captured node by a query with an index.

type QueryCaptures added in v1.9.0

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

QueryCaptures holds a sequence of [QueryCapture]s associated with a given QueryCursor.

func (*QueryCaptures) Next added in v1.9.0

func (qc *QueryCaptures) Next() (m *QueryMatch, index uint)

Next will return the next match in the sequence of matches, as well as the index of the capture.

Subsequent calls to QueryCaptures.Next will overwrite the memory at the same location as prior matches, since the memory is reused. You can think of this as a stateful iterator. If you need to keep the data of a prior match without it being overwritten, you should copy what you need before calling QueryCaptures.Next again.

If there are no more matches, it will return nil.

type QueryCursor

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

QueryCursor is a stateful struct used to execute a query on a tree.

func NewQueryCursor

func NewQueryCursor() (qc *QueryCursor)

NewQueryCursor creates a new query cursor.

The cursor stores the state that is needed to iteratively search for matches. To use the query cursor, first call `ts_query_cursor_exec` to start running a given query on a given syntax node. Then, there are two options for consuming the results of the query:

  1. Repeatedly call `ts_query_cursor_next_match` to iterate over all of the *matches* in the order that they were found. Each match contains the index of the pattern that matched, and an array of captures. Because multiple patterns can match the same set of nodes, one match may contain captures that appear *before* some of the captures from a previous match.
  2. Repeatedly call `ts_query_cursor_next_capture` to iterate over all of the individual *captures* in the order that they appear. This is useful if don't care about which pattern matched, and just want a single ordered sequence of captures.

If you don't care about consuming all of the results, you can stop calling `ts_query_cursor_next_match` or `ts_query_cursor_next_capture` at any point.

You can then start executing another query on another node by calling
`ts_query_cursor_exec` again.

func (*QueryCursor) Captures added in v1.9.0

func (qc *QueryCursor) Captures(q *Query, n Node, text []byte) QueryCaptures

Captures iterates over all of the individual captures in the order that they appear.

This is useful if you don't care about which pattern matched, and just want a single, ordered sequence of captures.

func (*QueryCursor) DidExceedMatchLimit added in v1.3.3

func (c *QueryCursor) DidExceedMatchLimit() bool

DidExceedMatchLimit see above.

func (*QueryCursor) MatchLimit added in v1.3.3

func (c *QueryCursor) MatchLimit() uint32

MatchLimit see above.

func (*QueryCursor) Matches added in v1.9.0

func (qc *QueryCursor) Matches(q *Query, n Node, text []byte) (qm QueryMatches)

Matches iterates over all of the matches in the order that they were found.

Each match contains the index of the pattern that matched, and a list of captures. Because multiple patterns can match the same set of nodes, one match may contain captures that appear *before* some of the captures from a previous match.

func (*QueryCursor) NextCapture

func (c *QueryCursor) NextCapture() (_ *QueryMatch, i uint)

func (*QueryCursor) NextMatch

func (c *QueryCursor) NextMatch() (_ *QueryMatch)

func (*QueryCursor) RemoveMatch added in v1.3.2

func (c *QueryCursor) RemoveMatch(matchID uint)

func (*QueryCursor) SetByteRange added in v1.3.0

func (c *QueryCursor) SetByteRange(start, end uint32)

SetByteRange sets the range of bytes in which the query will be executed.

func (*QueryCursor) SetMatchLimit added in v1.3.3

func (c *QueryCursor) SetMatchLimit(limit uint32)

SetMatchLimit see above.

func (*QueryCursor) SetMaxStartDepth added in v1.3.2

func (c *QueryCursor) SetMaxStartDepth(maxStartDepth uint32)

SetMaxStartDepth sets the maximum start depth for a query cursor.

This prevents cursors from exploring children nodes at a certain depth. Note if a pattern includes many children, then they will still be checked.

The zero max start depth value can be used as a special behavior and it helps to destructure a subtree by staying on a node and using captures for interested parts. Note that the zero max start depth only limit a search depth for a pattern's root node but other nodes that are parts of the pattern may be searched at any depth what defined by the pattern structure.

Set to UnlimitedMaxDepth to remove the maximum start depth.

func (*QueryCursor) SetPointRange

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

SetPointRange sets the range of row/column positions in which the query will be executed.

func (*QueryCursor) SetTimeout added in v1.7.0

func (c *QueryCursor) SetTimeout(micros int)

SetTimeout sets the maximum duration in microseconds that query execution should be allowed to take before halting.

If query execution takes longer than this, it will halt early, returning NULL. See [`ts_query_cursor_next_match`] or [`ts_query_cursor_next_capture`] for more information.

func (*QueryCursor) Timeout added in v1.7.0

func (c *QueryCursor) Timeout() (micros int)

Timeout returns the duration in microseconds that query execution is allowed to take.

This is set via [`ts_query_cursor_set_timeout_micros`].

type QueryError

type QueryError struct {
	Message string
	Offset  uint
	Kind    QueryErrorKind
	Point
	// contains filtered or unexported fields
}

QueryError holds detailed query error. The Offset argument will be set to the byte offset of the error, the Kind argument will be set to a value that indicates the type, of error and inner will represent the error class.

func (QueryError) Error

func (e QueryError) Error() string

func (QueryError) Unwrap added in v1.9.0

func (e QueryError) Unwrap() error

type QueryErrorKind added in v1.9.0

type QueryErrorKind uint32

QueryErrorKind indicates the type of QueryErrorKind.

const (
	QueryErrorNone      QueryErrorKind = C.TSQueryErrorNone
	QueryErrorSyntax    QueryErrorKind = C.TSQueryErrorSyntax
	QueryErrorNodeType  QueryErrorKind = C.TSQueryErrorNodeType
	QueryErrorField     QueryErrorKind = C.TSQueryErrorField
	QueryErrorCapture   QueryErrorKind = C.TSQueryErrorCapture
	QueryErrorStructure QueryErrorKind = C.TSQueryErrorStructure
	QueryErrorLanguage  QueryErrorKind = C.TSQueryErrorLanguage
	QueryErrorPredicate QueryErrorKind = 100
)

Error types.

func (QueryErrorKind) String added in v1.9.0

func (i QueryErrorKind) String() string

type QueryMatch

type QueryMatch struct {
	Captures     []QueryCapture
	PatternIndex uint
	ID           uint
	// contains filtered or unexported fields
}

QueryMatch allows you to iterate over the matches.

func (*QueryMatch) NodesForCaptureIndex added in v1.9.0

func (qm *QueryMatch) NodesForCaptureIndex(captureIndex uint) []Node

func (*QueryMatch) Remove added in v1.9.0

func (qm *QueryMatch) Remove()

type QueryMatches added in v1.9.0

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

QueryMatches holds a sequence of [QueryMatch]es associated with a given QueryCursor.

func (*QueryMatches) Next added in v1.9.0

func (qm *QueryMatches) Next() *QueryMatch

Next will return the next match in the sequence of matches.

Subsequent calls to QueryMatches.Next will overwrite the memory at the same location as prior matches, since the memory is reused. You can think of this as a stateful iterator. If you need to keep the data of a prior match without it being overwritten, you should copy what you need before calling QueryMatches.Next again.

If there are no more matches, it will return nil.

type QueryPredicate added in v1.9.0

type QueryPredicate struct {
	Operator string
	Args     []QueryPredicateArg
}

type QueryPredicateArg added in v1.9.0

type QueryPredicateArg struct {
	CaptureID *uint
	String    *string
}

type QueryPredicateStep

type QueryPredicateStep struct {
	Type    QueryPredicateStepType
	ValueID uint32
}

QueryPredicateStep represents one step in a predicate.

type QueryPredicateStepType

type QueryPredicateStepType uint32

QueryPredicateStepType represents type of step in a predicate.

const (
	QueryPredicateStepTypeDone    QueryPredicateStepType = C.TSQueryPredicateStepTypeDone
	QueryPredicateStepTypeCapture QueryPredicateStepType = C.TSQueryPredicateStepTypeCapture
	QueryPredicateStepTypeString  QueryPredicateStepType = C.TSQueryPredicateStepTypeString
)

Possible query predicate steps.

func (QueryPredicateStepType) String added in v1.4.3

func (i QueryPredicateStepType) String() string

type QueryPredicateSteps added in v1.3.4

type QueryPredicateSteps []QueryPredicateStep

QueryPredicateSteps holds all the steps for a predicate.

type QueryProperty added in v1.9.0

type QueryProperty struct {
	CaptureID *uint
	Value     *string
	Key       string
}

QueryProperty holds a kv pair associated with a particular pattern in a Query.

func NewQueryProperty added in v1.9.0

func NewQueryProperty(key string, value *string, captureID *uint) QueryProperty

type Range

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

Range represents a range in the input.

type ReadFunc

type ReadFunc func(offset uint32, position Point) []byte

ReadFunc is a function to retrieve a chunk of text at a given byte offset and (row, column) position. It should return nil to indicate the end of the document.

type StateID added in v1.3.2

type StateID = C.TSStateId

StateID is used for parser state ID.

type Symbol

type Symbol = C.TSSymbol

Symbol indicates the symbol.

type SymbolType

type SymbolType uint32

SymbolType indicates the type of symbol.

const (
	SymbolTypeRegular   SymbolType = C.TSSymbolTypeRegular
	SymbolTypeAnonymous SymbolType = C.TSSymbolTypeAnonymous
	SymbolTypeSupertype SymbolType = C.TSSymbolTypeSupertype
	SymbolTypeAuxiliary SymbolType = C.TSSymbolTypeAuxiliary
)

Possible symbol types.

func (SymbolType) String

func (i SymbolType) String() string

type TextPredicateCapture added in v1.9.0

type TextPredicateCapture struct {
	Value         any
	Type          TextPredicateType
	CaptureID     uint
	Positive      bool
	MatchAllNodes bool
}

type TextPredicateType added in v1.9.0

type TextPredicateType int
const (
	TextPredicateTypeEqCapture TextPredicateType = iota
	TextPredicateTypeEqString
	TextPredicateTypeMatchString
	TextPredicateTypeAnyString
)

type Tree

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

Tree represents the syntax tree of an entire source code file Note: Tree instances are not thread safe; you must copy a tree if you want to use it on multiple threads simultaneously.

func (*Tree) Close added in v1.11.0

func (t *Tree) Close()

Close releases the resources associated with the tree. After calling Close, the Tree must not be used again.

func (*Tree) Copy

func (t *Tree) Copy() *Tree

Copy creates a shallow copy of the syntax tree. This is very fast.

You need to copy a syntax tree in order to use it on more than one thread at a time, as syntax trees are not thread safe.

func (*Tree) Edit

func (t *Tree) Edit(i InputEdit)

Edit the syntax tree to keep it in sync with source code that has been edited.

You MUST describe the edit both in terms of byte offsets and in terms of (row, column) coordinates.

func (*Tree) GetChangedRanges added in v1.3.1

func (t *Tree) GetChangedRanges(other *Tree) []Range

GetChangedRanges compares an old edited syntax tree to a new syntax tree representing the same document, returning an array of ranges whose syntactic structure has changed.

For this to work correctly, the old syntax tree must have been edited such that its ranges match up to the new tree. Generally, you'll want to call this function right after calling one of the [`ts_parser_parse`] functions. You need to pass the old tree that was passed to parse, as well as the new tree that was returned from that function.

The returned array is allocated using `malloc` and the caller is responsible for freeing it using `free`. The length of the array will be written to the given `length` pointer.

func (*Tree) IncludedRanges added in v1.3.3

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

IncludedRanges returns the array of included ranges that was used to parse the syntax tree.

The returned pointer must be freed by the caller.

func (*Tree) Language added in v1.3.2

func (t *Tree) Language() *Language

Language returns the language that was used to parse the syntax tree.

func (*Tree) PrintDotGraph added in v1.3.3

func (t *Tree) PrintDotGraph(name string) (err error)

PrintDotGraph writes a DOT graph describing the syntax tree to the given file.

func (*Tree) RootNode

func (t *Tree) RootNode() Node

RootNode returns root node of the syntax tree.

func (*Tree) RootNodeWithOffset added in v1.3.3

func (t *Tree) RootNodeWithOffset(ofs uint32, extent Point) Node

RootNodeWithOffset returns the root node of the syntax tree, but with its position shifted forward by the given offset.

type TreeCursor

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

TreeCursor allows you to walk a syntax tree more efficiently than is possible using the `Node` functions. It is a mutable object that is always on a certain syntax node, and can be moved imperatively to different nodes.

func NewTreeCursor

func NewTreeCursor(n Node) (c *TreeCursor)

NewTreeCursor creates a new tree cursor starting from the given node.

A tree cursor allows you to walk a syntax tree more efficiently than is possible using the [`TSNode`] functions. It is a mutable object that is always on a certain syntax node, and can be moved imperatively to different nodes.

func (*TreeCursor) Copy added in v1.3.2

func (c *TreeCursor) Copy() *TreeCursor

Copy returns a copy of the tree cursor.

func (*TreeCursor) CurrentDepth added in v1.3.2

func (c *TreeCursor) CurrentDepth() uint32

CurrentDepth returns the depth of the cursor's current node relative to the original node that the cursor was constructed with.

func (*TreeCursor) CurrentDescendantIndex added in v1.3.2

func (c *TreeCursor) CurrentDescendantIndex() uint32

CurrentDescendantIndex returns the index of the cursor's current node out of all of the descendants of the original node that the cursor was constructed with.

func (*TreeCursor) CurrentFieldID added in v1.3.2

func (c *TreeCursor) CurrentFieldID() FieldID

CurrentFieldID returns the field id of the tree cursor's current node.

This returns zero if the current node doesn't have a field. See also `ts_node_child_by_field_id`, `ts_language_field_id_for_name`.

func (*TreeCursor) CurrentFieldName

func (c *TreeCursor) CurrentFieldName() string

CurrentFieldName gets the field name of the tree cursor's current node.

This returns empty string if the current node doesn't have a field. See also `ts_node_child_by_field_name`.

func (*TreeCursor) CurrentNode

func (c *TreeCursor) CurrentNode() Node

CurrentNode returns the cursor's current node.

func (*TreeCursor) GoToFirstChild

func (c *TreeCursor) GoToFirstChild() bool

GoToFirstChild moves the cursor to the first child of its current node.

This returns `true` if the cursor successfully moved, and returns `false` if there were no children.

func (*TreeCursor) GoToFirstChildForByte

func (c *TreeCursor) GoToFirstChildForByte(b uint32) int64

GoToFirstChildForByte moves the cursor to the first child of its current node that extends beyond the given byte offset.

This returns the index of the child node if one was found, and returns -1 if no such child was found.

func (*TreeCursor) GoToFirstChildForPoint added in v1.3.2

func (c *TreeCursor) GoToFirstChildForPoint(p Point) int64

GoToFirstChildForPoint moves the cursor to the first child of its current node that extends beyond the given point.

This returns the index of the child node if one was found, and returns -1 if no such child was found.

func (*TreeCursor) GoToNextSibling

func (c *TreeCursor) GoToNextSibling() bool

GoToNextSibling moves the cursor to the next sibling of its current node.

This returns `true` if the cursor successfully moved, and returns `false` if there was no next sibling node.

func (*TreeCursor) GoToParent

func (c *TreeCursor) GoToParent() bool

GoToParent moves the cursor to the parent of its current node.

This returns `true` if the cursor successfully moved, and returns `false` if there was no parent node (the cursor was already on the root node).

func (*TreeCursor) GotoDescendant added in v1.3.2

func (c *TreeCursor) GotoDescendant(goalDescendantIndex uint32)

GotoDescendant moves the cursor to the node that is the nth descendant of the original node that the cursor was constructed with, where zero represents the original node itself.

func (*TreeCursor) GotoLastChild added in v1.3.2

func (c *TreeCursor) GotoLastChild() bool

GotoLastChild moves the cursor to the last child of its current node.

This returns `true` if the cursor successfully moved, and returns `false` if there were no children.

Note that this function may be slower than [`ts_tree_cursor_goto_first_child`] because it needs to iterate through all the children to compute the child's position.

func (*TreeCursor) GotoPreviousSibling added in v1.3.2

func (c *TreeCursor) GotoPreviousSibling() bool

GotoPreviousSibling moves the cursor to the previous sibling of its current node.

This returns `true` if the cursor successfully moved, and returns `false` if there was no previous sibling node.

Note, that this function may be slower than `ts_tree_cursor_goto_next_sibling` due to how node positions are stored. In the worst case, this will need to iterate through all the children upto the previous sibling node to recalculate its position.

func (*TreeCursor) Reset

func (c *TreeCursor) Reset(n Node)

Reset re-initializes a tree cursor to start at the original node that the cursor was constructed with.

func (*TreeCursor) ResetTo added in v1.3.2

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

ResetTo re-initializes a tree cursor to the same position as another cursor.

Unlike `ts_tree_cursor_reset`, this will not lose parent information and allows reusing already created cursors.

Jump to

Keyboard shortcuts

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