Documentation
¶
Index ¶
- Constants
- func NewQuery(language *Language, source string) (*Query, *QueryError)
- func SetAllocator(newMalloc func(size uint) unsafe.Pointer, ...)
- type CaptureQuantifier
- type Decoder
- type IncludedRangesError
- type InputEdit
- type Language
- func (l *Language) AbiVersion() uint32
- func (l *Language) FieldCount() uint32
- func (l *Language) FieldIdForName(name string) uint16
- func (l *Language) FieldNameForId(id uint16) string
- func (l *Language) IdForNodeKind(kind string, named bool) uint16
- func (l *Language) LookaheadIterator(state uint16) *LookaheadIterator
- func (l *Language) Metadata() *LanguageMetadata
- func (l *Language) NextState(state uint16, id uint16) uint16
- func (l *Language) NodeKindCount() uint32
- func (l *Language) NodeKindForId(id uint16) string
- func (l *Language) NodeKindIsNamed(id uint16) bool
- func (l *Language) NodeKindIsSupertype(id uint16) bool
- func (l *Language) NodeKindIsVisible(id uint16) bool
- func (l *Language) ParseStateCount() uint32
- func (l *Language) Version() uint32deprecated
- type LanguageError
- type LanguageMetadata
- type LogType
- type Logger
- type LookaheadIterator
- func (l *LookaheadIterator) Close()
- func (l *LookaheadIterator) Iter() []uint16
- func (l *LookaheadIterator) IterNames() []string
- func (l *LookaheadIterator) Language() *Language
- func (l *LookaheadIterator) Reset(language *Language, state uint16) bool
- func (l *LookaheadIterator) ResetState(state uint16) bool
- func (l *LookaheadIterator) Symbol() uint16
- func (l *LookaheadIterator) SymbolName() string
- type Node
- func (n *Node) ByteRange() (uint, uint)
- func (n *Node) Child(i uint) *Node
- func (n *Node) ChildByFieldId(fieldId uint16) *Node
- func (n *Node) ChildByFieldName(fieldName string) *Node
- func (n *Node) ChildCount() uint
- func (n *Node) ChildWithDescendant(descendant *Node) *Node
- func (n *Node) Children(cursor *TreeCursor) []Node
- func (n *Node) ChildrenByFieldName(fieldName string, cursor *TreeCursor) []Node
- func (n *Node) DescendantCount() uint
- func (n *Node) DescendantForByteRange(start, end uint) *Node
- func (n *Node) DescendantForPointRange(start, end Point) *Node
- func (n *Node) Edit(edit *InputEdit)
- func (n *Node) EndByte() uint
- func (n *Node) EndPosition() Point
- func (n *Node) Equals(other Node) bool
- func (n *Node) FieldNameForChild(childIndex uint32) string
- func (n *Node) FieldNameForNamedChild(namedChildIndex uint32) string
- func (n *Node) FirstChildForByte(byteOffset uint) *Node
- func (n *Node) FirstNamedChildForByte(byteOffset uint) *Node
- func (n *Node) GrammarId() uint16
- func (n *Node) GrammarName() string
- func (n *Node) HasChanges() bool
- func (n *Node) HasError() bool
- func (n *Node) Id() uintptr
- func (n *Node) IsError() bool
- func (n *Node) IsExtra() bool
- func (n *Node) IsMissing() bool
- func (n *Node) IsNamed() bool
- func (n *Node) Kind() string
- func (n *Node) KindId() uint16
- func (n *Node) Language() *Language
- func (n *Node) NamedChild(i uint) *Node
- func (n *Node) NamedChildCount() uint
- func (n *Node) NamedChildren(cursor *TreeCursor) []Node
- func (n *Node) NamedDescendantForByteRange(start, end uint) *Node
- func (n *Node) NamedDescendantForPointRange(start, end Point) *Node
- func (n *Node) NextNamedSibling() *Node
- func (n *Node) NextParseState() uint16
- func (n *Node) NextSibling() *Node
- func (n *Node) Parent() *Node
- func (n *Node) ParseState() uint16
- func (n *Node) PrevNamedSibling() *Node
- func (n *Node) PrevSibling() *Node
- func (n *Node) Range() Range
- func (n *Node) StartByte() uint
- func (n *Node) StartPosition() Point
- func (n *Node) ToSexp() string
- func (n *Node) Utf16Text(source []uint16) []uint16
- func (n *Node) Utf8Text(source []byte) string
- func (n *Node) Walk() *TreeCursor
- type ParseOptions
- type ParseState
- type Parser
- func (p *Parser) CancellationFlag() *uintptrdeprecated
- func (p *Parser) Close()
- func (p *Parser) IncludedRanges() []Range
- func (p *Parser) Language() *Language
- func (p *Parser) Logger() *Logger
- func (p *Parser) Parse(text []byte, oldTree *Tree) *Tree
- func (p *Parser) ParseCtx(ctx context.Context, text []byte, oldTree *Tree) *Treedeprecated
- func (p *Parser) ParseCustomEncoding(callback func(int, Point) []byte, oldTree *Tree, options *ParseOptions, ...) *Tree
- func (p *Parser) ParseUTF16(text []uint16, oldTree *Tree) *Treedeprecated
- func (p *Parser) ParseUTF16BE(text []uint16, oldTree *Tree) *Tree
- func (p *Parser) ParseUTF16BEWith(callback func(int, Point) []uint16, oldTree *Tree) *Treedeprecated
- func (p *Parser) ParseUTF16BEWithOptions(callback func(int, Point) []uint16, oldTree *Tree, options *ParseOptions) *Tree
- func (p *Parser) ParseUTF16LE(text []uint16, oldTree *Tree) *Tree
- func (p *Parser) ParseUTF16LEWith(callback func(int, Point) []uint16, oldTree *Tree) *Treedeprecated
- func (p *Parser) ParseUTF16LEWithOptions(callback func(int, Point) []uint16, oldTree *Tree, options *ParseOptions) *Tree
- func (p *Parser) ParseUTF16With(callback func(int, Point) []uint16, oldTree *Tree) *Treedeprecated
- func (p *Parser) ParseWith(callback func(int, Point) []byte, oldTree *Tree) *Treedeprecated
- func (p *Parser) ParseWithOptions(callback func(int, Point) []byte, oldTree *Tree, options *ParseOptions) *Tree
- func (p *Parser) PrintDotGraphs(file *os.File)
- func (p *Parser) Reset()
- func (p *Parser) SetCancellationFlag(flag *uintptr)deprecated
- func (p *Parser) SetIncludedRanges(ranges []Range) error
- func (p *Parser) SetLanguage(l *Language) error
- func (p *Parser) SetLogger(logger Logger)
- func (p *Parser) SetTimeoutMicros(timeoutMicros uint64)deprecated
- func (p *Parser) StopPrintingDotGraphs()
- func (p *Parser) TimeoutMicros() uint64deprecated
- type Point
- type PropertyPredicate
- type Query
- func (q *Query) CaptureIndexForName(name string) (uint, bool)
- func (q *Query) CaptureNames() []string
- func (q *Query) CaptureQuantifiers(index uint) []CaptureQuantifier
- func (q *Query) Close()
- func (q *Query) DisableCapture(captureName string)
- func (q *Query) DisablePattern(index uint)
- func (q *Query) EndByteForPattern(index uint) uint
- func (q *Query) GeneralPredicates(index uint) []QueryPredicate
- func (q *Query) IsPatternGuaranteedAtStep(byteOffset uint) bool
- func (q *Query) IsPatternNonLocal(index uint) bool
- func (q *Query) IsPatternRooted(index uint) bool
- func (q *Query) PatternCount() uint
- func (q *Query) PropertyPredicates(index uint) []PropertyPredicate
- func (q *Query) PropertySettings(index uint) []QueryProperty
- func (q *Query) StartByteForPattern(index uint) uint
- type QueryCapture
- type QueryCaptures
- type QueryCursor
- func (qc *QueryCursor) Captures(query *Query, node *Node, text []byte) QueryCaptures
- func (qc *QueryCursor) Close()
- func (qc *QueryCursor) DidExceedMatchLimit() bool
- func (qc *QueryCursor) MatchLimit() uint
- func (qc *QueryCursor) Matches(query *Query, node *Node, text []byte) QueryMatches
- func (qc *QueryCursor) MatchesWithOptions(query *Query, node *Node, text []byte, options QueryCursorOptions) QueryMatches
- func (qc *QueryCursor) SetByteRange(startByte uint, endByte uint) *QueryCursor
- func (qc *QueryCursor) SetMatchLimit(limit uint)
- func (qc *QueryCursor) SetMaxStartDepth(depth *uint) *QueryCursor
- func (qc *QueryCursor) SetPointRange(startPoint Point, endPoint Point) *QueryCursor
- func (qc *QueryCursor) SetTimeoutMicros(timeoutMicros uint64)
- func (qc *QueryCursor) TimeoutMicros() uint64
- type QueryCursorOptions
- type QueryCursorState
- type QueryError
- type QueryErrorKind
- type QueryMatch
- type QueryMatches
- type QueryPredicate
- type QueryPredicateArg
- type QueryProperty
- type Range
- type TextPredicateCapture
- type TextPredicateType
- type Tree
- func (t *Tree) ChangedRanges(other *Tree) []Range
- func (t *Tree) Clone() *Tree
- func (t *Tree) Close()
- func (t *Tree) Edit(edit *InputEdit)
- func (t *Tree) IncludedRanges() []Range
- func (t *Tree) Language() *Language
- func (t *Tree) PrintDotGraph(file int)
- func (t *Tree) RootNode() *Node
- func (t *Tree) RootNodeWithOffset(offsetBytes int, offsetExtent Point) *Node
- func (t *Tree) Walk() *TreeCursor
- type TreeCursor
- func (tc *TreeCursor) Close()
- func (tc *TreeCursor) Copy() *TreeCursor
- func (tc *TreeCursor) Depth() uint32
- func (tc *TreeCursor) DescendantIndex() uint32
- func (tc *TreeCursor) FieldId() uint16
- func (tc *TreeCursor) FieldName() string
- func (tc *TreeCursor) GotoDescendant(descendantIndex uint32)
- func (tc *TreeCursor) GotoFirstChild() bool
- func (tc *TreeCursor) GotoFirstChildForByte(byteIndex uint32) *uint
- func (tc *TreeCursor) GotoFirstChildForPoint(point Point) *uint
- func (tc *TreeCursor) GotoLastChild() bool
- func (tc *TreeCursor) GotoNextSibling() bool
- func (tc *TreeCursor) GotoParent() bool
- func (tc *TreeCursor) GotoPreviousSibling() bool
- func (tc *TreeCursor) Node() *Node
- func (tc *TreeCursor) Reset(node Node)
- func (tc *TreeCursor) ResetTo(cursor *TreeCursor)
Examples ¶
Constants ¶
const LANGUAGE_VERSION = C.TREE_SITTER_LANGUAGE_VERSION
const MIN_COMPATIBLE_LANGUAGE_VERSION = C.TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION
Variables ¶
This section is empty.
Functions ¶
Types ¶
type CaptureQuantifier ¶
type CaptureQuantifier int
const ( CaptureQuantifierZero CaptureQuantifier = iota CaptureQuantifierZeroOrOne CaptureQuantifierZeroOrMore CaptureQuantifierOne CaptureQuantifierOneOrMore )
type Decoder ¶ added in v0.25.0
type Decoder interface { // Decode takes a byte slice and returns the decoded code point and number of bytes consumed // Returns -1 as codePoint if decoding fails Decode(data []byte) (codePoint int32, bytesRead uint32) }
Decoder interface defines the required method for custom decoding
type IncludedRangesError ¶
type IncludedRangesError struct {
Index uint32
}
An error that occurred in Parser.SetIncludedRanges.
func (*IncludedRangesError) Error ¶
func (i *IncludedRangesError) Error() string
type Language ¶
type Language struct {
Inner *C.TSLanguage
}
An opaque object that defines how to parse a particular language. The code for each Language is generated by the Tree-sitter CLI.
func NewLanguage ¶
func (*Language) AbiVersion ¶ added in v0.25.0
Get the ABI version number that indicates which version of the Tree-sitter CLI that was used to generate this Language.
func (*Language) FieldCount ¶
Get the number of distinct field names in this language.
func (*Language) FieldIdForName ¶
Get the numerical id for the given field name.
func (*Language) FieldNameForId ¶
Get the field names for the given numerical id.
func (*Language) IdForNodeKind ¶
Get the numeric id for the given node kind.
func (*Language) LookaheadIterator ¶
func (l *Language) LookaheadIterator(state uint16) *LookaheadIterator
Create a new lookahead iterator for this language and parse state.
This returns `nil` if state is invalid for this language.
Iterating LookaheadIterator will yield valid symbols in the given parse state. Newly created lookahead iterators will return the `ERROR` symbol from LookaheadIterator.Symbol.
Lookahead iterators can be useful to generate suggestions and improve syntax error diagnostics. To get symbols valid in an ERROR node, use the lookahead iterator on its first leaf node state. For `MISSING` nodes, a lookahead iterator created on the previous non-extra leaf node may be appropriate.
func (*Language) Metadata ¶ added in v0.25.0
func (l *Language) Metadata() *LanguageMetadata
Get the metadata for this language. This information is generated by the CLI, and relies on the language author providing the correct metadata in the language's `tree-sitter.json` file.
func (*Language) NextState ¶
Get the next parse state. Combine this with Language.LookaheadIterator to generate completion suggestions or valid symbols in error nodes.
func (*Language) NodeKindCount ¶
Get the number of distinct node types in this language.
func (*Language) NodeKindForId ¶
Get the name of the node kind for the given numerical id.
func (*Language) NodeKindIsNamed ¶
Check if the node type for the given numerical id is named (as opposed to an anonymous node type).
func (*Language) NodeKindIsSupertype ¶ added in v0.24.0
Check if the node type for the given numerical id is a supertype.
func (*Language) NodeKindIsVisible ¶
Check if the node type for the given numerical id is visible (as opposed to a hidden node type).
func (*Language) ParseStateCount ¶
Get the number of valid states in this language.
func (*Language) Version
deprecated
Deprecated: Use Language.AbiVersion instead.
Get the ABI version number that indicates which version of the Tree-sitter CLI that was used to generate this Language.
type LanguageError ¶
type LanguageError struct {
// contains filtered or unexported fields
}
An error that occurred when trying to assign an incompatible [TSLanguage] to a [TSParser].
func (*LanguageError) Error ¶
func (l *LanguageError) Error() string
type LanguageMetadata ¶ added in v0.25.0
The metadata associated with a language.
Currently, this metadata can be used to check the [Semantic Version](https://semver.org/) of the language. This version information should be used to signal if a given parser might be incompatible with existing queries when upgrading between major versions, or minor versions if it's in zerover.
type LookaheadIterator ¶
type LookaheadIterator struct {
// contains filtered or unexported fields
}
func (*LookaheadIterator) Close ¶
func (l *LookaheadIterator) Close()
func (*LookaheadIterator) IterNames ¶
func (l *LookaheadIterator) IterNames() []string
Iterate symbol names.
func (*LookaheadIterator) Language ¶
func (l *LookaheadIterator) Language() *Language
func (*LookaheadIterator) Reset ¶
func (l *LookaheadIterator) Reset(language *Language, state uint16) bool
Reset the lookahead iterator.
This returns `true` if the language was set successfully and `false` otherwise.
func (*LookaheadIterator) ResetState ¶
func (l *LookaheadIterator) ResetState(state uint16) bool
Reset the lookahead iterator to another state.
This returns `true` if the iterator was reset to the given state and `false` otherwise.
func (*LookaheadIterator) Symbol ¶
func (l *LookaheadIterator) Symbol() uint16
Get the current symbol of the lookahead iterator.
func (*LookaheadIterator) SymbolName ¶
func (l *LookaheadIterator) SymbolName() string
Get the current symbol name of the lookahead iterator.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
A single node within a syntax Tree. Note that this is a C-compatible struct
Example ¶
parser := NewParser() defer parser.Close() language := NewLanguage(tree_sitter_go.Language()) parser.SetLanguage(language) tree := parser.Parse( []byte(` package main func main() { return } `), nil, ) defer tree.Close() rootNode := tree.RootNode() fmt.Println(rootNode.Kind()) fmt.Println(rootNode.StartPosition()) fmt.Println(rootNode.EndPosition()) functionNode := rootNode.Child(1) fmt.Println(functionNode.Kind()) fmt.Println(functionNode.ChildByFieldName("name").Kind()) functionNameNode := functionNode.Child(1) fmt.Println(functionNameNode.StartPosition()) fmt.Println(functionNameNode.EndPosition())
Output: source_file {1 3} {7 2} function_declaration identifier {4 8} {4 12}
func (*Node) Child ¶
Get the node's child at the given index, where zero represents the first child.
This method is fairly fast, but its cost is technically log(i), so if you might be iterating over a long list of children, you should use Node.Children instead.
func (*Node) ChildByFieldId ¶
Get this node's child with the given numerical field id.
See also Node.ChildByFieldName. You can convert a field name to an id using Language.FieldIdForName.
func (*Node) ChildByFieldName ¶
Get the first child with the given field name.
If multiple children may have the same field name, access them using Node.ChildrenByFieldName
func (*Node) ChildWithDescendant ¶ added in v0.24.0
Get the node that contains `descendant`. Note that this can return `descendant` itself.
func (*Node) Children ¶
func (n *Node) Children(cursor *TreeCursor) []Node
Iterate over this node's children.
A TreeCursor is used to retrieve the children efficiently. Obtain a TreeCursor by calling Tree.Walk or Node.Walk. To avoid unnecessary allocations, you should reuse the same cursor for subsequent calls to this method.
If you're walking the tree recursively, you may want to use the TreeCursor APIs directly instead.
func (*Node) ChildrenByFieldName ¶
func (n *Node) ChildrenByFieldName(fieldName string, cursor *TreeCursor) []Node
Iterate over this node's children with a given field name.
See also Node.Children.
func (*Node) DescendantCount ¶
Get the node's number of descendants, including one for the node itself.
func (*Node) DescendantForByteRange ¶
Get the smallest node within this node that spans the given range.
func (*Node) DescendantForPointRange ¶
Get the smallest node within this node that spans the given range.
func (*Node) Edit ¶
Edit this node to keep it in-sync with source code that has been edited.
This function is only rarely needed. When you edit a syntax tree with the Tree.Edit method, all of the nodes that you retrieve from the tree afterward will already reflect the edit. You only need to use Node.Edit when you have a specific Node instance that you want to keep and continue to use after an edit.
func (*Node) EndPosition ¶
Get this node's end position in terms of rows and columns.
func (*Node) FieldNameForChild ¶
Get the field name of this node's child at the given index.
func (*Node) FieldNameForNamedChild ¶ added in v0.24.0
Get the field name of this node's named child at the given index.
func (*Node) FirstChildForByte ¶ added in v0.24.0
Get the node's first child that contains or starts after the given byte offset.
func (*Node) FirstNamedChildForByte ¶ added in v0.24.0
Get the node's first named child that contains or starts after the given byte offset.
func (*Node) GrammarId ¶
Get the node's type as a numerical id as it appears in the grammar ignoring aliases.
func (*Node) GrammarName ¶
Get this node's symbol name as it appears in the grammar ignoring aliases as a string.
func (*Node) HasError ¶
Check if this node represents a syntax error or contains any syntax errors anywhere within it.
func (*Node) Id ¶
Get a numeric id for this node that is unique.
Within a given syntax tree, no two nodes have the same id. However, if a new tree is created based on an older tree, and a node from the old tree is reused in the process, then that node will have the same id in both trees.
func (*Node) IsError ¶
Check if this node represents a syntax error.
Syntax errors represent parts of the code that could not be incorporated into a valid syntax tree.
func (*Node) IsExtra ¶
Check if this node is *extra*.
Extra nodes represent things like comments, which are not required in the grammar, but can appear anywhere.
func (*Node) IsMissing ¶
Check if this node is *missing*.
Missing nodes are inserted by the parser in order to recover from certain kinds of syntax errors.
func (*Node) IsNamed ¶
Check if this node is *named*.
Named nodes correspond to named rules in the grammar, whereas *anonymous* nodes correspond to string literals in the grammar.
func (*Node) NamedChild ¶
Get this node's *named* child at the given index.
See also Node.IsNamed. This method is fairly fast, but its cost is technically log(i), so if you might be iterating over a long list of children, you should use Node.NamedChildren instead.
func (*Node) NamedChildren ¶
func (n *Node) NamedChildren(cursor *TreeCursor) []Node
Iterate over this node's named children.
See also Node.Children.
func (*Node) NamedDescendantForByteRange ¶
Get the smallest named node within this node that spans the given range.
func (*Node) NamedDescendantForPointRange ¶
Get the smallest named node within this node that spans the given range.
func (*Node) NextNamedSibling ¶
Get this node's next named sibling.
func (*Node) NextParseState ¶
Get the parse state after this node.
func (*Node) Parent ¶
Get this node's immediate parent. Prefer Node.ChildWithDescendant for iterating over this node's ancestors.
func (*Node) PrevNamedSibling ¶
Get this node's previous named sibling.
func (*Node) Range ¶
Get the range of source code that this node represents, both in terms of raw bytes and of row/column coordinates.
func (*Node) StartPosition ¶
Get this node's start position in terms of rows and columns.
func (*Node) Walk ¶
func (n *Node) Walk() *TreeCursor
Create a new TreeCursor starting from this node.
Note that the given node is considered the root of the cursor, and the cursor cannot walk outside this node.
type ParseOptions ¶ added in v0.25.0
type ParseOptions struct { // A function that is called periodically during parsing to check // whether parsing should be cancelled. If the progress callback returns // `true`, then parsing will be cancelled. You can also use this to instrument // parsing and check where the parser is at in the document. The progress callback // takes a single argument, which is a [ParseState] representing the current // state of the parser. ProgressCallback func(ParseState) bool }
Options for parsing
The [ParseOptions.ProgressCallback] property is a function that is called periodically during parsing to check whether parsing should be cancelled.
See Parser.ParseWithOptions for more information.
type ParseState ¶ added in v0.25.0
type ParseState struct { // The byte offset in the document that the parser is at. CurrentByteOffset uint32 // Indicates whether the parser has encountered an error during parsing. HasError bool }
A stateful object that is passed into the progress callback [ParseOptions.ProgressCallback] to provide the current state of the parser.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
A stateful object that this is used to produce a Tree based on some source code.
func (*Parser) CancellationFlag
deprecated
Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.
Get the parser's current cancellation flag pointer.
func (*Parser) IncludedRanges ¶
Get the ranges of text that the parser will include when parsing.
func (*Parser) Parse ¶
Parse a slice of UTF8 text.
Arguments: ¶
- `text` The UTF8-encoded text to parse.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
Example ¶
parser := NewParser() defer parser.Close() language := NewLanguage(tree_sitter_go.Language()) parser.SetLanguage(language) tree := parser.Parse( []byte(` package main func main() { return } `), nil, ) defer tree.Close() rootNode := tree.RootNode() fmt.Println(rootNode.ToSexp())
Output: (source_file (package_clause (package_identifier)) (function_declaration name: (identifier) parameters: (parameter_list) body: (block (return_statement))))
func (*Parser) ParseCtx
deprecated
Deprecated: Use Parser.ParseWithOptions instead, and handle cancellation in the callback, this will be removed in 0.26.
Parse a slice of UTF8 text.
Arguments: ¶
- `ctx` The context to parse with.
- `text` The UTF8-encoded text to parse.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
func (*Parser) ParseCustomEncoding ¶ added in v0.25.0
func (p *Parser) ParseCustomEncoding( callback func(int, Point) []byte, oldTree *Tree, options *ParseOptions, decode unsafe.Pointer, ) *Tree
Parse text provided in chunks by a callback using a custom encoding. This is useful for parsing text in encodings that are not UTF-8 or UTF-16.
Arguments: ¶
- `callback` A function that takes a byte offset and position and returns a slice of text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using [`Tree::edit`].
- `options` Options for parsing the text. This can be used to set a progress callback.
- `decode` A function that takes a byte slice and returns the number of bytes consumed. It will also write the resulting code point to `codePoint`. If decoding fails, the function should write -1 to the code point. The signature for the function is the following: func myDecodeFn(data *C.char, length C.uint32_t, codePoint *C.int32_t) C.uint32_t Note that this function *must* be a C function, as it's called many times during parsing. To have a Go function be callable from C, you must use the `//export` directive. More info can be found at https://pkg.go.dev/cmd/cgo#hdr-C_references_to_Go. The reason for this is that knowing the function body at compile time rather than loading it at runtime is important for performance. This is also a significantly advanced feature, and should only be used if you have a good reason to do so, and understand how to implement the C function. An example of how to use this can be found in `parser_test.go`.
func (*Parser) ParseUTF16
deprecated
Deprecated: Use Parser.ParseUTF16LE or Parser.ParseUTF16BE instead. Parse a slice of UTF16 text.
Arguments: ¶
- `text` The UTF16-encoded text to parse.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
func (*Parser) ParseUTF16BE ¶ added in v0.24.0
/ Parse a slice of UTF16 big-endian text. / / # Arguments: / * `text` The UTF16-encoded text to parse. / * `old_tree` A previous syntax tree parsed from the same document. If the text of the / document has changed since `old_tree` was created, then you must edit `old_tree` to match / the new text using Tree.Edit.
func (*Parser) ParseUTF16BEWith
deprecated
added in
v0.24.0
Deprecated: Use Parser.ParseUTF16BEWithOptions instead, this will be removed in 0.26.
Parse UTF16 big-endian text provided in chunks by a callback.
Arguments: ¶
- `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
func (*Parser) ParseUTF16BEWithOptions ¶ added in v0.25.0
func (p *Parser) ParseUTF16BEWithOptions(callback func(int, Point) []uint16, oldTree *Tree, options *ParseOptions) *Tree
Parse UTF16 big-endian text provided in chunks by a callback.
Arguments: ¶
- `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
- `options` Options for parsing the text. This can be used to set a progress callback.
func (*Parser) ParseUTF16LE ¶ added in v0.24.0
/ Parse a slice of UTF16 little-endian text. / / # Arguments: / * `text` The UTF16-encoded text to parse. / * `old_tree` A previous syntax tree parsed from the same document. If the text of the / document has changed since `old_tree` was created, then you must edit `old_tree` to match / the new text using Tree.Edit.
func (*Parser) ParseUTF16LEWith
deprecated
added in
v0.24.0
Deprecated: Use Parser.ParseUTF16LEWithOptions instead, this will be removed in 0.26.
Parse UTF16 little-endian text provided in chunks by a callback.
Arguments: ¶
- `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
func (*Parser) ParseUTF16LEWithOptions ¶ added in v0.25.0
func (p *Parser) ParseUTF16LEWithOptions(callback func(int, Point) []uint16, oldTree *Tree, options *ParseOptions) *Tree
Parse UTF16 little-endian text provided in chunks by a callback.
Arguments: ¶
- `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
- `options` Options for parsing the text. This can be used to set a progress callback.
func (*Parser) ParseUTF16With
deprecated
Deprecated: Use Parser.ParseUTF16LEWith or Parser.ParseUTF16BEWith instead, this will be removed in 0.26.
Parse UTF16 text provided in chunks by a callback.
Arguments: ¶
- `callback` A function that takes a code point offset and position and returns a slice of UTF16-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
func (*Parser) ParseWith
deprecated
Deprecated: Use Parser.ParseWithOptions instead, this will be removed in 0.26.
Parse UTF8 text provided in chunks by a callback.
Arguments: ¶
- `callback` A function that takes a byte offset and position and returns a slice of UTF8-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
func (*Parser) ParseWithOptions ¶ added in v0.25.0
func (p *Parser) ParseWithOptions(callback func(int, Point) []byte, oldTree *Tree, options *ParseOptions) *Tree
Parse UTF8 text provided in chunks by a callback.
Arguments: ¶
- `callback` A function that takes a byte offset and position and returns a slice of UTF8-encoded text starting at that byte offset and position. The slices can be of any length. If the given position is at the end of the text, the callback should return an empty slice.
- `old_tree` A previous syntax tree parsed from the same document. If the text of the document has changed since `old_tree` was created, then you must edit `old_tree` to match the new text using Tree.Edit.
- `options` Options for parsing the text. This can be used to set a progress callback, or context.
Example ¶
parser := NewParser() defer parser.Close() language := NewLanguage(tree_sitter_go.Language()) parser.SetLanguage(language) sourceCode := []byte(` package main func main() { return } `) readCallback := func(offset int, position Point) []byte { return sourceCode[offset:] } tree := parser.ParseWithOptions(readCallback, nil, nil) defer tree.Close() rootNode := tree.RootNode() fmt.Println(rootNode.ToSexp())
Output: (source_file (package_clause (package_identifier)) (function_declaration name: (identifier) parameters: (parameter_list) body: (block (return_statement))))
func (*Parser) PrintDotGraphs ¶
Set the destination to which the parser should write debugging graphs during parsing. The graphs are formatted in the DOT language. You may want to pipe these graphs directly to a `dot(1)` process in order to generate SVG output.
func (*Parser) Reset ¶
func (p *Parser) Reset()
Instruct the parser to start the next parse from the beginning.
If the parser previously failed because of a timeout or a cancellation, then by default, it will resume where it left off on the next call to Parser.Parse or other parsing functions. If you don't want to resume, and instead intend to use this parser to parse some other document, you must call `Reset` first.
func (*Parser) SetCancellationFlag
deprecated
Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.
Set the parser's current cancellation flag pointer.
If a pointer is assigned, then the parser will periodically read from this pointer during parsing. If it reads a non-zero value, it will halt early, returning `nil`. See Parser.Parse for more information.
func (*Parser) SetIncludedRanges ¶
Set the ranges of text that the parser should include when parsing.
By default, the parser will always include entire documents. This function allows you to parse only a *portion* of a document but still return a syntax tree whose ranges match up with the document as a whole. You can also pass multiple disjoint ranges.
If `ranges` is empty, then the entire document will be parsed. Otherwise, the given ranges must be ordered from earliest to latest in the document, and they must not overlap. That is, the following must hold for all `i` < `length - 1`:
ranges[i].end_byte <= ranges[i + 1].start_byte
If this requirement is not satisfied, method will return IncludedRangesError error with an offset in the passed ranges slice pointing to a first incorrect range.
func (*Parser) SetLanguage ¶
Set the language that the parser should use for parsing.
Returns an error indicating whether or not the language was successfully assigned. Nil means assignment succeeded. Non-nil means there was a version mismatch: the language was generated with an incompatible version of the Tree-sitter CLI. Check the language's ABI version using Language.Version and compare it to this library's LANGUAGE_VERSION and MIN_COMPATIBLE_LANGUAGE_VERSION constants.
func (*Parser) SetTimeoutMicros
deprecated
Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.
Set the maximum duration in microseconds that parsing should be allowed to take before halting.
If parsing takes longer than this, it will halt early, returning `nil`. See Parser.Parse for more information.
func (*Parser) StopPrintingDotGraphs ¶
func (p *Parser) StopPrintingDotGraphs()
Stop the parser from printing debugging graphs while parsing.
func (*Parser) TimeoutMicros
deprecated
Deprecated: Use Parser.ParseWithOptions and pass in a callback instead, this will be removed in 0.26.
Get the duration in microseconds that parsing is allowed to take.
This is set via Parser.SetTimeoutMicros.
type Point ¶
A position in a multi-line text document, in terms of rows and columns.
Rows and columns are zero-based.
type PropertyPredicate ¶
type PropertyPredicate struct { Property QueryProperty Positive bool }
type Query ¶
type Query struct { TextPredicates [][]TextPredicateCapture // contains filtered or unexported fields }
func (*Query) CaptureIndexForName ¶
Get the index for a given capture name.
func (*Query) CaptureNames ¶
Get the names of the captures used in the query.
func (*Query) CaptureQuantifiers ¶
func (q *Query) CaptureQuantifiers(index uint) []CaptureQuantifier
Get the quantifiers of the captures used in the query.
func (*Query) DisableCapture ¶
Disable a certain capture within a query.
This prevents the capture from being returned in matches, and also avoids any resource usage associated with recording the capture.
func (*Query) DisablePattern ¶
Disable a certain pattern within a query.
This prevents the pattern from matching, and also avoids any resource usage associated with the pattern.
func (*Query) EndByteForPattern ¶
Get the byte offset where the given pattern ends in the query's source.
func (*Query) GeneralPredicates ¶
func (q *Query) GeneralPredicates(index uint) []QueryPredicate
Get the other user-defined predicates associated with the given index.
This includes predicate with operators other than: * `match?` * `eq?` and `not-eq?` * `is?` and `is-not?` * `set!`
func (*Query) IsPatternGuaranteedAtStep ¶
Check if a given step in a query is 'definite'.
A query step is 'definite' if its parent pattern will be guaranteed to match successfully once it reaches the step.
func (*Query) IsPatternNonLocal ¶
Check if a given pattern within a query has a single root node.
func (*Query) IsPatternRooted ¶
Check if a given pattern within a query has a single root node.
func (*Query) PatternCount ¶
Get the number of patterns in the query.
func (*Query) PropertyPredicates ¶
func (q *Query) PropertyPredicates(index uint) []PropertyPredicate
Get the properties that are checked for the given pattern index.
This includes predicates with the operators `is?` and `is-not?`.
func (*Query) PropertySettings ¶
func (q *Query) PropertySettings(index uint) []QueryProperty
Get the properties that are set for the given pattern index.
This includes predicates with the operator `set!`.
func (*Query) StartByteForPattern ¶
Get the byte offset where the given pattern starts in the query's source.
type QueryCapture ¶
A particular Node that has been captured with a particular name within a Query. Note that this is a C-compatible struct
type QueryCaptures ¶
type QueryCaptures struct {
// contains filtered or unexported fields
}
A sequence of [QueryCapture]s associated with a given QueryCursor.
func (*QueryCaptures) Next ¶
func (qc *QueryCaptures) Next() (*QueryMatch, uint)
Next will return the next match in the sequence of matches, as well as the index of the capture.
Subsequent calls to QueryCaptures.Next will overwrite the memory at the same location as prior matches, since the memory is reused. You can think of this as a stateful iterator. If you need to keep the data of a prior match without it being overwritten, you should copy what you need before calling QueryCaptures.Next again.
If there are no more matches, it will return nil.
func (*QueryCaptures) SetByteRange ¶
func (qc *QueryCaptures) SetByteRange(startByte uint, endByte uint)
func (*QueryCaptures) SetPointRange ¶
func (qc *QueryCaptures) SetPointRange(startPoint Point, endPoint Point)
type QueryCursor ¶
type QueryCursor struct {
// contains filtered or unexported fields
}
A stateful object for executing a Query on a syntax Tree.
func NewQueryCursor ¶
func NewQueryCursor() *QueryCursor
Create a new cursor for executing a given query.
The cursor stores the state that is needed to iteratively search for matches.
func (*QueryCursor) Captures ¶
func (qc *QueryCursor) Captures(query *Query, node *Node, text []byte) QueryCaptures
Iterate over all of the individual captures in the order that they appear.
This is useful if you don't care about which pattern matched, and just want a single, ordered sequence of captures.
Example ¶
language := NewLanguage(tree_sitter_go.Language()) parser := NewParser() defer parser.Close() parser.SetLanguage(language) sourceCode := []byte(` package main import "fmt" func main() { fmt.Println("Hello, world!") } `) tree := parser.Parse(sourceCode, nil) defer tree.Close() query, err := NewQuery( language, ` (function_declaration name: (identifier) @function.name body: (block) @function.block ) `, ) if err != nil { panic(err) } defer query.Close() qc := NewQueryCursor() defer qc.Close() captures := qc.Captures(query, tree.RootNode(), sourceCode) for match, index := captures.Next(); match != nil; match, index = captures.Next() { fmt.Printf( "Capture %d: %s\n", index, match.Captures[index].Node.Utf8Text(sourceCode), ) }
Output: Capture 0: main Capture 1: { fmt.Println("Hello, world!") }
func (*QueryCursor) Close ¶
func (qc *QueryCursor) Close()
Delete the underlying memory for a query cursor.
func (*QueryCursor) DidExceedMatchLimit ¶
func (qc *QueryCursor) DidExceedMatchLimit() bool
Check if, on its last execution, this cursor exceeded its maximum number of in-progress matches.
func (*QueryCursor) MatchLimit ¶
func (qc *QueryCursor) MatchLimit() uint
Return the maximum number of in-progress matches for this cursor.
func (*QueryCursor) Matches ¶
func (qc *QueryCursor) Matches(query *Query, node *Node, text []byte) QueryMatches
Iterate over all of the matches in the order that they were found.
Each match contains the index of the pattern that matched, and a list of captures. Because multiple patterns can match the same set of nodes, one match may contain captures that appear *before* some of the captures from a previous match.
Example ¶
language := NewLanguage(tree_sitter_go.Language()) parser := NewParser() defer parser.Close() parser.SetLanguage(language) sourceCode := []byte(` package main import "fmt" func main() { fmt.Println("Hello, world!") } `) tree := parser.Parse(sourceCode, nil) defer tree.Close() query, err := NewQuery( language, ` (function_declaration name: (identifier) @function.name body: (block) @function.block ) `, ) if err != nil { panic(err) } defer query.Close() qc := NewQueryCursor() defer qc.Close() matches := qc.Matches(query, tree.RootNode(), sourceCode) for match := matches.Next(); match != nil; match = matches.Next() { for _, capture := range match.Captures { fmt.Printf( "Match %d, Capture %d (%s): %s\n", match.PatternIndex, capture.Index, query.CaptureNames()[capture.Index], capture.Node.Utf8Text(sourceCode), ) } }
Output: Match 0, Capture 0 (function.name): main Match 0, Capture 1 (function.block): { fmt.Println("Hello, world!") }
func (*QueryCursor) MatchesWithOptions ¶ added in v0.25.0
func (qc *QueryCursor) MatchesWithOptions(query *Query, node *Node, text []byte, options QueryCursorOptions) QueryMatches
Iterate over all of the matches in the order that they were found, with options.
Each match contains the index of the pattern that matched, and a list of captures. Because multiple patterns can match the same set of nodes, one match may contain captures that appear *before* some of the captures from a previous match.
func (*QueryCursor) SetByteRange ¶
func (qc *QueryCursor) SetByteRange(startByte uint, endByte uint) *QueryCursor
Set the range of bytes in which the query will be executed.
The query cursor will return matches that intersect with the given point range. This means that a match may be returned even if some of its captures fall outside the specified range, as long as at least part of the match overlaps with the range.
For example, if a query pattern matches a node that spans a larger area than the specified range, but part of that node intersects with the range, the entire match will be returned.
This will have no effect if the start byte is greater than the end byte.
func (*QueryCursor) SetMatchLimit ¶
func (qc *QueryCursor) SetMatchLimit(limit uint)
Set the maximum number of in-progress matches for this cursor. The limit must be > 0 and <= 65536.
func (*QueryCursor) SetMaxStartDepth ¶
func (qc *QueryCursor) SetMaxStartDepth(depth *uint) *QueryCursor
Set the maximum start depth for a query cursor.
This prevents cursors from exploring children nodes at a certain depth. Note if a pattern includes many children, then they will still be checked.
The zero max start depth value can be used as a special behavior and it helps to destructure a subtree by staying on a node and using captures for interested parts. Note that the zero max start depth only limit a search depth for a pattern's root node but other nodes that are parts of the pattern may be searched at any depth what defined by the pattern structure.
Set to `nil` to remove the maximum start depth.
func (*QueryCursor) SetPointRange ¶
func (qc *QueryCursor) SetPointRange(startPoint Point, endPoint Point) *QueryCursor
Set the range of (row, column) positions in which the query will be executed.
The query cursor will return matches that intersect with the given point range. This means that a match may be returned even if some of its captures fall outside the specified range, as long as at least part of the match overlaps with the range.
For example, if a query pattern matches a node that spans a larger area than the specified range, but part of that node intersects with the range, the entire match will be returned.
This will have no effect if the start point is greater than the end point.
func (*QueryCursor) SetTimeoutMicros ¶ added in v0.24.0
func (qc *QueryCursor) SetTimeoutMicros(timeoutMicros uint64)
Set the maximum duration in microseconds that query execution should be allowed to take before halting.
If query execution takes longer than this, it will halt early, returning None.
func (*QueryCursor) TimeoutMicros ¶ added in v0.24.0
func (qc *QueryCursor) TimeoutMicros() uint64
Get the duration in microseconds that query execution is allowed to take.
This is set via QueryCursor.SetTimeoutMicros
type QueryCursorOptions ¶ added in v0.25.0
type QueryCursorOptions struct { // A function that will be called periodically during the execution of the query to check // if query execution should be cancelled. If the progress callback returns `true`, then // query execution will be canceled. You can also use this to instrument query execution // and check where the query is at in the document. The progress callback takes a single // argument, which is a [QueryCursorState] representing the current state of the query. ProgressCallback func(QueryCursorState) bool }
Options for query execution
type QueryCursorState ¶ added in v0.25.0
type QueryCursorState struct { // The byte offset in the document that the query is at. CurrentByteOffset uint32 }
A stateful object that is passed into the progress callback [QueryOptions.ProgressCallback]. to provide the current state of the query.
type QueryError ¶
type QueryError struct { Message string Row uint Column uint Offset uint Kind QueryErrorKind }
func (QueryError) Error ¶
func (e QueryError) Error() string
type QueryErrorKind ¶
type QueryErrorKind int
const ( QueryErrorSyntax QueryErrorKind = iota QueryErrorNodeType QueryErrorField QueryErrorCapture QueryErrorPredicate QueryErrorStructure QueryErrorLanguage )
type QueryMatch ¶
type QueryMatch struct { Captures []QueryCapture PatternIndex uint // contains filtered or unexported fields }
A match of a Query to a particular set of [Node]s.
func (*QueryMatch) Id ¶
func (qm *QueryMatch) Id() uint
func (*QueryMatch) NodesForCaptureIndex ¶
func (qm *QueryMatch) NodesForCaptureIndex(captureIndex uint) []Node
func (*QueryMatch) Remove ¶
func (qm *QueryMatch) Remove()
func (*QueryMatch) SatisfiesTextPredicate ¶
func (qm *QueryMatch) SatisfiesTextPredicate(query *Query, buffer1, buffer2 []byte, text []byte) bool
type QueryMatches ¶
type QueryMatches struct {
// contains filtered or unexported fields
}
A sequence of [QueryMatch]es associated with a given QueryCursor.
func (*QueryMatches) Next ¶
func (qm *QueryMatches) Next() *QueryMatch
Next will return the next match in the sequence of matches.
Subsequent calls to QueryMatches.Next will overwrite the memory at the same location as prior matches, since the memory is reused. You can think of this as a stateful iterator. If you need to keep the data of a prior match without it being overwritten, you should copy what you need before calling QueryMatches.Next again.
If there are no more matches, it will return nil.
func (*QueryMatches) SetByteRange ¶
func (qm *QueryMatches) SetByteRange(startByte uint, endByte uint)
func (*QueryMatches) SetPointRange ¶
func (qm *QueryMatches) SetPointRange(startPoint Point, endPoint Point)
type QueryPredicate ¶
type QueryPredicate struct { Operator string Args []QueryPredicateArg }
A key-value pair associated with a particular pattern in a Query.
type QueryPredicateArg ¶
type QueryProperty ¶
A key-value pair associated with a particular pattern in a Query.
func NewQueryProperty ¶
func NewQueryProperty(key string, value *string, captureId *uint) QueryProperty
type Range ¶
A range of positions in a multi-line text document, both in terms of bytes and of rows and columns.
func (*Range) FromTSRange ¶
type TextPredicateCapture ¶
type TextPredicateCapture struct { Value any Type TextPredicateType CaptureId uint Positive bool MatchAllNodes bool }
type TextPredicateType ¶
type TextPredicateType int
const ( TextPredicateTypeEqCapture TextPredicateType = iota TextPredicateTypeEqString TextPredicateTypeMatchString TextPredicateTypeAnyString )
type Tree ¶
type Tree struct {
// contains filtered or unexported fields
}
A stateful object that this is used to produce a Tree based on some source code.
Example ¶
parser := NewParser() defer parser.Close() language := NewLanguage(tree_sitter_go.Language()) parser.SetLanguage(language) source := []byte(` package main func main() { return } `) tree := parser.Parse(source, nil) defer tree.Close() // We change the return statement to `return 1` newSource := append([]byte(nil), source[:46]...) newSource = append(newSource, []byte(" 1")...) newSource = append(newSource, source[46:]...) edit := &InputEdit{ StartByte: 46, OldEndByte: 46, NewEndByte: 46 + 2, StartPosition: Point{Row: 5, Column: 9}, OldEndPosition: Point{Row: 5, Column: 9}, NewEndPosition: Point{Row: 5, Column: 9 + 2}, } tree.Edit(edit) newTree := parser.Parse(newSource, tree) defer newTree.Close() for _, changedRange := range tree.ChangedRanges(newTree) { fmt.Println("Changed range:") fmt.Printf(" Start point: %v\n", changedRange.StartPoint) fmt.Printf(" End point: %v\n", changedRange.EndPoint) fmt.Printf(" Start byte: %d\n", changedRange.StartByte) fmt.Printf(" End byte: %d\n", changedRange.EndByte) }
Output: Changed range: Start point: {5 10} End point: {5 12} Start byte: 46 End byte: 48
func (*Tree) ChangedRanges ¶
Compare this old edited syntax tree to a new syntax tree representing the same document, returning a sequence of ranges whose syntactic structure has changed.
For this to work correctly, this syntax tree must have been edited such that its ranges match up to the new tree. Generally, you'll want to call this method right after calling one of the [Parser.parse] functions. Call it on the old tree that was passed to parse, and pass the new tree that was returned from `parse`.
The returned ranges indicate areas where the hierarchical structure of syntax nodes (from root to leaf) has changed between the old and new trees. Characters outside these ranges have identical ancestor nodes in both trees.
Note that the returned ranges may be slightly larger than the exact changed areas, but Tree-sitter attempts to make them as small as possible.
func (*Tree) Edit ¶
Edit the syntax tree to keep it in sync with source code that has been edited.
You must describe the edit both in terms of byte offsets and in terms of row/column coordinates.
func (*Tree) IncludedRanges ¶
Get the included ranges that were used to parse the syntax tree.
func (*Tree) PrintDotGraph ¶
Print a graph of the tree to the given file descriptor. The graph is formatted in the DOT language. You may want to pipe this graph directly to a `dot(1)` process in order to generate SVG output.
func (*Tree) RootNodeWithOffset ¶
Get the root node of the syntax tree, but with its position shifted forward by the given offset.
func (*Tree) Walk ¶
func (t *Tree) Walk() *TreeCursor
Create a new TreeCursor starting from the root of the tree.
type TreeCursor ¶
type TreeCursor struct {
// contains filtered or unexported fields
}
A stateful object for walking a syntax Tree efficiently.
Example ¶
parser := NewParser() defer parser.Close() language := NewLanguage(tree_sitter_go.Language()) parser.SetLanguage(language) tree := parser.Parse( []byte(` package main func main() { return } `), nil, ) defer tree.Close() cursor := tree.Walk() defer cursor.Close() fmt.Println(cursor.Node().Kind()) fmt.Println(cursor.GotoFirstChild()) fmt.Println(cursor.Node().Kind()) fmt.Println(cursor.GotoFirstChild()) fmt.Println(cursor.Node().Kind()) // Returns `false` because the `package` node has no children fmt.Println(cursor.GotoFirstChild()) fmt.Println(cursor.GotoNextSibling()) fmt.Println(cursor.Node().Kind()) fmt.Println(cursor.GotoParent()) fmt.Println(cursor.Node().Kind()) fmt.Println(cursor.GotoNextSibling()) fmt.Println(cursor.GotoNextSibling()) fmt.Println(cursor.Node().Kind())
Output: source_file true package_clause true package false true package_identifier true package_clause true false function_declaration
func (*TreeCursor) Close ¶
func (tc *TreeCursor) Close()
func (*TreeCursor) Copy ¶
func (tc *TreeCursor) Copy() *TreeCursor
func (*TreeCursor) Depth ¶
func (tc *TreeCursor) Depth() uint32
Get the depth of the cursor's current node relative to the original node that the cursor was constructed with.
func (*TreeCursor) DescendantIndex ¶
func (tc *TreeCursor) DescendantIndex() uint32
Get the index of the cursor's current node out of all of the descendants of the original node that the cursor was constructed with.
func (*TreeCursor) FieldId ¶
func (tc *TreeCursor) FieldId() uint16
Get the numerical field id of this tree cursor's current node.
See also TreeCursor.FieldName.
func (*TreeCursor) FieldName ¶
func (tc *TreeCursor) FieldName() string
Get the field name of this tree cursor's current node.
func (*TreeCursor) GotoDescendant ¶
func (tc *TreeCursor) GotoDescendant(descendantIndex uint32)
Move the cursor to the node that is the nth descendant of the original node that the cursor was constructed with, where zero represents the original node itself.
func (*TreeCursor) GotoFirstChild ¶
func (tc *TreeCursor) GotoFirstChild() bool
Move this cursor to the first child of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there were no children.
func (*TreeCursor) GotoFirstChildForByte ¶
func (tc *TreeCursor) GotoFirstChildForByte(byteIndex uint32) *uint
Move this cursor to the first child of its current node that extends beyond the given byte offset.
This returns the index of the child node if one was found, and returns `nil` if no such child was found.
func (*TreeCursor) GotoFirstChildForPoint ¶
func (tc *TreeCursor) GotoFirstChildForPoint(point Point) *uint
Move this cursor to the first child of its current node that extends beyond the given byte offset.
This returns the index of the child node if one was found, and returns `nil` if no such child was found.
func (*TreeCursor) GotoLastChild ¶
func (tc *TreeCursor) GotoLastChild() bool
Move this cursor to the last child of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there were no children.
Note that this function may be slower than TreeCursor.GotoFirstChild because it needs to iterate through all the children to compute the child's position.
func (*TreeCursor) GotoNextSibling ¶
func (tc *TreeCursor) GotoNextSibling() bool
Move this cursor to the next sibling of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there was no next sibling node.
Note that the given node is considered the root of the cursor, and the cursor cannot walk outside this node.
func (*TreeCursor) GotoParent ¶
func (tc *TreeCursor) GotoParent() bool
Move this cursor to the parent of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there was no parent node (the cursor was already on the root node).
Note that the given node is considered the root of the cursor, and the cursor cannot walk outside this node.
func (*TreeCursor) GotoPreviousSibling ¶
func (tc *TreeCursor) GotoPreviousSibling() bool
Move this cursor to the previous sibling of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there was no previous sibling node.
Note, that this function may be slower than TreeCursor.GotoNextSibling due to how node positions are stored. In the worst case, this will need to iterate through all the children upto the previous sibling node to recalculate its position. Also note that the node the cursor was constructed with is considered the root of the cursor, and the cursor cannot walk outside this node.
func (*TreeCursor) Reset ¶
func (tc *TreeCursor) Reset(node Node)
Re-initialize this tree cursor to start at the original node that the cursor was constructed with.
func (*TreeCursor) ResetTo ¶
func (tc *TreeCursor) ResetTo(cursor *TreeCursor)
Re-initialize a tree cursor to the same position as another cursor.
Unlike TreeCursor.Reset, this will not lose parent information and allows reusing already created cursors.