transit

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 14 Imported by: 0

README


Unit Tests Go Reference Releases Discord Discussion

transit

transit is a pure Go port of tree-sitter. tree-sitter is a parser generator and an incremental parsing library. It builds a concrete syntax tree of a source file, and it updates the tree after an edit without parsing the whole file again. Editors use it to highlight code and to find structure in code.

transit exists to serve two xo projects. rline uses it to highlight syntax as the user types, and usql uses it to complete from the context at the cursor. transit gives parsing information only.

Every Go package for tree-sitter today uses cgo, and a program that imports one needs a C compiler for each target. A program that imports transit needs the Go toolchain and nothing else.

Status

The generator and its C backend are ported. They write the golden parser.c and node-types.json of all 185 grammars of the set byte for byte, and on 2026-09-29 the gate of D9 holds: 151 grammars count, which ends phase 2. Ken accepted the target API in docs/API.md on 2026-10-01, which ended phase 1 (D103). Phase 3 has ported the runtime: the parser, the tree, the node, the tree cursor, and the query engine with the predicates of the Rust binding. The Go runtime gives the same trees and the same query matches as the C runtime for every corpus input of every fixture grammar. It parses with the tables and the lexers of C grammars, through the test module. The ported runtime tests of upstream pass. StatesAt gives the parse states at a cursor (D57, D70). The package inject finds the injections of a text and parses their layers, as upstream does (D72). The measurements of a prototype of the Go output are recorded in D73, and they end phase 3. In phase 4, the Go backend writes a grammar package with literal tables and a lexer as data (D74). The 17 fixture grammars are Go packages in 15 modules under grammars/, with their scanners ported to Go. Every test of phase 3 passes on them, and the speed targets of D37 hold on them. Ken tagged v0.1.0 of every module on 2026-10-01, which ended phase 4. docs/PLAN.md holds the plan, and the decisions record every answer that shapes it.

Documents

Document What it holds
docs/PLAN.md the plan, the testing plan, the phases and any open question
docs/GRAMMAR.md the rules for adding a grammar and porting its scanner
docs/CANDIDATES.md the set of grammars that Ken accepted, and how it was measured
docs/API.md the target Go API, from the working C example
docs/UPSTREAM.md the rules for porting upstream tree-sitter and each change that it makes
docs/RLINE.md what rline gets from transit, for the coding agents that work in rline
docs/USQL.md what usql gets from transit, for the coding agents that work in usql
docs/NEOVIM.md the predicates of Neovim that transit does not support, and the grammars whose queries use them
docs/BACKLOG.md the work that is known and not done
docs/decisions/ every decision, one file each, with an index
CONTRIBUTING.md how to change transit
AGENTS.md the rules for a coding agent, which also hold for a person

Grammars

The Go backend writes a package for each grammar that Ken chooses. The set of 185 grammars is in docs/CANDIDATES.md, and docs/GRAMMAR.md says how a grammar is added. These are the packages, one for each fixture grammar:

Package Upstream repository Tag
github.com/xo/transit/grammars/bash tree-sitter/tree-sitter-bash v0.25.0
github.com/xo/transit/grammars/c tree-sitter/tree-sitter-c v0.24.2
github.com/xo/transit/grammars/cpp tree-sitter/tree-sitter-cpp v0.23.4
github.com/xo/transit/grammars/embeddedtemplate tree-sitter/tree-sitter-embedded-template v0.25.0
github.com/xo/transit/grammars/go tree-sitter/tree-sitter-go v0.25.0
github.com/xo/transit/grammars/html tree-sitter/tree-sitter-html v0.23.2
github.com/xo/transit/grammars/java tree-sitter/tree-sitter-java v0.23.5
github.com/xo/transit/grammars/javascript tree-sitter/tree-sitter-javascript v0.25.0
github.com/xo/transit/grammars/jsdoc tree-sitter/tree-sitter-jsdoc v0.23.2
github.com/xo/transit/grammars/json tree-sitter/tree-sitter-json v0.24.8
github.com/xo/transit/grammars/php/php tree-sitter/tree-sitter-php v0.24.2
github.com/xo/transit/grammars/php/phponly tree-sitter/tree-sitter-php v0.24.2
github.com/xo/transit/grammars/python tree-sitter/tree-sitter-python v0.23.6
github.com/xo/transit/grammars/ruby tree-sitter/tree-sitter-ruby v0.23.1
github.com/xo/transit/grammars/rust tree-sitter/tree-sitter-rust v0.24.0
github.com/xo/transit/grammars/typescript/tsx tree-sitter/tree-sitter-typescript v0.23.2
github.com/xo/transit/grammars/typescript/typescript tree-sitter/tree-sitter-typescript v0.23.2

These packages hold SQL grammars of the set for usql (D106). A module that holds the language of one dialect has the name of the dialect, so the package name can differ from the grammar name (D107):

Package Grammar Upstream repository Tag
github.com/xo/transit/grammars/sql sql DerekStride/tree-sitter-sql v0.3.11
github.com/xo/transit/grammars/postgres/postgres postgres gmr/tree-sitter-postgres v1.2.4
github.com/xo/transit/grammars/postgres/plpgsql plpgsql gmr/tree-sitter-postgres v1.2.4
github.com/xo/transit/grammars/sqlserver TSQL Crary-Systems/tree-sitter-tsql 0.0.1
github.com/xo/transit/grammars/oracle plsql andreasmaierde/tree-sitter-plsql the branch main at 28aebef
github.com/xo/transit/grammars/cql cql shotover/tree-sitter-cql v0.2.0

These packages hold the grammars of the languages of dbmeta that are not SQL (D21, D23). A module that holds the language of one dialect has the name of the dialect, so the package name can differ from the grammar name (D107). udovin/tree-sitter-yql has no license file, so grammars/ydb has none (D20):

Package Grammar Upstream repository Tag
github.com/xo/transit/grammars/neo4j cypher taekwombo/tree-sitter-cypher M23-legacy
github.com/xo/transit/grammars/surrealdb surrealql surrealdb/surrealql-tree-sitter the branch master at 329dcec
github.com/xo/transit/grammars/sparql sparql GordianDziwis/tree-sitter-sparql 0.1.0
github.com/xo/transit/grammars/graphql graphql bkegley/tree-sitter-graphql the branch master at 5e66e96
github.com/xo/transit/grammars/ydb yql udovin/tree-sitter-yql the branch main at 7e8d3e1

xo writes some grammars in this repository (D42, D104). The package github.com/xo/transit/grammars/usql holds the grammar usql of the input of usql: SQL statements, meta commands such as \d and variables such as :name (D13). It is one language for every SQL dialect (D108). Language gives the language with dollar quotes and block comments, the options of PostgreSQL. LanguageFor gives the language with the options of another dialect, with the same tables:

lang := usql.LanguageFor(usql.Options{BlockComments: true, HashComments: true, Backticks: true})

The fields of usql.Options are the flags of the type Syntax of dbmeta: DollarQuotes, BlockComments, SlashComments, HashComments and Backticks.

Some grammars ship queries written for Neovim, which transit does not support now. docs/NEOVIM.md lists them.

Differences from upstream

transit differs from upstream tree-sitter only where a decision says so:

  1. For a grammar.json that is not valid JSON, the generator gives the error text of Go's encoding/json (D66).
  2. Two nodes compare with ==, which also compares their positions. Node.Equal compares them as ts_node_eq does (D68).
  3. The Go backend stops with an error for a large character set of surrogates only, where the C code of upstream reads past its array (D78).

transit also adds an API that upstream does not have, one decision each (D28), such as StatesAt (D57, D70). It does not evaluate the predicates of Neovim, and upstream does not either (docs/NEOVIM.md). docs/UPSTREAM.md says when one can be made. This section will list each one with its decision.

License

transit is under the MIT license. See LICENSE. Upstream tree-sitter is under the MIT license too, and LICENSE keeps its copyright line. Each grammar keeps the license of its own repository.

Documentation

Overview

Package transit is a pure Go port of tree-sitter, the parser generator and incremental parsing library.

This package holds the runtime: the parser, the tree, the query engine and the lookahead iterator. Phase 3 ports it from lib/src of upstream, one C file at a time. Today it holds all of the runtime. See docs/PLAN.md for the plan, and docs/decisions for the decisions that shape it.

This module requires no other module, so the examples that parse a text are in the grammar package github.com/xo/transit/grammars/json. They show a parse, an edit, a walk with a cursor, a query and a completion with StatesAt.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Encoding

type Encoding int

Encoding is the encoding of the text.

Encoding is TSInputEncoding.

const (
	// EncodingUTF8 is TSInputEncodingUTF8.
	EncodingUTF8 Encoding = iota
	// EncodingUTF16LE is TSInputEncodingUTF16LE.
	EncodingUTF16LE
	// EncodingUTF16BE is TSInputEncodingUTF16BE.
	EncodingUTF16BE
)

The encodings of the text.

func (Encoding) String

func (e Encoding) String() string

String returns the name of the encoding.

type Error

type Error string

Error is an error of the runtime.

const (
	// ErrIncompatibleLanguage is the error of SetLanguage for a language
	// whose ABI version the runtime does not accept.
	ErrIncompatibleLanguage Error = "incompatible language version"
	// ErrInvalidRanges is the error of SetIncludedRanges for ranges that
	// overlap or are not in order.
	ErrInvalidRanges Error = "invalid included ranges"
	// ErrNoLanguage is the error of a parse before SetLanguage.
	ErrNoLanguage Error = "parser has no language"
	// ErrLanguageMismatch is the error of a parse with an old tree of
	// another language.
	ErrLanguageMismatch Error = "old tree has another language"
	// ErrInvalidInput is the error of a parse with no input or with an
	// encoding that the runtime does not know.
	ErrInvalidInput Error = "invalid input"
)

The errors of the runtime.

func (Error) Error

func (e Error) Error() string

Error returns the text of the error.

type FieldID

type FieldID uint16

FieldID is the number of a field in the tables of a language. The field 0 is no field.

FieldID is TSFieldId.

type FieldInfo

type FieldInfo struct {
	// Multiple is true when it can hold more than one node.
	Multiple bool `json:"multiple"`
	// Required is true when it holds a node in every node of the type.
	Required bool `json:"required"`
	// Types holds the types of the nodes.
	Types []NodeKind `json:"types"`
}

FieldInfo says which nodes a field, or the children of a node, can hold.

type Input

type Input interface {
	ReadAt(offset int, at Point) []byte
}

Input gives the text in chunks. ReadAt returns the text from a byte offset, which is at a point, and an empty slice at the end of the text. The parser keeps the slice only until it calls ReadAt again.

Input is the member read of TSInput.

type InputEdit

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

InputEdit describes one edit of the text.

InputEdit is TSInputEdit.

Example

This example fills an InputEdit for text that a user types at the end of a text of three rows. Tree.Edit takes it before the next parse. A point counts its column in bytes from the start of its row.

The examples that parse a text are in the package github.com/xo/transit/grammars/json, because they need a grammar.

package main

import (
	"bytes"
	"fmt"
	"slices"

	"github.com/xo/transit"
)

func main() {
	src := []byte("SELECT name\nFROM t\nWHERE")
	insert := []byte(" id = 1;\n")
	start := len(src) // the end of the text

	// point gives the point of a byte offset of a text.
	point := func(text []byte, offset int) transit.Point {
		row := bytes.Count(text[:offset], []byte("\n"))
		column := offset - (bytes.LastIndexByte(text[:offset], '\n') + 1)
		return transit.Point{Row: row, Column: column}
	}
	newSrc := slices.Concat(src[:start], insert, src[start:])
	edit := transit.InputEdit{
		StartByte:   start,
		OldEndByte:  start,
		NewEndByte:  start + len(insert),
		StartPoint:  point(src, start),
		OldEndPoint: point(src, start),
		NewEndPoint: point(newSrc, start+len(insert)),
	}
	fmt.Printf("%+v\n", edit)
}
Output:
{StartByte:24 OldEndByte:24 NewEndByte:33 StartPoint:{Row:2 Column:5} OldEndPoint:{Row:2 Column:5} NewEndPoint:{Row:3 Column:0}}

type Language

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

Language is the tables of one grammar. A grammar package returns it. It is safe to share between goroutines.

Language is TSLanguage.

func NewLanguage

func NewLanguage(tables *abi.Language) *Language

NewLanguage builds a language from its tables. Only code under github.com/xo/transit/, such as a grammar package, can build an *abi.Language, because the package abi is internal (D63). The language keeps its own copy of the struct, and it shares the tables.

func (*Language) ABIVersion

func (l *Language) ABIVersion() int

ABIVersion returns the ABI version of the tables of the language.

ABIVersion is ts_language_abi_version.

func (*Language) FieldCount

func (l *Language) FieldCount() int

FieldCount returns the number of fields of the language.

FieldCount is ts_language_field_count.

func (*Language) FieldForName

func (l *Language) FieldForName(name string) (FieldID, bool)

FieldForName returns the field with a name, and reports whether the language has it.

FieldForName is ts_language_field_id_for_name. The field names of a language are sorted, and the C function stops when strncmp returns -1. glibc returns the difference of the first bytes that differ, and so does strncmp here, so the loop stops at the same field as in C.

func (*Language) FieldName

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

FieldName returns the name of a field. It returns "" for the field 0 and for a field that the language does not have.

FieldName is ts_language_field_name_for_id.

func (*Language) LookaheadIterator

func (l *Language) LookaheadIterator(state StateID) (*LookaheadIterator, bool)

LookaheadIterator returns an iterator of the symbols that are valid in a state. It returns false for a state that the language does not have.

LookaheadIterator is ts_lookahead_iterator_new.

func (*Language) Metadata

func (l *Language) Metadata() (LanguageMetadata, bool)

Metadata returns the version of the grammar. A language of ABI 14 has no version, and then Metadata returns false.

Metadata is ts_language_metadata.

func (*Language) Name

func (l *Language) Name() string

Name returns the name of the grammar. A language of ABI 14 has no name, and then Name returns "".

Name is ts_language_name.

func (*Language) NextState

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

NextState returns the parse state that follows a state after a symbol. It returns 0 when the symbol is not valid in the state.

NextState is ts_language_next_state.

func (*Language) StateCount

func (l *Language) StateCount() int

StateCount returns the number of parse states of the language.

StateCount is ts_language_state_count.

func (*Language) Subtypes

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

Subtypes returns the symbols that a supertype stands for. It returns nil for a symbol that is not a supertype, and for a language of ABI 14. The slice is a copy.

Subtypes is ts_language_subtypes.

func (*Language) Supertypes

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

Supertypes returns the supertype symbols of the language. A language of ABI 14 has none. The slice is a copy.

Supertypes is ts_language_supertypes.

func (*Language) SymbolCount

func (l *Language) SymbolCount() int

SymbolCount returns the number of symbols of the language, with the aliases.

SymbolCount is ts_language_symbol_count.

func (*Language) SymbolForName

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

SymbolForName returns the symbol with a name, named or anonymous, and reports whether the language has it.

SymbolForName is ts_language_symbol_for_name. The C function compares the names with strncmp, so the Go function does too. A named name that is a prefix of "ERROR", such as "ERR", finds the symbol of ERROR, as it does in C.

func (*Language) SymbolName

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

SymbolName returns the name of a symbol. It returns "" for a symbol that the language does not have.

SymbolName is ts_language_symbol_name.

func (*Language) SymbolType

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

SymbolType returns the kind of a symbol.

SymbolType is ts_language_symbol_type.

type LanguageMetadata

type LanguageMetadata struct {
	Major, Minor, Patch int
}

LanguageMetadata is the version of a grammar.

LanguageMetadata is TSLanguageMetadata.

type LogType

type LogType int

LogType says whether a log message comes from the parser or the lexer.

LogType is TSLogType.

const (
	// LogParse is TSLogTypeParse.
	LogParse LogType = iota
	// LogLex is TSLogTypeLex.
	LogLex
)

The sources of a log message.

func (LogType) String

func (t LogType) String() string

String returns the name of the source.

type LookaheadIterator

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

LookaheadIterator lists the symbols that the parser can accept in a state. It belongs to one goroutine at a time.

LookaheadIterator is LookaheadIterator and TSLookaheadIterator. In C, data and group_end point into a parse table. In Go, data is the table from the start of the state, and pos and groupEnd are indices into it.

func (*LookaheadIterator) Language

func (it *LookaheadIterator) Language() *Language

Language returns the language of the iterator.

Language is ts_lookahead_iterator_language.

func (*LookaheadIterator) Names

func (it *LookaheadIterator) Names() iter.Seq[string]

Names returns the names of the valid symbols that the iterator has not yet given. It moves the iterator as Symbols does.

Names calls ts_lookahead_iterator_next and ts_lookahead_iterator_current_symbol_name, as iter_names of the Rust binding does.

func (*LookaheadIterator) Reset

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

Reset moves the iterator to the start of a state of a language. It returns false, and leaves the iterator as it is, for a state that the language does not have.

Reset is ts_lookahead_iterator_reset.

func (*LookaheadIterator) ResetState

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

ResetState moves the iterator to the start of another state of the same language. It returns false, and leaves the iterator as it is, for a state that the language does not have.

ResetState is ts_lookahead_iterator_reset_state.

func (*LookaheadIterator) Symbols

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

Symbols returns the valid symbols that the iterator has not yet given. The iterator moves as the sequence runs, so a second range over it gives only the rest. Reset and ResetState start it again.

Symbols calls ts_lookahead_iterator_next and ts_lookahead_iterator_current_symbol, as the Iterator of the Rust binding does.

type Node

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

Node is a node of a tree. It is a small value, and two nodes compare with ==, which also compares their positions. Equal compares them as C does (D68). The zero Node is no node.

Node is TSNode. context holds the start byte, the start row, the start column and the alias of the node, as in C. id is the address of the subtree of the node: the root of the tree, or a child in the children of its parent.

func (Node) Child

func (n Node) Child(i int) (Node, bool)

Child returns the child of the node at an index, where the index counts the named and the anonymous children.

Child is ts_node_child.

func (Node) ChildByFieldID

func (n Node) ChildByFieldID(fieldID FieldID) (Node, bool)

ChildByFieldID returns the first child of the node with a field.

ChildByFieldID is ts_node_child_by_field_id. The goto of C is a labeled continue.

func (Node) ChildByFieldName

func (n Node) ChildByFieldName(name string) (Node, bool)

ChildByFieldName returns the first child of the node with a field.

ChildByFieldName is ts_node_child_by_field_name. The C function looks up the field with ts_language_field_id_for_name, which returns 0 for a name that the language does not have. The field 0 finds no child.

func (Node) ChildCount

func (n Node) ChildCount() int

ChildCount returns the number of the named and the anonymous children of the node.

ChildCount is ts_node_child_count.

func (Node) ChildWithDescendant

func (n Node) ChildWithDescendant(descendant Node) (Node, bool)

ChildWithDescendant returns the child of the node that holds descendant. The result can be descendant itself.

ChildWithDescendant is ts_node_child_with_descendant.

func (Node) Children

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

Children returns the named and the anonymous children of the node. It walks them with a tree cursor.

Children is children of Node in the Rust binding.

func (Node) ChildrenByFieldName

func (n Node) ChildrenByFieldName(name string) iter.Seq[Node]

ChildrenByFieldName returns the children of the node with a field. It walks them with a tree cursor.

ChildrenByFieldName is children_by_field_name of Node in the Rust binding.

func (Node) DescendantCount

func (n Node) DescendantCount() int

DescendantCount returns the number of the node and its descendants.

DescendantCount is ts_node_descendant_count.

func (Node) DescendantForByteRange

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

DescendantForByteRange returns the smallest node in the node that spans a range of bytes. It returns false when start is after end.

DescendantForByteRange is ts_node_descendant_for_byte_range.

func (Node) DescendantForPointRange

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

DescendantForPointRange returns the smallest node in the node that spans a range of points. It returns false when start is after end.

DescendantForPointRange is ts_node_descendant_for_point_range.

func (*Node) Edit

func (n *Node) Edit(e InputEdit)

Edit moves the start of the node to match an edit of the text. A node that comes from a tree after Tree.Edit already matches the edit, so Edit is only for a node that the caller kept from before the edit.

Edit is ts_node_edit.

func (Node) EndByte

func (n Node) EndByte() int

EndByte returns the byte offset where the node ends.

EndByte is ts_node_end_byte.

func (Node) EndPoint

func (n Node) EndPoint() Point

EndPoint returns the point where the node ends.

EndPoint is ts_node_end_point.

func (Node) Equal

func (n Node) Equal(other Node) bool

Equal reports whether n and other are the same node of the same tree. It does not compare the positions of the nodes, so a node that Edit moved is Equal to the node before the edit, as in C, and == tells them apart.

Equal is ts_node_eq.

func (Node) FieldNameForChild

func (n Node) FieldNameForChild(i int) string

FieldNameForChild returns the field name of the child of the node at an index, or "" when the child has no field.

FieldNameForChild is ts_node_field_name_for_child.

func (Node) FieldNameForNamedChild

func (n Node) FieldNameForNamedChild(i int) string

FieldNameForNamedChild returns the field name of the named child of the node at an index, or "" when the child has no field.

FieldNameForNamedChild is ts_node_field_name_for_named_child.

func (Node) FirstChildForByte

func (n Node) FirstChildForByte(offset int) (Node, bool)

FirstChildForByte returns the first child of the node that ends after a byte offset.

FirstChildForByte is ts_node_first_child_for_byte.

func (Node) FirstNamedChildForByte

func (n Node) FirstNamedChildForByte(offset int) (Node, bool)

FirstNamedChildForByte returns the first named child of the node that ends after a byte offset.

FirstNamedChildForByte is ts_node_first_named_child_for_byte.

func (Node) GrammarID

func (n Node) GrammarID() Symbol

GrammarID returns the symbol of the node in the grammar, before any alias.

GrammarID is ts_node_grammar_symbol.

func (Node) GrammarKind

func (n Node) GrammarKind() string

GrammarKind returns the name of the symbol of the node in the grammar, before any alias.

GrammarKind is ts_node_grammar_type.

func (Node) HasChanges

func (n Node) HasChanges() bool

HasChanges reports whether an edit changed the node.

HasChanges is ts_node_has_changes.

func (Node) HasError

func (n Node) HasError() bool

HasError reports whether the node is an error or holds one.

HasError is ts_node_has_error.

func (Node) IsError

func (n Node) IsError() bool

IsError reports whether the node is an ERROR node.

IsError is ts_node_is_error.

func (Node) IsExtra

func (n Node) IsExtra() bool

IsExtra reports whether the node is an extra, such as a comment.

IsExtra is ts_node_is_extra.

func (Node) IsMissing

func (n Node) IsMissing() bool

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

IsMissing is ts_node_is_missing.

func (Node) IsNamed

func (n Node) IsNamed() bool

IsNamed reports whether the node is named, or has a named alias.

IsNamed is ts_node_is_named.

func (Node) Kind

func (n Node) Kind() string

Kind returns the name of the symbol of the node, or of its alias.

Kind is ts_node_type.

func (Node) KindID

func (n Node) KindID() Symbol

KindID returns the symbol of the node, or of its alias.

KindID is ts_node_symbol.

func (Node) Language

func (n Node) Language() *Language

Language returns the language of the tree of the node.

Language is ts_node_language.

func (Node) NamedChild

func (n Node) NamedChild(i int) (Node, bool)

NamedChild returns the named child of the node at an index, where the index counts only the named children.

NamedChild is ts_node_named_child.

func (Node) NamedChildCount

func (n Node) NamedChildCount() int

NamedChildCount returns the number of the named children of the node.

NamedChildCount is ts_node_named_child_count.

func (Node) NamedChildren

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

NamedChildren returns the named children of the node. It walks them with a tree cursor.

NamedChildren is named_children of Node in the Rust binding.

func (Node) NamedDescendantForByteRange

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

NamedDescendantForByteRange returns the smallest named node in the node that spans a range of bytes. It returns false when start is after end.

NamedDescendantForByteRange is ts_node_named_descendant_for_byte_range.

func (Node) NamedDescendantForPointRange

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

NamedDescendantForPointRange returns the smallest named node in the node that spans a range of points. It returns false when start is after end.

NamedDescendantForPointRange is ts_node_named_descendant_for_point_range.

func (Node) NextNamedSibling

func (n Node) NextNamedSibling() (Node, bool)

NextNamedSibling returns the next named sibling of the node.

NextNamedSibling is ts_node_next_named_sibling.

func (Node) NextParseState

func (n Node) NextParseState() StateID

NextParseState returns the parse state after the node.

NextParseState is ts_node_next_parse_state.

func (Node) NextSibling

func (n Node) NextSibling() (Node, bool)

NextSibling returns the next sibling of the node.

NextSibling is ts_node_next_sibling.

func (Node) Parent

func (n Node) Parent() (Node, bool)

Parent returns the parent of the node. It returns false for the root.

Parent is ts_node_parent.

func (Node) ParseState

func (n Node) ParseState() StateID

ParseState returns the parse state of the node.

ParseState is ts_node_parse_state.

func (Node) PrevNamedSibling

func (n Node) PrevNamedSibling() (Node, bool)

PrevNamedSibling returns the previous named sibling of the node.

PrevNamedSibling is ts_node_prev_named_sibling.

func (Node) PrevSibling

func (n Node) PrevSibling() (Node, bool)

PrevSibling returns the previous sibling of the node.

PrevSibling is ts_node_prev_sibling.

func (Node) Range

func (n Node) Range() Range

Range returns the range of the node, in bytes and in points.

Range is range of Node in the Rust binding.

func (Node) StartByte

func (n Node) StartByte() int

StartByte returns the byte offset where the node starts.

StartByte is ts_node_start_byte.

func (Node) StartPoint

func (n Node) StartPoint() Point

StartPoint returns the point where the node starts.

StartPoint is ts_node_start_point.

func (Node) String

func (n Node) String() string

String returns the node and its named descendants as an S-expression.

String is ts_node_string.

func (Node) Text

func (n Node) Text(src []byte) string

Text returns the text of the node in src, the text that the parse read.

Text is utf8_text of Node in the Rust binding. It does not check that the text is valid UTF-8.

func (Node) Walk

func (n Node) Walk() *TreeCursor

Walk returns a cursor at the node. The node is the root of the cursor, and the cursor does not walk out of it.

Walk is ts_tree_cursor_new.

type NodeKind

type NodeKind struct {
	Kind  string `json:"type"`
	Named bool   `json:"named"`
}

NodeKind names a node type: its kind, and whether it is named.

type NodeType

type NodeType struct {
	// Kind and Named name the node type, as Node.Kind and Node.IsNamed give
	// them for a node of the type.
	Kind  string `json:"type"`
	Named bool   `json:"named"`
	// Root is true for the type of the root node of a tree.
	Root bool `json:"root,omitempty"`
	// Extra is true for a type that can appear anywhere, such as a comment.
	Extra bool `json:"extra,omitempty"`
	// Fields holds the children of each field, by the name of the field.
	Fields map[string]FieldInfo `json:"fields,omitempty"`
	// Children holds the named children that no field holds, or nil when
	// there are none.
	Children *FieldInfo `json:"children,omitempty"`
	// Subtypes holds the types of a supertype.
	Subtypes []NodeKind `json:"subtypes,omitempty"`
}

NodeType is one entry of node-types.json: a kind of node that a tree can hold, with the children that it can have. A supertype, such as the _expression of many grammars, has Subtypes and no children.

type Parser

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

Parser builds trees. It belongs to one goroutine at a time.

Parser is TSParser.

func NewParser

func NewParser() *Parser

NewParser returns a parser with no language.

NewParser is ts_parser_new.

func (*Parser) IncludedRanges

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

IncludedRanges returns a copy of the ranges of the text that the parser reads.

IncludedRanges is ts_parser_included_ranges.

func (*Parser) Language

func (p *Parser) Language() *Language

Language returns the language of the parser, or nil.

Language is ts_parser_language.

func (*Parser) Parse

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

Parse parses src, in UTF-8. When old is the tree of an earlier version of the text, after Tree.Edit, the parser reuses the parts of it that the edits did not change. ParseInput holds the rest of the rules.

Parse is ts_parser_parse_string.

func (*Parser) ParseInput

func (p *Parser) ParseInput(ctx context.Context, in Input, enc Encoding, old *Tree) (*Tree, error)

ParseInput parses the text that in gives, in the encoding enc. When old is the tree of an earlier version of the text, after Tree.Edit, the parser reuses the parts of it that the edits did not change.

When ctx ends, ParseInput returns its error, wrapped. The parser keeps its state, and the next call goes on from the same point with the same input, unless Reset or SetLanguage is called first.

ParseInput is ts_parser_parse.

func (*Parser) PrintDotGraphs

func (p *Parser) PrintDotGraphs(w io.Writer)

PrintDotGraphs writes a graph of the stack and of the trees to w in the DOT language of Graphviz, as the parser works. A nil writer stops the graphs.

PrintDotGraphs is ts_parser_print_dot_graphs. The C function takes a file descriptor.

func (*Parser) Reset

func (p *Parser) Reset()

Reset makes the next parse start from the start of the text, and not go on from a parse that a context stopped.

Reset is ts_parser_reset.

func (*Parser) SetIncludedRanges

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

SetIncludedRanges sets the ranges of the text that the parser reads. It returns ErrInvalidRanges for ranges that are not in order or that overlap. No ranges is the whole text.

SetIncludedRanges is ts_parser_set_included_ranges.

func (*Parser) SetLanguage

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

SetLanguage sets the language of the parser, and resets the parser. It returns ErrIncompatibleLanguage for a language whose ABI version the runtime does not accept, or that has no lex function, and the parser then has no language. A nil language removes the language of the parser.

SetLanguage is ts_parser_set_language.

func (*Parser) SetLogger

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

SetLogger sets the function that gets the log messages of the parser and of the lexer. A nil function stops the log.

SetLogger is ts_parser_set_logger.

func (*Parser) StatesAt

func (p *Parser) StatesAt(ctx context.Context, src []byte, offset int, old *Tree) ([]StateID, error)

StatesAt parses src up to offset, and returns the parse state of each stack version at offset, before the parser recovers from an error. A consumer lists the symbols that can come next with the lookahead iterator of each state.

StatesAt stops each stack version before the version reduces or detects an error on the first token that ends after offset, or on the end of the text. A token with no width at offset, such as one that an external scanner gives before a word, is handled. The lexer reads the text after offset as it does in a parse of all of src, so a token before offset is the token of that parse. When offset is inside a word, StatesAt gives the states before the word. A word that ends at offset is handled, so to complete a word, a consumer gives the offset of its start.

The states come in the order of the stack versions, with no state twice. A version that recovers from an error before offset gives the state that it has at offset after the recovery. When old is the tree of src, after Tree.Edit, the parser reuses the parts of it that come before offset. old does not change.

StatesAt uses the parser, so it resets the parser first, as Reset does, and a parse that a context stopped does not go on. When ctx ends, StatesAt returns its error, wrapped.

type Point

type Point struct {
	Row    int
	Column int
}

Point is a position as a row and a column. Both count from zero, and the column counts bytes.

Point is TSPoint.

type Quantifier

type Quantifier int

Quantifier is how many times a capture can appear in one match of a pattern.

Quantifier is TSQuantifier.

const (
	// QuantifierZero is TSQuantifierZero. The capture does not appear.
	QuantifierZero Quantifier = iota
	// QuantifierZeroOrOne is TSQuantifierZeroOrOne. The capture appears at
	// most once.
	QuantifierZeroOrOne
	// QuantifierZeroOrMore is TSQuantifierZeroOrMore. The capture can appear
	// any number of times.
	QuantifierZeroOrMore
	// QuantifierOne is TSQuantifierOne. The capture appears once.
	QuantifierOne
	// QuantifierOneOrMore is TSQuantifierOneOrMore. The capture appears at
	// least once.
	QuantifierOneOrMore
)

The quantifiers of a capture.

func (Quantifier) String

func (q Quantifier) String() string

String returns the name of the quantifier.

type Query

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

Query is a compiled query. It is safe to share between goroutines, after any call to DisablePattern or DisableCapture.

Query is Query of the Rust binding.

func NewQuery

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

NewQuery compiles a query from a text of one or more patterns, for a language. The error is a *QueryError.

NewQuery is Query::new, with Query::new_raw and Query::from_raw_parts.

func (*Query) CaptureIndexForName

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

CaptureIndexForName returns the index of a capture name, and reports whether the query has it.

CaptureIndexForName is Query::capture_index_for_name.

func (*Query) CaptureNames

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

CaptureNames returns the names of the captures of the query. The index of a name is the Index of a QueryCapture. The slice is the query's own, so do not change it.

CaptureNames is Query::capture_names.

func (*Query) CaptureQuantifiers

func (q *Query) CaptureQuantifiers(index int) []Quantifier

CaptureQuantifiers returns the quantifier of each capture in a pattern.

CaptureQuantifiers is Query::capture_quantifiers.

func (*Query) DisableCapture

func (q *Query) DisableCapture(name string)

DisableCapture makes the query give no capture with a name. The query then does less work.

DisableCapture is Query::disable_capture.

func (*Query) DisablePattern

func (q *Query) DisablePattern(index int)

DisablePattern makes a pattern of the query match nothing. The query then does less work.

DisablePattern is Query::disable_pattern.

func (*Query) EndByteForPattern

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

EndByteForPattern returns the byte offset where a pattern ends in the text of the query. It panics for a pattern that the query does not have, as the Rust binding does.

EndByteForPattern is Query::end_byte_for_pattern.

func (*Query) GeneralPredicates

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

GeneralPredicates returns the predicates of a pattern that the query does not evaluate: each operator but #eq?, #match?, #any-of?, #is?, #is-not?, #set! and their not- and any- forms.

GeneralPredicates is Query::general_predicates.

func (*Query) IsPatternGuaranteedAtStep

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

IsPatternGuaranteedAtStep reports whether the step at a byte offset of the text of the query is definite: whether its pattern is sure to match once the cursor reaches it.

IsPatternGuaranteedAtStep is Query::is_pattern_guaranteed_at_step.

func (*Query) IsPatternNonLocal

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

IsPatternNonLocal reports whether a pattern is non-local: whether a match of it can start in a node that is outside the range of the cursor.

IsPatternNonLocal is Query::is_pattern_non_local.

func (*Query) IsPatternRooted

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

IsPatternRooted reports whether a pattern has a single root node.

IsPatternRooted is Query::is_pattern_rooted.

func (*Query) PatternCount

func (q *Query) PatternCount() int

PatternCount returns the number of patterns of the query.

PatternCount is Query::pattern_count.

func (*Query) PropertyPredicates

func (q *Query) PropertyPredicates(index int) []QueryPropertyPredicate

PropertyPredicates returns the properties that a pattern tests, with #is? and #is-not?.

PropertyPredicates is Query::property_predicates.

func (*Query) PropertySettings

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

PropertySettings returns the properties that a pattern sets, with #set!.

PropertySettings is Query::property_settings.

func (*Query) StartByteForPattern

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

StartByteForPattern returns the byte offset where a pattern starts in the text of the query. It panics for a pattern that the query does not have, as the Rust binding does.

StartByteForPattern is Query::start_byte_for_pattern.

type QueryCapture

type QueryCapture struct {
	Node  Node
	Index int
}

QueryCapture is one captured node. Index is its place in CaptureNames.

QueryCapture is QueryCapture of the Rust binding.

type QueryCursor

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

QueryCursor runs a query on a tree. It belongs to one goroutine at a time. Matches and Captures evaluate the text predicates of the query (D27).

QueryCursor is QueryCursor of the Rust binding.

func NewQueryCursor

func NewQueryCursor() *QueryCursor

NewQueryCursor returns a cursor that runs queries.

NewQueryCursor is QueryCursor::new.

func (*QueryCursor) Captures

func (c *QueryCursor) Captures(ctx context.Context, q *Query, n Node, src []byte) iter.Seq2[QueryMatch, int]

Captures runs a query on the node n and its descendants, and gives each capture in the order of the text, with the match that holds it. The int is the index of the capture in the Captures of the match. src is the text of the tree. A match whose text predicates fail is left out, and removed from the cursor.

Each range of the sequence runs the query from the start. When ctx ends, the sequence ends, so a caller that needs to know reads ctx.Err().

Captures is QueryCursor::captures and QueryCursor::captures_with_options, with the iterator QueryCaptures.

func (*QueryCursor) DidExceedMatchLimit

func (c *QueryCursor) DidExceedMatchLimit() bool

DidExceedMatchLimit reports whether the last run of the cursor had more matches in progress than its limit.

DidExceedMatchLimit is QueryCursor::did_exceed_match_limit.

func (*QueryCursor) MatchLimit

func (c *QueryCursor) MatchLimit() int

MatchLimit returns the largest number of matches that the cursor keeps in progress at one time.

MatchLimit is QueryCursor::match_limit.

func (*QueryCursor) Matches

func (c *QueryCursor) Matches(ctx context.Context, q *Query, n Node, src []byte) iter.Seq[QueryMatch]

Matches runs a query on the node n and its descendants, and gives each match in the order that the cursor finds it. src is the text of the tree. A match whose text predicates fail is left out.

Each range of the sequence runs the query from the start. When ctx ends, the sequence ends, so a caller that needs to know reads ctx.Err().

The Rust binding has a fault, which the port keeps: #any-eq?, #any-not-eq?, #any-match? and #any-not-match? hold when no node of their capture holds them, so they keep every match.

Matches is QueryCursor::matches and QueryCursor::matches_with_options, with the iterator QueryMatches.

func (*QueryCursor) SetByteRange

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

SetByteRange makes the cursor look only for matches that meet the range of bytes from start to end.

SetByteRange is QueryCursor::set_byte_range.

func (*QueryCursor) SetContainingByteRange

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

SetContainingByteRange makes the cursor give only the matches whose nodes are all inside the range of bytes from start to end. It works with SetByteRange, for example to find the matches that meet row 5000 and lie inside rows 4500 to 5500.

SetContainingByteRange is QueryCursor::set_containing_byte_range.

func (*QueryCursor) SetContainingPointRange

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

SetContainingPointRange makes the cursor give only the matches whose nodes are all inside the range of points from start to end.

SetContainingPointRange is QueryCursor::set_containing_point_range.

func (*QueryCursor) SetMatchLimit

func (c *QueryCursor) SetMatchLimit(limit int)

SetMatchLimit sets the largest number of matches that the cursor keeps in progress at one time. The limit must be above 0 and at most 65536.

SetMatchLimit is QueryCursor::set_match_limit.

func (*QueryCursor) SetMaxStartDepth

func (c *QueryCursor) SetMaxStartDepth(depth int)

SetMaxStartDepth makes the cursor start a match only at a node whose depth below the node of the run is at most depth. A depth of 0 starts a match only at that node. The other nodes of a pattern can still be at any depth. A negative depth removes the limit.

SetMaxStartDepth is QueryCursor::set_max_start_depth, where None is a negative depth.

func (*QueryCursor) SetPointRange

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

SetPointRange makes the cursor look only for matches that meet the range of points from start to end.

SetPointRange is QueryCursor::set_point_range.

type QueryError

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

QueryError says where a query fails to compile.

QueryError is QueryError of the Rust binding.

func (*QueryError) Error

func (e *QueryError) Error() string

Error returns the text of the error, as the Display of QueryError of the Rust binding writes it.

Error is the Display of QueryError.

type QueryErrorKind

type QueryErrorKind int

QueryErrorKind is the kind of fault in the source of a query.

QueryErrorKind is TSQueryError.

const (
	// QueryErrorNone is TSQueryErrorNone. The query has no fault.
	QueryErrorNone QueryErrorKind = iota
	// QueryErrorSyntax is TSQueryErrorSyntax. The source is not valid.
	QueryErrorSyntax
	// QueryErrorNodeType is TSQueryErrorNodeType. The language has no node
	// with the name.
	QueryErrorNodeType
	// QueryErrorField is TSQueryErrorField. The language has no field with
	// the name.
	QueryErrorField
	// QueryErrorCapture is TSQueryErrorCapture. A predicate names a capture
	// that the pattern does not have.
	QueryErrorCapture
	// QueryErrorStructure is TSQueryErrorStructure. The pattern cannot match
	// any tree of the language.
	QueryErrorStructure
	// QueryErrorLanguage is TSQueryErrorLanguage. The ABI version of the
	// language is not one that the runtime accepts.
	QueryErrorLanguage
	// QueryErrorPredicate is QueryErrorKind::Predicate of the Rust binding,
	// which TSQueryError does not have. A predicate of the query does not
	// parse. The query API returns it, and newQuery never returns it.
	QueryErrorPredicate
)

The kinds of fault in the source of a query.

func (QueryErrorKind) String

func (k QueryErrorKind) String() string

String returns the name of the kind.

type QueryMatch

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

QueryMatch is one match of a pattern. Captures is valid until the sequence that gave the match moves on, because the cursor reuses it, as the Rust binding reuses the match of its streaming iterator. Copy it to keep it.

QueryMatch is QueryMatch of the Rust binding.

func (QueryMatch) Remove

func (m QueryMatch) Remove()

Remove removes the match from the cursor that found it, so that the sequence that gave the match gives no more captures of it. Call it only while that sequence runs. The next run of the cursor gives the same ids to other matches, so a call after that can remove one of them. Remove does nothing for a zero QueryMatch, which no cursor gave (D94).

Remove is remove of QueryMatch in the Rust binding.

type QueryPredicate

type QueryPredicate struct {
	Operator string
	Args     []QueryPredicateArg
}

QueryPredicate is a predicate that the query does not evaluate: its operator, such as "lua-match?", and its arguments.

QueryPredicate is QueryPredicate of the Rust binding.

type QueryPredicateArg

type QueryPredicateArg struct {
	// IsCapture is true for a capture, and then Capture is its index. For a
	// string, Value is the string.
	IsCapture bool
	Capture   int
	Value     string
}

QueryPredicateArg is an argument of a general predicate: a capture or a string.

QueryPredicateArg is QueryPredicateArg of the Rust binding, an enum of Capture and String.

type QueryProperty

type QueryProperty struct {
	Key string
	// Value is the value of the property. HasValue is false when the
	// predicate names no value.
	Value    string
	HasValue bool
	// CaptureID is the index of the capture that the predicate names, or -1
	// when it names none.
	CaptureID int
}

QueryProperty is a key and a value of #set!, #is? or #is-not? in a pattern.

QueryProperty is QueryProperty of the Rust binding.

type QueryPropertyPredicate

type QueryPropertyPredicate struct {
	Property QueryProperty
	Positive bool
}

QueryPropertyPredicate is a property of #is?, which is positive, or of #is-not?, which is not.

QueryPropertyPredicate is the tuple (QueryProperty, bool) of property_predicates of the Rust binding.

type Range

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

Range is a range of the text, in bytes and in points.

Range is TSRange.

type StateID

type StateID uint16

StateID is the number of a parse state in the tables of a language.

StateID is TSStateId.

type Symbol

type Symbol uint16

Symbol is the number of a symbol in the tables of a language.

Symbol is TSSymbol.

type SymbolType

type SymbolType int

SymbolType is the kind of a symbol.

SymbolType is TSSymbolType.

const (
	// SymbolRegular is a named symbol that is visible in the tree, such as
	// identifier. It is TSSymbolTypeRegular.
	SymbolRegular SymbolType = iota
	// SymbolAnonymous is a symbol that is visible in the tree and has no name,
	// such as a keyword or a punctuation mark. It is TSSymbolTypeAnonymous.
	SymbolAnonymous
	// SymbolSupertype is a hidden symbol that stands for a set of symbols,
	// such as expression. It is TSSymbolTypeSupertype.
	SymbolSupertype
	// SymbolAuxiliary is a hidden symbol, such as a rule whose name starts
	// with an underscore. It is TSSymbolTypeAuxiliary.
	SymbolAuxiliary
)

The kinds of a symbol.

func (SymbolType) String

func (t SymbolType) String() string

String returns the name of the kind.

type Tree

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

Tree is a syntax tree. It is safe for reads from many goroutines. Edit changes it, so call Copy first to keep a version.

Tree is TSTree.

func (*Tree) ChangedRanges

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

ChangedRanges compares the tree, after an edit, with a new tree of the same text. It returns the ranges whose structure of nodes changed. Call it on the old tree that the parse used, with the new tree that the parse returned.

ChangedRanges is ts_tree_get_changed_ranges.

func (*Tree) Close

func (t *Tree) Close()

Close releases the nodes of the tree. After Close, the program must not use the tree, or a node or a cursor of it, and the runtime does not check this. A node that another tree shares, after Copy or after a parse with the tree as the old tree, stays in the other tree. Close is optional. The garbage collector frees a tree that the program does not close (D91).

Close is ts_tree_delete. The C function releases the root into a pool of its own, whose capacity is 0, so no parser takes the freed nodes again. The Go function does the same, and then clears the tree, so that it keeps no node alive.

func (*Tree) Copy

func (t *Tree) Copy() *Tree

Copy returns a copy of the tree. The copy shares the nodes of the tree, so it costs little. Edit changes only the tree that it is called on.

Copy is ts_tree_copy.

func (*Tree) Edit

func (t *Tree) Edit(e InputEdit)

Edit changes the tree to match an edit of the text. Give the edit both in bytes and in points.

Edit is ts_tree_edit.

func (*Tree) IncludedRanges

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

IncludedRanges returns a copy of the included ranges of the parse that made the tree.

IncludedRanges is ts_tree_included_ranges.

func (*Tree) Language

func (t *Tree) Language() *Language

Language returns the language of the tree.

Language is ts_tree_language.

func (*Tree) PrintDotGraph

func (t *Tree) PrintDotGraph(w io.Writer)

PrintDotGraph writes a graph of the tree to w, in the DOT language. The program dot of Graphviz draws it.

PrintDotGraph is ts_tree_print_dot_graph. The C function writes to a file descriptor, and the Go function writes to w.

func (*Tree) RootNode

func (t *Tree) RootNode() Node

RootNode returns the root node of the tree.

RootNode is ts_tree_root_node.

func (*Tree) RootNodeWithOffset

func (t *Tree) RootNodeWithOffset(offset int, at Point) Node

RootNodeWithOffset returns the root node of the tree, moved forward by a number of bytes and by a point.

RootNodeWithOffset is ts_tree_root_node_with_offset.

func (*Tree) Walk

func (t *Tree) Walk() *TreeCursor

Walk returns a cursor at the root node of the tree.

Walk is walk of Tree in the Rust binding.

type TreeCursor

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

TreeCursor walks a tree. It belongs to one goroutine at a time.

TreeCursor is TSTreeCursor and TreeCursor.

func (*TreeCursor) Copy

func (c *TreeCursor) Copy() *TreeCursor

Copy returns a copy of the cursor, at the same node.

Copy is ts_tree_cursor_copy.

func (*TreeCursor) Depth

func (c *TreeCursor) Depth() int

Depth returns the depth of the node of the cursor below the root of the cursor, where the root has the depth 0.

Depth is ts_tree_cursor_current_depth.

func (*TreeCursor) DescendantIndex

func (c *TreeCursor) DescendantIndex() int

DescendantIndex returns the index of the node of the cursor among the descendants of the root of the cursor, as GotoDescendant counts them.

DescendantIndex is ts_tree_cursor_current_descendant_index.

func (*TreeCursor) FieldID

func (c *TreeCursor) FieldID() FieldID

FieldID returns the field of the node of the cursor, or 0 when it has no field.

FieldID is ts_tree_cursor_current_field_id.

func (*TreeCursor) FieldName

func (c *TreeCursor) FieldName() string

FieldName returns the name of the field of the node of the cursor, or "" when it has no field.

FieldName is ts_tree_cursor_current_field_name.

func (*TreeCursor) GotoDescendant

func (c *TreeCursor) GotoDescendant(index int)

GotoDescendant moves the cursor to the descendant of the root of the cursor with an index, in the order of a walk from the root, where the root has the index 0.

GotoDescendant is ts_tree_cursor_goto_descendant.

func (*TreeCursor) GotoFirstChild

func (c *TreeCursor) GotoFirstChild() bool

GotoFirstChild moves the cursor to the first child of its node. It returns false, and does not move, when the node has no children.

GotoFirstChild is ts_tree_cursor_goto_first_child.

func (*TreeCursor) GotoFirstChildForByte

func (c *TreeCursor) GotoFirstChildForByte(offset int) (int, bool)

GotoFirstChildForByte moves the cursor to the first child of its node that ends after a byte offset. It returns the index of the child, or false, and no move, when no child ends after the offset.

GotoFirstChildForByte is ts_tree_cursor_goto_first_child_for_byte.

func (*TreeCursor) GotoFirstChildForPoint

func (c *TreeCursor) GotoFirstChildForPoint(at Point) (int, bool)

GotoFirstChildForPoint moves the cursor to the first child of its node that ends after a point. It returns the index of the child, or false, and no move, when no child ends after the point.

GotoFirstChildForPoint is ts_tree_cursor_goto_first_child_for_point.

func (*TreeCursor) GotoLastChild

func (c *TreeCursor) GotoLastChild() bool

GotoLastChild moves the cursor to the last child of its node. It returns false, and does not move, when the node has no children.

GotoLastChild is ts_tree_cursor_goto_last_child.

func (*TreeCursor) GotoNextSibling

func (c *TreeCursor) GotoNextSibling() bool

GotoNextSibling moves the cursor to the next sibling of its node. It returns false, and does not move, when the node has no next sibling.

GotoNextSibling is ts_tree_cursor_goto_next_sibling.

func (*TreeCursor) GotoParent

func (c *TreeCursor) GotoParent() bool

GotoParent moves the cursor to the parent of its node. It returns false, and does not move, when the node is the root of the cursor.

GotoParent is ts_tree_cursor_goto_parent.

func (*TreeCursor) GotoPreviousSibling

func (c *TreeCursor) GotoPreviousSibling() bool

GotoPreviousSibling moves the cursor to the previous sibling of its node. It returns false, and does not move, when the node has no previous sibling.

GotoPreviousSibling is ts_tree_cursor_goto_previous_sibling.

func (*TreeCursor) Node

func (c *TreeCursor) Node() Node

Node returns the node of the cursor.

Node is ts_tree_cursor_current_node.

func (*TreeCursor) Reset

func (c *TreeCursor) Reset(n Node)

Reset moves the cursor to a node, which becomes the root of the cursor.

Reset is ts_tree_cursor_reset.

func (*TreeCursor) ResetTo

func (c *TreeCursor) ResetTo(other *TreeCursor)

ResetTo moves the cursor to the node of another cursor, with the root of that cursor.

ResetTo is ts_tree_cursor_reset_to.

Directories

Path Synopsis
cmd
transit command
Command transit is the command of transit (D41).
Command transit is the command of transit (D41).
Package generate is the parser generator of transit, a port of the crate crates/generate of upstream tree-sitter (D7).
Package generate is the parser generator of transit, a port of the crate crates/generate of upstream tree-sitter (D7).
backend/c
Package c is the C backend of the transit generator (D8).
Package c is the C backend of the transit generator (D8).
backend/go
Package golang is the Go backend of the transit generator (D8).
Package golang is the Go backend of the transit generator (D8).
internal/fxhash
Package fxhash gives the generator the hash and the order of iteration of the hash sets that upstream tree-sitter uses.
Package fxhash gives the generator the hash and the order of iteration of the hash sets that upstream tree-sitter uses.
internal/regexsyntax/ast
Package ast is the syntax tree of a regular expression, its parser and a walk of the tree.
Package ast is the syntax tree of a regular expression, its parser and a walk of the tree.
internal/regexsyntax/hir
Package hir is the high level intermediate form (the HIR) of a regular expression, and the translator that makes it from a syntax tree.
Package hir is the high level intermediate form (the HIR) of a regular expression, and the translator that makes it from a syntax tree.
internal/regexsyntax/unicodetables
Package unicodetables holds the Unicode tables of the Rust crate regex-syntax 0.8.11, as Go data.
Package unicodetables holds the Unicode tables of the Rust crate regex-syntax 0.8.11, as Go data.
grammars
usql module
Package inject finds the injections of a text and parses the layer of each (D27).
Package inject finds the injections of a text and parses the layer of each (D27).
internal
abi
Package abi holds the tables of a grammar in the shape of TSLanguage of lib/src/parser.h of upstream.
Package abi holds the tables of a grammar in the shape of TSLanguage of lib/src/parser.h of upstream.
grammartest
Package grammartest holds the tests of a grammar package, which the grammar_test.go that the Go backend writes calls: the corpus test, the query test, the highlight test and the generator test of docs/GRAMMAR.md.
Package grammartest holds the tests of a grammar package, which the grammar_test.go that the Go backend writes calls: the corpus test, the query test, the highlight test and the generator test of docs/GRAMMAR.md.
wctype
Package wctype holds the character functions of <wctype.h> and <ctype.h> that the Go scanners of the grammars call (D39, D46).
Package wctype holds the character functions of <wctype.h> and <ctype.h> that the Go scanners of the grammars call (D39, D46).
styles module

Jump to

Keyboard shortcuts

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