treesitter

    An experimental pure MoonBit port of Tree-sitter, with mbtx grammar definitions.

    Download zip
    Version
    0.1.0
    License
    MIT
    Last updated
    21 days ago
    Downloads
    324

    #Tree-sitter in pure MoonBit

    A faithful port of Tree-sitter 0.28.0 (commit 4a412a01a0147d0f50bf7e749572fa632d1ab203) to MoonBit: the parser generator, the parsing runtime, queries, highlighting, tags, the external scanners of the upstream fixture grammars and the tree-sitter CLI. Each package is a structural, file-by-file translation of the corresponding upstream source and is tested differentially against the pinned upstream build (see Validation).

    Languages are portable tables (@language.Language) that the MoonBit runtime executes directly; no C runtime, Rust generator or dynamic library is involved. COMPATIBILITY.md lists what differs from upstream and why; PORTING.md maps every package to its upstream source.

    #Install

    moon add moonbit-community/treesitter@0.1.0 moon add moonbit-community/tree-sitter-json@0.24.8 # or any module in grammars/ moon install moonbit-community/treesitter/cmd/treesitter@0.1.0 # the CLI (native)

    #Library

    The root package moonbit-community/treesitter is the port of upstream's Rust binding (lib/binding_rust/lib.rs): Parser, Tree, Node, TreeCursor, Query, QueryCursor, LookaheadIterator and friends, with the same names and semantics.

    ///|
    test "generate a grammar, parse and query" {
    // A grammar.json document (here built with the @grammar DSL; upstream's
    // `tree-sitter generate` writes the same format to src/grammar.json).
    let grammar = @grammar.Grammar::new("words", [
    ("document", Repeat(Symbol("word"))),
    ("word", @grammar.pattern("[a-z]+")),
    ])
    let generated = @generate.generate_from_grammar_json(
    grammar.to_json().stringify(),
    )
    // `generated.c_code` is the parser.c upstream would emit, byte for byte.
    let language = @treesitter.Language::new(generated.language)
    let parser = @treesitter.Parser::new()
    parser.set_language(language)
    let source = @utf8.encode("hello moonbit")
    guard parser.parse(source) is Some(tree) else { fail("parse failed") }
    inspect(tree.root_node().to_sexp(), content="(document (word) (word))")
    let query = @treesitter.Query::new(language, "(word) @w")
    let cursor = @treesitter.QueryCursor::new()
    let matches = cursor.matches(query, tree.root_node(), source)
    let mut count = 0
    while matches.next() is Some(_) {
    count += 1
    }
    inspect(count, content="2")
    }

    PackageUpstream source
    moonbit-community/treesitterlib/binding_rust/lib.rs
    runtimelib/src (parser, lexer, stack, subtree, tree, node, tree cursor, changed ranges)
    languageTSLanguage (lib/src/parser.h, language.c) as portable tables
    querylib/src/query.c
    generatecrates/generate
    regex_syntax, regexthe regex-syntax 0.8 subset the generator and tags use, and a matcher
    highlight, tagscrates/highlight, crates/tags
    scannersthe C external scanners of the upstream fixture and test grammars and of the grammars in grammars/
    query_testing, cli_testthe CLI's assertion and corpus testing
    cli, loader, config, clap, clap_complete, cmd/treesittercrates/cli, crates/loader, crates/config, and the clap subset they use (native only)
    grammara MoonBit DSL producing grammar.json (no upstream equivalent; stands in for grammar.js)

    The runtime, query, generator, highlight and tags packages build for native, JavaScript and Wasm GC. The CLI, loader and config are native only.

    #Grammar modules

    grammars/ holds one MoonBit module per grammar repository of grammars/grammars.json, for example moonbit-community/tree-sitter-json in grammars/json. Each mirrors the grammar's Rust binding (LANGUAGE is language(), HIGHLIGHTS_QUERY is highlights_query, and so on) and embeds tables that this port's generator builds from the pinned src/grammar.json, in the compact format of @language.Language::from_compact_base64:

    import { "moonbit-community/treesitter", "moonbit-community/tree-sitter-json" @tree_sitter_json, }

    The repository root is a workspace (moon.work) of the core module and the grammar modules, so moon check and moon test cover them all. sh tools/grammars/update.sh regenerates the modules from the pinned grammar checkouts, and python3 tools/oracle/compare_modules.py checks their tables against upstream's parser.c.

    #Command line

    moon build --target native --release cmd/treesitter _build/native/release/build/moonbit-community/treesitter/cmd/treesitter/treesitter.exe --help

    The executable is tree-sitter 0.28.0: same subcommands, flags, help text and output. In a grammar directory, generate reads grammar.js (with node, bun or deno, as upstream), src/grammar.json or a MoonBit grammar.mbtx, and writes src/parser.c, src/node-types.json, src/grammar.json and the portable src/language.json. parse, query, highlight, tags, test and fuzz load languages through tree-sitter.json exactly like upstream.

    MoonBit cannot load compiled parsers, so:

    • build writes a MoonBit module with pub fn language() -> @language.Language instead of a shared library (--wasm is rejected);
    • grammars with an external scanner use its port in scanners, or a src/scanner.mbtx defining pub fn scanner() -> @runtime.ExternalScanner, which the CLI compiles into a cached driver;
    • playground is unavailable.

    #Validation

    Every package is compared with the pinned upstream build:

    CARGO="cargo +1.97.1" sh tools/oracle/oracle_setup.sh # pinned upstream + reference outputs sh tools/oracle/oracle.sh # generator, runtime, queries bash tools/oracle/diff_cli.sh # CLI commands python3 tools/oracle/compare_modules.py # grammar modules' tables moon test --target native # ported upstream test suites

    The oracle checks that the generator emits byte-identical parser.c and node-types.json for all 108 upstream test, fixture and additional grammars (including error messages for rejected grammars), that parse trees, incremental edits, changed ranges, parser logs, UTF-16 input and included ranges match the C runtime on every corpus input and random mutations and edits of them, and that query matches and captures match query.c. The CLI comparison runs 1,695 command lines through both executables. The ported upstream test suites (tests/, and the tests of each package) run with moon test.

    #License

    MIT, preserving Tree-sitter attribution in LICENSE and NOTICE. Unicode data has its own license in licenses/UNICODE.txt.

    Logger

    type Logger = (LogType, String) -> Unit

    A callback that receives log messages during parsing.

    Utf8Error

    Rust's core::str::Utf8Error, raised by [Node::utf8_text].

    DotGraphOutput

    pub(open) trait DotGraphOutput {
    fn write_dot_graph(Self, Bytes) -> Unit
    }

    A destination for DOT graphs ([Tree::print_dot_graph], [Parser::print_dot_graphs_to]). Upstream writes the graphs to a file descriptor as bytes, which are not always valid UTF-8: the label of an UNEXPECTED character holds its low byte (C's %c), and a truncated log message may end inside a character.

    A Buffer receives exactly upstream's bytes. A StringBuilder receives them decoded as UTF-8, with invalid sequences replaced by U+FFFD.

    TextProvider

    pub(open) trait TextProvider {
    fn text(Self, Node) -> Iter[BytesView]
    }

    A source of node text for evaluating text predicates (#eq?, #match?, #any-of? and their variants): the text of a node as a sequence of chunks, which are concatenated.

    Implemented for source bytes (Bytes, BytesView) and for callbacks via [TextCallback].

    IncludedRangesError

    pub(all) suberror IncludedRangesError {
    IncludedRangesError(Int)
    } derive(Eq,
    Debug
    )

    An error that occurred in [Parser::set_included_ranges]: the index of the first incorrect range.

    LanguageError

    pub(all) suberror LanguageError {
    Version(Int)
    NotParseable
    } derive(Eq,
    Debug
    )

    An error that occurred when trying to assign a [Language] to a [Parser].

    QueryError

    pub(all) suberror QueryError {
    QueryError(row~ : Int, column~ : Int, offset~ : Int, message~ : String, kind~ : QueryErrorKind)
    } derive(Eq,
    Debug
    )

    An error that occurred when trying to create a [Query].
    impl Show for QueryError

    QueryError::column

    fn QueryError::column(self : QueryError) -> Int

    The zero-based column of the error.

    QueryError::kind

    The kind of the error.

    QueryError::message

    fn QueryError::message(self : QueryError) -> String

    The error message (without the Query error at ... prefix).

    QueryError::offset

    fn QueryError::offset(self : QueryError) -> Int

    The byte offset of the error in the query source.

    QueryError::row

    fn QueryError::row(self : QueryError) -> Int

    The zero-based row of the error.

    CaptureQuantifier

    pub(all) enum CaptureQuantifier {
    Zero
    ZeroOrOne
    ZeroOrMore
    One
    OneOrMore
    } derive(Eq,
    Debug
    )

    A quantifier for captures.

    ControlFlow

    pub(all) enum ControlFlow {
    Continue
    Break
    } derive(Eq,
    Debug
    )

    The result of a progress callback: whether to continue or to stop the operation (Rust's ControlFlow<()>).

    InputEdit

    pub(all) struct InputEdit {
    start_byte : Int
    old_end_byte : Int
    new_end_byte : Int
    start_position : Point
    old_end_position : Point
    new_end_position : Point
    } derive(Eq,
    Debug
    )

    A summary of a change to a text document.

    InputEdit::edit_point

    fn InputEdit::edit_point(self : InputEdit, point : Point, byte : Int) -> (Point, Int)

    Edit a point to keep it in-sync with source code that has been edited.

    This function updates a single point's byte offset and row/column position based on this edit operation, returning the edited (point, byte). This is useful for editing points without requiring a tree or node instance.

    InputEdit::edit_range

    fn InputEdit::edit_range(self : InputEdit, range : Range) -> Range

    Edit a range to keep it in-sync with source code that has been edited, returning the edited range.

    This function updates a range's start and end positions based on this edit operation. This is useful for editing ranges without requiring a tree or node instance.

    Language

    pub struct Language {
    // private fields
    }

    An object that defines how to parse a particular language: the generated parse tables (@language.Language, the equivalent of TSLanguage) plus, for grammars with external tokens, the factory for their external scanner (the equivalent of the scanner functions linked into a C parser).
    impl Eq for Language
    impl Hash for Language

    Language::abi_version

    fn Language::abi_version(self : Language) -> Int

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

    Language::external_scanner

    The external scanner factory of this language, if any.

    Language::field_count

    fn Language::field_count(self : Language) -> Int

    Get the number of distinct field names in this language.

    Language::field_id_for_name

    fn Language::field_id_for_name(self : Language, field_name : StringView) -> Int?

    Get the numerical id for the given field name. Field ids are never 0.

    Language::field_name_for_id

    fn Language::field_name_for_id(self : Language, field_id : Int) -> String?

    Get the field name for the given numerical id.

    Language::id_for_node_kind

    fn Language::id_for_node_kind(self : Language, kind : StringView, named : Bool) -> Int

    Get the numeric id for the given node kind.

    Language::is_parseable

    fn Language::is_parseable(self : Language) -> Bool

    Check whether this language can be assigned to a parser.

    A language whose grammar uses external tokens can only be used for parsing when it was created with its external scanner.

    Language::lookahead_iterator

    fn Language::lookahead_iterator(self : Language, state : Int) -> LookaheadIterator?

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

    This returns None if state is invalid for this language.

    Iterating [LookaheadIterator] will yield valid symbols in the given parse state. A newly created iterator is not positioned on a symbol, so [LookaheadIterator::current_symbol] returns None until the first [LookaheadIterator::next] call.

    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 a missing node, use the node's parse_state. Keep in mind that lookahead symbols are valid in that parse state, but are not necessarily valid continuations in the context of the actual following token or guaranteed to be considered during error recovery.

    Language::metadata

    fn Language::metadata(self : Language) -> 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.

    Language::name

    fn Language::name(self : Language) -> String?

    Get the name of this language. This returns None in older parsers.

    Language::new

    Create a language from its parse tables and, if the grammar has external tokens, its external scanner.

    Language::next_state

    fn Language::next_state(self : Language, state : Int, id : Int) -> Int

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

    Example: language.next_state(node.parse_state(), node.grammar_id()).

    Language::node_kind_count

    fn Language::node_kind_count(self : Language) -> Int

    Get the number of distinct node types in this language.

    Language::node_kind_for_id

    fn Language::node_kind_for_id(self : Language, id : Int) -> String?

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

    Language::node_kind_is_named

    fn Language::node_kind_is_named(self : Language, id : Int) -> Bool

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

    Language::node_kind_is_supertype

    fn Language::node_kind_is_supertype(self : Language, id : Int) -> Bool

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

    Language::node_kind_is_visible

    fn Language::node_kind_is_visible(self : Language, id : Int) -> Bool

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

    Language::parse_state_count

    fn Language::parse_state_count(self : Language) -> Int

    Get the number of valid states in this language.

    Language::raw

    The parse tables of this language.

    Language::subtypes_for_supertype

    fn Language::subtypes_for_supertype(self : Language, supertype : Int) -> ArrayView[Int]

    Get a list of all subtype symbols for a given supertype symbol.

    Language::supertypes

    fn Language::supertypes(self : Language) -> ArrayView[Int]

    Get a list of all supertype symbols for the language.

    LanguageMetadata

    pub(all) struct LanguageMetadata {
    major_version : Int
    minor_version : Int
    patch_version : Int
    } derive(Eq,
    Debug
    )

    The metadata associated with a language.

    Currently, this metadata can be used to check the Semantic Version 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.

    LogType

    pub(all) enum LogType {
    Parse
    Lex
    } derive(Eq,
    Debug
    )

    A type of log message.

    LookaheadIterator

    pub struct LookaheadIterator {
    // private fields
    }

    A stateful object that is used to look up symbols valid in a specific parse state.

    LookaheadIterator::current_symbol

    fn LookaheadIterator::current_symbol(self : LookaheadIterator) -> Int?

    Get the current symbol of the lookahead iterator.

    Returns None if the iterator is not positioned on a symbol: before the first [LookaheadIterator::next] call, after the iterator is exhausted, and after a [LookaheadIterator::reset] or [LookaheadIterator::reset_state] call.

    LookaheadIterator::current_symbol_name

    fn LookaheadIterator::current_symbol_name(self : LookaheadIterator) -> String?

    Get the current symbol name of the lookahead iterator.

    Returns None if the iterator is not positioned on a symbol.

    LookaheadIterator::iter

    fn LookaheadIterator::iter(self : LookaheadIterator) -> Iter[Int]

    Iterate the remaining valid symbols.

    LookaheadIterator::iter_names

    fn LookaheadIterator::iter_names(self : LookaheadIterator) -> Iter[String]

    Iterate the names of the remaining valid symbols.

    LookaheadIterator::language

    Get the current language of the lookahead iterator.

    LookaheadIterator::next

    fn LookaheadIterator::next(self : LookaheadIterator) -> Int?

    Advance to the next valid symbol, returning it (Iterator::next).

    LookaheadIterator::reset

    fn LookaheadIterator::reset(self : LookaheadIterator, language : Language, state : Int) -> Bool

    Reset the lookahead iterator.

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

    LookaheadIterator::reset_state

    fn LookaheadIterator::reset_state(self : LookaheadIterator, state : Int) -> Bool

    Reset the lookahead iterator to another state.

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

    LossyUtf8

    pub struct LossyUtf8 {
    // private fields
    }

    An iterator over the UTF-8 decoded chunks of a byte string, yielding "\u{FFFD}" for each invalid sequence.

    LossyUtf8::iter

    fn LossyUtf8::iter(self : LossyUtf8) -> Iter[String]

    Iterate the remaining chunks.

    LossyUtf8::new

    fn LossyUtf8::new(bytes : BytesView) -> LossyUtf8

    Create a lossy UTF-8 iterator over bytes.

    LossyUtf8::next

    fn LossyUtf8::next(self : LossyUtf8) -> String?

    The next chunk: a maximal valid run of text, or a replacement character.

    Node

    pub struct Node {
    // private fields
    }

    A single node within a syntax [Tree].
    impl Eq for Node
    impl Hash for Node
    impl Show for Node
    impl Debug for Node

    Node::byte_range

    fn Node::byte_range(self : Node) -> (Int, Int)

    Get the byte range of source code that this node represents, as (start, end).

    Node::child

    fn Node::child(self : Node, i : Int) -> Node?

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

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

    Node::child_by_field_id

    fn Node::child_by_field_id(self : Node, field_id : Int) -> Node?

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

    See also child_by_field_name. You can convert a field name to an id using [Language::field_id_for_name].

    Node::child_by_field_name

    fn Node::child_by_field_name(self : Node, field_name : StringView) -> Node?

    Get the first child with the given field name.

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

    Node::child_count

    fn Node::child_count(self : Node) -> Int

    Get this node's number of children.

    Node::child_with_descendant

    fn Node::child_with_descendant(self : Node, descendant : Node) -> Node?

    Get the node that contains descendant.

    Note that this can return descendant itself.

    Node::children

    fn Node::children(self : Node, cursor : TreeCursor) -> Iter[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.

    Node::children_by_field_id

    fn Node::children_by_field_id(self : Node, field_id : Int, cursor : TreeCursor) -> Iter[Node]

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

    See also [Node::children_by_field_name].

    Node::children_by_field_name

    fn Node::children_by_field_name(self : Node, field_name : StringView, cursor : TreeCursor) -> Iter[Node]

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

    See also [Node::children].

    Node::descendant_count

    fn Node::descendant_count(self : Node) -> Int

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

    Node::descendant_for_byte_range

    fn Node::descendant_for_byte_range(self : Node, start : Int, end : Int) -> Node?

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

    Node::descendant_for_point_range

    fn Node::descendant_for_point_range(self : Node, start : Point, end : Point) -> Node?

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

    Node::edit

    fn Node::edit(self : Node, edit : InputEdit) -> Node

    Edit this node to keep it in-sync with source code that has been edited, returning the edited node (upstream mutates the Copy node in place).

    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.

    Node::end_byte

    fn Node::end_byte(self : Node) -> Int

    Get the byte offset where this node ends.

    Node::end_position

    fn Node::end_position(self : Node) -> Point

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

    Node::field_name_for_child

    fn Node::field_name_for_child(self : Node, child_index : Int) -> String?

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

    Node::field_name_for_named_child

    fn Node::field_name_for_named_child(self : Node, named_child_index : Int) -> String?

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

    Node::first_child_for_byte

    fn Node::first_child_for_byte(self : Node, byte : Int) -> Node?

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

    Node::first_named_child_for_byte

    fn Node::first_named_child_for_byte(self : Node, byte : Int) -> Node?

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

    Node::grammar_id

    fn Node::grammar_id(self : Node) -> Int

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

    Node::grammar_name

    fn Node::grammar_name(self : Node) -> String

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

    Node::has_changes

    fn Node::has_changes(self : Node) -> Bool

    Check if this node has been edited.

    Node::has_error

    fn Node::has_error(self : Node) -> Bool

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

    Node::id

    fn Node::id(self : Node) -> UInt64

    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.
    • A node not marked as having changes does not guarantee it was reused.
    • If a node is marked as having changed in the old tree, it will not be reused.

    Node::is_error

    fn Node::is_error(self : Node) -> Bool

    Check if this node represents a syntax error.

    Syntax errors represent parts of the code that could not be incorporated into a valid syntax tree.

    Node::is_extra

    fn Node::is_extra(self : Node) -> Bool

    Check if this node is extra.

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

    Node::is_missing

    fn Node::is_missing(self : Node) -> Bool

    Check if this node is missing.

    Missing nodes are inserted by the parser in order to recover from certain kinds of syntax errors.

    Node::is_named

    fn Node::is_named(self : Node) -> Bool

    Check if this node is named.

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

    Node::kind

    fn Node::kind(self : Node) -> String

    Get this node's type as a string.

    Node::kind_id

    fn Node::kind_id(self : Node) -> Int

    Get this node's type as a numerical id.

    Node::language

    fn Node::language(self : Node) -> Language

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

    Node::named_child

    fn Node::named_child(self : Node, i : Int) -> Node?

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

    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::named_children] instead.

    Node::named_child_count

    fn Node::named_child_count(self : Node) -> Int

    Get this node's number of named children.

    Node::named_children

    fn Node::named_children(self : Node, cursor : TreeCursor) -> Iter[Node]

    Iterate over this node's named children.

    See also [Node::children].

    Node::named_descendant_for_byte_range

    fn Node::named_descendant_for_byte_range(self : Node, start : Int, end : Int) -> Node?

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

    Node::named_descendant_for_point_range

    fn Node::named_descendant_for_point_range(self : Node, start : Point, end : Point) -> Node?

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

    Node::next_named_sibling

    fn Node::next_named_sibling(self : Node) -> Node?

    Get this node's next named sibling.

    Node::next_parse_state

    fn Node::next_parse_state(self : Node) -> Int

    Get the parse state after this node.

    Node::next_sibling

    fn Node::next_sibling(self : Node) -> Node?

    Get this node's next sibling.

    Node::parent

    fn Node::parent(self : Node) -> Node?

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

    Node::parse_state

    fn Node::parse_state(self : Node) -> Int

    Get the parse state immediately before this node.

    For a missing node, this is the state from the recovery path that was selected by the parser. It can be used with [Language::lookahead_iterator] to inspect the symbols that are valid in that state. This does not necessarily include every symbol that could be recovered by inserting a missing node, because the recovery process can consider multiple stack versions.

    Node::prev_named_sibling

    fn Node::prev_named_sibling(self : Node) -> Node?

    Get this node's previous named sibling.

    Node::prev_sibling

    fn Node::prev_sibling(self : Node) -> Node?

    Get this node's previous sibling.

    Node::range

    fn Node::range(self : Node) -> Range

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

    Node::raw

    The runtime node wrapped by this node.

    Node::start_byte

    fn Node::start_byte(self : Node) -> Int

    Get the byte offset where this node starts.

    Node::start_position

    fn Node::start_position(self : Node) -> Point

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

    Node::to_sexp

    fn Node::to_sexp(self : Node) -> String

    Get an S-expression representing the node.

    Node::utf16_text

    fn Node::utf16_text(self : Node, source : ArrayView[UInt16]) -> ArrayView[UInt16]

    The text of this node in UTF-16 source (node offsets are in bytes, i.e. twice the code unit offsets).

    Node::utf8_text

    fn Node::utf8_text(self : Node, source : BytesView) -> String raise
    Utf8Error

    The text of this node in source, decoded as UTF-8. Raises Rust's Utf8Error when the bytes are not valid UTF-8; aborts, as Rust's slice indexing panics, when the node's range is not within source.

    Node::walk

    fn Node::walk(self : Node) -> 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.

    ParseOptions

    pub(all) struct ParseOptions {
    progress_callback : (ParseState) -> ControlFlow?
    }

    Options for parsing; currently a progress callback that can cancel the parse by returning Break.

    ParseOptions::new

    fn ParseOptions::new(progress_callback? : (ParseState) -> ControlFlow) -> ParseOptions

    Create parse options.

    ParseState

    pub struct ParseState {
    // private fields
    }

    The state of the parser that is passed to a parse progress callback.

    ParseState::current_byte_offset

    fn ParseState::current_byte_offset(self : ParseState) -> Int

    The byte offset the parser has reached.

    ParseState::has_error

    fn ParseState::has_error(self : ParseState) -> Bool

    Whether the parser has encountered an error.

    Parser

    pub struct Parser {
    // private fields
    }

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

    Parser::delete

    fn Parser::delete(self : Parser) -> Unit

    Release the parser, as dropping the Rust Parser does: stop printing dot graphs, remove the logger and delete the C parser, which destroys the external scanner of a parse that was cancelled and not reset.

    MoonBit has no destructors, so this is explicit; without it, an outstanding scanner's destroy callback is never called. The parser is left without a language and can be given a new one.

    Parser::included_ranges

    fn Parser::included_ranges(self : Parser) -> Array[Range]

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

    Parser::language

    fn Parser::language(self : Parser) -> Language?

    Get the parser's current language.

    Parser::logger

    fn Parser::logger(self : Parser) -> (LogType, String) -> Unit?

    Get the parser's current logger.

    Parser::new

    fn Parser::new() -> Parser

    Create a new parser.

    Parser::parse

    fn Parser::parse(self : Parser, text : BytesView, old_tree? : Tree) -> Tree?

    Parse a slice of UTF8 text.

    • 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].

    Returns a [Tree] if parsing succeeded, or None if the parser has not yet had a language assigned with [Parser::set_language].

    Parser::parse_custom_encoding

    fn Parser::parse_custom_encoding(self : Parser, decode : (BytesView) -> (Int, Int), callback : (Int, Point) -> BytesView, old_tree? : Tree, options? : ParseOptions) -> 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.

    • decode: decodes the next code point from the start of the given bytes, returning (code point, bytes consumed); the code point is -1 if decoding fails (upstream's Decode::decode).
    • callback: a function that takes a byte offset and position and returns a slice of text starting at that byte offset and position.
    • old_tree: a previous syntax tree parsed from the same document.
    • options: options for parsing the text, e.g. a progress callback.

    Parser::parse_utf16_be

    fn Parser::parse_utf16_be(self : Parser, input : ArrayView[UInt16], old_tree? : Tree) -> Tree?

    Parse a slice of UTF16 big-endian text.

    As in lib.rs, the code units are passed to the parser in memory order of a little-endian host, so big-endian input is given as byte-swapped units (Rust's u16::to_be).

    Parser::parse_utf16_be_with_options

    fn Parser::parse_utf16_be_with_options(self : Parser, callback : (Int, Point) -> ArrayView[UInt16], old_tree? : Tree, options? : ParseOptions) -> Tree?

    Parse UTF16 big-endian text provided in chunks by a callback. See [Parser::parse_utf16_be] for how the code units are interpreted.

    Parser::parse_utf16_le

    fn Parser::parse_utf16_le(self : Parser, input : ArrayView[UInt16], old_tree? : Tree) -> Tree?

    Parse a slice of UTF16 little-endian text.

    • input: the UTF16-encoded text to parse.
    • old_tree: a previous syntax tree parsed from the same document.

    Parser::parse_utf16_le_with_options

    fn Parser::parse_utf16_le_with_options(self : Parser, callback : (Int, Point) -> ArrayView[UInt16], old_tree? : Tree, options? : ParseOptions) -> Tree?

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

    • callback: a function that takes a code unit offset and position and returns a slice of UTF16-encoded text starting at that offset and position. 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.
    • options: options for parsing the text, e.g. a progress callback.

    Parser::parse_with_options

    fn Parser::parse_with_options(self : Parser, callback : (Int, Point) -> BytesView, old_tree? : Tree, options? : ParseOptions) -> Tree?

    Parse text provided in chunks by a callback.

    • 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.
    • options: options for parsing the text, e.g. a progress callback.

    Parser::print_dot_graphs

    fn Parser::print_dot_graphs(self : Parser, writer : (String) -> Unit) -> Unit

    Set the destination to which the parser should write debugging graphs during parsing. The graphs are formatted in the DOT language; writer receives the output in pieces, decoded as UTF-8 with invalid sequences replaced by U+FFFD (see [DotGraphOutput]; use [Parser::print_dot_graphs_to] for upstream's exact bytes).

    Parser::print_dot_graphs_to

    fn[W : DotGraphOutput] Parser::print_dot_graphs_to(self : Parser, output : W) -> Unit

    Set the destination to which the parser should write debugging graphs during parsing, as [Parser::print_dot_graphs] does; a Buffer output receives exactly the bytes upstream writes.

    Parser::reset

    fn Parser::reset(self : Parser) -> Unit

    Instruct the parser to start the next parse from the beginning.

    If the parser previously failed because of a callback, then by default, it will resume where it left off on the next call to 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.

    Parser::set_included_ranges

    fn Parser::set_included_ranges(self : Parser, ranges : ArrayView[Range]) -> Unit raise IncludedRangesError

    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, ranges[i].end_byte <=ranges[i + 1].start_byte must hold. If this requirement is not satisfied, this raises [IncludedRangesError] with the index of the first incorrect range.

    Parser::set_language

    fn Parser::set_language(self : Parser, language : Language) -> Unit raise LanguageError

    Set the language that the parser should use for parsing.

    Assignment fails if the language cannot be used for parsing, or if it was generated with an incompatible version of the Tree-sitter CLI. Check this using [Language::is_parseable] and [Language::abi_version].

    Parser::set_logger

    fn Parser::set_logger(self : Parser, logger : (LogType, String) -> Unit?) -> Unit

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

    Parser::stop_printing_dot_graphs

    fn Parser::stop_printing_dot_graphs(self : Parser) -> Unit

    Stop the parser from printing debugging graphs while parsing.

    Point

    pub(all) struct Point {
    row : Int
    column : Int
    } derive(Compare, Default, Eq, Hash,
    Debug
    )

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

    Rows and columns are zero-based.
    impl Show for Point

    Point::new

    fn Point::new(row : Int, column : Int) -> Point

    Create a point.

    Query

    pub struct Query {
    // private fields
    }

    A set of patterns that match nodes in a syntax tree.
    impl Eq for Query

    Query::capture_index_for_name

    fn Query::capture_index_for_name(self : Query, name : StringView) -> Int?

    Get the index for a given capture name.

    Query::capture_names

    fn Query::capture_names(self : Query) -> ArrayView[String]

    Get the names of the captures used in the query.

    Query::capture_quantifiers

    fn Query::capture_quantifiers(self : Query, index : Int) -> ArrayView[CaptureQuantifier]

    Get the quantifiers of the captures used in the given pattern.

    Query::deep_clone

    fn Query::deep_clone(self : Query) -> Query

    Create a deep copy of this query.

    Queries can be shared across cursors without cloning. You should only need this when you want an independent copy to mutate (e.g. via disable_capture or disable_pattern).

    Query::disable_capture

    fn Query::disable_capture(self : Query, name : StringView) -> Unit

    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.

    Query::disable_pattern

    fn Query::disable_pattern(self : Query, index : Int) -> Unit

    Disable a certain pattern within a query.

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

    Query::end_byte_for_pattern

    fn Query::end_byte_for_pattern(self : Query, pattern_index : Int) -> Int

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

    Query::general_predicates

    fn Query::general_predicates(self : Query, index : Int) -> ArrayView[QueryPredicate]

    Get the other user-defined predicates associated with the given index.

    This includes predicate with operators other than match?, eq? and not-eq? (and their any- variants), any-of? and not-any-of?, is? and is-not?, and set!.

    Query::is_pattern_guaranteed_at_step

    fn Query::is_pattern_guaranteed_at_step(self : Query, byte_offset : Int) -> Bool

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

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

    Query::is_pattern_non_local

    fn Query::is_pattern_non_local(self : Query, index : Int) -> Bool

    Check if a given pattern within a query is non-local.

    Query::is_pattern_rooted

    fn Query::is_pattern_rooted(self : Query, index : Int) -> Bool

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

    Query::new

    fn Query::new(language : Language, source : String) -> Query raise QueryError

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

    Query::new_raw

    fn Query::new_raw(language : Language, source : Bytes) ->
    Query
    raise QueryError

    Constructs a raw query without performing extra checks specific to the bindings, such as predicate validation, and computes the row, column and message of a failure from the error offset.

    Query::pattern_count

    fn Query::pattern_count(self : Query) -> Int

    Get the number of patterns in the query.

    Query::property_predicates

    fn Query::property_predicates(self : Query, index : Int) -> ArrayView[(QueryProperty, Bool)]

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

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

    Query::property_settings

    fn Query::property_settings(self : Query, index : Int) -> ArrayView[QueryProperty]

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

    This includes predicates with the operator set!.

    Query::raw

    The runtime query wrapped by this query.

    Query::start_byte_for_pattern

    fn Query::start_byte_for_pattern(self : Query, pattern_index : Int) -> Int

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

    QueryCapture

    pub(all) struct QueryCapture {
    node : Node
    index : Int
    }

    A particular [Node] that has been captured with a particular name within a [Query].

    QueryCaptures

    pub struct QueryCaptures[T] {
    // private fields
    }

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

    Each element contains a [QueryMatch] and the index of the new capture within [QueryMatch::captures].

    QueryCaptures::iter

    fn[T : TextProvider] QueryCaptures::iter(self : QueryCaptures[T]) -> Iter[(QueryMatch, Int)]

    Iterate the remaining captures.

    QueryCaptures::next

    fn[T : TextProvider] QueryCaptures::next(self : QueryCaptures[T]) -> (QueryMatch, Int)?

    Advance to the next capture whose match satisfies its text predicates. Matches that fail them are removed from the cursor.

    QueryCaptures::set_byte_range

    fn[T] QueryCaptures::set_byte_range(self : QueryCaptures[T], start : Int, end : Int) -> Unit

    Set the byte range in which the remaining captures are searched.

    QueryCaptures::set_point_range

    fn[T] QueryCaptures::set_point_range(self : QueryCaptures[T], start : Point, end : Point) -> Unit

    Set the point range in which the remaining captures are searched.

    QueryCursor

    pub struct QueryCursor {
    // private fields
    }

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

    QueryCursor::captures

    fn[T] QueryCursor::captures(self : QueryCursor, query : Query, node : Node, text_provider : T) -> QueryCaptures[T]

    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.

    QueryCursor::captures_with_options

    fn[T] QueryCursor::captures_with_options(self : QueryCursor, query : Query, node : Node, text_provider : T, options : QueryCursorOptions) -> QueryCaptures[T]

    Iterate over all of the individual captures in the order that they appear, with options.

    QueryCursor::did_exceed_match_limit

    fn QueryCursor::did_exceed_match_limit(self : QueryCursor) -> Bool

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

    QueryCursor::match_limit

    fn QueryCursor::match_limit(self : QueryCursor) -> Int

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

    QueryCursor::matches

    fn[T] QueryCursor::matches(self : QueryCursor, query : Query, node : Node, text_provider : T) -> QueryMatches[T]

    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.

    Matches whose text predicates fail (according to text_provider) are skipped.

    QueryCursor::matches_with_options

    fn[T] QueryCursor::matches_with_options(self : QueryCursor, query : Query, node : Node, text_provider : T, options : QueryCursorOptions) -> QueryMatches[T]

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

    QueryCursor::new

    Create a new cursor for executing a given query.

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

    QueryCursor::set_byte_range

    fn QueryCursor::set_byte_range(self : QueryCursor, start : Int, end : Int) -> QueryCursor

    Set the range in which the query will be executed, in terms of byte offsets (start..end).

    QueryCursor::set_containing_byte_range

    fn QueryCursor::set_containing_byte_range(self : QueryCursor, start : Int, end : Int) -> QueryCursor

    Set the byte range within which all matches must be fully contained.

    In contrast to set_byte_range, this will restrict the query cursor to only return matches where all nodes are fully contained within the given range. Both functions can be used together, e.g. to search for any matches that intersect line 5000, as long as they are fully contained within lines 4500-5500.

    QueryCursor::set_containing_point_range

    fn QueryCursor::set_containing_point_range(self : QueryCursor, start : Point, end : Point) -> QueryCursor

    Set the point range within which all matches must be fully contained.

    QueryCursor::set_match_limit

    fn QueryCursor::set_match_limit(self : QueryCursor, limit : Int) -> Unit

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

    QueryCursor::set_max_start_depth

    fn QueryCursor::set_max_start_depth(self : QueryCursor, max_start_depth : Int?) -> 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 limits a search depth for a pattern's root node but other nodes that are parts of the pattern may be searched at any depth depending on what is defined by the pattern structure.

    Set to None to remove the maximum start depth.

    QueryCursor::set_point_range

    fn QueryCursor::set_point_range(self : QueryCursor, start : Point, end : Point) -> QueryCursor

    Set the range in which the query will be executed, in terms of rows and columns (start..end).

    QueryCursorOptions

    pub(all) struct QueryCursorOptions {
    progress_callback : (QueryCursorState) -> ControlFlow?
    }

    Options for query execution; currently a progress callback that can cancel the execution by returning Break.

    QueryCursorOptions::new

    Create query cursor options.

    QueryCursorState

    pub struct QueryCursorState {
    // private fields
    }

    The state of a query cursor passed to a query progress callback.

    QueryCursorState::current_byte_offset

    fn QueryCursorState::current_byte_offset(self : QueryCursorState) -> Int

    The byte offset the query execution has reached.

    QueryErrorKind

    pub(all) enum QueryErrorKind {
    Syntax
    NodeType
    Field
    Capture
    Predicate
    Structure
    Language
    } derive(Eq,
    Debug
    )

    The kind of a [QueryError].

    QueryMatch

    pub struct QueryMatch {
    pattern_index : Int
    // private fields
    }

    A match of a [Query] to a particular set of [Node]s.
    impl Debug for QueryMatch

    QueryMatch::captures

    fn QueryMatch::captures(self : QueryMatch) -> ArrayView[QueryCapture]

    The captures of this match.

    QueryMatch::id

    fn QueryMatch::id(self : QueryMatch) -> UInt

    The id of this match.

    QueryMatch::nodes_for_capture_index

    fn QueryMatch::nodes_for_capture_index(self : QueryMatch, capture_ix : Int) -> Iter[Node]

    The nodes captured with the given capture index, in order.

    QueryMatch::remove

    fn QueryMatch::remove(self : QueryMatch) -> Unit

    Remove this match from its cursor's pending results.

    QueryMatch::satisfies_text_predicates

    fn[T : TextProvider] QueryMatch::satisfies_text_predicates(self : QueryMatch, query : Query, text_provider : T) -> Bool

    Check the text predicates (#eq?, #match?, #any-of? and their variants) of this match's pattern against the text of the captured nodes.

    For a quantified capture, eq?/match?/not-eq?/not-match? must hold for every captured node, while the any- variants need one node; #eq? between two captures compares their nodes pairwise and fails when the counts differ; #any-of? must hold for every node.

    QueryMatches

    pub struct QueryMatches[T] {
    // private fields
    }

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

    QueryMatches::iter

    Iterate the remaining matches.

    QueryMatches::next

    fn[T : TextProvider] QueryMatches::next(self : QueryMatches[T]) -> QueryMatch?

    Advance to the next match whose text predicates are satisfied.

    QueryMatches::set_byte_range

    fn[T] QueryMatches::set_byte_range(self : QueryMatches[T], start : Int, end : Int) -> Unit

    Set the byte range in which the remaining matches are searched.

    QueryMatches::set_point_range

    fn[T] QueryMatches::set_point_range(self : QueryMatches[T], start : Point, end : Point) -> Unit

    Set the point range in which the remaining matches are searched.

    QueryPredicate

    pub(all) struct QueryPredicate {
    operator : String
    args : Array[QueryPredicateArg]
    } derive(Eq,
    Debug
    )

    A predicate with a user-defined operator associated with a particular pattern in a [Query].

    QueryPredicateArg

    pub(all) enum QueryPredicateArg {
    Capture(Int)
    String(String)
    } derive(Eq,
    Debug
    )

    An argument of a [QueryPredicate]: a capture index or a string.

    QueryProperty

    pub(all) struct QueryProperty {
    key : String
    value : String?
    capture_id : Int?
    } derive(Eq,
    Debug
    )

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

    QueryProperty::new

    fn QueryProperty::new(key : String, value : String?, capture_id : Int?) -> QueryProperty

    Create a query property.

    Range

    pub(all) struct Range {
    start_byte : Int
    end_byte : Int
    start_point : Point
    end_point : Point
    } derive(Eq, Hash,
    Debug
    )

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

    TextCallback

    pub struct TextCallback {
    // private fields
    }

    A [TextProvider] backed by a function from a node to its text chunks (upstream implements TextProvider for such closures directly).

    TextCallback::new

    fn TextCallback::new(f : (Node) -> Iter[BytesView]) -> TextCallback

    Wrap a function from a node to its text chunks.

    Tree

    pub struct Tree {
    // private fields
    }

    A tree that represents the syntactic structure of a source code file.
    impl Debug for Tree

    Tree::changed_ranges

    fn Tree::changed_ranges(self : Tree, other : Tree) -> Array[Range]

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

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

    Tree::clone

    fn Tree::clone(self : Tree) -> Tree

    Create a shallow copy of the syntax tree. This is very fast; the copy can be edited independently of the original.

    Tree::edit

    fn Tree::edit(self : Tree, edit : InputEdit) -> Unit

    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.

    Tree::included_ranges

    fn Tree::included_ranges(self : Tree) -> Array[Range]

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

    Tree::language

    fn Tree::language(self : Tree) -> Language

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

    Tree::print_dot_graph

    fn[W : DotGraphOutput] Tree::print_dot_graph(self : Tree, output : W) -> Unit

    Print a graph of the tree to the given output. 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.

    Tree::raw

    The runtime tree wrapped by this tree.

    Tree::root_node

    fn Tree::root_node(self : Tree) -> Node

    Get the root node of the syntax tree.

    Tree::root_node_with_offset

    fn Tree::root_node_with_offset(self : Tree, offset_bytes : Int, offset_extent : Point) -> Node

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

    Tree::walk

    fn Tree::walk(self : Tree) -> TreeCursor

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

    TreeCursor

    pub struct TreeCursor {
    // private fields
    }

    A stateful object for walking a syntax [Tree] efficiently.

    TreeCursor::clone

    fn TreeCursor::clone(self : TreeCursor) -> TreeCursor

    Create an independent copy of this cursor at the same position.

    TreeCursor::depth

    fn TreeCursor::depth(self : TreeCursor) -> Int

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

    TreeCursor::descendant_index

    fn TreeCursor::descendant_index(self : TreeCursor) -> Int

    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.

    TreeCursor::field_id

    fn TreeCursor::field_id(self : TreeCursor) -> Int?

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

    See also field_name.

    TreeCursor::field_name

    fn TreeCursor::field_name(self : TreeCursor) -> String?

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

    TreeCursor::goto_descendant

    fn TreeCursor::goto_descendant(self : TreeCursor, descendant_index : Int) -> Unit

    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.

    TreeCursor::goto_first_child

    fn TreeCursor::goto_first_child(self : TreeCursor) -> 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.

    TreeCursor::goto_first_child_for_byte

    fn TreeCursor::goto_first_child_for_byte(self : TreeCursor, index : Int) -> Int?

    Move this cursor to the first child of its current node that contains or starts after the given byte offset.

    This returns the index of the child node if one was found, and returns None if no such child was found.

    TreeCursor::goto_first_child_for_point

    fn TreeCursor::goto_first_child_for_point(self : TreeCursor, point : Point) -> Int?

    Move this cursor to the first child of its current node that contains or starts after the given point.

    This returns the index of the child node if one was found, and returns None if no such child was found.

    TreeCursor::goto_last_child

    fn TreeCursor::goto_last_child(self : TreeCursor) -> 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 goto_first_child because it needs to iterate through all the children to compute the child's position.

    TreeCursor::goto_next_sibling

    fn TreeCursor::goto_next_sibling(self : TreeCursor) -> 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 node the cursor was constructed with is considered the root of the cursor, and the cursor cannot walk outside this node.

    TreeCursor::goto_parent

    fn TreeCursor::goto_parent(self : TreeCursor) -> 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 node the cursor was constructed with is considered the root of the cursor, and the cursor cannot walk outside this node.

    TreeCursor::goto_previous_sibling

    fn TreeCursor::goto_previous_sibling(self : TreeCursor) -> 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 goto_next_sibling due to how node positions are stored. In the worst case, this will need to iterate through all the children up to 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.

    TreeCursor::node

    fn TreeCursor::node(self : TreeCursor) -> Node

    Get the tree cursor's current [Node].

    TreeCursor::reset

    fn TreeCursor::reset(self : TreeCursor, node : Node) -> Unit

    Re-initialize this tree cursor to start at the given node.

    TreeCursor::reset_to

    fn TreeCursor::reset_to(self : TreeCursor, cursor : TreeCursor) -> Unit

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

    Unlike reset, this will not lose parent information and allows reusing already created cursors.

    format_sexp

    fn format_sexp(sexp : String, initial_indent_level : Int) -> String

    Pretty-print an S-expression produced by [Node::to_sexp], one node per line, indenting nested nodes by two spaces per level starting at initial_indent_level (upstream's {:#} formatting of a node).

    language_version

    let language_version : Int

    The latest ABI version that is supported by the current version of the library.

    When Languages are generated by the Tree-sitter CLI, they are assigned an ABI version number that corresponds to the current CLI version. The Tree-sitter library is generally backwards-compatible with languages generated using older CLI versions, but is not forwards-compatible.

    min_compatible_language_version

    let min_compatible_language_version : Int

    The earliest ABI version that is supported by the current version of the library.