tree_sitter

package module
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2025 License: MIT Imports: 11 Imported by: 46

README

Go Tree-sitter

CI Go version Version Docs

This repository contains Go bindings for the Tree-sitter parsing library.

To use this in your Go project, run:

go get github.com/tree-sitter/go-tree-sitter@latest

Example usage:

package main

import (
    "fmt"

    tree_sitter "github.com/tree-sitter/go-tree-sitter"
    tree_sitter_javascript "github.com/tree-sitter/tree-sitter-javascript/bindings/go"
)

func main() {
    code := []byte("const foo = 1 + 2")

    parser := tree_sitter.NewParser()
    defer parser.Close()
    parser.SetLanguage(tree_sitter.NewLanguage(tree_sitter_javascript.Language()))

    tree := parser.Parse(code, nil)
    defer tree.Close()

    root := tree.RootNode()
    fmt.Println(root.ToSexp())
}

By default, none of the grammars are included in this package. This way, you can only bring in what you need, but it's at the slight cost of having to call go get n times.

In the example above, to fetch the JavaScript grammar, you can run the following:

go get github.com/tree-sitter/tree-sitter-javascript@latest

Alternatively you can also load grammars at runtime from a shared library via purego.

The example below shows how to load the JavaScript grammar from a shared library (libtree-sitter-PARSER_NAME.so) at runtime on Linux & macOS:

For more information on other platforms, see the purego documentation

package main

import (
	tree_sitter "github.com/tree-sitter/go-tree-sitter"
	"github.com/ebitengine/purego"
)

func main() {
	path := "/path/to/your/parser.so"
	lib, err := purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_GLOBAL)
	if err != nil {
        // handle error
    }

	var javascriptLanguage func() uintptr
	purego.RegisterLibFunc(&javascriptLanguage, lib, "tree_sitter_javascript")

	language := tree_sitter.NewLanguage(unsafe.Pointer(javascriptLanguage()))
}

[!NOTE] Due to bugs with runtime.SetFinalizer and CGO, you must always call Close on an object that allocates memory from C. This must be done for the Parser, Tree, TreeCursor, Query, QueryCursor, and LookaheadIterator objects.

For more information, see the documentation.

Documentation

Index

Examples

Constants

View Source
const LANGUAGE_VERSION = C.TREE_SITTER_LANGUAGE_VERSION
View Source
const MIN_COMPATIBLE_LANGUAGE_VERSION = C.TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION

Variables

This section is empty.

Functions

func NewQuery

func NewQuery(language *Language, source string) (*Query, *QueryError)

func SetAllocator

func SetAllocator(
	newMalloc func(size uint) unsafe.Pointer,
	newCalloc func(num, size uint) unsafe.Pointer,
	newRealloc func(ptr unsafe.Pointer, size uint) unsafe.Pointer,
	newFree func(ptr unsafe.Pointer),
)

Sets the memory allocation functions that the core library should use.

Types

type CaptureQuantifier

type CaptureQuantifier int
const (
	CaptureQuantifierZero CaptureQuantifier = iota
	CaptureQuantifierZeroOrOne
	CaptureQuantifierZeroOrMore
	CaptureQuantifierOne
	CaptureQuantifierOneOrMore
)

type Decoder added in v0.25.0

type Decoder interface {
	// Decode takes a byte slice and returns the decoded code point and number of bytes consumed
	// Returns -1 as codePoint if decoding fails
	Decode(data []byte) (codePoint int32, bytesRead uint32)
}

Decoder interface defines the required method for custom decoding

type IncludedRangesError

type IncludedRangesError struct {
	Index uint32
}

An error that occurred in Parser.SetIncludedRanges.

func (*IncludedRangesError) Error

func (i *IncludedRangesError) Error() string

type InputEdit

type InputEdit struct {
	StartByte      uint
	OldEndByte     uint
	NewEndByte     uint
	StartPosition  Point
	OldEndPosition Point
	NewEndPosition Point
}

type Language

type Language struct {
	Inner *C.TSLanguage
}

An opaque object that defines how to parse a particular language. The code for each Language is generated by the Tree-sitter CLI.

func NewLanguage

func NewLanguage(ptr unsafe.Pointer) *Language

func (*Language) AbiVersion added in v0.25.0

func (l *Language) AbiVersion() uint32

Get the ABI version number that indicates which version of the Tree-sitter CLI that was used to generate this Language.

func (*Language) FieldCount

func (l *Language) FieldCount() uint32

Get the number of distinct field names in this language.

func (*Language) FieldIdForName

func (l *Language) FieldIdForName(name string) uint16

Get the numerical id for the given field name.

func (*Language) FieldNameForId

func (l *Language) FieldNameForId(id uint16) string

Get the field names for the given numerical id.

func (*Language) IdForNodeKind

func (l *Language) IdForNodeKind(kind string, named bool) uint16

Get the numeric id for the given node kind.

func (*Language) LookaheadIterator

func (l *Language) LookaheadIterator(state uint16) *LookaheadIterator

Create a new lookahead iterator for this language and parse state.

This returns `nil` if state is invalid for this language.

Iterating LookaheadIterator will yield valid symbols in the given parse state. Newly created lookahead iterators will return the `ERROR` symbol from LookaheadIterator.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 (*Language) Metadata added in v0.25.0

func (l *Language) Metadata() *LanguageMetadata

Get the metadata for this language. This information is generated by the CLI, and relies on the language author providing the correct metadata in the language's `tree-sitter.json` file.

func (*Language) NextState

func (l *Language) NextState(state uint16, id uint16) uint16

Get the next parse state. Combine this with Language.LookaheadIterator to generate completion suggestions or valid symbols in error nodes.

func (*Language) NodeKindCount

func (l *Language) NodeKindCount() uint32

Get the number of distinct node types in this language.

func (*Language) NodeKindForId

func (l *Language) NodeKindForId(id uint16) string

Get the name of the node kind for the given numerical id.

func (*Language) NodeKindIsNamed

func (l *Language) NodeKindIsNamed(id uint16) bool

Check if the node type for the given numerical id is named (as opposed to an anonymous node type).

func (*Language) NodeKindIsSupertype added in v0.24.0

func (l *Language) NodeKindIsSupertype(id uint16) bool

Check if the node type for the given numerical id is a supertype.

func (*Language) NodeKindIsVisible

func (l *Language) NodeKindIsVisible(id uint16) bool

Check if the node type for the given numerical id is visible (as opposed to a hidden node type).

func (*Language) ParseStateCount

func (l *Language) ParseStateCount() uint32

Get the number of valid states in this language.

func (*Language) Version deprecated

func (l *Language) Version() uint32

Deprecated: Use Language.AbiVersion instead.

Get the ABI version number that indicates which version of the Tree-sitter CLI that was used to generate this Language.

type LanguageError

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

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

func (*LanguageError) Error

func (l *LanguageError) Error() string

type LanguageMetadata added in v0.25.0

type LanguageMetadata struct {
	MajorVersion uint8
	MinorVersion uint8
	PatchVersion uint8
}

The metadata associated with a language.

Currently, this metadata can be used to check the [Semantic Version](https://semver.org/) of the language. This version information should be used to signal if a given parser might be incompatible with existing queries when upgrading between major versions, or minor versions if it's in zerover.

type LogType

type LogType int
const (
	LogTypeParse LogType = iota
	LogTypeLex
)

type Logger

type Logger = func(LogType, string)

A callback that receives log messages during parser.

type LookaheadIterator

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

func (*LookaheadIterator) Close

func (l *LookaheadIterator) Close()

func (*LookaheadIterator) Iter

func (l *LookaheadIterator) Iter() []uint16

Iterate symbols.

func (*LookaheadIterator) IterNames

func (l *LookaheadIterator) IterNames() []string

Iterate symbol names.

func (*LookaheadIterator) Language

func (l *LookaheadIterator) Language() *Language

func (*LookaheadIterator) Reset

func (l *LookaheadIterator) Reset(language *Language, state uint16) bool

Reset the lookahead iterator.

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

func (*LookaheadIterator) ResetState

func (l *LookaheadIterator) ResetState(state uint16) bool

Reset the lookahead iterator to another state.

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

func (*LookaheadIterator) Symbol

func (l *LookaheadIterator) Symbol() uint16

Get the current symbol of the lookahead iterator.

func (*LookaheadIterator) SymbolName

func (l *LookaheadIterator) SymbolName() string

Get the current symbol name of the lookahead iterator.

type Node

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

A single node within a syntax Tree. Note that this is a C-compatible struct

Example
parser := NewParser()
defer parser.Close()

language := NewLanguage(tree_sitter_go.Language())

parser.SetLanguage(language)

tree := parser.Parse(
	[]byte(`
			package main


			func main() {
				return
			}
		`),
	nil,
)
defer tree.Close()

rootNode := tree.RootNode()
fmt.Println(rootNode.Kind())
fmt.Println(rootNode.StartPosition())
fmt.Println(rootNode.EndPosition())

functionNode := rootNode.Child(1)
fmt.Println(functionNode.Kind())
fmt.Println(functionNode.ChildByFieldName("name").Kind())

functionNameNode := functionNode.Child(1)
fmt.Println(functionNameNode.StartPosition())
fmt.Println(functionNameNode.EndPosition())
Output:

source_file
{1 3}
{7 2}
function_declaration
identifier
{4 8}
{4 12}

func (*Node) ByteRange

func (n *Node) ByteRange() (uint, uint)

Get the byte range of source code that this node represents.

func (*Node) Child

func (n *Node) Child(i uint) *Node

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

This method is fairly fast, but its cost is technically log(i), so if you might be iterating over a long list of children, you should use Node.Children instead.

func (*Node) ChildByFieldId

func (n *Node) ChildByFieldId(fieldId uint16) *Node

Get this node's child with the given numerical field id.

See also Node.ChildByFieldName. You can convert a field name to an id using Language.FieldIdForName.

func (*Node) ChildByFieldName

func (n *Node) ChildByFieldName(fieldName string) *Node

Get the first child with the given field name.

If multiple children may have the same field name, access them using Node.ChildrenByFieldName

func (*Node) ChildCount

func (n *Node) ChildCount() uint

Get this node's number of children.

func (*Node) ChildWithDescendant added in v0.24.0

func (n *Node) ChildWithDescendant(descendant *Node) *Node

Get the node that contains `descendant`. Note that this can return `descendant` itself.

func (*Node) Children

func (n *Node) Children(cursor *TreeCursor) []Node

Iterate over this node's children.

A TreeCursor is used to retrieve the children efficiently. Obtain a TreeCursor by calling Tree.Walk or Node.Walk. To avoid unnecessary allocations, you should reuse the same cursor for subsequent calls to this method.

If you're walking the tree recursively, you may want to use the TreeCursor APIs directly instead.

func (*Node) ChildrenByFieldName

func (n *Node) ChildrenByFieldName(fieldName string, cursor *TreeCursor) []Node

Iterate over this node's children with a given field name.

See also Node.Children.

func (*Node) DescendantCount

func (n *Node) DescendantCount() uint

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

func (*Node) DescendantForByteRange

func (n *Node) DescendantForByteRange(start, end uint) *Node

Get the smallest node within this node that spans the given range.

func (*Node) DescendantForPointRange

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

Get the smallest node within this node that spans the given range.

func (*Node) Edit

func (n *Node) Edit(edit *InputEdit)

Edit this 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 Tree.Edit method, all of the nodes that you retrieve from the tree afterward will already reflect the edit. You only need to use Node.Edit when you have a specific Node instance that you want to keep and continue to use after an edit.

func (*Node) EndByte

func (n *Node) EndByte() uint

Get the byte offsets where this node end.

func (*Node) EndPosition

func (n *Node) EndPosition() Point

Get this node's end position in terms of rows and columns.

func (*Node) Equals added in v0.25.0

func (n *Node) Equals(other Node) bool

Check if two nodes are identical.

func (*Node) FieldNameForChild

func (n *Node) FieldNameForChild(childIndex uint32) string

Get the field name of this node's child at the given index.

func (*Node) FieldNameForNamedChild added in v0.24.0

func (n *Node) FieldNameForNamedChild(namedChildIndex uint32) string

Get the field name of this node's named child at the given index.

func (*Node) FirstChildForByte added in v0.24.0

func (n *Node) FirstChildForByte(byteOffset uint) *Node

Get the node's first child that contains or starts after the given byte offset.

func (*Node) FirstNamedChildForByte added in v0.24.0

func (n *Node) FirstNamedChildForByte(byteOffset uint) *Node

Get the node's first named child that contains or starts after the given byte offset.

func (*Node) GrammarId

func (n *Node) GrammarId() uint16

Get the node's type as a numerical id as it appears in the grammar ignoring aliases.

func (*Node) GrammarName

func (n *Node) GrammarName() string

Get this node's symbol name as it appears in the grammar ignoring aliases as a string.

func (*Node) HasChanges

func (n *Node) HasChanges() bool

Check if this node has been edited.

func (*Node) HasError

func (n *Node) HasError() bool

Check if this node represents a syntax error or contains any syntax errors anywhere within it.

func (*Node) Id

func (n *Node) Id() uintptr

Get a numeric id for this node that is unique.

Within a given syntax tree, no two nodes have the same id. However, if a new tree is created based on an older tree, and a node from the old tree is reused in the process, then that node will have the same id in both trees.

func (*Node) IsError

func (n *Node) IsError() bool

Check if this node represents 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

Check if this node is *extra*.

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

func (*Node) IsMissing

func (n *Node) IsMissing() bool

Check if this 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

Check if this node is *named*.

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

func (*Node) Kind

func (n *Node) Kind() string

Get this node's type as a string.

func (*Node) KindId

func (n *Node) KindId() uint16

Get this node's type as a numerical id.

func (*Node) Language

func (n *Node) Language() *Language

Get the Language that was used to parse this node's syntax tree.

func (*Node) NamedChild

func (n *Node) NamedChild(i uint) *Node

Get this node's *named* child at the given index.

See also Node.IsNamed. This method is fairly fast, but its cost is technically log(i), so if you might be iterating over a long list of children, you should use Node.NamedChildren instead.

func (*Node) NamedChildCount

func (n *Node) NamedChildCount() uint

Get this node's number of *named* children.

See also Node.IsNamed.

func (*Node) NamedChildren

func (n *Node) NamedChildren(cursor *TreeCursor) []Node

Iterate over this node's named children.

See also Node.Children.

func (*Node) NamedDescendantForByteRange

func (n *Node) NamedDescendantForByteRange(start, end uint) *Node

Get the smallest named node within this node that spans the given range.

func (*Node) NamedDescendantForPointRange

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

Get the smallest named node within this node that spans the given range.

func (*Node) NextNamedSibling

func (n *Node) NextNamedSibling() *Node

Get this node's next named sibling.

func (*Node) NextParseState

func (n *Node) NextParseState() uint16

Get the parse state after this node.

func (*Node) NextSibling

func (n *Node) NextSibling() *Node

Get this node's next sibling.

func (*Node) Parent

func (n *Node) Parent() *Node

Get this node's immediate parent. Prefer Node.ChildWithDescendant for iterating over this node's ancestors.

func (*Node) ParseState

func (n *Node) ParseState() uint16

Get this node's parse state.

func (*Node) PrevNamedSibling

func (n *Node) PrevNamedSibling() *Node

Get this node's previous named sibling.

func (*Node) PrevSibling

func (n *Node) PrevSibling() *Node

Get this node's previous sibling.

func (*Node) Range

func (n *Node) Range() Range

Get the range of source code that this node represents, both in terms of raw bytes and of row/column coordinates.

func (*Node) StartByte

func (n *Node) StartByte() uint

Get the byte offsets where this node starts.

func (*Node) StartPosition

func (n *Node) StartPosition() Point

Get this node's start position in terms of rows and columns.

func (*Node) ToSexp

func (n *Node) ToSexp() string

func (*Node) Utf16Text

func (n *Node) Utf16Text(source []uint16) []uint16

func (*Node) Utf8Text

func (n *Node) Utf8Text(source []byte) string

func (*Node) Walk

func (n *Node) Walk() *TreeCursor

Create a new TreeCursor starting from this node.

Note that the given node is considered the root of the cursor, and the cursor cannot walk outside this node.

type ParseOptions added in v0.25.0

type ParseOptions struct {
	// A function that is called periodically during parsing to check
	// whether parsing should be cancelled. If the progress callback returns
	// `true`, then parsing will be cancelled. You can also use this to instrument
	// parsing and check where the parser is at in the document. The progress callback
	// takes a single argument, which is a [ParseState] representing the current
	// state of the parser.
	ProgressCallback func(ParseState) bool
}

Options for parsing

The [ParseOptions.ProgressCallback] property is a function that is called periodically during parsing to check whether parsing should be cancelled.

See Parser.ParseWithOptions for more information.

type ParseState added in v0.25.0

type ParseState struct {
	// The byte offset in the document that the parser is at.
	CurrentByteOffset uint32

	// Indicates whether the parser has encountered an error during parsing.
	HasError bool
}

A stateful object that is passed into the progress callback [ParseOptions.ProgressCallback] to provide the current state of the parser.

type Parser

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

A stateful object that this is used to produce a Tree based on some source code.

func NewParser

func NewParser() *Parser

Create a new parser.

func (*Parser) CancellationFlag deprecated

func (p *Parser) CancellationFlag() *uintptr

Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.

Get the parser's current cancellation flag pointer.

func (*Parser) Close

func (p *Parser) Close()

func (*Parser) IncludedRanges

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

Get the ranges of text that the parser will include when parsing.

func (*Parser) Language

func (p *Parser) Language() *Language

Get the parser's current language.

func (*Parser) Logger

func (p *Parser) Logger() *Logger

Get the parser's current logger.

func (*Parser) Parse

func (p *Parser) Parse(text []byte, oldTree *Tree) *Tree

Parse a slice of UTF8 text.

Arguments:

  • `text` The UTF8-encoded text to parse.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
Example
parser := NewParser()
defer parser.Close()

language := NewLanguage(tree_sitter_go.Language())

parser.SetLanguage(language)

tree := parser.Parse(
	[]byte(`
			package main


			func main() {
				return
			}
		`),
	nil,
)
defer tree.Close()

rootNode := tree.RootNode()
fmt.Println(rootNode.ToSexp())
Output:

(source_file (package_clause (package_identifier)) (function_declaration name: (identifier) parameters: (parameter_list) body: (block (return_statement))))

func (*Parser) ParseCtx deprecated

func (p *Parser) ParseCtx(ctx context.Context, text []byte, oldTree *Tree) *Tree

Deprecated: Use Parser.ParseWithOptions instead, and handle cancellation in the callback, this will be removed in 0.26.

Parse a slice of UTF8 text.

Arguments:

  • `ctx` The context to parse with.
  • `text` The UTF8-encoded text to parse.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.

func (*Parser) ParseCustomEncoding added in v0.25.0

func (p *Parser) ParseCustomEncoding(
	callback func(int, Point) []byte,
	oldTree *Tree,
	options *ParseOptions,
	decode unsafe.Pointer,
) *Tree

Parse text provided in chunks by a callback using a custom encoding. This is useful for parsing text in encodings that are not UTF-8 or UTF-16.

Arguments:

  • `callback` A function that takes a byte offset and position and returns a slice of text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using [`Tree::edit`].
  • `options` Options for parsing the text. This can be used to set a progress callback.
  • `decode` A function that takes a byte slice and returns the number of bytes consumed. It will also write the resulting code point to `codePoint`. If decoding fails, the function should write -1 to the code point. The signature for the function is the following: func myDecodeFn(data *C.char, length C.uint32_t, codePoint *C.int32_t) C.uint32_t Note that this function *must* be a C function, as it's called many times during parsing. To have a Go function be callable from C, you must use the `//export` directive. More info can be found at https://pkg.go.dev/cmd/cgo#hdr-C_references_to_Go. The reason for this is that knowing the function body at compile time rather than loading it at runtime is important for performance. This is also a significantly advanced feature, and should only be used if you have a good reason to do so, and understand how to implement the C function. An example of how to use this can be found in `parser_test.go`.

func (*Parser) ParseUTF16 deprecated

func (p *Parser) ParseUTF16(text []uint16, oldTree *Tree) *Tree

Deprecated: Use Parser.ParseUTF16LE or Parser.ParseUTF16BE instead. Parse a slice of UTF16 text.

Arguments:

  • `text` The UTF16-encoded text to parse.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.

func (*Parser) ParseUTF16BE added in v0.24.0

func (p *Parser) ParseUTF16BE(text []uint16, oldTree *Tree) *Tree

/ Parse a slice of UTF16 big-endian text. / / # Arguments: / * `text` The UTF16-encoded text to parse. / * `old_tree` A previous syntax tree parsed from the same document. If the text of the / document has changed since `old_tree` was created, then you must edit `old_tree` to match / the new text using Tree.Edit.

func (*Parser) ParseUTF16BEWith deprecated added in v0.24.0

func (p *Parser) ParseUTF16BEWith(callback func(int, Point) []uint16, oldTree *Tree) *Tree

Deprecated: Use Parser.ParseUTF16BEWithOptions instead, this will be removed in 0.26.

Parse UTF16 big-endian text provided in chunks by a callback.

Arguments:

  • `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.

func (*Parser) ParseUTF16BEWithOptions added in v0.25.0

func (p *Parser) ParseUTF16BEWithOptions(callback func(int, Point) []uint16, oldTree *Tree, options *ParseOptions) *Tree

Parse UTF16 big-endian text provided in chunks by a callback.

Arguments:

  • `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
  • `options` Options for parsing the text. This can be used to set a progress callback.

func (*Parser) ParseUTF16LE added in v0.24.0

func (p *Parser) ParseUTF16LE(text []uint16, oldTree *Tree) *Tree

/ Parse a slice of UTF16 little-endian text. / / # Arguments: / * `text` The UTF16-encoded text to parse. / * `old_tree` A previous syntax tree parsed from the same document. If the text of the / document has changed since `old_tree` was created, then you must edit `old_tree` to match / the new text using Tree.Edit.

func (*Parser) ParseUTF16LEWith deprecated added in v0.24.0

func (p *Parser) ParseUTF16LEWith(callback func(int, Point) []uint16, oldTree *Tree) *Tree

Deprecated: Use Parser.ParseUTF16LEWithOptions instead, this will be removed in 0.26.

Parse UTF16 little-endian text provided in chunks by a callback.

Arguments:

  • `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.

func (*Parser) ParseUTF16LEWithOptions added in v0.25.0

func (p *Parser) ParseUTF16LEWithOptions(callback func(int, Point) []uint16, oldTree *Tree, options *ParseOptions) *Tree

Parse UTF16 little-endian text provided in chunks by a callback.

Arguments:

  • `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
  • `options` Options for parsing the text. This can be used to set a progress callback.

func (*Parser) ParseUTF16With deprecated

func (p *Parser) ParseUTF16With(callback func(int, Point) []uint16, oldTree *Tree) *Tree

Deprecated: Use Parser.ParseUTF16LEWith or Parser.ParseUTF16BEWith instead, this will be removed in 0.26.

Parse UTF16 text provided in chunks by a callback.

Arguments:

  • `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.

func (*Parser) ParseWith deprecated

func (p *Parser) ParseWith(callback func(int, Point) []byte, oldTree *Tree) *Tree

Deprecated: Use Parser.ParseWithOptions instead, this will be removed in 0.26.

Parse UTF8 text provided in chunks by a callback.

Arguments:

  • `callback` A function that takes a byte offset and position and returns a slice of UTF8-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.

func (*Parser) ParseWithOptions added in v0.25.0

func (p *Parser) ParseWithOptions(callback func(int, Point) []byte, oldTree *Tree, options *ParseOptions) *Tree

Parse UTF8 text provided in chunks by a callback.

Arguments:

  • `callback` A function that takes a byte offset and position and returns a slice of UTF8-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
  • `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
  • `options` Options for parsing the text. This can be used to set a progress callback, or context.
Example
parser := NewParser()
defer parser.Close()

language := NewLanguage(tree_sitter_go.Language())

parser.SetLanguage(language)

sourceCode := []byte(`
			package main

			func main() {
				return
			}
	`)

readCallback := func(offset int, position Point) []byte {
	return sourceCode[offset:]
}

tree := parser.ParseWithOptions(readCallback, nil, nil)
defer tree.Close()

rootNode := tree.RootNode()
fmt.Println(rootNode.ToSexp())
Output:

(source_file (package_clause (package_identifier)) (function_declaration name: (identifier) parameters: (parameter_list) body: (block (return_statement))))

func (*Parser) PrintDotGraphs

func (p *Parser) PrintDotGraphs(file *os.File)

Set the destination to which the parser should 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.

func (*Parser) Reset

func (p *Parser) Reset()

Instruct 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 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 `Reset` first.

func (*Parser) SetCancellationFlag deprecated

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

Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.

Set the parser's current cancellation flag pointer.

If a 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 `nil`. See Parser.Parse for more information.

func (*Parser) SetIncludedRanges

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

Set 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.

If `ranges` is empty, 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` < `length - 1`:

ranges[i].end_byte <= ranges[i + 1].start_byte

If this requirement is not satisfied, method will return IncludedRangesError error with an offset in the passed ranges slice pointing to a first incorrect range.

func (*Parser) SetLanguage

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

Set the language that the parser should use for parsing.

Returns an error indicating whether or not the language was successfully assigned. Nil means assignment succeeded. Non-nil means there was a version mismatch: the language was generated with an incompatible version of the Tree-sitter CLI. Check the language's ABI version using Language.Version and compare it to this library's LANGUAGE_VERSION and MIN_COMPATIBLE_LANGUAGE_VERSION constants.

func (*Parser) SetLogger

func (p *Parser) SetLogger(logger Logger)

Set the logging callback that a parser should use during parsing.

func (*Parser) SetTimeoutMicros deprecated

func (p *Parser) SetTimeoutMicros(timeoutMicros uint64)

Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.

Set 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 `nil`. See Parser.Parse for more information.

func (*Parser) StopPrintingDotGraphs

func (p *Parser) StopPrintingDotGraphs()

Stop the parser from printing debugging graphs while parsing.

func (*Parser) TimeoutMicros deprecated

func (p *Parser) TimeoutMicros() uint64

Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.

Get the duration in microseconds that parsing is allowed to take.

This is set via Parser.SetTimeoutMicros.

type Point

type Point struct {
	Row    uint
	Column uint
}

A position in a multi-line text document, in terms of rows and columns.

Rows and columns are zero-based.

func NewPoint

func NewPoint(row, column uint) Point

type PropertyPredicate

type PropertyPredicate struct {
	Property QueryProperty
	Positive bool
}

type Query

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

func (*Query) CaptureIndexForName

func (q *Query) CaptureIndexForName(name string) (uint, bool)

Get the index for a given capture name.

func (*Query) CaptureNames

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

Get the names of the captures used in the query.

func (*Query) CaptureQuantifiers

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

Get the quantifiers of the captures used in the query.

func (*Query) Close

func (q *Query) Close()

func (*Query) DisableCapture

func (q *Query) DisableCapture(captureName string)

Disable 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.

func (*Query) DisablePattern

func (q *Query) DisablePattern(index uint)

Disable a certain pattern within a query.

This prevents the pattern from matching, and also avoids any resource usage associated with the pattern.

func (*Query) EndByteForPattern

func (q *Query) EndByteForPattern(index uint) uint

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

func (*Query) GeneralPredicates

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

Get 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

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

Check if a given step in a query is 'definite'.

A query step is 'definite' if its parent pattern will be guaranteed to match successfully once it reaches the step.

func (*Query) IsPatternNonLocal

func (q *Query) IsPatternNonLocal(index uint) bool

Check if a given pattern within a query has a single root node.

func (*Query) IsPatternRooted

func (q *Query) IsPatternRooted(index uint) bool

Check if a given pattern within a query has a single root node.

func (*Query) PatternCount

func (q *Query) PatternCount() uint

Get the number of patterns in the query.

func (*Query) PropertyPredicates

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

Get the properties that are checked for the given pattern index.

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

func (*Query) PropertySettings

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

Get the properties that are set for the given pattern index.

This includes predicates with the operator `set!`.

func (*Query) StartByteForPattern

func (q *Query) StartByteForPattern(index uint) uint

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

type QueryCapture

type QueryCapture struct {
	Node  Node
	Index uint32
}

A particular Node that has been captured with a particular name within a Query. Note that this is a C-compatible struct

type QueryCaptures

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

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

func (*QueryCaptures) Next

func (qc *QueryCaptures) Next() (*QueryMatch, 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.

func (*QueryCaptures) SetByteRange

func (qc *QueryCaptures) SetByteRange(startByte uint, endByte uint)

func (*QueryCaptures) SetPointRange

func (qc *QueryCaptures) SetPointRange(startPoint Point, endPoint Point)

type QueryCursor

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

A stateful object for executing a Query on a syntax Tree.

func NewQueryCursor

func NewQueryCursor() *QueryCursor

Create a new cursor for executing a given query.

The cursor stores the state that is needed to iteratively search for matches.

func (*QueryCursor) Captures

func (qc *QueryCursor) Captures(query *Query, node *Node, text []byte) QueryCaptures

Iterate 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.

Example
language := NewLanguage(tree_sitter_go.Language())
parser := NewParser()
defer parser.Close()
parser.SetLanguage(language)

sourceCode := []byte(`
		package main

		import "fmt"

		func main() { fmt.Println("Hello, world!") }
	`)

tree := parser.Parse(sourceCode, nil)
defer tree.Close()

query, err := NewQuery(
	language,
	`
		(function_declaration
			name: (identifier) @function.name
			body: (block) @function.block
		)
		`,
)
if err != nil {
	panic(err)
}
defer query.Close()

qc := NewQueryCursor()
defer qc.Close()

captures := qc.Captures(query, tree.RootNode(), sourceCode)

for match, index := captures.Next(); match != nil; match, index = captures.Next() {
	fmt.Printf(
		"Capture %d: %s\n",
		index,
		match.Captures[index].Node.Utf8Text(sourceCode),
	)
}
Output:

Capture 0: main
Capture 1: { fmt.Println("Hello, world!") }

func (*QueryCursor) Close

func (qc *QueryCursor) Close()

Delete the underlying memory for a query cursor.

func (*QueryCursor) DidExceedMatchLimit

func (qc *QueryCursor) DidExceedMatchLimit() bool

Check if, on its last execution, this cursor exceeded its maximum number of in-progress matches.

func (*QueryCursor) MatchLimit

func (qc *QueryCursor) MatchLimit() uint

Return the maximum number of in-progress matches for this cursor.

func (*QueryCursor) Matches

func (qc *QueryCursor) Matches(query *Query, node *Node, text []byte) QueryMatches

Iterate 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.

Example
language := NewLanguage(tree_sitter_go.Language())
parser := NewParser()
defer parser.Close()
parser.SetLanguage(language)

sourceCode := []byte(`
		package main

		import "fmt"

		func main() { fmt.Println("Hello, world!") }
	`)

tree := parser.Parse(sourceCode, nil)
defer tree.Close()

query, err := NewQuery(
	language,
	`
		(function_declaration
			name: (identifier) @function.name
			body: (block) @function.block
		)
		`,
)
if err != nil {
	panic(err)
}
defer query.Close()

qc := NewQueryCursor()
defer qc.Close()

matches := qc.Matches(query, tree.RootNode(), sourceCode)

for match := matches.Next(); match != nil; match = matches.Next() {
	for _, capture := range match.Captures {
		fmt.Printf(
			"Match %d, Capture %d (%s): %s\n",
			match.PatternIndex,
			capture.Index,
			query.CaptureNames()[capture.Index],
			capture.Node.Utf8Text(sourceCode),
		)
	}
}
Output:

Match 0, Capture 0 (function.name): main
Match 0, Capture 1 (function.block): { fmt.Println("Hello, world!") }

func (*QueryCursor) MatchesWithOptions added in v0.25.0

func (qc *QueryCursor) MatchesWithOptions(query *Query, node *Node, text []byte, options QueryCursorOptions) QueryMatches

Iterate over all of the matches in the order that they were found, with options.

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) SetByteRange

func (qc *QueryCursor) SetByteRange(startByte uint, endByte uint) *QueryCursor

Set the range of bytes in which the query will be executed.

The query cursor will return matches that intersect with the given point range. This means that a match may be returned even if some of its captures fall outside the specified range, as long as at least part of the match overlaps with the range.

For example, if a query pattern matches a node that spans a larger area than the specified range, but part of that node intersects with the range, the entire match will be returned.

This will have no effect if the start byte is greater than the end byte.

func (*QueryCursor) SetMatchLimit

func (qc *QueryCursor) SetMatchLimit(limit uint)

Set the maximum number of in-progress matches for this cursor. The limit must be > 0 and <= 65536.

func (*QueryCursor) SetMaxStartDepth

func (qc *QueryCursor) SetMaxStartDepth(depth *uint) *QueryCursor

Set 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 `nil` to remove the maximum start depth.

func (*QueryCursor) SetPointRange

func (qc *QueryCursor) SetPointRange(startPoint Point, endPoint Point) *QueryCursor

Set the range of (row, column) positions in which the query will be executed.

The query cursor will return matches that intersect with the given point range. This means that a match may be returned even if some of its captures fall outside the specified range, as long as at least part of the match overlaps with the range.

For example, if a query pattern matches a node that spans a larger area than the specified range, but part of that node intersects with the range, the entire match will be returned.

This will have no effect if the start point is greater than the end point.

func (*QueryCursor) SetTimeoutMicros added in v0.24.0

func (qc *QueryCursor) SetTimeoutMicros(timeoutMicros uint64)

Set 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 None.

func (*QueryCursor) TimeoutMicros added in v0.24.0

func (qc *QueryCursor) TimeoutMicros() uint64

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

This is set via QueryCursor.SetTimeoutMicros

type QueryCursorOptions added in v0.25.0

type QueryCursorOptions struct {
	// A function that will be called periodically during the execution of the query to check
	// if query execution should be cancelled. If the progress callback returns `true`, then
	// query execution will be canceled. You can also use this to instrument query execution
	// and check where the query is at in the document. The progress callback takes a single
	// argument, which is a [QueryCursorState] representing the current state of the query.
	ProgressCallback func(QueryCursorState) bool
}

Options for query execution

type QueryCursorState added in v0.25.0

type QueryCursorState struct {
	// The byte offset in the document that the query is at.
	CurrentByteOffset uint32
}

A stateful object that is passed into the progress callback [QueryOptions.ProgressCallback]. to provide the current state of the query.

type QueryError

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

func (QueryError) Error

func (e QueryError) Error() string

type QueryErrorKind

type QueryErrorKind int
const (
	QueryErrorSyntax QueryErrorKind = iota
	QueryErrorNodeType
	QueryErrorField
	QueryErrorCapture
	QueryErrorPredicate
	QueryErrorStructure
	QueryErrorLanguage
)

type QueryMatch

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

A match of a Query to a particular set of [Node]s.

func (*QueryMatch) Id

func (qm *QueryMatch) Id() uint

func (*QueryMatch) NodesForCaptureIndex

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

func (*QueryMatch) Remove

func (qm *QueryMatch) Remove()

func (*QueryMatch) SatisfiesTextPredicate

func (qm *QueryMatch) SatisfiesTextPredicate(query *Query, buffer1, buffer2 []byte, text []byte) bool

type QueryMatches

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

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

func (*QueryMatches) Next

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.

func (*QueryMatches) SetByteRange

func (qm *QueryMatches) SetByteRange(startByte uint, endByte uint)

func (*QueryMatches) SetPointRange

func (qm *QueryMatches) SetPointRange(startPoint Point, endPoint Point)

type QueryPredicate

type QueryPredicate struct {
	Operator string
	Args     []QueryPredicateArg
}

A key-value pair associated with a particular pattern in a Query.

type QueryPredicateArg

type QueryPredicateArg struct {
	CaptureId *uint
	String    *string
}

type QueryProperty

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

A key-value pair associated with a particular pattern in a Query.

func NewQueryProperty

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

type Range

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

A range of positions in a multi-line text document, both in terms of bytes and of rows and columns.

func (*Range) FromTSRange

func (r *Range) FromTSRange(tr C.TSRange)

func (*Range) ToTSRange

func (r *Range) ToTSRange() C.TSRange

type TextPredicateCapture

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

type TextPredicateType

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

type Tree

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

A stateful object that this is used to produce a Tree based on some source code.

Example
parser := NewParser()
defer parser.Close()

language := NewLanguage(tree_sitter_go.Language())

parser.SetLanguage(language)

source := []byte(`
			package main


			func main() {
				return
			}
	`)

tree := parser.Parse(source, nil)
defer tree.Close()

// We change the return statement to `return 1`

newSource := append([]byte(nil), source[:46]...)
newSource = append(newSource, []byte(" 1")...)
newSource = append(newSource, source[46:]...)

edit := &InputEdit{
	StartByte:      46,
	OldEndByte:     46,
	NewEndByte:     46 + 2,
	StartPosition:  Point{Row: 5, Column: 9},
	OldEndPosition: Point{Row: 5, Column: 9},
	NewEndPosition: Point{Row: 5, Column: 9 + 2},
}

tree.Edit(edit)

newTree := parser.Parse(newSource, tree)
defer newTree.Close()

for _, changedRange := range tree.ChangedRanges(newTree) {
	fmt.Println("Changed range:")
	fmt.Printf(" Start point: %v\n", changedRange.StartPoint)
	fmt.Printf(" End point: %v\n", changedRange.EndPoint)
	fmt.Printf(" Start byte: %d\n", changedRange.StartByte)
	fmt.Printf(" End byte: %d\n", changedRange.EndByte)
}
Output:

Changed range:
 Start point: {5 10}
 End point: {5 12}
 Start byte: 46
 End byte: 48

func (*Tree) ChangedRanges

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

Compare this old edited syntax tree to a new syntax tree representing the same document, returning a sequence of ranges whose syntactic structure has changed.

For this to work correctly, this syntax tree must have been edited such that its ranges match up to the new tree. Generally, you'll want to call this method right after calling one of the [Parser.parse] functions. Call it on the old tree that was passed to parse, and pass the new tree that was returned from `parse`.

The returned ranges indicate areas where the hierarchical structure of syntax nodes (from root to leaf) has changed between the old and new trees. Characters outside these ranges have identical ancestor nodes in both trees.

Note that the returned ranges may be slightly larger than the exact changed areas, but Tree-sitter attempts to make them as small as possible.

func (*Tree) Clone

func (t *Tree) Clone() *Tree

func (*Tree) Close

func (t *Tree) Close()

func (*Tree) Edit

func (t *Tree) Edit(edit *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) IncludedRanges

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

Get the included ranges that were used to parse the syntax tree.

func (*Tree) Language

func (t *Tree) Language() *Language

Get the language that was used to parse the syntax tree.

func (*Tree) PrintDotGraph

func (t *Tree) PrintDotGraph(file int)

Print a graph of the tree to the given file descriptor. The graph is formatted in the DOT language. You may want to pipe this graph directly to a `dot(1)` process in order to generate SVG output.

func (*Tree) RootNode

func (t *Tree) RootNode() *Node

Get the root node of the syntax tree.

func (*Tree) RootNodeWithOffset

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

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

func (*Tree) Walk

func (t *Tree) Walk() *TreeCursor

Create a new TreeCursor starting from the root of the tree.

type TreeCursor

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

A stateful object for walking a syntax Tree efficiently.

Example
parser := NewParser()
defer parser.Close()

language := NewLanguage(tree_sitter_go.Language())

parser.SetLanguage(language)

tree := parser.Parse(
	[]byte(`
			package main


			func main() {
				return
			}
		`),
	nil,
)
defer tree.Close()

cursor := tree.Walk()
defer cursor.Close()

fmt.Println(cursor.Node().Kind())

fmt.Println(cursor.GotoFirstChild())
fmt.Println(cursor.Node().Kind())

fmt.Println(cursor.GotoFirstChild())
fmt.Println(cursor.Node().Kind())

// Returns `false` because the `package` node has no children
fmt.Println(cursor.GotoFirstChild())

fmt.Println(cursor.GotoNextSibling())
fmt.Println(cursor.Node().Kind())

fmt.Println(cursor.GotoParent())
fmt.Println(cursor.Node().Kind())

fmt.Println(cursor.GotoNextSibling())
fmt.Println(cursor.GotoNextSibling())
fmt.Println(cursor.Node().Kind())
Output:

source_file
true
package_clause
true
package
false
true
package_identifier
true
package_clause
true
false
function_declaration

func (*TreeCursor) Close

func (tc *TreeCursor) Close()

func (*TreeCursor) Copy

func (tc *TreeCursor) Copy() *TreeCursor

func (*TreeCursor) Depth

func (tc *TreeCursor) Depth() uint32

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

func (*TreeCursor) DescendantIndex

func (tc *TreeCursor) DescendantIndex() uint32

Get 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) FieldId

func (tc *TreeCursor) FieldId() uint16

Get the numerical field id of this tree cursor's current node.

See also TreeCursor.FieldName.

func (*TreeCursor) FieldName

func (tc *TreeCursor) FieldName() string

Get the field name of this tree cursor's current node.

func (*TreeCursor) GotoDescendant

func (tc *TreeCursor) GotoDescendant(descendantIndex uint32)

Move 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) GotoFirstChild

func (tc *TreeCursor) GotoFirstChild() bool

Move this 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 (tc *TreeCursor) GotoFirstChildForByte(byteIndex uint32) *uint

Move this 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 `nil` if no such child was found.

func (*TreeCursor) GotoFirstChildForPoint

func (tc *TreeCursor) GotoFirstChildForPoint(point Point) *uint

Move this 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 `nil` if no such child was found.

func (*TreeCursor) GotoLastChild

func (tc *TreeCursor) GotoLastChild() bool

Move this 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 TreeCursor.GotoFirstChild because it needs to iterate through all the children to compute the child's position.

func (*TreeCursor) GotoNextSibling

func (tc *TreeCursor) GotoNextSibling() bool

Move this 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.

Note that the given node is considered the root of the cursor, and the cursor cannot walk outside this node.

func (*TreeCursor) GotoParent

func (tc *TreeCursor) GotoParent() bool

Move this 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).

Note that the given node is considered the root of the cursor, and the cursor cannot walk outside this node.

func (*TreeCursor) GotoPreviousSibling

func (tc *TreeCursor) GotoPreviousSibling() bool

Move this 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 TreeCursor.GotoNextSibling 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. Also note that the node the cursor was constructed with is considered the root of the cursor, and the cursor cannot walk outside this node.

func (*TreeCursor) Node

func (tc *TreeCursor) Node() *Node

Get the tree cursor's current Node.

func (*TreeCursor) Reset

func (tc *TreeCursor) Reset(node Node)

Re-initialize this tree cursor to start at the original node that the cursor was constructed with.

func (*TreeCursor) ResetTo

func (tc *TreeCursor) ResetTo(cursor *TreeCursor)

Re-initialize a tree cursor to the same position as another cursor.

Unlike TreeCursor.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