Documentation
¶
Index ¶
- Constants
- Variables
- type CaptureQuantifier
- type FieldID
- type Input
- type InputEdit
- type InputEncoding
- type IterMode
- type Iterator
- type Language
- func (l *Language) Copy() *Language
- func (l *Language) Delete()
- func (l *Language) FieldCount() uint32
- func (l *Language) FieldID(name string) FieldID
- func (l *Language) FieldName(idx int) string
- func (l *Language) NextState(curr StateID, sym Symbol) StateID
- func (l *Language) StateCount() uint32
- func (l *Language) SymbolCount() uint32
- func (l *Language) SymbolID(name string, isNamed bool) Symbol
- func (l *Language) SymbolName(s Symbol) string
- func (l *Language) SymbolType(s Symbol) SymbolType
- func (l *Language) Version() int
- type LanguageError
- type LookaheadIterator
- func (iter *LookaheadIterator) CurrentSymbol() Symbol
- func (iter *LookaheadIterator) CurrentSymbolName() string
- func (iter *LookaheadIterator) Delete()
- func (iter *LookaheadIterator) Language() *Language
- func (iter *LookaheadIterator) Next() bool
- func (iter *LookaheadIterator) Reset(lang *Language, stateID StateID) bool
- func (iter *LookaheadIterator) ResetState(stateID StateID) bool
- type Node
- func (n Node) Child(idx uint32) Node
- func (n Node) ChildByFieldID(id FieldID) Node
- func (n Node) ChildByFieldName(name string) Node
- func (n Node) ChildContainingDescendant(d Node) Node
- func (n Node) ChildCount() uint32
- func (n Node) ChildWithDescendant(d Node) Node
- func (n Node) Content(input []byte) string
- func (n Node) DescendantCount() uint32
- func (n Node) DescendantForByteRange(start, end uint32) Node
- func (n Node) DescendantForPointRange(start, end Point) Node
- func (n Node) Edit(i InputEdit)
- func (n Node) EndByte() uint
- func (n Node) EndPoint() Point
- func (n Node) Equal(other Node) bool
- func (n Node) FieldNameForChild(idx int) string
- func (n Node) FieldNameForNamedChild(idx uint32) string
- func (n Node) FirstChildForByte(ofs uint32) Node
- func (n Node) FirstNamedChildForByte(ofs uint32) Node
- func (n Node) GrammarSymbol() Symbol
- func (n Node) GrammarType() string
- func (n Node) HasChanges() bool
- func (n Node) HasError() bool
- func (n Node) IsError() bool
- func (n Node) IsExtra() bool
- func (n Node) IsMissing() bool
- func (n Node) IsNamed() bool
- func (n Node) IsNull() bool
- func (n Node) Language() *Language
- func (n Node) NamedChild(idx uint32) Node
- func (n Node) NamedChildCount() uint32
- func (n Node) NamedDescendantForByteRange(start, end uint32) Node
- func (n Node) NamedDescendantForPointRange(start, end Point) Node
- func (n Node) NextNamedSibling() Node
- func (n Node) NextParseState() StateID
- func (n Node) NextSibling() Node
- func (n Node) Parent() Node
- func (n Node) ParseState() StateID
- func (n Node) PrevNamedSibling() Node
- func (n Node) PrevSibling() Node
- func (n Node) Range() Range
- func (n Node) StartByte() uint
- func (n Node) StartPoint() Point
- func (n Node) String() string
- func (n Node) Symbol() Symbol
- func (n Node) Type() string
- type Parser
- func (p *Parser) CancellationFlag() *uint64
- func (p *Parser) Debug()
- func (p *Parser) IncludedRanges() (out []Range)
- func (p *Parser) Language() (_ *Language)
- func (p *Parser) Logger() C.TSLogger
- func (p *Parser) Parse(ctx context.Context, oldTree *Tree, input Input) (*Tree, error)
- func (p *Parser) ParseString(ctx context.Context, oldTree *Tree, content []byte, opts ...InputEncoding) (*Tree, error)
- func (p *Parser) PrintDotGraphs(name string) (err error)
- func (p *Parser) Reset()
- func (p *Parser) SetCancellationFlag(flag *uint64)
- func (p *Parser) SetIncludedRanges(ranges []Range) bool
- func (p *Parser) SetLanguage(lang *Language) bool
- func (p *Parser) SetLogger(logger C.TSLogger)
- func (p *Parser) SetTimeoutMicros(limit int)
- func (p *Parser) TimeoutMicros() int
- type Point
- type Predicator
- type PropertyPredicate
- type Query
- func (q *Query) CaptureCount() uint32
- func (q *Query) CaptureIndexForName(name string) (i int, ok bool)
- func (q *Query) CaptureNameForID(id uint32) string
- func (q *Query) CaptureNames() []string
- func (q *Query) CaptureQuantifierForID(id, captureID uint32) C.TSQuantifier
- func (q *Query) CaptureQuantifiers(index uint) []CaptureQuantifier
- func (q *Query) DisableCapture(name string)
- func (q *Query) DisablePattern(patIdx uint32)
- func (q *Query) EndByteForPattern(i int) uint32
- func (q *Query) GeneralPredicates(index uint) []QueryPredicate
- func (q *Query) IsPatternGuaranteedAtStep(byteOfs uint32) bool
- func (q *Query) IsPatternNonLocal(patIdx uint32) bool
- func (q *Query) IsPatternRooted(patIdx uint32) bool
- func (q *Query) PatternCount() uint32
- func (q *Query) PredicatesForPattern(patternIndex uint32) []QueryPredicateSteps
- func (q *Query) PropertyPredicates(index uint) []PropertyPredicate
- func (q *Query) PropertySettings(index uint) []QueryProperty
- func (q *Query) StartByteForPattern(i int) uint32
- func (q *Query) StringCount() uint32
- func (q *Query) StringValueForID(id uint32) string
- type QueryCapture
- type QueryCaptures
- type QueryCursor
- func (qc *QueryCursor) Captures(q *Query, n Node, text []byte) QueryCaptures
- func (c *QueryCursor) DidExceedMatchLimit() bool
- func (c *QueryCursor) MatchLimit() uint32
- func (qc *QueryCursor) Matches(q *Query, n Node, text []byte) (qm QueryMatches)
- func (c *QueryCursor) NextCapture() (_ *QueryMatch, i uint)
- func (c *QueryCursor) NextMatch() (_ *QueryMatch)
- func (c *QueryCursor) RemoveMatch(matchID uint)
- func (c *QueryCursor) SetByteRange(start, end uint32)
- func (c *QueryCursor) SetMatchLimit(limit uint32)
- func (c *QueryCursor) SetMaxStartDepth(maxStartDepth uint32)
- func (c *QueryCursor) SetPointRange(start, end Point)
- func (c *QueryCursor) SetTimeout(micros int)
- func (c *QueryCursor) Timeout() (micros int)
- type QueryError
- type QueryErrorKind
- type QueryMatch
- type QueryMatches
- type QueryPredicate
- type QueryPredicateArg
- type QueryPredicateStep
- type QueryPredicateStepType
- type QueryPredicateSteps
- type QueryProperty
- type Range
- type ReadFunc
- type StateID
- type Symbol
- type SymbolType
- type TextPredicateCapture
- type TextPredicateType
- type Tree
- func (t *Tree) Close()
- func (t *Tree) Copy() *Tree
- func (t *Tree) Edit(i InputEdit)
- func (t *Tree) GetChangedRanges(other *Tree) []Range
- func (t *Tree) IncludedRanges() []Range
- func (t *Tree) Language() *Language
- func (t *Tree) PrintDotGraph(name string) (err error)
- func (t *Tree) RootNode() Node
- func (t *Tree) RootNodeWithOffset(ofs uint32, extent Point) Node
- type TreeCursor
- func (c *TreeCursor) Copy() *TreeCursor
- func (c *TreeCursor) CurrentDepth() uint32
- func (c *TreeCursor) CurrentDescendantIndex() uint32
- func (c *TreeCursor) CurrentFieldID() FieldID
- func (c *TreeCursor) CurrentFieldName() string
- func (c *TreeCursor) CurrentNode() Node
- func (c *TreeCursor) GoToFirstChild() bool
- func (c *TreeCursor) GoToFirstChildForByte(b uint32) int64
- func (c *TreeCursor) GoToFirstChildForPoint(p Point) int64
- func (c *TreeCursor) GoToNextSibling() bool
- func (c *TreeCursor) GoToParent() bool
- func (c *TreeCursor) GotoDescendant(goalDescendantIndex uint32)
- func (c *TreeCursor) GotoLastChild() bool
- func (c *TreeCursor) GotoPreviousSibling() bool
- func (c *TreeCursor) Reset(n Node)
- func (c *TreeCursor) ResetTo(src *TreeCursor)
Constants ¶
const ( InputEncodingUTF8 = C.TSInputEncodingUTF8 InputEncodingUTF16 = C.TSInputEncodingUTF16 )
Input encoding types.
const ( QuantifierZero = C.TSQuantifierZero QuantifierZeroOrOne = C.TSQuantifierZeroOrOne QuantifierZeroOrMore = C.TSQuantifierZeroOrMore QuantifierOne = C.TSQuantifierOne QuantifierOneOrMore = C.TSQuantifierOneOrMore )
Possible quantifiers.
const ( TREE_SITTER_LANGUAGE_VERSION = int(C.TREE_SITTER_LANGUAGE_VERSION) TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION = int(C.TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION) )
const (
// UnlimitedMaxDepth is used for turning off max depth limit for query cursor.
UnlimitedMaxDepth = maxUint32
)
Variables ¶
var ( ErrOperationLimit = errors.New("operation limit was hit") ErrNoLanguage = errors.New("cannot parse without language") )
Possible error types.
var ( ErrPredicateBase = errors.New("predicate error") ErrPredicateArgsWrongCount = fmt.Errorf("%w: wrong arguments #", ErrPredicateBase) ErrPredicateInvalidArg = fmt.Errorf("%w: invalid argument", ErrPredicateBase) ErrPredicateWrongStart = fmt.Errorf("%w: must begin with a literal value", ErrPredicateBase) ErrPredicateWrongType = fmt.Errorf("%w: invalid type", ErrPredicateBase) ErrPredicateRegex = fmt.Errorf("%w: invalid regex", ErrPredicateBase) ErrPredicateFnBase = errors.New("predicate fn error") ErrPredicateFnWrongRet = fmt.Errorf("%w: invalid return type", ErrPredicateFnBase) ErrPredicateFnMissing = fmt.Errorf("%w: none registered", ErrPredicateFnBase) )
Query related errors.
Functions ¶
This section is empty.
Types ¶
type CaptureQuantifier ¶ added in v1.9.0
type CaptureQuantifier = C.TSQuantifier
const ( CaptureQuantifierZero CaptureQuantifier = C.TSQuantifierZero CaptureQuantifierZeroOrOne CaptureQuantifier = C.TSQuantifierZeroOrOne CaptureQuantifierZeroOrMore CaptureQuantifier = C.TSQuantifierZeroOrMore CaptureQuantifierOne CaptureQuantifier = C.TSQuantifierOne CaptureQuantifierOneOrMore CaptureQuantifier = C.TSQuantifierOneOrMore )
type Input ¶
type Input struct {
// Payload an arbitrary pointer that will be passed to each invocation
// of the Read function. NOTE: I do see it passed into ts_parser_parse()
// however I don't see it used. Just keeping it here for documenting purposes.
Payload unsafe.Pointer
// Read is a function to retrieve a chunk of text at a given byte offset
// and (row, column) position. The function should return a pointer to the
// text and write its length to the [`bytes_read`] pointer. The parser does
// not take ownership of this buffer; it just borrows it until it has
// finished reading it. The function should write a zero value to the
// [`bytes_read`] pointer to indicate the end of the document.
Read ReadFunc
// Encoding is an indication of how the text is encoded.
// Either `TSInputEncodingUTF8` or `TSInputEncodingUTF16`.
Encoding InputEncoding
}
Input type lets you specify how to read the text.
type InputEdit ¶ added in v1.3.3
type InputEdit struct {
StartIndex uint
OldEndIndex uint
NewEndIndex uint
StartPoint Point
OldEndPoint Point
NewEndPoint Point
}
InputEdit represents one edit in the input.
type InputEncoding ¶
type InputEncoding = C.TSInputEncoding
InputEncoding indicates the encoding of the text to parse.
type Iterator ¶
type Iterator struct {
// contains filtered or unexported fields
}
Iterator for a tree of nodes.
func NewIterator ¶
NewIterator takes a node and mode (DFS/BFS) and returns iterator over children of the node.
type Language ¶
type Language struct {
// contains filtered or unexported fields
}
Language defines how to parse a particular programming language.
func NewLanguage ¶
NewLanguage initializes a new language from the provided pointer.
func (*Language) Delete ¶ added in v1.3.2
func (l *Language) Delete()
Delete frees any dynamically-allocated resources for this language, if this is the last reference.
func (*Language) FieldCount ¶ added in v1.3.2
FieldCount returns the number of distinct field names in the language.
func (*Language) FieldID ¶ added in v1.3.2
FieldID returns the numerical id for the given field name string.
func (*Language) NextState ¶ added in v1.3.2
NextState returns the next parse state. Combine this with lookahead iterators to generate completion suggestions or valid symbols in error nodes. Use `ts_node_grammar_symbol` for valid symbols.
func (*Language) StateCount ¶ added in v1.3.2
StateCount returns the number of valid states in the language.
func (*Language) SymbolCount ¶
SymbolCount returns the number of distinct field names in the language.
func (*Language) SymbolID ¶ added in v1.3.2
SymbolID returns the numerical id for the given node type string.
func (*Language) SymbolName ¶
SymbolName returns a node type string for the given Symbol.
func (*Language) SymbolType ¶
func (l *Language) SymbolType(s Symbol) SymbolType
SymbolType returns named, anonymous, or a hidden type for a Symbol.
type LanguageError ¶ added in v1.9.0
type LanguageError int
LanguageError represents an error that occurred when trying to assign an incompatible [TSLanguage] to a [TSParser].
func (LanguageError) Error ¶ added in v1.9.0
func (e LanguageError) Error() string
type LookaheadIterator ¶ added in v1.5.0
type LookaheadIterator struct {
// contains filtered or unexported fields
}
LookaheadIterator holds the pointer to the corresponding C struct.
func NewLookaheadIterator ¶ added in v1.5.0
func NewLookaheadIterator(lang *Language, stateID StateID) *LookaheadIterator
NewLookaheadIterator creates a new lookahead iterator for the given language and parse state.
This returns `NULL` if state is invalid for the language.
Repeatedly using `ts_lookahead_iterator_next` and `ts_lookahead_iterator_current_symbol` will generate valid symbols in the given parse state. Newly created lookahead iterators will contain the `ERROR` symbol.
Lookahead iterators can be useful to generate suggestions and improve syntax error diagnostics. To get symbols valid in an ERROR node, use the lookahead iterator on its first leaf node state. For `MISSING` nodes, a lookahead iterator created on the previous non-extra leaf node may be appropriate.
func (*LookaheadIterator) CurrentSymbol ¶ added in v1.5.0
func (iter *LookaheadIterator) CurrentSymbol() Symbol
CurrentSymbol returns the current symbol of the lookahead iterator.
func (*LookaheadIterator) CurrentSymbolName ¶ added in v1.5.0
func (iter *LookaheadIterator) CurrentSymbolName() string
CurrentSymbolName returns the current symbol type of the lookahead iterator as a null terminated string.
func (*LookaheadIterator) Delete ¶ added in v1.5.0
func (iter *LookaheadIterator) Delete()
Delete deletes a lookahead iterator freeing all the memory used.
func (*LookaheadIterator) Language ¶ added in v1.5.0
func (iter *LookaheadIterator) Language() *Language
Language returns the current language of the lookahead iterator.
func (*LookaheadIterator) Next ¶ added in v1.5.0
func (iter *LookaheadIterator) Next() bool
Next advances the lookahead iterator to the next symbol.
This returns `true` if there is a new symbol and `false` otherwise.
func (*LookaheadIterator) Reset ¶ added in v1.5.0
func (iter *LookaheadIterator) Reset(lang *Language, stateID StateID) bool
Reset resets the lookahead iterator.
This returns `true` if the language was set successfully and `false` otherwise.
func (*LookaheadIterator) ResetState ¶ added in v1.5.0
func (iter *LookaheadIterator) ResetState(stateID StateID) bool
ResetState resets the lookahead iterator to another state.
This returns `true` if the iterator was reset to the given state and `false` otherwise.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node represents a single node in the syntax tree It tracks its start and end positions in the source code, as well as its relation to other nodes like its parent, siblings and children.
func (Node) Child ¶
Child returns the node's child at the given index, where zero represents the first child.
func (Node) ChildByFieldID ¶ added in v1.3.3
ChildByFieldID returns the node's child with the given numerical field id.
You can convert a field name to an id using the `ts_language_field_id_for_name` function.
func (Node) ChildByFieldName ¶
ChildByFieldName returns the node's child with the given field name.
func (Node) ChildContainingDescendant ¶ added in v1.3.0
ChildContainingDescendant returns the node's child that contains `descendant`. Deprecated: use [`ts_node_contains_descendant`] instead, this will be removed in 0.25
Get the node's child containing `descendant`. This will not return the descendant if it is a direct child of `self`, for that use `ts_node_contains_descendant`.
func (Node) ChildCount ¶
ChildCount returns the node's number of children.
func (Node) ChildWithDescendant ¶ added in v1.7.0
ChildWithDescendant returns the node that contains `descendant`.
NOTE: that this can return `descendant` itself, unlike the deprecated function [`ts_node_child_containing_descendant`].
func (Node) DescendantCount ¶ added in v1.3.3
DescendantCount returns the node's number of descendants, including one for the node itself.
func (Node) DescendantForByteRange ¶ added in v1.3.3
DescendantForByteRange returns the smallest node within this node that spans the given range of bytes.
func (Node) DescendantForPointRange ¶ added in v1.3.3
DescendantForPointRange returns the smallest node within this node that spans the given range of {row, column} positions.
func (Node) Edit ¶
Edit the node to keep it in-sync with source code that has been edited.
This function is only rarely needed. When you edit a syntax tree with the `ts_tree_edit` function, all of the nodes that you retrieve from the tree afterward will already reflect the edit. You only need to use `ts_node_edit` when you have a `TSNode` instance that you want to keep and continue to use after an edit.
func (Node) FieldNameForChild ¶
FieldNameForChild returns the field name of the child at the given index, or "" if not named.
func (Node) FieldNameForNamedChild ¶ added in v1.7.0
FieldNameForNamedChild returns the field name for node's named child at the given index, where zero represents the first named child. Returns NULL, if no field is found.
func (Node) FirstChildForByte ¶ added in v1.3.3
FirstChildForByte returns the node's first child that extends beyond the given byte offset.
func (Node) FirstNamedChildForByte ¶ added in v1.3.3
FirstNamedChildForByte returns the node's first named child that extends beyond the given byte offset.
func (Node) GrammarSymbol ¶ added in v1.3.2
GrammarSymbol returns the node's symbol as it appears in the grammar, ignoring aliases. This should be used in `ts_language_next_state` instead of `ts_node_symbol`.
func (Node) GrammarType ¶ added in v1.3.2
GrammarType returns the node's type as it appears in the grammar, ignoring aliases.
func (Node) HasChanges ¶
HasChanges checks if a syntax node has been edited.
func (Node) IsError ¶
IsError checks if the node is a syntax error.
Syntax errors represent parts of the code that could not be incorporated into a valid syntax tree.
func (Node) IsExtra ¶
IsExtra checks if the node is *extra*.
Extra nodes represent things like comments, which are not required the grammar, but can appear anywhere.
func (Node) IsMissing ¶
IsMissing checks if the node is *missing*.
Missing nodes are inserted by the parser in order to recover from certain kinds of syntax errors.
func (Node) IsNamed ¶
IsNamed checks if the node is *named*.
Named nodes correspond to named rules in the grammar, whereas *anonymous* nodes correspond to string literals in the grammar.
func (Node) IsNull ¶
IsNull checks if the node is null.
Functions like `ts_node_child` and `ts_node_next_sibling` will return a null node to indicate that no such node was found.
func (Node) NamedChild ¶
NamedChild returns the node's *named* child at the given index.
See also `ts_node_is_named`.
func (Node) NamedChildCount ¶
NamedChildCount returns the node's number of *named* children.
See also `ts_node_is_named`.
func (Node) NamedDescendantForByteRange ¶ added in v1.3.0
NamedDescendantForByteRange returns the smallest named node within this node that spans the given range of bytes.
func (Node) NamedDescendantForPointRange ¶
NamedDescendantForPointRange returns the smallest named node within this node that spans the given range of row/column positions.
func (Node) NextNamedSibling ¶
NextNamedSibling returns the node's next *named* sibling.
func (Node) NextParseState ¶ added in v1.3.3
NextParseState returns the parse state after this node.
func (Node) NextSibling ¶
NextSibling returns the node's next sibling.
func (Node) Parent ¶
Parent returns the node's immediate parent.
Prefer `ts_node_child_containing_descendant` for iterating over the node's ancestors.
func (Node) ParseState ¶ added in v1.3.3
ParseState returns this node's parse state.
func (Node) PrevNamedSibling ¶
PrevNamedSibling returns the node's previous *named* sibling.
func (Node) PrevSibling ¶
PrevSibling returns the node's previous sibling.
func (Node) StartPoint ¶
StartPoint returns the node's start position in terms of rows and columns.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser produces concrete syntax tree based on source code using Language.
func (*Parser) CancellationFlag ¶ added in v1.3.3
CancellationFlag returns the parser's current cancellation flag pointer.
func (*Parser) IncludedRanges ¶ added in v1.3.2
IncludedRanges returns the ranges of text that the parser will include when parsing.
The returned pointer is owned by the parser. The caller should not free it or write to it.
func (*Parser) Parse ¶
Parse produces new Tree by reading from a callback defined in input it is useful if your data is stored in specialized data structure as it will avoid copying the data into []bytes and faster access to edited part of the data.
If you are parsing this document for the first time, pass `NULL` for the `old_tree` parameter. Otherwise, if you have already parsed an earlier version of this document and the document has since been edited, pass the previous syntax tree so that the unchanged parts of it can be reused. This will save time and memory. For this to work correctly, you must have already edited the old syntax tree using the [`ts_tree_edit`] function in a way that exactly matches the source code changes.
See Input for details about it.
This function returns a syntax tree on success, and `NULL` on failure. There are three possible reasons for failure:
- The parser does not have a language assigned. Check for this using the [`ts_parser_language`] function.
- Parsing was cancelled due to a timeout that was set by an earlier call to the [`ts_parser_set_timeout_micros`] function. You can resume parsing from where the parser left out by calling [`ts_parser_parse`] again with the same arguments. Or you can start parsing from scratch by first calling [`ts_parser_reset`].
- Parsing was cancelled using a cancellation flag that was set by an earlier call to [`ts_parser_set_cancellation_flag`]. You can resume parsing from where the parser left out by calling [`ts_parser_parse`] again with the same arguments.
func (*Parser) ParseString ¶ added in v1.3.3
func (p *Parser) ParseString(ctx context.Context, oldTree *Tree, content []byte, opts ...InputEncoding) (*Tree, error)
ParseString produces new Tree from content (optionally using old tree).
Uses the parser to parse some source code stored in one contiguous buffer. If the optional encoding is passed, it will be used for parsing. See `Parse()` for further details, as the behavior virtually the same.
func (*Parser) PrintDotGraphs ¶ added in v1.3.3
PrintDotGraphs can be used to write debugging graphs during parsing.
The graphs are formatted in the DOT language. You may want to pipe these graphs directly to a `dot(1)` process in order to generate SVG output. You can turn off this logging by passing a negative number.
func (*Parser) Reset ¶
func (p *Parser) Reset()
Reset instructs the parser to start the next parse from the beginning.
If the parser previously failed because of a timeout or a cancellation, then by default, it will resume where it left off on the next call to `ts_parser_parse` or other parsing functions. If you don't want to resume, and instead intend to use this parser to parse some other document, you must call `ts_parser_reset` first.
func (*Parser) SetCancellationFlag ¶ added in v1.3.3
SetCancellationFlag sets the parser's current cancellation flag pointer.
If a non-null pointer is assigned, then the parser will periodically read from this pointer during parsing. If it reads a non-zero value, it will halt early, returning NULL. See [`ts_parser_parse`] for more information.
func (*Parser) SetIncludedRanges ¶
SetIncludedRanges sets the ranges of text that the parser should include when parsing.
By default, the parser will always include entire documents. This function allows you to parse only a *portion* of a document but still return a syntax tree whose ranges match up with the document as a whole. You can also pass multiple disjoint ranges.
The second and third parameters specify the location and length of an array of ranges. The parser does *not* take ownership of these ranges; it copies the data, so it doesn't matter how these ranges are allocated.
If `count` is zero, then the entire document will be parsed. Otherwise, the given ranges must be ordered from earliest to latest in the document, and they must not overlap. That is, the following must hold for all:
`i < count - 1`: `ranges[i].end_byte <= ranges[i + 1].start_byte`
If this requirement is not satisfied, the operation will fail, the ranges will not be assigned, and this function will return `false`. On success, this function returns `true`.
func (*Parser) SetLanguage ¶
SetLanguage sets the language that the parser should use for parsing.
Returns a boolean indicating whether or not the language was successfully assigned. True means assignment succeeded. False means there was a version mismatch: the language was generated with an incompatible version of the Tree-sitter CLI. Check the language's version using `ts_language_version` and compare it to this library's `TREE_SITTER_LANGUAGE_VERSION` and `TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION` constants.
func (*Parser) SetLogger ¶ added in v1.3.5
SetLogger sets the logger that a parser should use during parsing.
The parser does not take ownership over the logger payload. If a logger was previously assigned, the caller is responsible for releasing any memory owned by the previous logger.
func (*Parser) SetTimeoutMicros ¶ added in v1.3.2
SetTimeoutMicros limits the maximum duration in microseconds that parsing should be allowed to take before halting.
If parsing takes longer than this, it will halt early, returning NULL. See `ts_parser_parse` for more information.
func (*Parser) TimeoutMicros ¶ added in v1.3.2
TimeoutMicros returns the duration in microseconds that parsing is allowed to take.
type Predicator ¶ added in v1.9.0
type PropertyPredicate ¶ added in v1.9.0
type PropertyPredicate struct {
Property QueryProperty
Positive bool
}
type Query ¶
type Query struct {
TextPredicates [][]TextPredicateCapture
// contains filtered or unexported fields
}
Query is a tree query, compiled from a string of S-expressions. The query itself is immutable. The mutable state used in the process of executing the query is stored in a `TSQueryCursor`.
func NewQuery ¶
NewQuery creates a new query from a string containing one or more S-expression patterns. The query is associated with a particular language, and can only be run on syntax nodes parsed with that language.
If all of the given patterns are valid, this returns a `TSQuery`. If a pattern is invalid, it returns an error which provides two pieces of information about the problem:
- The byte offset of the error is written to the `error_offset` parameter.
- The type of error is written to the `error_type` parameter.
func (*Query) CaptureCount ¶
CaptureCount returns the number of captures in the query.
func (*Query) CaptureIndexForName ¶ added in v1.9.0
CaptureIndexForName returns the index for a given capture name.
func (*Query) CaptureNameForID ¶ added in v1.3.0
CaptureNameForID returns the name and length of one of the query's captures, or one of the query's string literals. Each capture and string is associated with a numeric id based on the order that it appeared in the query's source.
func (*Query) CaptureNames ¶ added in v1.9.0
CaptureNames returns the names of the captures used in the query.
func (*Query) CaptureQuantifierForID ¶ added in v1.3.0
func (q *Query) CaptureQuantifierForID(id, captureID uint32) C.TSQuantifier
CaptureQuantifierForID returns the quantifier of the query's captures. Each capture is associated with a numeric id based on the order that it appeared in the query's source.
func (*Query) CaptureQuantifiers ¶ added in v1.9.0
func (q *Query) CaptureQuantifiers(index uint) []CaptureQuantifier
CaptureQuantifiers returns the quantifiers of the captures used in the query.
func (*Query) DisableCapture ¶ added in v1.3.3
DisableCapture disables a certain capture within a query.
This prevents the capture from being returned in matches, and also avoids any resource usage associated with recording the capture. Currently, there is no way to undo this.
func (*Query) DisablePattern ¶ added in v1.3.3
DisablePattern disables a certain pattern within a query.
This prevents the pattern from matching and removes most of the overhead associated with the pattern. Currently, there is no way to undo this.
func (*Query) EndByteForPattern ¶ added in v1.6.0
EndByteForPattern returns the byte offset where the given pattern ends in the query's source.
This can be useful when combining queries by concatenating their source code strings.
func (*Query) GeneralPredicates ¶ added in v1.9.0
func (q *Query) GeneralPredicates(index uint) []QueryPredicate
GeneralPredicates returns the other user-defined predicates associated with the given index.
This includes predicate with operators other than: * `match?` * `eq?` and `not-eq?` * `is?` and `is-not?` * `set!`
func (*Query) IsPatternGuaranteedAtStep ¶ added in v1.3.3
IsPatternGuaranteedAtStep checks if a given pattern is guaranteed to match once a given step is reached. The step is specified by its byte offset in the query's source code.
func (*Query) IsPatternNonLocal ¶ added in v1.3.3
IsPatternNonLocal checks if the given pattern in the query is 'non local'.
A non-local pattern has multiple root nodes and can match within a repeating sequence of nodes, as specified by the grammar. Non-local patterns disable certain optimizations that would otherwise be possible when executing a query on a specific range of a syntax tree.
func (*Query) IsPatternRooted ¶ added in v1.3.3
IsPatternRooted checks if the given pattern in the query has a single root node.
func (*Query) PatternCount ¶
PatternCount returns the number of patterns in the query.
func (*Query) PredicatesForPattern ¶
func (q *Query) PredicatesForPattern(patternIndex uint32) []QueryPredicateSteps
PredicatesForPattern returns all of the predicates for the given pattern in the query.
The predicates are represented as a single array of steps. There are three types of steps in this array, which correspond to the three legal values for the `type` field:
- `TSQueryPredicateStepTypeCapture` - Steps with this type represent names of captures. Their `value_id` can be used with the `ts_query_capture_name_for_id` function to obtain the name of the capture.
- `TSQueryPredicateStepTypeString` - Steps with this type represent literal strings. Their `value_id` can be used with the `ts_query_string_value_for_id` function to obtain their string value.
- `TSQueryPredicateStepTypeDone` - Steps with this type are *sentinels* that represent the end of an individual predicate. If a pattern has two predicates, then there will be two steps with this `type` in the array.
func (*Query) PropertyPredicates ¶ added in v1.9.0
func (q *Query) PropertyPredicates(index uint) []PropertyPredicate
PropertyPredicates returns the properties that are checked for the given pattern index.
This includes predicates with the operators `is?` and `is-not?`.
func (*Query) PropertySettings ¶ added in v1.9.0
func (q *Query) PropertySettings(index uint) []QueryProperty
PropertySettings returns the properties that are set for the given pattern index.
This includes predicates with the operator `set!`.
func (*Query) StartByteForPattern ¶ added in v1.3.3
StartByteForPattern returns the byte offset where the given pattern starts in the query's source.
This can be useful when combining queries by concatenating their source code strings.
func (*Query) StringCount ¶
StringCount returns the number of string literals in the query.
func (*Query) StringValueForID ¶ added in v1.3.0
StringValueForID returns the string value associated with the given query id.
type QueryCapture ¶
QueryCapture is a captured node by a query with an index.
type QueryCaptures ¶ added in v1.9.0
type QueryCaptures struct {
// contains filtered or unexported fields
}
QueryCaptures holds a sequence of [QueryCapture]s associated with a given QueryCursor.
func (*QueryCaptures) Next ¶ added in v1.9.0
func (qc *QueryCaptures) Next() (m *QueryMatch, index uint)
Next will return the next match in the sequence of matches, as well as the index of the capture.
Subsequent calls to QueryCaptures.Next will overwrite the memory at the same location as prior matches, since the memory is reused. You can think of this as a stateful iterator. If you need to keep the data of a prior match without it being overwritten, you should copy what you need before calling QueryCaptures.Next again.
If there are no more matches, it will return nil.
type QueryCursor ¶
type QueryCursor struct {
// contains filtered or unexported fields
}
QueryCursor is a stateful struct used to execute a query on a tree.
func NewQueryCursor ¶
func NewQueryCursor() (qc *QueryCursor)
NewQueryCursor creates a new query cursor.
The cursor stores the state that is needed to iteratively search for matches. To use the query cursor, first call `ts_query_cursor_exec` to start running a given query on a given syntax node. Then, there are two options for consuming the results of the query:
- Repeatedly call `ts_query_cursor_next_match` to iterate over all of the *matches* in the order that they were found. Each match contains the index of the pattern that matched, and an array of captures. Because multiple patterns can match the same set of nodes, one match may contain captures that appear *before* some of the captures from a previous match.
- Repeatedly call `ts_query_cursor_next_capture` to iterate over all of the individual *captures* in the order that they appear. This is useful if don't care about which pattern matched, and just want a single ordered sequence of captures.
If you don't care about consuming all of the results, you can stop calling `ts_query_cursor_next_match` or `ts_query_cursor_next_capture` at any point.
You can then start executing another query on another node by calling `ts_query_cursor_exec` again.
func (*QueryCursor) Captures ¶ added in v1.9.0
func (qc *QueryCursor) Captures(q *Query, n Node, text []byte) QueryCaptures
Captures iterates over all of the individual captures in the order that they appear.
This is useful if you don't care about which pattern matched, and just want a single, ordered sequence of captures.
func (*QueryCursor) DidExceedMatchLimit ¶ added in v1.3.3
func (c *QueryCursor) DidExceedMatchLimit() bool
DidExceedMatchLimit see above.
func (*QueryCursor) MatchLimit ¶ added in v1.3.3
func (c *QueryCursor) MatchLimit() uint32
MatchLimit see above.
func (*QueryCursor) Matches ¶ added in v1.9.0
func (qc *QueryCursor) Matches(q *Query, n Node, text []byte) (qm QueryMatches)
Matches iterates over all of the matches in the order that they were found.
Each match contains the index of the pattern that matched, and a list of captures. Because multiple patterns can match the same set of nodes, one match may contain captures that appear *before* some of the captures from a previous match.
func (*QueryCursor) NextCapture ¶
func (c *QueryCursor) NextCapture() (_ *QueryMatch, i uint)
func (*QueryCursor) NextMatch ¶
func (c *QueryCursor) NextMatch() (_ *QueryMatch)
func (*QueryCursor) RemoveMatch ¶ added in v1.3.2
func (c *QueryCursor) RemoveMatch(matchID uint)
func (*QueryCursor) SetByteRange ¶ added in v1.3.0
func (c *QueryCursor) SetByteRange(start, end uint32)
SetByteRange sets the range of bytes in which the query will be executed.
func (*QueryCursor) SetMatchLimit ¶ added in v1.3.3
func (c *QueryCursor) SetMatchLimit(limit uint32)
SetMatchLimit see above.
func (*QueryCursor) SetMaxStartDepth ¶ added in v1.3.2
func (c *QueryCursor) SetMaxStartDepth(maxStartDepth uint32)
SetMaxStartDepth sets the maximum start depth for a query cursor.
This prevents cursors from exploring children nodes at a certain depth. Note if a pattern includes many children, then they will still be checked.
The zero max start depth value can be used as a special behavior and it helps to destructure a subtree by staying on a node and using captures for interested parts. Note that the zero max start depth only limit a search depth for a pattern's root node but other nodes that are parts of the pattern may be searched at any depth what defined by the pattern structure.
Set to UnlimitedMaxDepth to remove the maximum start depth.
func (*QueryCursor) SetPointRange ¶
func (c *QueryCursor) SetPointRange(start, end Point)
SetPointRange sets the range of row/column positions in which the query will be executed.
func (*QueryCursor) SetTimeout ¶ added in v1.7.0
func (c *QueryCursor) SetTimeout(micros int)
SetTimeout sets the maximum duration in microseconds that query execution should be allowed to take before halting.
If query execution takes longer than this, it will halt early, returning NULL. See [`ts_query_cursor_next_match`] or [`ts_query_cursor_next_capture`] for more information.
func (*QueryCursor) Timeout ¶ added in v1.7.0
func (c *QueryCursor) Timeout() (micros int)
Timeout returns the duration in microseconds that query execution is allowed to take.
This is set via [`ts_query_cursor_set_timeout_micros`].
type QueryError ¶
type QueryError struct {
Message string
Offset uint
Kind QueryErrorKind
Point
// contains filtered or unexported fields
}
QueryError holds detailed query error. The Offset argument will be set to the byte offset of the error, the Kind argument will be set to a value that indicates the type, of error and inner will represent the error class.
func (QueryError) Error ¶
func (e QueryError) Error() string
func (QueryError) Unwrap ¶ added in v1.9.0
func (e QueryError) Unwrap() error
type QueryErrorKind ¶ added in v1.9.0
type QueryErrorKind uint32
QueryErrorKind indicates the type of QueryErrorKind.
const ( QueryErrorNone QueryErrorKind = C.TSQueryErrorNone QueryErrorSyntax QueryErrorKind = C.TSQueryErrorSyntax QueryErrorNodeType QueryErrorKind = C.TSQueryErrorNodeType QueryErrorField QueryErrorKind = C.TSQueryErrorField QueryErrorCapture QueryErrorKind = C.TSQueryErrorCapture QueryErrorStructure QueryErrorKind = C.TSQueryErrorStructure QueryErrorLanguage QueryErrorKind = C.TSQueryErrorLanguage QueryErrorPredicate QueryErrorKind = 100 )
Error types.
func (QueryErrorKind) String ¶ added in v1.9.0
func (i QueryErrorKind) String() string
type QueryMatch ¶
type QueryMatch struct {
Captures []QueryCapture
PatternIndex uint
ID uint
// contains filtered or unexported fields
}
QueryMatch allows you to iterate over the matches.
func (*QueryMatch) NodesForCaptureIndex ¶ added in v1.9.0
func (qm *QueryMatch) NodesForCaptureIndex(captureIndex uint) []Node
func (*QueryMatch) Remove ¶ added in v1.9.0
func (qm *QueryMatch) Remove()
type QueryMatches ¶ added in v1.9.0
type QueryMatches struct {
// contains filtered or unexported fields
}
QueryMatches holds a sequence of [QueryMatch]es associated with a given QueryCursor.
func (*QueryMatches) Next ¶ added in v1.9.0
func (qm *QueryMatches) Next() *QueryMatch
Next will return the next match in the sequence of matches.
Subsequent calls to QueryMatches.Next will overwrite the memory at the same location as prior matches, since the memory is reused. You can think of this as a stateful iterator. If you need to keep the data of a prior match without it being overwritten, you should copy what you need before calling QueryMatches.Next again.
If there are no more matches, it will return nil.
type QueryPredicate ¶ added in v1.9.0
type QueryPredicate struct {
Operator string
Args []QueryPredicateArg
}
type QueryPredicateArg ¶ added in v1.9.0
type QueryPredicateStep ¶
type QueryPredicateStep struct {
Type QueryPredicateStepType
ValueID uint32
}
QueryPredicateStep represents one step in a predicate.
type QueryPredicateStepType ¶
type QueryPredicateStepType uint32
QueryPredicateStepType represents type of step in a predicate.
const ( QueryPredicateStepTypeDone QueryPredicateStepType = C.TSQueryPredicateStepTypeDone QueryPredicateStepTypeCapture QueryPredicateStepType = C.TSQueryPredicateStepTypeCapture QueryPredicateStepTypeString QueryPredicateStepType = C.TSQueryPredicateStepTypeString )
Possible query predicate steps.
func (QueryPredicateStepType) String ¶ added in v1.4.3
func (i QueryPredicateStepType) String() string
type QueryPredicateSteps ¶ added in v1.3.4
type QueryPredicateSteps []QueryPredicateStep
QueryPredicateSteps holds all the steps for a predicate.
type QueryProperty ¶ added in v1.9.0
QueryProperty holds a kv pair associated with a particular pattern in a Query.
func NewQueryProperty ¶ added in v1.9.0
func NewQueryProperty(key string, value *string, captureID *uint) QueryProperty
type ReadFunc ¶
ReadFunc is a function to retrieve a chunk of text at a given byte offset and (row, column) position. It should return nil to indicate the end of the document.
type SymbolType ¶
type SymbolType uint32
SymbolType indicates the type of symbol.
const ( SymbolTypeRegular SymbolType = C.TSSymbolTypeRegular SymbolTypeAnonymous SymbolType = C.TSSymbolTypeAnonymous SymbolTypeSupertype SymbolType = C.TSSymbolTypeSupertype SymbolTypeAuxiliary SymbolType = C.TSSymbolTypeAuxiliary )
Possible symbol types.
func (SymbolType) String ¶
func (i SymbolType) String() string
type TextPredicateCapture ¶ added in v1.9.0
type TextPredicateCapture struct {
Value any
Type TextPredicateType
CaptureID uint
Positive bool
MatchAllNodes bool
}
type TextPredicateType ¶ added in v1.9.0
type TextPredicateType int
const ( TextPredicateTypeEqCapture TextPredicateType = iota TextPredicateTypeEqString TextPredicateTypeMatchString TextPredicateTypeAnyString )
type Tree ¶
type Tree struct {
// contains filtered or unexported fields
}
Tree represents the syntax tree of an entire source code file Note: Tree instances are not thread safe; you must copy a tree if you want to use it on multiple threads simultaneously.
func (*Tree) Close ¶ added in v1.11.0
func (t *Tree) Close()
Close releases the resources associated with the tree. After calling Close, the Tree must not be used again.
func (*Tree) Copy ¶
Copy creates a shallow copy of the syntax tree. This is very fast.
You need to copy a syntax tree in order to use it on more than one thread at a time, as syntax trees are not thread safe.
func (*Tree) Edit ¶
Edit the syntax tree to keep it in sync with source code that has been edited.
You MUST describe the edit both in terms of byte offsets and in terms of (row, column) coordinates.
func (*Tree) GetChangedRanges ¶ added in v1.3.1
GetChangedRanges compares an old edited syntax tree to a new syntax tree representing the same document, returning an array of ranges whose syntactic structure has changed.
For this to work correctly, the old syntax tree must have been edited such that its ranges match up to the new tree. Generally, you'll want to call this function right after calling one of the [`ts_parser_parse`] functions. You need to pass the old tree that was passed to parse, as well as the new tree that was returned from that function.
The returned array is allocated using `malloc` and the caller is responsible for freeing it using `free`. The length of the array will be written to the given `length` pointer.
func (*Tree) IncludedRanges ¶ added in v1.3.3
IncludedRanges returns the array of included ranges that was used to parse the syntax tree.
The returned pointer must be freed by the caller.
func (*Tree) Language ¶ added in v1.3.2
Language returns the language that was used to parse the syntax tree.
func (*Tree) PrintDotGraph ¶ added in v1.3.3
PrintDotGraph writes a DOT graph describing the syntax tree to the given file.
type TreeCursor ¶
type TreeCursor struct {
// contains filtered or unexported fields
}
TreeCursor allows you to walk a syntax tree more efficiently than is possible using the `Node` functions. It is a mutable object that is always on a certain syntax node, and can be moved imperatively to different nodes.
func NewTreeCursor ¶
func NewTreeCursor(n Node) (c *TreeCursor)
NewTreeCursor creates a new tree cursor starting from the given node.
A tree cursor allows you to walk a syntax tree more efficiently than is possible using the [`TSNode`] functions. It is a mutable object that is always on a certain syntax node, and can be moved imperatively to different nodes.
func (*TreeCursor) Copy ¶ added in v1.3.2
func (c *TreeCursor) Copy() *TreeCursor
Copy returns a copy of the tree cursor.
func (*TreeCursor) CurrentDepth ¶ added in v1.3.2
func (c *TreeCursor) CurrentDepth() uint32
CurrentDepth returns the depth of the cursor's current node relative to the original node that the cursor was constructed with.
func (*TreeCursor) CurrentDescendantIndex ¶ added in v1.3.2
func (c *TreeCursor) CurrentDescendantIndex() uint32
CurrentDescendantIndex returns the index of the cursor's current node out of all of the descendants of the original node that the cursor was constructed with.
func (*TreeCursor) CurrentFieldID ¶ added in v1.3.2
func (c *TreeCursor) CurrentFieldID() FieldID
CurrentFieldID returns the field id of the tree cursor's current node.
This returns zero if the current node doesn't have a field. See also `ts_node_child_by_field_id`, `ts_language_field_id_for_name`.
func (*TreeCursor) CurrentFieldName ¶
func (c *TreeCursor) CurrentFieldName() string
CurrentFieldName gets the field name of the tree cursor's current node.
This returns empty string if the current node doesn't have a field. See also `ts_node_child_by_field_name`.
func (*TreeCursor) CurrentNode ¶
func (c *TreeCursor) CurrentNode() Node
CurrentNode returns the cursor's current node.
func (*TreeCursor) GoToFirstChild ¶
func (c *TreeCursor) GoToFirstChild() bool
GoToFirstChild moves the cursor to the first child of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there were no children.
func (*TreeCursor) GoToFirstChildForByte ¶
func (c *TreeCursor) GoToFirstChildForByte(b uint32) int64
GoToFirstChildForByte moves the cursor to the first child of its current node that extends beyond the given byte offset.
This returns the index of the child node if one was found, and returns -1 if no such child was found.
func (*TreeCursor) GoToFirstChildForPoint ¶ added in v1.3.2
func (c *TreeCursor) GoToFirstChildForPoint(p Point) int64
GoToFirstChildForPoint moves the cursor to the first child of its current node that extends beyond the given point.
This returns the index of the child node if one was found, and returns -1 if no such child was found.
func (*TreeCursor) GoToNextSibling ¶
func (c *TreeCursor) GoToNextSibling() bool
GoToNextSibling moves the cursor to the next sibling of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there was no next sibling node.
func (*TreeCursor) GoToParent ¶
func (c *TreeCursor) GoToParent() bool
GoToParent moves the cursor to the parent of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there was no parent node (the cursor was already on the root node).
func (*TreeCursor) GotoDescendant ¶ added in v1.3.2
func (c *TreeCursor) GotoDescendant(goalDescendantIndex uint32)
GotoDescendant moves the cursor to the node that is the nth descendant of the original node that the cursor was constructed with, where zero represents the original node itself.
func (*TreeCursor) GotoLastChild ¶ added in v1.3.2
func (c *TreeCursor) GotoLastChild() bool
GotoLastChild moves the cursor to the last child of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there were no children.
Note that this function may be slower than [`ts_tree_cursor_goto_first_child`] because it needs to iterate through all the children to compute the child's position.
func (*TreeCursor) GotoPreviousSibling ¶ added in v1.3.2
func (c *TreeCursor) GotoPreviousSibling() bool
GotoPreviousSibling moves the cursor to the previous sibling of its current node.
This returns `true` if the cursor successfully moved, and returns `false` if there was no previous sibling node.
Note, that this function may be slower than `ts_tree_cursor_goto_next_sibling` due to how node positions are stored. In the worst case, this will need to iterate through all the children upto the previous sibling node to recalculate its position.
func (*TreeCursor) Reset ¶
func (c *TreeCursor) Reset(n Node)
Reset re-initializes a tree cursor to start at the original node that the cursor was constructed with.
func (*TreeCursor) ResetTo ¶ added in v1.3.2
func (c *TreeCursor) ResetTo(src *TreeCursor)
ResetTo re-initializes a tree cursor to the same position as another cursor.
Unlike `ts_tree_cursor_reset`, this will not lose parent information and allows reusing already created cursors.