transit

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 15 Imported by: 17 modules, 9 packages

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

README


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.

Install

transit needs Go 1.27.1 or later. Get the runtime, and the package of each grammar that your program parses:

go get github.com/xo/transit
go get github.com/xo/transit/grammars/json

The runtime imports only the Go standard library. Each grammar is a module of its own, so your program builds only the grammars that it imports. Grammars lists them. The colors of the highlighting are in the module github.com/xo/transit/styles, which you get in the same way.

Quick start

This program parses a text of JSON and prints its tree as an S-expression. It is the example Example_parse of the package grammars/json:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/xo/transit"
	"github.com/xo/transit/grammars/json"
)

func main() {
	src := []byte(`{"name": "transit", "tags": [1, 2]}`)
	parser := transit.NewParser()
	if err := parser.SetLanguage(json.Language()); err != nil {
		log.Fatal(err)
	}
	tree, err := parser.Parse(context.Background(), src, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(tree.RootNode())
}

It prints:

(document (object (pair key: (string (string_content)) value: (string (string_content))) (pair key: (string (string_content)) value: (array (number) (number)))))

A Node gives its kind, its position, its text, its parent, its children and its fields. The example Example_fields of grammars/json reads each pair of an object by its fields:

object, _ := tree.RootNode().NamedChild(0)
for pair := range object.NamedChildren() {
	key, _ := pair.ChildByFieldName("key")
	value, _ := pair.ChildByFieldName("value")
	fmt.Printf("%s = %s (%s)\n", key.Text(src), value.Text(src), value.Kind())
}

A text with a syntax error still gives a tree. Node.HasError says that the tree holds an ERROR or a MISSING node, and Example_errors of grammars/json finds each one.

Highlighting

Each grammar package holds the queries of its grammar in Queries, such as queries/highlights.scm. A highlight query gives a capture name, such as keyword or string, to each node that it matches. The module styles gives a color to each capture name. It bundles the styles of chroma and other styles, in dark and light forms.

These images show the samples of three grammars in the style onedark, which is dark, and the style github, which is light. The body of the PostgreSQL function is in PL/pgSQL, and the grammar plpgsql highlights it through an injection. The third image is the input of usql, with its meta commands and variables:

PostgreSQL in the styles onedark and github

Go in the styles onedark and github

The input of usql in the styles onedark and github

The command transit draws these images, as The command transit says. It can draw the sample of each language in each style. To draw these three again, run this command in the root of the repository:

(cd cmd/transit && for l in postgres go usql; do go run . preview -f svg --styles onedark,github --columns 2 $l > ../../docs/images/lang-$l.svg; done)

This code highlights the Go code func (c Circle) Area() float64 { return math.Pi * c.R * c.R } with the highlight query of the package grammars/go, and gives each capture the color of the style onedark. It comes from Example_highlight of grammars/go. Captures gives the captures in the order of the text, which is the order that a highlighter needs:

text, err := golang.Queries.ReadFile("queries/highlights.scm")
if err != nil {
	log.Fatal(err)
}
query, err := transit.NewQuery(golang.Language(), string(text))
if err != nil {
	log.Fatal(err)
}
style, ok := styles.Get("onedark")
if !ok {
	log.Fatal("no style onedark")
}
names := query.CaptureNames()
cursor := transit.NewQueryCursor()
for m, i := range cursor.Captures(context.Background(), query, tree.RootNode(), src) {
	c := m.Captures[i]
	name := names[c.Index]
	fmt.Printf("%-16s %-8s %s\n", name, c.Node.Text(src), style.Lookup(name).Fg)
}
keyword          func     #c678dd
variable         c        #abb2bf
type             Circle   #e5c07b
function.method  Area     #61afef
...

To write the text to a terminal, give the first capture of each node the color of its entry, and write the text between the captures with no color. Example_ansi of grammars/go does it with 24-bit colors. Color.To256 and Color.To16 reduce a color for a terminal with fewer colors:

if fg := style.Lookup(name).Fg; fg.IsSet() {
	r, g, bl := fg.RGB()
	fmt.Fprintf(&b, "\x1b[38;2;%d;%d;%dm%s\x1b[0m", r, g, bl, n.Text(src))
} else {
	b.WriteString(n.Text(src))
}

A program compiles a query once and shares it, because a query costs much more to compile than to run.

More examples

Each example below is an example function of a package, and go test runs it. The full code of each one is in the package, and pkg.go.dev shows it.

Queries and captures

A query finds the nodes that match a pattern. Matches evaluates the predicates of the query, such as #eq?, and gives only the matches that pass. Example_matches of grammars/json finds each pair whose key is id:

query, err := transit.NewQuery(json.Language(), `(pair
  key: (string (string_content) @key)
  value: (_) @value
  (#eq? @key "id"))`)
if err != nil {
	log.Fatal(err)
}
value, _ := query.CaptureIndexForName("value")
cursor := transit.NewQueryCursor()
for m := range cursor.Matches(context.Background(), query, tree.RootNode(), src) {
	for _, c := range m.Captures {
		if c.Index == value {
			fmt.Printf("id %s at byte %d\n", c.Node.Text(src), c.Node.StartByte())
		}
	}
}
Editing and parsing again

After an edit, tell the old tree about the edit with Tree.Edit, and parse the new text with the old tree. The parser reuses the parts of the old tree that did not change. Tree.ChangedRanges gives the ranges whose syntax changed, so a line editor highlights only those ranges again. This comes from Example_edit of grammars/json:

// Insert `, "three"` at byte 5 of `[1, 2]`, before the `]`.
insert := []byte(`, "three"`)
newSrc := slices.Concat(src[:5], insert, src[5:])
tree.Edit(transit.InputEdit{
	StartByte:   5,
	OldEndByte:  5,
	NewEndByte:  5 + len(insert),
	StartPoint:  transit.Point{Row: 0, Column: 5},
	OldEndPoint: transit.Point{Row: 0, Column: 5},
	NewEndPoint: transit.Point{Row: 0, Column: 5 + len(insert)},
})
newTree, err := parser.Parse(ctx, newSrc, tree)
if err != nil {
	log.Fatal(err)
}
for _, r := range tree.ChangedRanges(newTree) {
	fmt.Printf("changed: %s\n", newSrc[r.StartByte:r.EndByte])
}

ExampleInputEdit of the root package computes the points of an edit on a text of several rows.

Walking a tree with a cursor

A TreeCursor walks a tree, and it is faster than Node.Child for a walk of many nodes. Example_treeCursor of grammars/json prints each named node with its field name:

cursor := tree.Walk()
for {
	if n := cursor.Node(); n.IsNamed() {
		field := cursor.FieldName()
		if field != "" {
			field += ": "
		}
		fmt.Printf("%*s%s%s %q\n", 2*cursor.Depth(), "", field, n.Kind(), n.Text(src))
	}
	if cursor.GotoFirstChild() {
		continue
	}
	for !cursor.GotoNextSibling() {
		if !cursor.GotoParent() {
			return
		}
	}
}
Injections

An injection is a part of a text in another language, such as a script in HTML, or the body of a PostgreSQL function in PL/pgSQL. The package github.com/xo/transit/inject reads the injection query of each grammar, and parses each injection as a layer of its own. Example_layers of grammars/postgres/postgres parses a function whose body is in PL/pgSQL:

lookup := lookup() // gives the *inject.Config of "postgres" and of "plpgsql"
config, _ := lookup("postgres")
layers, err := config.Layers(context.Background(), transit.NewParser(), src, lookup)
if err != nil {
	log.Fatal(err)
}
for _, l := range layers {
	// The range of the root layer ends at the largest offset, so the
	// text of a range ends at the end of src at most.
	var texts []string
	for _, r := range l.Ranges {
		texts = append(texts, strings.TrimSpace(string(src[r.StartByte:min(r.EndByte, len(src))])))
	}
	fmt.Printf("%d %-8s %q\n", l.Depth, l.Name, texts)
}

The layers are the function in postgres, its body in plpgsql, and each expression of the body in postgres again. Example_layers of grammars/html parses HTML with a script, and Example_replacer of the same package replaces the text of a template tag before the layer is parsed.

The usql grammar and the options of a dialect

The package github.com/xo/transit/grammars/usql reads the input of usql: SQL statements, meta commands such as \d, and variables such as :name. usql.LanguageFor gives the grammar with the options of a SQL dialect. Example_languageFor of grammars/usql splits a script of Oracle into its statements. With the options of Oracle, a procedure and an anonymous block are each one statement:

oracle := usql.Options{BlockComments: true, BeginEndBlocks: true, AnonymousBlocks: true, DashComments: true}
language := usql.LanguageFor(oracle)

The example parses the script with that language, as the quick start does, and prints the first line of each statement:

for n := range tree.RootNode().NamedChildren() {
	if n.Kind() != "statement" {
		continue
	}
	// print the first line of the statement
	text, _, _ := bytes.Cut([]byte(n.Text(src)), []byte("\n"))
	fmt.Printf("  %d: %s\n", n.StartPoint().Row+1, text)
}

Example_cursor of the same package finds whether a cursor is in a meta command, in a variable or in a SQL statement.

Completion with StatesAt

Parser.StatesAt gives the parse states at a byte offset, before the parser recovers from an error. The lookahead iterator of each state gives the symbols that the parser can accept there. A completion lists them. Example_statesAt of grammars/json lists what can come after {"a": 1, "b": :

states, err := parser.StatesAt(context.Background(), src, len(src), nil)
if err != nil {
	log.Fatal(err)
}
var tokens, nodes []string
for _, state := range states {
	it, ok := language.LookaheadIterator(state)
	if !ok {
		continue
	}
	for sym := range it.Symbols() {
		switch language.SymbolType(sym) {
		case transit.SymbolAnonymous:
			tokens = append(tokens, language.SymbolName(sym))
		case transit.SymbolRegular:
			nodes = append(nodes, language.SymbolName(sym))
		}
	}
}

It prints:

tokens: [{ [ "]
nodes: [comment object array string number true false null]

In an injection, inject.Layer.StatesAt gives the parse states of one layer. Example_statesAt of grammars/postgres/postgres lists the keywords that can start a statement of PL/pgSQL in the body of a function.

Sample programs

The module github.com/xo/transit/_example holds two programs that use transit as rline and usql will (D53). Run them in the folder _example:

Program What it does
go run ./highlight -dialect mysql -style onedark -colors 256 It types a text of usql one key at a time, parses again after each key, and prints the text in the colors of a style
go run ./complete -dialect postgres -text 'select * from ' It lists the keywords and the kinds of node that can come at a cursor in a SQL statement

The flag -dialect takes athena, clickhouse, cql, duckdb, generic, mysql, oracle, postgres, presto, sqlite3, sqlserver or trino.

The command transit

The command transit highlights the syntax of a text in a terminal, as an HTML page or as an SVG image, with each grammar of the repository and each style of the package styles. It is pure Go, and it is in the module github.com/xo/transit/cmd/transit (D149). Each release from v0.8.0 on has an archive of the command for Linux, macOS and Windows, on amd64 and arm64. From v0.8.1 on, go install builds it too:

go install github.com/xo/transit/cmd/transit@latest

To build it from a clone of the repository, run go build in the folder cmd/transit.

# highlight a file, with its language from its name
transit main.go
# another style, with line numbers and the background of the style
transit -s dracula -n -b main.go
# the standard input, with the name that gives its language
git show HEAD:main.go | transit --filename main.go
# an HTML page, and an SVG image
transit -f html query.sql > query.html
transit -f svg main.go > main.svg
# the code sample of a language, in one style or in each style
transit preview go
transit preview --all-styles python
transit preview -f svg --styles onedark,github --columns 2 go > go.svg
# the languages and the styles
transit languages
transit styles

The language comes from --lang, then from the name of the file, then from a #! line. A text of a language that the command does not have comes out as plain text. --color is auto, always or never, and with auto the command writes colors only to a terminal, and not when NO_COLOR is set. The default style is onedark, as in usql. $TRANSIT_STYLE gives the style when --style does not, and --style also takes the path of a style file.

The file config.yaml in the folder transit of the config folder of the user, such as ~/.config/transit/config.yaml, gives the defaults of the flags, as the config files of usql and hail do. Each key is the name of a flag, and a key of a subcommand is under its name. The command line and $TRANSIT_STYLE win over the file. The command reads config.yml when config.yaml does not exist, and --config FILE or $TRANSIT_CONFIG names another file:

style: github
line-numbers: true
background: true
preview:
  styles: [onedark, github]

An SVG image draws a red line under a parse error. The package github.com/xo/transit/samples holds the code sample of each language. The subcommand generate runs the generator, as tree-sitter generate does (D41).

Grammars

The Go backend writes a package for each grammar that the maintainers choose. 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/cql cql shotover/tree-sitter-cql v0.2.0

The repository of cql has no highlight query, so xo wrote queries/highlights.scm of this package (D113).

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, block comments, dash comments and backslash escapes. LanguageFor gives the language with the options of a dialect, with the same tables:

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

The fields of usql.Options are the flags of the type Syntax of dbmeta: DollarQuotes, BlockComments, SlashComments, HashComments, Backticks, DashComments, Brackets and BackslashEscapes. dbmeta holds the value of each flag for each dialect. With DashComments, -- starts a comment. Without it, -- is text, as in the relationship (a)--(b) of Cypher (D139). With Brackets, a name in square brackets, such as [a b] of SQL Server and SQLite, is a quoted identifier. Without it, [ is text, as in a[1] of PostgreSQL (D140). With BackslashEscapes, a backslash escapes the next character in a string in single quotes and in a name in double quotes, as in MySQL. Without it, a backslash in such a string or name is text, as in 'C:\data\', and only a doubled quote escapes a quote. A string of the form E'...' of PostgreSQL keeps the backslash escapes (D142). Three more fields are not flags of dbmeta. BeginEndBlocks and AnonymousBlocks are described below. Batches keeps a batch of CQL, from BEGIN BATCH to APPLY BATCH, in one statement. It is off by default.

The package github.com/xo/transit/grammars/mysql holds the grammar mysql, which xo writes from the reference manual of MySQL 8.4 (D42, D106). It covers the SQL that MySQL 8.4 and MariaDB share, with backticks, # and -- comments, version comments such as /*!40101 ... */, the variables @name and @@session.name, and stored programs with BEGIN ... END bodies. It does not read the DELIMITER command of the mysql client. The usql grammar ends a statement at each ;, so by default it splits such a body into several statements, and the MySQL grammar finds an error in each part. The option BeginEndBlocks of usql.Options keeps the body in one statement (D112). It is off by default. One identifier token covers each keyword that MySQL does not reserve, and the reserved words of MySQL 8.4 are not identifiers, so the package adds about 1 MB to a binary (D123).

The package github.com/xo/transit/grammars/oracle holds the grammar oracle, which xo writes from the SQL Language Reference and the PL/SQL Language Reference of Oracle Database 23ai (D124). It covers the lexical structure, with the strings of the form q'[...]', the expressions, the types, the function calls with their analytic clauses, and the full SELECT, with CONNECT BY, PIVOT, MODEL, MATCH_RECOGNIZE and JSON_TABLE. It also covers the statements that change data, such as INSERT, UPDATE, DELETE and MERGE, the statements of transactions and of sessions, such as COMMIT and ALTER SESSION, and GRANT, REVOKE, COMMENT, TRUNCATE and the other statements of the SQL Language Reference that do not create or change an object. It reads the statements that define objects: CREATE, ALTER and DROP of tables, indexes, views, materialized views, types, domains, property graphs and the other objects of the manual, with the columns, the constraints and the partitions of a table. The physical options of an object, such as STORAGE, are a list of words. It reads PL/SQL in the same grammar, because Oracle does not put PL/SQL in a quoted string: anonymous blocks, CREATE PROCEDURE, CREATE FUNCTION, CREATE PACKAGE, CREATE PACKAGE BODY, CREATE TRIGGER, CREATE TYPE BODY, the functions of WITH, each declaration and statement of PL/SQL, and the conditional compilation with $IF. A / alone on its line ends a statement, as in a script of SQL*Plus. The option BeginEndBlocks of usql.Options keeps a stored program, a package spec, a package body and a type body each in one statement (D112, D144), and the option AnonymousBlocks keeps an anonymous block, which starts with BEGIN or DECLARE, in one statement (D128). Both are off by default. The package adds about 3.3 MB to a binary (D125). The grammar of andreasmaierde/tree-sitter-plsql stays in the golden set, but it has no Go package.

The package github.com/xo/transit/grammars/sqlserver holds the grammar sqlserver, which xo writes from the Transact-SQL reference of SQL Server 2025 (D124). It covers the lexical structure, with bracketed identifiers, variables such as @name and @@ROWCOUNT, temporary tables such as #t, binary and money constants and comments that nest. It covers the expressions, the types, the function calls with OVER and WITHIN GROUP, and the full SELECT, with TOP, INTO, APPLY, PIVOT, the table hints, FOR SYSTEM_TIME, the rowset functions such as OPENJSON, FOR XML, FOR JSON and OPTION. It also covers INSERT, UPDATE, DELETE and MERGE with OUTPUT, BULK INSERT, TRUNCATE TABLE, the statements of transactions, SET, USE, EXECUTE, PRINT, RAISERROR, THROW, the control-of-flow language, such as IF, WHILE, BEGIN ... END and TRY ... CATCH, DECLARE and the statements of cursors. It covers the statements that define objects: CREATE, ALTER and DROP of tables, with temporal, ledger, graph and memory-optimized tables, of each kind of index, of views, schemas, synonyms, types, statistics, databases, logins, users, roles and the other objects of the reference, and GRANT, DENY, REVOKE and UPDATE STATISTICS. It reads CREATE and ALTER of procedures, functions and triggers, with their parameters and options, the natively compiled modules with BEGIN ATOMIC, and the modules of an assembly. It reads ENABLE TRIGGER, the statements of Service Broker, such as SEND, RECEIVE and WAITFOR (RECEIVE ...), BACKUP, RESTORE, DBCC, KILL, CHECKPOINT and the other statements of the reference. A statement does not need a semicolon at its end. A line with only GO and an optional count ends a batch, as in sqlcmd. The body of a procedure or a trigger runs to the end of its batch. The package adds about 1.5 MB to a binary. The grammar of Crary-Systems/tree-sitter-tsql stays in the golden set, but it has no Go package.

The package github.com/xo/transit/grammars/sqlite3 holds the grammar sqlite3, which xo writes from the SQL reference of SQLite (D126). It covers the lexical structure, with the names in double quotes, in brackets and in backquotes, the BLOB literals such as X'0A', the numbers with _ between their digits, the parameters ?NNN, :name, @name and $name, and the comments. It covers the expressions with the precedence of the reference, with -> and ->>, IS DISTINCT FROM, GLOB, REGEXP, MATCH, CAST and RAISE, the function calls with FILTER, OVER and ORDER BY in their arguments, and the full SELECT, with WITH, the joins, the table-valued functions, INDEXED BY, VALUES, WINDOW and the compound operators. It covers each other statement of the reference: INSERT and REPLACE with the upsert, UPDATE with FROM, DELETE, RETURNING, CREATE TABLE with each constraint, the generated columns, WITHOUT ROWID and STRICT, CREATE VIRTUAL TABLE with the arguments of a module, ALTER TABLE, CREATE INDEX, CREATE VIEW, CREATE TRIGGER, DROP, ATTACH, DETACH, PRAGMA, the statements of transactions and savepoints, ANALYZE, REINDEX, VACUUM and EXPLAIN. SQLite reserves few of its keywords, so one identifier token covers each keyword that SQLite does not reserve. The grammar has no external scanner. The package adds about 0.6 MB to a binary.

The package github.com/xo/transit/grammars/duckdb holds the grammar duckdb, which xo writes from the SQL documentation of DuckDB 2.0 (D126). It covers the lexical structure, with the names in double quotes and in backquotes, the strings with E before them, the dollar-quoted strings, the bit strings such as B'0101' and the hex strings such as X'CAFE', the numbers with _ between their digits, the parameters ?, $1 and $name, and the comments, which nest. It covers the expressions with the precedence of DuckDB, with :: and TRY_CAST, the lists, the structs and the maps, the subscripts and the slices, the lambdas in both forms, the list comprehensions, the calls of a function after a dot, COLUMNS and *COLUMNS, the star with EXCLUDE, REPLACE and RENAME, the named arguments, FILTER, WITHIN GROUP, IGNORE NULLS and the window functions. It covers the types, and the full query: WITH with RECURSIVE and USING KEY, SELECT with DISTINCT ON, a query that starts with FROM, each kind of join with ASOF, POSITIONAL, SEMI, ANTI and NEAREST, the table functions, a file as a table, PIVOT and UNPIVOT in both forms, the samples, GROUP BY ALL, QUALIFY, the set operations with BY NAME, ORDER BY ALL and LIMIT with a percent. It covers the statements that change rows: INSERT with OR REPLACE, BY NAME, ON CONFLICT and RETURNING, UPDATE, DELETE, TRUNCATE and MERGE INTO. It covers the statements that change the schema: CREATE TABLE with its constraints and its generated columns, ALTER TABLE, the views, the indexes, the sequences, the schemas, the types, the macros, the secrets, the triggers and DROP. It covers each other statement of the documentation: COPY, EXPORT DATABASE, IMPORT DATABASE, ATTACH, DETACH, USE, CONNECT, CHECKPOINT, VACUUM, ANALYZE, INSTALL, LOAD, UPDATE EXTENSIONS, the extension repositories, SET, RESET, PRAGMA, DESCRIBE, SUMMARIZE, SHOW, EXPLAIN, the prepared statements, CALL, the statements of transactions and COMMENT ON. It does not read the statements of the extension DuckPGQ, such as CREATE PROPERTY GRAPH. The external scanner reads the comments and the dollar-quoted strings. The package adds about 1.3 MB to a binary.

The package github.com/xo/transit/grammars/clickhouse holds the grammar clickhouse, which xo writes from the SQL reference of ClickHouse (D127). It covers the lexical structure, with the names in backquotes and in double quotes, the strings with backslash escapes, the heredoc strings such as $doc$text$doc$, the numbers in each form with 0x, 0b, inf and nan, the query parameters such as {id:UInt32}, and the comments with --, //, # and /* */, which nest. It covers the expressions with the precedence of ClickHouse, with the ternary operator ?:, the lambdas, :: and CAST, AT TIME ZONE and AT LOCAL, the arrays, the tuples and the maps, the elements of a tuple such as t.1, the paths of a JSON column, an alias with AS in any expression, GLOBAL IN, the parametric aggregate functions such as quantile(0.9)(x), FILTER, the window functions, COLUMNS and the star with EXCEPT, REPLACE and APPLY. It covers the types, such as Nullable, LowCardinality, Tuple with names, Map, Nested, Enum8 with its values, DateTime64 with a time zone, AggregateFunction, JSON, Variant and Dynamic. It covers the full query: WITH with expressions and subqueries, SELECT with DISTINCT ON and TOP, a query that starts with FROM, FINAL, SAMPLE, ARRAY JOIN, each kind of join with GLOBAL, ANY, ASOF, SEMI, ANTI and PASTE, the table functions, PREWHERE, GROUP BY with WITH ROLLUP, WITH CUBE and WITH TOTALS, QUALIFY, ORDER BY with WITH FILL and INTERPOLATE, LIMIT BY, LIMIT with WITH TIES, the set operations, SETTINGS, INTO OUTFILE and FORMAT. It covers EXPLAIN of a query. It covers INSERT with VALUES, a query, FROM INFILE, a table function and the data of a format after FORMAT, and DELETE, UPDATE and TRUNCATE. It covers CREATE DATABASE, CREATE TABLE with its columns, indexes, projections, constraints, engine, keys, TTL and AS, CREATE VIEW, MATERIALIZED VIEW with REFRESH, LIVE VIEW and WINDOW VIEW, CREATE DICTIONARY, CREATE FUNCTION, CREATE NAMED COLLECTION, CREATE INDEX with ASC and DESC, and each action of ALTER TABLE. It covers DROP, DETACH, ATTACH, UNDROP, RENAME, EXCHANGE and OPTIMIZE. It covers each form of SHOW, DESCRIBE, EXISTS, CHECK, KILL, each command of SYSTEM, SET, SET ROLE and USE. It covers GRANT, REVOKE, and CREATE and ALTER of the users, the roles, the policies, the quotas and the settings profiles. It covers MOVE, WATCH, BACKUP, RESTORE, EXECUTE AS, the statements of transactions, the workloads, the resources, the handlers, the tokens, EXPLAIN of each statement, and PARALLEL WITH. The external scanner reads the comments, the heredoc strings and the data of INSERT after FORMAT. The package adds about 1.9 MB to a binary.

The package github.com/xo/transit/grammars/trino holds the grammar trino, which xo writes from the SQL documentation of Trino (D127). It also serves the SQL of Presto and of Athena. It covers the lexical structure, with the names in double quotes, the strings with doubled quotes, the Unicode strings such as U&'caf\00E9', the binary strings such as X'CAFE', the numbers with _ and in hexadecimal, octal and binary form, the parameter ?, and the comments with -- and /* */. It covers the expressions with the precedence of Trino, with CAST and TRY_CAST, AT TIME ZONE and AT LOCAL, ||, LIKE with ESCAPE, IS DISTINCT FROM, the quantified comparisons, EXISTS, UNIQUE and MATCH, CASE with the predicates of its simple form, the lambdas, the arrays, ROW, the subscripts, the fields of a row, the methods of a value such as 'abc'.length(), the functions of a type such as varchar::chr(65), the typed literals, the intervals, the values such as CURRENT_DATE, the functions of JSON, LISTAGG, FILTER, the window functions with their frames, and the special forms such as EXTRACT, TRIM and SUBSTRING. It covers the types, such as DECIMAL(10, 2), ROW with names, MAP, TIMESTAMP(6) WITH TIME ZONE and INTERVAL DAY TO SECOND. It covers the full query: WITH with RECURSIVE, WITH SESSION and WITH FUNCTION with the body of a SQL routine, each kind of join, LATERAL, UNNEST, the table functions with DESCRIPTOR, TABLESAMPLE, MATCH_RECOGNIZE, PIVOT, JSON_TABLE, NEAREST, GROUP BY with AUTO, ROLLUP, CUBE and GROUPING SETS, WINDOW, the set operations with CORRESPONDING, ORDER BY, OFFSET, LIMIT and FETCH with WITH TIES. It covers INSERT, UPDATE, DELETE and MERGE, with the branches of a table after @, and TRUNCATE. It covers CREATE, ALTER and DROP of the tables, the views, the materialized views, the schemas, the catalogs, the roles, the branches and the functions, with the properties after WITH, CREATE TABLE AS with WITH NO DATA, and each action of ALTER TABLE, with EXECUTE, and ALTER ... SET AUTHORIZATION of each kind of object. It covers COMMENT ON, REFRESH MATERIALIZED VIEW, ANALYZE, GRANT, REVOKE and DENY on each kind of object, each form of SET and RESET, USE, PREPARE, EXECUTE with IMMEDIATE, DEALLOCATE PREPARE, DESCRIBE, each form of SHOW, EXPLAIN and EXPLAIN ANALYZE with their options, CALL, and the statements of transactions. The grammar needs no external scanner. The package adds about 1.0 MB to a binary.

The package github.com/xo/transit/grammars/sql holds the grammar sql, the generic SQL grammar, which xo writes for the dialects that have no grammar of their own (D143). It replaces the grammar of DerekStride/tree-sitter-sql, and its package has the same functions. It reads the SQL that most dialects share, and the forms that several of them add, from the SQL documentation of Snowflake, BigQuery and Databricks. It is lenient, because it serves highlighting, so a form of one dialect can parse as a generic form. It covers the comments with --, //, # and /* */, the strings with doubled quotes and backslash escapes, the strings in three quotes, the raw strings, the bytes and the strings in $$, the names in double quotes and in backticks, and the parameters ?, :name, @name, $1 and ${name}. It covers the expressions, with CAST, TRY_CAST, SAFE_CAST and ::, LIKE, ILIKE, RLIKE and REGEXP with ANY and ALL, IS DISTINCT FROM, the function calls with DISTINCT, FILTER, WITHIN GROUP, IGNORE NULLS and OVER, the window frames, the named arguments, the lambdas, the arrays, the STRUCT values, the object constants, the access to a field with : and ., the subscripts, the intervals, DIV, the expression WITH of BigQuery, and WHERE and HAVING MAX in the arguments of an aggregate. A string in double quotes after a type, as in DATE "2024-01-01", is a constant of BigQuery where no alias can come. It covers the full query: WITH with RECURSIVE, SELECT with DISTINCT, TOP and AS STRUCT, the star with EXCEPT, EXCLUDE, REPLACE, RENAME and ILIKE, each kind of join with LATERAL, APPLY, ASOF and MATCH_CONDITION, UNNEST, the table functions, the stages of Snowflake, VALUES in FROM, the time travel of each of the three dialects, PIVOT, UNPIVOT, TABLESAMPLE, SAMPLE, LATERAL VIEW, GROUP BY with ALL, ROLLUP, CUBE and GROUPING SETS, HAVING, WINDOW, QUALIFY, ORDER BY, LIMIT, OFFSET, FETCH, SORT BY, FOR UPDATE, START WITH and CONNECT BY, MATCH_RECOGNIZE, the outer join with (+), the version of a table after @, the pipe syntax with |> and the set operations with MINUS, BY NAME and CORRESPONDING. It covers INSERT with OVERWRITE, PARTITION, REPLACE WHERE and the multi-table form and OVERWRITE DIRECTORY, UPDATE, DELETE, MERGE, TRUNCATE and COPY INTO. It covers CREATE, ALTER and DROP of the tables, the views, the materialized views, the indexes, the functions and the procedures, with OR REPLACE, IF NOT EXISTS, TEMPORARY, TRANSIENT, CLONE, the types ARRAY<T>, STRUCT<...> and MAP<K, V> and the constraints. The CREATE, ALTER and DROP of any other object, such as a schema, a sequence or a stage, and the options of each object, are lists of options. It covers COMMENT ON, USE, SET, UNSET, SHOW, DESCRIBE, EXPLAIN, GRANT, REVOKE, CALL, EXECUTE IMMEDIATE, the statements of transactions, PUT, GET, UNDROP, EXPORT DATA, LOAD DATA, ASSERT, OPTIMIZE and VACUUM. It covers the scripting of the three dialects: the blocks with DECLARE and EXCEPTION, IF, CASE, LOOP, WHILE, REPEAT, FOR, the cursors and the handlers, also as the body of a procedure. The grammar needs no external scanner, so a comment does not nest. The package adds about 1.3 MB to a binary, where the package of the grammar of DerekStride/tree-sitter-sql added about 3.0 MB.

The package github.com/xo/transit/grammars/postgres/postgres holds the grammar postgres, which xo writes from the reference manual of PostgreSQL 19 (D122). It covers the lexical structure, the expressions, the types, the function calls and the full SELECT, with WITH, VALUES and TABLE. It also covers INSERT, UPDATE, DELETE, MERGE, COPY, the statements of transactions, of prepared statements and of cursors, and the utility statements, such as EXPLAIN, SET and VACUUM. It covers each statement that defines objects, such as CREATE TABLE, CREATE FUNCTION, CREATE TRIGGER, CREATE ROLE, GRANT and CREATE PUBLICATION, and each other command of the manual. docs/BACKLOG.md lists the forms that it leaves out. The variables of psql are part of the usql grammar, which gives this grammar a placeholder of the same length in place of each variable (D101).

The package github.com/xo/transit/grammars/postgres/plpgsql of the same module holds the grammar plpgsql, which xo writes from the chapter on PL/pgSQL of the same manual (D122). It reads the statements of PL/pgSQL in the body of a function or of a DO block. Each expression and each SQL statement in the body is one node, sql_expression or sql_statement, and the injection query of plpgsql gives its text to the grammar postgres. The body of a function or of a DO block in dollar quotes is the node function_body of postgres, and the injection query of postgres gives it to plpgsql or to postgres, as the LANGUAGE of the statement says.

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). docs/UPSTREAM.md says when one can be made, and docs/API.md gives each one:

  1. Parser.StatesAt gives the parse states at a byte offset, before the parser recovers from an error (D57, D70).
  2. NodeType, FieldInfo and NodeKind give node-types.json in Go, as the function NodeTypes of a grammar package returns it (D76).
  3. inject.WithReplacer replaces the text of nodes before a layer is parsed (D101).
  4. inject.Layer.Text and inject.Layer.StatesAt give the text that a layer parses and the parse states of the layer at an offset (D111).

transit does not evaluate the predicates of Neovim, and upstream does not either (docs/NEOVIM.md).

Documents

These documents are for a person who changes transit. CONTRIBUTING.md says how to change it, and AGENTS.md holds the rules for a coding agent, which also hold for a person. The folder docs/ holds the other documents:

Document What it holds
docs/PLAN.md the status of the work, 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 the maintainer 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

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. It ports lib/src of upstream, and each Go file ports one C file. 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, with an
	// encoding that the runtime does not know, or with no decode function.
	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}}

func (InputEdit) EditPoint added in v0.4.0

func (e InputEdit) EditPoint(p *Point, byteOffset *int)

EditPoint changes a point and its byte offset so that they stay at the same place in the text after the edit e. It needs no tree and no node.

EditPoint is InputEdit::edit_point of the Rust binding, with ts_point_edit.

func (InputEdit) EditRange added in v0.4.0

func (e InputEdit) EditRange(r *Range)

EditRange changes a range so that it stays at the same place in the text after the edit e. It needs no tree and no node.

EditRange is InputEdit::edit_range of the Rust binding, with ts_range_edit.

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. Only the whole named name "ERROR" finds the symbol of ERROR. The name of a symbol must have the length of name, so a name with a NUL byte finds no symbol.

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. data holds the values of a small state, and row holds the values of a large state.

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 labels of C become loops: descend is the outer loop, scan is the inner loop, and not_found is the code after the loop over the children. notFound is true where C jumps from descend to not_found.

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. It returns false when descendant is the node 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) ParseCustomEncoding added in v0.4.0

func (p *Parser) ParseCustomEncoding(ctx context.Context, in Input, decode func(b []byte) (rune, int), old *Tree) (*Tree, error)

ParseCustomEncoding parses the text that in gives, in an encoding that the runtime does not know. The parser calls decode to read each character. decode gets the text from the character to the end of the chunk, and it returns the code point and the number of bytes that the character takes. It returns -1 as the code point when the text is not valid. ParseInput holds the rest of the rules.

ParseCustomEncoding is Parser::parse_custom_encoding of the Rust binding, with ts_parser_parse and TSInputEncodingCustom.

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 with a TSInput in the encoding enc.

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) Copy added in v0.4.0

func (q *Query) Copy() *Query

Copy returns a copy of the query. A query is safe to share between goroutines without a copy. Copy is for a query that DisablePattern or DisableCapture changes apart from q.

Copy is Query::deep_clone, with ts_query_copy. Its name follows ts_query_copy, as Tree.Copy follows ts_tree_copy.

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 cursor drops the matches in progress. The sequence then gives only the captures of the matches that finished before, and it ends. 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 cursor drops the matches in progress and 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 module
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
bash module
c module
clickhouse module
cpp module
cql module
duckdb module
go module
graphql module
html module
java module
javascript module
jsdoc module
json module
mysql module
neo4j module
oracle module
php module
postgres module
python module
ruby module
rust module
sparql module
sql module
sqlite3 module
sqlserver module
surrealdb module
trino module
typescript module
usql module
ydb 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.
corpus
Package corpus reads the corpus of a grammar package, the tree-sitter.json of its module and its testdata/failing.txt.
Package corpus reads the corpus of a grammar package, the tree-sitter.json of its module and its testdata/failing.txt.
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).
Package samples holds a short code sample of each language of the command transit, one file for each language, such as go.txt (D149).
Package samples holds a short code sample of each language of the command transit, one file for each language, such as go.txt (D149).
styles module

Jump to

Keyboard shortcuts

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