Dart API Reference
Dart API Reference v1.15.7
Section titled “Dart API Reference v1.15.7”Functions
Section titled “Functions”detectLanguageFromExtension()
Section titled “detectLanguageFromExtension()”Detect language name from a file extension (without leading dot).
Returns null for unrecognized extensions. The match is case-insensitive.
Signature:
Future<String?> detectLanguageFromExtension(String ext)Example:
final result = detectLanguageFromExtension("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
ext |
String |
Yes | The ext |
Returns: String?
detectLanguageFromPath()
Section titled “detectLanguageFromPath()”Detect language name from a file path.
Extracts the file extension and looks it up. Returns null if the
path has no extension or the extension is not recognized.
Signature:
Future<String?> detectLanguageFromPath(String path)Example:
final result = detectLanguageFromPath("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
String |
Yes | Path to the file |
Returns: String?
detectLanguageFromContent()
Section titled “detectLanguageFromContent()”Detect language name from file content using the shebang line (#!).
Inspects only the first line of content. If it begins with #!, the
interpreter name is extracted and mapped to a language name.
Handles common patterns:
#!/usr/bin/env python3→"python"#!/bin/bash→"bash"#!/usr/bin/env node→"javascript"
The -S flag accepted by some env implementations is skipped automatically.
Version suffixes (e.g. python3.11, ruby3.2) are stripped before matching.
A leading UTF-8 BOM (U+FEFF) is skipped before the #! check, so a
BOM-prefixed script is still detected by its shebang.
Returns null when content does not start with #! (after stripping a
leading BOM), the shebang is malformed, or the interpreter is not recognised.
Signature:
Future<String?> detectLanguageFromContent(String content)Example:
final result = detectLanguageFromContent("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
String |
Yes | The content to process |
Returns: String?
getHighlightsQuery()
Section titled “getHighlightsQuery()”Get the highlights query for a language, if bundled.
Returns the contents of highlights.scm as a static string, or null
if no highlights query is bundled for this language.
Signature:
Future<String?> getHighlightsQuery(String language)Example:
final result = getHighlightsQuery("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
language |
String |
Yes | The language |
Returns: String?
getInjectionsQuery()
Section titled “getInjectionsQuery()”Get the injections query for a language, if bundled.
Returns the contents of injections.scm as a static string, or null
if no injections query is bundled for this language.
Signature:
Future<String?> getInjectionsQuery(String language)Example:
final result = getInjectionsQuery("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
language |
String |
Yes | The language |
Returns: String?
getLocalsQuery()
Section titled “getLocalsQuery()”Get the locals query for a language, if bundled.
Returns the contents of locals.scm as a static string, or null
if no locals query is bundled for this language.
Signature:
Future<String?> getLocalsQuery(String language)Example:
final result = getLocalsQuery("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
language |
String |
Yes | The language |
Returns: String?
getTagsQuery()
Section titled “getTagsQuery()”Get the tags query for a language, if bundled.
Returns the contents of tags.scm as a static string, or null
if no tags query is bundled for this language.
Signature:
Future<String?> getTagsQuery(String language)Example:
final result = getTagsQuery("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
language |
String |
Yes | The language |
Returns: String?
getIndentsQuery()
Section titled “getIndentsQuery()”Get the indents query for a language, if bundled.
Returns the contents of indents.scm (used for auto-indentation) as a static
string, or null if no indents query is bundled for this language.
Signature:
Future<String?> getIndentsQuery(String language)Example:
final result = getIndentsQuery("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
language |
String |
Yes | The language |
Returns: String?
getFoldsQuery()
Section titled “getFoldsQuery()”Get the folds query for a language, if bundled.
Returns the contents of folds.scm (used for code folding) as a static string,
or null if no folds query is bundled for this language.
Signature:
Future<String?> getFoldsQuery(String language)Example:
final result = getFoldsQuery("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
language |
String |
Yes | The language |
Returns: String?
getLanguage()
Section titled “getLanguage()”Get a tree-sitter Language by name using the global registry.
Resolves language aliases (e.g., "shell" maps to "bash").
When the download feature is enabled (default), automatically downloads
the parser from GitHub releases if not found locally.
Errors:
Returns Error.LanguageNotFound if the language is not recognized,
or Error.Download if auto-download fails.
Signature:
Future<Language> getLanguage(String name)Example:
final result = getLanguage("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: Language
Errors: Throws Error.
getParser()
Section titled “getParser()”Get a Parser pre-configured for the given language.
This is a convenience function that calls get_language and configures
a new parser in one step.
Errors:
Returns Error.LanguageNotFound if the language is not recognized, or
Error.ParserSetup if the language cannot be applied to the parser.
Signature:
Future<Parser> getParser(String name)Example:
final result = getParser("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: Parser
Errors: Throws Error.
detectLanguage()
Section titled “detectLanguage()”Detect language name from a file path or extension.
This compatibility alias matches the pre-Alef Python binding API.
Signature:
Future<String?> detectLanguage(String path)Example:
final result = detectLanguage("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
String |
Yes | Path to the file |
Returns: String?
availableLanguages()
Section titled “availableLanguages()”List all available language names (sorted, deduplicated, includes aliases).
Returns names of both statically compiled and dynamically loadable languages, plus any configured aliases.
Signature:
Future<List<String>> availableLanguages()Example:
final result = availableLanguages();Returns: List<String>
hasLanguage()
Section titled “hasLanguage()”Check if a language is available by name or alias.
Returns true if the language can be loaded (statically compiled,
dynamically available, or a known alias for one of these).
Signature:
Future<bool> hasLanguage(String name)Example:
final result = hasLanguage("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: bool
languageCount()
Section titled “languageCount()”Return the number of available languages.
Includes statically compiled languages, dynamically loadable languages, and aliases.
Signature:
Future<PlatformInt64> languageCount()Example:
final result = languageCount();Returns: PlatformInt64
process()
Section titled “process()”Process source code and extract file intelligence using the global registry.
Parses the source with tree-sitter and extracts metrics, structure, imports,
exports, comments, docstrings, symbols, diagnostics, and/or chunks based on
the flags set in ProcessConfig.
Errors:
Returns Error.InvalidRange if the config carries a zero-valued limit or
the source exceeds ProcessConfig.max_source_bytes,
Error.ParseTimeout if the parse exceeds
ProcessConfig.parse_timeout_ms, Error.LanguageNotFound if the
language is unknown, or Error.ParseFailed if parsing yields no tree.
Signature:
Future<ProcessResult> process(String source, ProcessConfig config)Example:
final result = process("value", ProcessConfig());Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
source |
String |
Yes | The source |
config |
ProcessConfig |
Yes | The configuration options |
Returns: ProcessResult
Errors: Throws Error.
init()
Section titled “init()”Initialize the language pack with the given configuration.
Applies any custom cache directory, then downloads all languages and groups specified in the config. This is the recommended entry point when you want to pre-warm the cache before use.
Errors:
Returns an error if configuration cannot be applied or if downloads fail.
Signature:
Future<void> init(PackConfig config)Example:
init(PackConfig());Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
config |
PackConfig |
Yes | The configuration options |
Returns: No return value.
Errors: Throws Error.
configure()
Section titled “configure()”Apply download configuration without downloading anything.
Use this to set a custom cache directory before the first call to
get_language or any download function. Changing the cache dir
after languages have been registered has no effect on already-loaded
languages.
PackConfig.cache_dir is a BASE directory, not the final libs path: this
crate appends tree-sitter-language-pack/v{version}/libs to it, the same
suffix applied to the platform default cache directory. In the example below,
files actually land under /tmp/my-parsers/tree-sitter-language-pack/v{version}/libs/,
never directly in /tmp/my-parsers/. Call cache_dir to read back the
resolved, fully-suffixed path.
Errors:
Returns an error if the lock cannot be acquired.
Signature:
Future<void> configure(PackConfig config)Example:
configure(PackConfig());Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
config |
PackConfig |
Yes | The configuration options |
Returns: No return value.
Errors: Throws Error.
download()
Section titled “download()”Download specific languages to the local cache.
Returns the number of distinct languages available after the call. Already compiled or cached languages are included in the count.
Aliases are resolved before counting, so ["shell", "bash"] names one
language and returns 1.
Errors:
Returns an error if any language is not available in the manifest or if the download fails.
Signature:
Future<PlatformInt64> download(List<String> names)Example:
final result = download([]);Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
names |
List<String> |
Yes | The names |
Returns: PlatformInt64
Errors: Throws Error.
prefetch()
Section titled “prefetch()”Prefetch grammars: download any not already loadable from disk, then load every requested language into the process registry so a subsequent hot loop only parses.
Unlike download(), this does not trust in-memory availability — it downloads
whenever a grammar is not actually loadable from disk (fixing the case where a
known-but-not-downloaded grammar is reported present), then resolves and caches
every requested language. Call it once, up front, before a parallel workload.
Errors:
Returns Error.Download if a required grammar cannot be fetched, or
Error.LanguageNotFound if a requested name is unknown.
Signature:
Future<void> prefetch(List<String> languages)Example:
prefetch([]);Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
languages |
List<String> |
Yes | The languages |
Returns: No return value.
Errors: Throws Error.
downloadAll()
Section titled “downloadAll()”Download all available languages from the remote manifest.
Downloads the platform bundle and extracts every library it contains. Languages that appear in the manifest but are absent from the bundle (e.g. grammars that failed to compile at release time) are silently skipped — they are not treated as an error.
Returns the total number of languages now available (statically compiled plus downloaded and cached).
Errors:
Returns an error if the manifest cannot be fetched or the bundle download fails.
Signature:
Future<PlatformInt64> downloadAll()Example:
final result = downloadAll();Returns: PlatformInt64
Errors: Throws Error.
downloadGroup()
Section titled “downloadGroup()”Download every language in a named group.
Groups are defined by the remote manifest, not by this library, and let you
ensure a curated set of related grammars in one call instead of listing each
name to download(). Already-cached languages are skipped.
Call manifest_groups to discover the group names the manifest actually
defines. The published manifest currently defines a single group, "all";
earlier revisions of this documentation advertised "web", "data", and
"systems", which the manifest has never contained, so every call following
that example failed. Do not hardcode a group name without checking.
Returns the total number of languages now available (statically compiled plus downloaded and cached).
Errors:
Returns Error.Download if the manifest cannot be fetched, if the group
is unknown — the message lists the groups the manifest defines — or if any
constituent language fails to download.
Signature:
Future<PlatformInt64> downloadGroup(String name)Example:
final result = downloadGroup("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: PlatformInt64
Errors: Throws Error.
manifestLanguages()
Section titled “manifestLanguages()”Return all language names available in the remote manifest (371).
Fetches (and caches) the remote manifest to discover the full list of
downloadable languages. Use downloaded_languages to list what is
already cached locally.
Errors:
Returns an error if the manifest cannot be fetched.
Signature:
Future<List<String>> manifestLanguages()Example:
final result = manifestLanguages();Returns: List<String>
Errors: Throws Error.
manifestGroups()
Section titled “manifestGroups()”Return the names of every language group the remote manifest defines, sorted.
Group names are manifest data, not a compile-time constant of this library, so
this is the only reliable way to learn what download_group and
PackConfig.groups accept. The published manifest currently defines just
"all".
Errors:
Returns Error.Download if the manifest cannot be fetched.
Signature:
Future<List<String>> manifestGroups()Example:
final result = manifestGroups();Returns: List<String>
Errors: Throws Error.
downloadedLanguages()
Section titled “downloadedLanguages()”Return languages that are already downloaded and cached locally.
Does not perform any network requests. Returns an empty list if the cache directory does not exist or cannot be read.
Signature:
Future<List<String>> downloadedLanguages()Example:
final result = downloadedLanguages();Returns: List<String>
cleanCache()
Section titled “cleanCache()”Delete all cached parser shared libraries.
Resets the cache registration so the next call to get_language or
a download function will re-register the (now empty) cache directory.
Errors:
Returns an error if the cache directory cannot be removed.
Signature:
Future<void> cleanCache()Example:
cleanCache();Returns: No return value.
Errors: Throws Error.
cacheDir()
Section titled “cacheDir()”Return the effective cache directory path.
This is {base}/tree-sitter-language-pack/v{version}/libs/, where {base} is
either the custom BASE directory set via configure / init
(PackConfig.cache_dir) or the platform default cache directory — both are
suffixed identically, so a custom cache_dir is never used as the final libs
path. The default resolves to ~/.cache/tree-sitter-language-pack/v{version}/libs/
on a typical Unix system.
Errors:
Returns an error if no cache directory can be resolved: version is somehow
invalid, or (with no custom cache_dir configured) the platform reports none
and TREE_SITTER_LANGUAGE_PACK_CACHE_DIR is unset. This crate no longer falls
back to the temporary directory for the latter case — see #101 H2.
Signature:
Future<String> cacheDir()Example:
final result = cacheDir();Returns: String
Errors: Throws Error.
ByteRange
Section titled “ByteRange”A byte range — start (inclusive) to end (exclusive).
| Field | Type | Default | Description |
|---|---|---|---|
start |
PlatformInt64 |
— | Inclusive start byte offset. |
end |
PlatformInt64 |
— | Exclusive end byte offset. |
ChunkContext
Section titled “ChunkContext”Metadata for a single chunk of source code.
| Field | Type | Default | Description |
|---|---|---|---|
language |
String |
— | Language name used to parse this chunk. |
chunkIndex |
PlatformInt64 |
— | Zero-indexed position of this chunk within the file’s chunk list. |
totalChunks |
PlatformInt64 |
— | Total number of chunks the file was split into. |
nodeTypes |
List<String> |
[] |
Tree-sitter node kinds that appear at the top level of this chunk. |
contextPath |
List<String> |
[] |
Hierarchical path of enclosing structural items (e.g., ["MyClass", "my_method"]). |
symbolsDefined |
List<String> |
[] |
Names of symbols defined within this chunk. |
comments |
List<CommentInfo> |
[] |
Comments contained within this chunk. |
docstrings |
List<DocstringInfo> |
[] |
Docstrings contained within this chunk. Populated only for Python — the same language for which ProcessResult.docstrings is populated, and by the same classifier. Always empty for every other language. |
hasErrorNodes |
bool |
— | Whether this chunk contains any tree-sitter error nodes. |
CodeChunk
Section titled “CodeChunk”A chunk of source code with rich metadata.
| Field | Type | Default | Description |
|---|---|---|---|
content |
String |
— | The raw source text of this chunk. |
startByte |
PlatformInt64 |
— | Inclusive start byte offset of this chunk in the original source. |
endByte |
PlatformInt64 |
— | Exclusive end byte offset of this chunk in the original source. |
startLine |
PlatformInt64 |
— | Zero-indexed start line of this chunk. |
endLine |
PlatformInt64 |
— | Zero-indexed row of the last byte actually included in this chunk (inclusive — the same row a Span.end_line would report for a node ending on that byte). Computed the same way regardless of whether the source has a trailing newline: it is always the row of end_byte - 1, never a phantom row past the file’s real content. |
metadata |
ChunkContext |
— | Contextual metadata about this chunk. |
CommentInfo
Section titled “CommentInfo”A comment extracted from source code.
| Field | Type | Default | Description |
|---|---|---|---|
text |
String |
— | The raw text content of the comment. |
kind |
CommentKind |
CommentKind.Line |
The kind of comment (line, block, or doc). |
span |
Span |
— | Source span covering the comment. |
associatedNode |
String? |
null |
Name of the syntax node this comment is directly associated with. |
DataAttribute
Section titled “DataAttribute”An XML-style attribute attached to an Element node.
Populated only for DataNodeKind.Element; always empty for KeyValue and
Sequence nodes.
| Field | Type | Default | Description |
|---|---|---|---|
name |
String |
— | Attribute name (e.g. "class", "href"). |
value |
String |
— | Attribute value as a raw string (quotes stripped). |
span |
Span |
— | Source span covering the entire name="value" attribute token. |
DataNode
Section titled “DataNode”A node in the hierarchical data tree produced by data-format extraction.
When ProcessConfig.data_extraction is
true, ProcessResult.data is populated with a root DataNode whose
children mirror the structure of the parsed file.
The kind field determines which other fields are meaningful:
kind |
key |
value |
attributes |
children |
|---|---|---|---|---|
KeyValue |
key / mapping key / index | leaf value | empty | nested map |
Element |
XML tag name | text content | XML attrs | child elements |
Sequence |
positional index ("0") |
leaf value | empty | sub-items |
| Field | Type | Default | Description |
|---|---|---|---|
kind |
DataNodeKind |
DataNodeKind.KeyValue |
Whether this node is a key/value pair, XML element, or sequence item. |
key |
String? |
null |
Key, attribute name, tag name, or positional index ("0", "1", …). null at the document root. |
value |
String? |
null |
Leaf scalar value, if any. null for containers (objects, arrays, XML elements with child elements). |
attributes |
List<DataAttribute> |
[] |
Attributes on element-shape nodes (XML STag attributes). Empty for all other kinds. |
children |
List<DataNode> |
[] |
Children for nested containers and XML element bodies. |
span |
Span |
— | Source span covering this node in the original source file. |
Diagnostic
Section titled “Diagnostic”A diagnostic (syntax error, missing node, etc.) from parsing.
| Field | Type | Default | Description |
|---|---|---|---|
message |
String |
— | Human-readable description of the diagnostic. |
severity |
DiagnosticSeverity |
DiagnosticSeverity.Error |
Severity of the diagnostic. |
span |
Span |
— | Source span where the diagnostic was detected. |
DocSection
Section titled “DocSection”A section within a docstring (e.g., Args, Returns, Raises).
| Field | Type | Default | Description |
|---|---|---|---|
kind |
String |
— | Section kind (e.g., "args", "returns", "raises"). |
name |
String? |
null |
Parameter or return value name, if applicable. |
description |
String |
— | Description text for this section. |
DocstringInfo
Section titled “DocstringInfo”A docstring extracted from source code.
| Field | Type | Default | Description |
|---|---|---|---|
text |
String |
— | The raw text of the docstring. |
format |
DocstringFormat |
DocstringFormat.PythonTripleQuote |
The docstring format (Python, JSDoc, Rustdoc, etc.). |
span |
Span |
— | Source span covering the docstring. |
associatedItem |
String? |
null |
Name of the item this docstring documents. |
parsedSections |
List<DocSection> |
[] |
Parsed sections of the docstring (Args, Returns, Raises, etc.). Reserved: not yet populated. Always empty, for every DocstringFormat. Parsing a docstring body into sections requires implementing each convention’s own layout (Google/NumPy/reST style for Python, @param/@returns for JSDoc/Javadoc, and so on), which no extractor here does yet. The field is kept rather than removed so a consumer’s deserializer does not need updating once it is. |
DownloadManager
Section titled “DownloadManager”Manages downloading and caching of pre-built parser shared libraries.
Methods
Section titled “Methods”create()
Section titled “create()”Create a new download manager for the given version.
Errors:
Returns Error.Download if version is empty, contains a path
separator or .., or contains a character outside [A-Za-z0-9.+-] — see
validate_version — or if no cache directory can be resolved (see
Self.default_cache_dir).
Signature:
static Future<DownloadManager> create(String version)Example:
final result = DownloadManager.create("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
version |
String |
Yes | The version |
Returns: DownloadManager
Errors: Throws Error.
installedLanguages()
Section titled “installedLanguages()”List languages that are already downloaded and cached.
Derived from the on-disk cache filenames, one canonical name per file, plus
every alias that resolves to it (via aliases_for) — so
this list agrees with the user-facing
LanguageRegistry.available_languages
about which names are “available”; both report "shell" once bash is
cached, for example. A previous version reported canonical names only,
which could never agree with available_languages(). See #107.
Returns an empty list if the cache directory does not exist. If it exists
but cannot be read (e.g. a permission error), also returns an empty list —
changing this to a Result would be a breaking change across every
language binding — but logs a tracing.warn! so the failure is not
silently indistinguishable from “nothing installed”.
Signature:
Future<List<String>> installedLanguages()Example:
final result = instance.installedLanguages();Returns: List<String>
downloadAllBestEffort()
Section titled “downloadAllBestEffort()”Download the platform bundle and extract every library file it contains.
Unlike Self.ensure_languages, this does not check the manifest language list
against archive contents — it simply extracts all .so/.dylib/.dll files
from the bundle. Languages in the manifest that are missing from the archive
are silently ignored rather than returning an error.
Returns the number of library files extracted (including those already cached).
Signature:
Future<PlatformInt64> downloadAllBestEffort()Example:
final result = instance.downloadAllBestEffort();Returns: PlatformInt64
Errors: Throws Error.
cleanCache()
Section titled “cleanCache()”Remove all cached parser libraries.
Acquires the cross-process lock so clean_cache cannot race a concurrent
downloader (avoids Windows sharing-violation errors against an in-flight
bundle write). The .download.lock file itself is not removed — it is
permanent infrastructure; deleting it could allow a concurrent process that
already opened the file to continue holding a stale lock handle while a new
process opens a fresh inode, breaking the mutual-exclusion guarantee.
Signature:
Future<void> cleanCache()Example:
instance.cleanCache();Returns: No return value.
Errors: Throws Error.
ExportInfo
Section titled “ExportInfo”An export statement extracted from source code.
| Field | Type | Default | Description |
|---|---|---|---|
name |
String |
— | The exported name. |
kind |
ExportKind |
ExportKind.Named |
The kind of export (named, default, or re-export). |
span |
Span |
— | Source span covering the export statement. |
FileMetrics
Section titled “FileMetrics”Aggregate metrics for a source file.
| Field | Type | Default | Description |
|---|---|---|---|
totalLines |
PlatformInt64 |
— | Total number of lines (including blank and comment lines). |
codeLines |
PlatformInt64 |
— | Number of lines containing non-blank, non-comment source code. |
commentLines |
PlatformInt64 |
— | Number of lines that are entirely comments. |
blankLines |
PlatformInt64 |
— | Number of blank (whitespace-only) lines. |
totalBytes |
PlatformInt64 |
— | Total byte length of the source file. |
nodeCount |
PlatformInt64 |
— | Total number of nodes in the syntax tree. |
errorCount |
PlatformInt64 |
— | Number of error nodes in the syntax tree (parse errors). |
maxDepth |
PlatformInt64 |
— | Maximum nesting depth reached in the syntax tree. |
ImportInfo
Section titled “ImportInfo”An import statement extracted from source code.
| Field | Type | Default | Description |
|---|---|---|---|
source |
String |
— | The module or path being imported from. |
items |
List<String> |
[] |
Specific names imported from the source module. For import a, b / from m import a, b, every entry’s base name (never the alias). For a JavaScript/TypeScript named-imports clause (import { a, b as c } from 'm'), every specifier’s original name. Populated for Python and JavaScript/TypeScript only. Always empty for every other language this library recognises import statements for — Rust, Go, Java, Kotlin, and Elixir (import/alias/require/use) — and for a JS/TS namespace import (import * as ns) or default import (import x from 'm'), neither of which names individual items. |
alias |
String? |
null |
Alias assigned to the import (e.g., import numpy as np). Populated for Python’s single-name form (import numpy as np, from m import a as b) and JavaScript/TypeScript’s namespace form (import * as ns from 'm') or a named-imports clause naming exactly one specifier (import { a as b } from 'm'). null for Rust, Go, Java, Kotlin, and Elixir (which has its own as: alias option on alias directives, not yet extracted here) — and for a Python statement that aliases several names at once (import os, sys as s), where there is no single alias to report for the statement as a whole, so only items is populated for it. |
isWildcard |
bool |
— | Whether this is a wildcard import (e.g., import * or use foo.*). Detected from the syntax tree — a dedicated wildcard node (wildcard_import in Python, use_wildcard in Rust) or a bare * token outside of string-literal content — not by searching the import’s source text for a * character, so a glob in an import path string (import a from './glob*.js') is not mistaken for one. |
span |
Span |
— | Source span covering the import statement. |
Language
Section titled “Language”LanguageRegistry
Section titled “LanguageRegistry”Thread-safe registry of tree-sitter language parsers.
Manages both statically compiled and dynamically loaded language grammars.
Use LanguageRegistry.new() for the default registry, or access the
global instance via the module-level convenience functions
(get_language, available_languages, etc.).
Methods
Section titled “Methods”create()
Section titled “create()”Create a new registry populated with all statically compiled languages.
When the dynamic-loading feature is enabled, the registry also knows
about dynamically loadable grammars and will load them on demand.
Signature:
static Future<LanguageRegistry> create()Example:
final result = LanguageRegistry.create();Returns: LanguageRegistry
getLanguage()
Section titled “getLanguage()”Get a tree-sitter Language by name.
Resolves aliases (e.g., "shell" -> "bash", "makefile" -> "make"),
then looks up the language in the static table. When the dynamic-loading
feature is enabled, falls back to loading a shared library on demand.
Errors:
Returns Error.LanguageNotFound if the name (after alias resolution)
does not match any known grammar.
Signature:
Future<Language> getLanguage(String name)Example:
final result = instance.getLanguage("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: Language
Errors: Throws Error.
availableLanguages()
Section titled “availableLanguages()”List all available language names, sorted and deduplicated.
Includes statically compiled languages, dynamically loadable languages
(if the dynamic-loading feature is enabled), and all configured aliases.
Signature:
Future<List<String>> availableLanguages()Example:
final result = instance.availableLanguages();Returns: List<String>
hasParser()
Section titled “hasParser()”Check whether this language can be parsed right now, without downloading.
Resolves aliases, then answers from exactly the lookup
get_language performs: the statically compiled
table, the already-loaded dynamic grammars, and the parser shared
libraries present in the primary and extra (download-cache) library
directories. It never performs network I/O.
A previous implementation consulted only the statically compiled table.
That table is empty in every build that does not set TSLP_LANGUAGES,
so the function answered false for languages this registry parses
perfectly well.
Contrast has_language, which is also true for a
grammar that is merely known to the manifest and would have to be
downloaded first. The pair distinguishes “we can parse it offline, now”
from “we recognise the name”.
The first true answer for a dynamic grammar loads its shared library:
loading is the only way to know the grammar is usable, since a truncated
or wrong-architecture library exists on disk but cannot parse. Loads are
cached process-wide, so repeat calls are cheap.
use tree_sitter_language_pack::{detect_language_from_extension, LanguageRegistry};
let registry = LanguageRegistry::new();// Extension detection uses the static ext table for all 371 grammars.let lang = detect_language_from_extension("feature"); // always returns Some("gherkin")// Parser availability depends on what is compiled in or cached on disk.let can_parse = lang.map(|name| registry.has_parser(name)).unwrap_or(false);Signature:
Future<bool> hasParser(String name)Example:
final result = instance.hasParser("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: bool
hasLanguage()
Section titled “hasLanguage()”Check whether a language is available by name or alias.
Returns true if the language can be loaded, either from the static
table or from a dynamic library on disk.
Every branch is one more way to answer true, so they are ordered
cheapest-first and the filesystem is only consulted once every in-memory
source has said no. Probing the loaded-grammar map and the manifest ahead
of the stat calls is what keeps this off the syscall path for the
languages a process actually uses.
Signature:
Future<bool> hasLanguage(String name)Example:
final result = instance.hasLanguage("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: bool
languageCount()
Section titled “languageCount()”Return the total number of available languages (including aliases).
Counts the same set available_languages
lists, without materialising or sorting it.
Signature:
Future<PlatformInt64> languageCount()Example:
final result = instance.languageCount();Returns: PlatformInt64
process()
Section titled “process()”Parse source code and extract file intelligence based on config in a single pass.
Errors:
Returns Error.InvalidRange if the config is invalid (see
ProcessConfig.validate) or if the source
exceeds the configured
max_source_bytes;
Error.LanguageNotFound if the language is unknown; or
Error.ParseFailed if parsing produces no tree.
Signature:
Future<ProcessResult> process(String source, ProcessConfig config)Example:
final result = instance.process("value", ProcessConfig());Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
source |
String |
Yes | The source |
config |
ProcessConfig |
Yes | The configuration options |
Returns: ProcessResult
Errors: Throws Error.
A single syntax node within a Tree.
Nodes hold a strong reference to their parent tree so they remain valid regardless of how the tree is moved or stored at the FFI boundary.
Methods
Section titled “Methods”kind()
Section titled “kind()”Return the node’s kind name (e.g. "function_definition").
Signature:
Future<String> kind()Example:
final result = instance.kind();Returns: String
kindId()
Section titled “kindId()”Return the node’s numeric kind ID.
Tree-sitter assigns a stable u16 ID to every node kind in a grammar
(e.g. "function_definition" → 42). Comparing kind_id() is cheaper
than comparing the string kind() in tight AST loops.
Signature:
Future<int> kindId()Example:
final result = instance.kindId();Returns: int
startByte()
Section titled “startByte()”Return the inclusive start byte offset of this node.
Signature:
Future<PlatformInt64> startByte()Example:
final result = instance.startByte();Returns: PlatformInt64
endByte()
Section titled “endByte()”Return the exclusive end byte offset of this node.
Signature:
Future<PlatformInt64> endByte()Example:
final result = instance.endByte();Returns: PlatformInt64
byteRange()
Section titled “byteRange()”Return the node’s byte range as a ByteRange.
Callers should slice their own source bytes — this is a zero-copy text accessor.
Signature:
Future<ByteRange> byteRange()Example:
final result = instance.byteRange();Returns: ByteRange
startPosition()
Section titled “startPosition()”Return the start Point (row, column).
Signature:
Future<Point> startPosition()Example:
final result = instance.startPosition();Returns: Point
endPosition()
Section titled “endPosition()”Return the end Point (row, column).
Signature:
Future<Point> endPosition()Example:
final result = instance.endPosition();Returns: Point
isNamed()
Section titled “isNamed()”True when this node is named (not punctuation/whitespace).
Signature:
Future<bool> isNamed()Example:
final result = instance.isNamed();Returns: bool
isError()
Section titled “isError()”True when this is an error node.
Signature:
Future<bool> isError()Example:
final result = instance.isError();Returns: bool
isMissing()
Section titled “isMissing()”True when this is a missing-token node.
Signature:
Future<bool> isMissing()Example:
final result = instance.isMissing();Returns: bool
isExtra()
Section titled “isExtra()”True when this is an “extra” node (e.g. a comment).
Signature:
Future<bool> isExtra()Example:
final result = instance.isExtra();Returns: bool
hasError()
Section titled “hasError()”True when this node or any descendant is an error.
Signature:
Future<bool> hasError()Example:
final result = instance.hasError();Returns: bool
parent()
Section titled “parent()”Return this node’s parent, if any.
Signature:
Future<Node?> parent()Example:
final result = instance.parent();Returns: Node?
child()
Section titled “child()”Return the i-th child of this node, if any.
Signature:
Future<Node?> child(int index)Example:
final result = instance.child(42);Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
index |
int |
Yes | The index |
Returns: Node?
childCount()
Section titled “childCount()”Total number of children (including unnamed).
Signature:
Future<PlatformInt64> childCount()Example:
final result = instance.childCount();Returns: PlatformInt64
namedChild()
Section titled “namedChild()”Return the i-th named child of this node, if any.
Signature:
Future<Node?> namedChild(int index)Example:
final result = instance.namedChild(42);Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
index |
int |
Yes | The index |
Returns: Node?
namedChildCount()
Section titled “namedChildCount()”Number of named children of this node.
Signature:
Future<PlatformInt64> namedChildCount()Example:
final result = instance.namedChildCount();Returns: PlatformInt64
childByFieldName()
Section titled “childByFieldName()”Look up a child by its grammar-defined field name.
Signature:
Future<Node?> childByFieldName(String name)Example:
final result = instance.childByFieldName("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: Node?
toSexp()
Section titled “toSexp()”Return the S-expression form of this node’s subtree.
Signature:
Future<String> toSexp()Example:
final result = instance.toSexp();Returns: String
walk()
Section titled “walk()”Return a TreeCursor positioned at this node.
Signature:
Future<TreeCursor> walk()Example:
final result = instance.walk();Returns: TreeCursor
PackConfig
Section titled “PackConfig”Configuration for the tree-sitter language pack.
Controls cache directory and which languages to pre-download. Can be loaded from a TOML file, constructed programmatically, or passed as a dict/object from language bindings.
| Field | Type | Default | Description |
|---|---|---|---|
cacheDir |
String? |
null |
Override the BASE directory the parser cache lives under. This is a base, not the final library path: the crate appends tree-sitter-language-pack/v{version}/libs to it, exactly as it does to the platform default. So cache_dir = "/tmp/my-parsers" resolves to /tmp/my-parsers/tree-sitter-language-pack/v{version}/libs/. The suffix is not cosmetic. It keeps the whole cache tree — manifest, bundles and lock file included — inside a directory this library owns and versions. Earlier releases used this path verbatim, which put those files in the configured directory’s PARENT and let a cache built by one crate version be reused by another. Default base: the platform cache dir, e.g. ~/.cache on Linux. |
languages |
List<String>? |
[] |
Languages to pre-download on init. Each entry is a language name (e.g. "python", "rust"). |
groups |
List<String>? |
[] |
Language groups to pre-download. Group names come from the remote manifest, so the valid set is not fixed by this library; the published manifest currently defines only "all". Call manifest_groups to enumerate them. An unknown name makes init fail. |
Parser
Section titled “Parser”A tree-sitter parser configured for one language at a time.
Methods
Section titled “Methods”create()
Section titled “create()”Construct a new parser with no language set and no parse limits.
Call Parser.set_language before parsing. Limits are opt-in via
set_max_source_bytes and
set_parse_timeout_ms; both default to
unbounded so that existing callers are unaffected.
Signature:
static Future<Parser> create()Example:
final result = Parser.create();Returns: Parser
setMaxSourceBytes()
Section titled “setMaxSourceBytes()”Refuse to parse sources longer than max_bytes.
null (the default) means no limit. Over-limit input makes
parse and parse_bytes return
null after emitting a WARN; input is never silently truncated.
See RECOMMENDED_MAX_SOURCE_BYTES.
Signature:
Future<void> setMaxSourceBytes({PlatformInt64? maxBytes})Example:
instance.setMaxSourceBytes(42);Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
maxBytes |
PlatformInt64? |
No | The max bytes |
Returns: No return value.
setParseTimeoutMs()
Section titled “setParseTimeoutMs()”Cancel a parse that exceeds timeout_ms milliseconds of wall clock.
null (the default) means no budget. Cancellation runs through
tree-sitter’s parse progress callback, so it is granular to that
callback’s interval rather than exact.
See RECOMMENDED_PARSE_TIMEOUT_MS.
Signature:
Future<void> setParseTimeoutMs({int? timeoutMs})Example:
instance.setParseTimeoutMs(42);Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
timeoutMs |
int? |
No | The timeout ms |
Returns: No return value.
setLanguage()
Section titled “setLanguage()”Configure the parser to use the language identified by name (e.g. "python").
Resolves the language through the global registry — auto-downloading
if necessary, when the download feature is enabled.
Errors:
Returns Error.LanguageNotFound if the language is not recognized,
or Error.ParserSetup if the language ABI is incompatible.
Signature:
Future<void> setLanguage(String name)Example:
instance.setLanguage("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: No return value.
Errors: Throws Error.
parse()
Section titled “parse()”Parse a UTF-8 source string.
Returns null if no language is set, if the parse was cancelled by the
configured timeout, or if the source
exceeds the configured size limit. Each
non-parse outcome is logged, so an empty result is never silent.
Concurrency
Section titled “Concurrency”Parsing runs fully in parallel across threads for almost every language — no lock is
taken. The exception is the small set of grammars whose external scanner keeps mutable
process-global state (currently just properties): parses of that language are
serialized against each other through an internal per-language lock, so that concurrent
threads can’t corrupt shared scanner state. Every other language is unaffected by that
lock and never waits on it.
Signature:
Future<Tree?> parse(String source)Example:
final result = instance.parse("value");Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
source |
String |
Yes | The source |
Returns: Tree?
parseBytes()
Section titled “parseBytes()”Parse a raw byte slice.
Same outcomes as parse, including the concurrency behaviour documented
there.
Signature:
Future<Tree?> parseBytes(Uint8List source)Example:
final result = instance.parseBytes(Uint8List.fromList([100, 97, 116, 97]));Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
source |
Uint8List |
Yes | The source |
Returns: Tree?
reset()
Section titled “reset()”Reset internal state. The next call to parse will
not be incremental.
Signature:
Future<void> reset()Example:
instance.reset();Returns: No return value.
A source position — row + column, zero-indexed.
| Field | Type | Default | Description |
|---|---|---|---|
row |
PlatformInt64 |
— | Zero-indexed row number. |
column |
PlatformInt64 |
— | Zero-indexed column, counted in bytes from the start of the row. This is tree_sitter.Point.column verbatim, and tree-sitter defines it as a byte offset — not characters, and not UTF-16 code units. Measured on a row of the form x = '<c>' where <c> is a single 4-byte character (an emoji), the string node reports columns 4..10, identical to its byte range; the character columns would be 4..7 and the UTF-16 columns 4..8. Anything that builds LSP positions (UTF-16) or editor caret columns (characters) from this field is silently wrong on every row containing a non-ASCII byte, and must re-measure the row against the source text instead. Earlier releases documented this field as UTF-16 code units; that was never what the value contained. |
ProcessConfig
Section titled “ProcessConfig”Configuration for the process() function.
Controls which analysis features are enabled and whether chunking is performed.
| Field | Type | Default | Description |
|---|---|---|---|
language |
String |
"" |
Language name (required). |
structure |
bool |
true |
Extract structural items (functions, classes, etc.). Default: true. |
imports |
bool |
true |
Extract import statements. Default: true. |
exports |
bool |
true |
Extract export statements. Default: true. |
comments |
bool |
false |
Extract comments. Default: false. |
docstrings |
bool |
false |
Extract docstrings. Default: false. |
symbols |
bool |
false |
Extract symbol definitions. Default: false. |
diagnostics |
bool |
false |
Include parse diagnostics. Default: false. |
chunkMaxSize |
PlatformInt64? |
null |
Maximum chunk size in bytes. null disables chunking. Some(0) is rejected by ProcessConfig.validate with Error.InvalidRange. A zero-sized chunk limit previously produced an empty chunk list and silently discarded the whole source; use null to mean “do not chunk”. |
dataExtraction |
bool |
false |
Extract hierarchical key/value data tree from data-format files. Default: false. When true, ProcessResult.data is populated with a DataNode tree for supported languages: JSON, YAML, TOML, .properties, HCL/HOCON, INI, editorconfig, KDL, CUE, CSV, PSV, PO, nginx config, Caddy config, XML, and DTD. For languages outside this set the field is left as null. |
maxSourceBytes |
PlatformInt64? |
null |
Reject source longer than this many bytes instead of parsing it. Default: null (unbounded). Tree-sitter allocates and walks proportionally to input size, so an unbounded parse of attacker-supplied input is a denial-of-service vector. The default stays unbounded for backward compatibility; services handling untrusted input should opt in, e.g. with RECOMMENDED_MAX_SOURCE_BYTES. Exceeding the limit fails the call with Error.InvalidRange — the source is never silently truncated. |
parseTimeoutMs |
int? |
null |
Wall-clock budget for the parse step, in milliseconds. Default: null (no timeout). Enforced through tree-sitter’s parse progress callback, which the parser invokes periodically; cancellation is therefore granular to that callback interval rather than exact. A parse that exceeds the budget fails with Error.ParseTimeout. |
ProcessResult
Section titled “ProcessResult”Complete analysis result from processing a source file.
Contains metrics, structural analysis, imports/exports, comments,
docstrings, symbols, diagnostics, and optionally chunked code segments.
Fields are populated based on the ProcessConfig flags.
| Field | Type | Default | Description |
|---|---|---|---|
language |
String |
— | The language name used to parse the source file. |
metrics |
FileMetrics |
— | File-level metrics (line counts, byte size, error count). |
structure |
List<StructureItem> |
[] |
Top-level structural items (functions, classes, etc.). |
imports |
List<ImportInfo> |
[] |
Import statements extracted from the source. |
exports |
List<ExportInfo> |
[] |
Export statements extracted from the source. |
comments |
List<CommentInfo> |
[] |
Comments extracted from the source. |
docstrings |
List<DocstringInfo> |
[] |
Docstrings extracted from the source. |
symbols |
List<SymbolInfo> |
[] |
Symbol definitions (variables, types, functions) extracted from the source. |
diagnostics |
List<Diagnostic> |
[] |
Parse diagnostics (syntax errors, missing nodes) from tree-sitter. |
chunks |
List<CodeChunk> |
[] |
Syntax-aware code chunks produced when chunking is enabled. |
data |
DataNode? |
null |
Hierarchical data tree extracted when config.data_extraction is true. Populated for supported data-format languages (JSON, YAML, TOML, properties, HCL, INI, XML, CSV, and more). null when data_extraction is false (the default) or when the language is not a recognised data format. See DataNode for the shape of the returned tree. |
Byte and line/column range in source code.
Represents both byte offsets (for slicing) and human-readable line/column positions (for display and diagnostics).
| Field | Type | Default | Description |
|---|---|---|---|
startByte |
PlatformInt64 |
— | Inclusive start byte offset in the source. |
endByte |
PlatformInt64 |
— | Exclusive end byte offset in the source. |
startLine |
PlatformInt64 |
— | Zero-indexed line number of the span’s start. |
startColumn |
PlatformInt64 |
— | Zero-indexed column of the span’s start, counted in bytes from the start of the line — not characters, not UTF-16 code units. |
endLine |
PlatformInt64 |
— | Zero-indexed line number of the span’s end. |
endColumn |
PlatformInt64 |
— | Zero-indexed column of the span’s end, counted in bytes from the start of the line — not characters, not UTF-16 code units. |
StructureItem
Section titled “StructureItem”A structural item (function, class, struct, etc.) in source code.
| Field | Type | Default | Description |
|---|---|---|---|
kind |
StructureKind |
StructureKind.Function |
The kind of structural item. |
name |
String? |
null |
The declared name of the item, if present. |
visibility |
String? |
null |
Visibility modifier (e.g., "pub", "public", "private"). |
span |
Span |
— | Source span covering the entire item declaration. |
children |
List<StructureItem> |
[] |
Nested structural items (e.g., methods within a class). |
decorators |
List<String> |
[] |
Decorator or attribute names applied to the item. Reserved: not yet populated. Always empty, for every language. Recognising a decorator requires per-language grammar knowledge (a Python decorated_definition wrapper, Java/C# annotations, Rust attributes each have a different shape), which no extractor here implements yet. The field is kept rather than removed so a consumer’s deserializer does not need updating once it is. |
docComment |
String? |
null |
Documentation comment attached to the item, if any. The text of the comment (or run of comments) immediately preceding the item, with no blank line in between, when that comment is classified as a doc comment. Multiple adjacent single-line doc comments (Rust ///) are joined with \n in source order. Populated for Rust (//////!), Java (/** */), and JavaScript/ TypeScript (/** */). null for every other language, and for a preceding comment that is not in doc-comment form (a plain # comment in Python, Ruby, or Elixir) — Python’s docstring convention is captured separately, as DocstringInfo, not through this field. |
signature |
String? |
null |
Full signature text of the item (e.g., function parameters and return type). The item’s own source text from its start up to the start of its body (see StructureItem.body_span), trimmed of trailing whitespace — for example fn add(a: i32, b: i32) -> i32 for a Rust function whose body is { a + b }. null only when that text is empty, which does not happen for any item StructureKind currently reports. Populated for every language and kind this library extracts structure for, since it is derived from body_span’s boundary rather than per-language syntax. |
bodySpan |
Span? |
null |
Source span covering only the body of the item, if distinct from the declaration. |
SymbolInfo
Section titled “SymbolInfo”A symbol (variable, function, type, etc.) extracted from source code.
| Field | Type | Default | Description |
|---|---|---|---|
name |
String |
— | The name of the symbol. |
kind |
SymbolKind |
SymbolKind.Variable |
The kind of symbol (variable, function, class, etc.). |
span |
Span |
— | Source span covering the symbol definition. |
typeAnnotation |
String? |
null |
Explicit type annotation, if present in the source. |
doc |
String? |
null |
Documentation comment immediately preceding this symbol, resolved by the same walk StructureItem.doc_comment uses (see doc_comment_at) — never hard-coded null. Populated for Rust (//////!), Java (/** */), and JavaScript/ TypeScript (/** */) — the languages whose comment classification recognizes a doc-kind comment. null for every other language (e.g. Python, Go, Ruby, which have no doc-kind comment classification), and also null when a symbol in a supported language simply has no doc comment immediately above it. |
A parsed syntax tree. Cheap to clone (refcount bump).
Methods
Section titled “Methods”rootNode()
Section titled “rootNode()”Return the root Node of this tree.
Signature:
Future<Node> rootNode()Example:
final result = instance.rootNode();Returns: Node
walk()
Section titled “walk()”Return a TreeCursor positioned at the root.
Signature:
Future<TreeCursor> walk()Example:
final result = instance.walk();Returns: TreeCursor
TreeCursor
Section titled “TreeCursor”A cursor for traversing a Tree.
Methods
Section titled “Methods”node()
Section titled “node()”Return the Node at the cursor’s current position.
Signature:
Future<Node> node()Example:
final result = instance.node();Returns: Node
gotoFirstChild()
Section titled “gotoFirstChild()”Move the cursor to the first child of the current node.
Returns true if a child existed.
Signature:
Future<bool> gotoFirstChild()Example:
final result = instance.gotoFirstChild();Returns: bool
gotoParent()
Section titled “gotoParent()”Move the cursor to the parent of the current node.
Returns true if a parent existed.
Signature:
Future<bool> gotoParent()Example:
final result = instance.gotoParent();Returns: bool
gotoNextSibling()
Section titled “gotoNextSibling()”Move the cursor to the next sibling of the current node.
Returns true if a sibling existed.
Signature:
Future<bool> gotoNextSibling()Example:
final result = instance.gotoNextSibling();Returns: bool
fieldName()
Section titled “fieldName()”Return the field name for the current node, if any.
Signature:
Future<String?> fieldName()Example:
final result = instance.fieldName();Returns: String?
DataNodeKind
Section titled “DataNodeKind”The kind of a data node extracted from a data-format file.
Classifies each node in the hierarchical DataNode tree returned when
data_extraction is enabled on ProcessConfig.
Wire format (public JSON contract)
Section titled “Wire format (public JSON contract)”Unit variants serialize as a bare string ("KeyValue"). DO NOT add
#[serde(tag = "...")] or rename variants — every language binding has a
hand-written deserializer matching this exact shape, and any change breaks
all bindings’ process() tests simultaneously.
Covered by tests/wire_format.rs.
| Value | Description |
|---|---|
KeyValue |
A key/value pair or mapping (json/toml/properties/yaml/hcl/cue/kdl pair, or a wrapper “object”/“mapping” container). |
Element |
An XML element with a tag name in key and attributes in attributes. |
Sequence |
A positional sequence item (JSON array element, YAML block sequence item, CSV/PSV row or cell). |
StructureKind
Section titled “StructureKind”The kind of structural item found in source code.
Categorizes top-level and nested declarations such as functions, classes,
structs, enums, traits, and more. Use Other for
language-specific constructs that do not fit a standard category.
Wire format (public JSON contract)
Section titled “Wire format (public JSON contract)”Unit variants serialize as a bare string ("Function"); the Other
variant serializes as a single-keyed object ({"Other": "macro"}). DO
NOT add #[serde(tag = "...")] or rename variants — every language
binding has a hand-written deserializer matching this exact shape, and
any change breaks all bindings’ process() tests simultaneously.
Covered by tests/wire_format.rs.
| Value | Description |
|---|---|
Function |
A free-standing or associated function. |
Method |
A method defined inside a class, struct, trait, or impl block. |
Class |
A class definition. |
Struct |
A struct definition. |
Interface |
An interface or protocol definition. |
Enum |
An enum definition. |
Module |
A module or package declaration. |
Trait |
A trait definition. |
Impl |
An impl block (Rust) or similar implementation block. |
Namespace |
A namespace declaration. |
Other |
A language-specific construct that does not fit any standard category. — Fields: 0: String |
CommentKind
Section titled “CommentKind”The kind of a comment found in source code.
Distinguishes between single-line comments, block (multi-line) comments, and documentation comments.
| Value | Description |
|---|---|
Line |
A single-line comment (e.g., // ... or # ...). |
Block |
A block or multi-line comment using slash-star delimiters. |
Doc |
A documentation comment such as /// ... or slash-double-star block. |
DocstringFormat
Section titled “DocstringFormat”The format of a docstring extracted from source code.
Identifies the docstring convention used, which varies by language
(e.g., Python triple-quoted strings, JSDoc, Rustdoc /// comments).
Wire format (public JSON contract)
Section titled “Wire format (public JSON contract)”Unit variants serialize as a bare string ("JSDoc"); the Other
variant serializes as a single-keyed object ({"Other": "rst"}). DO
NOT add #[serde(tag = "...")]. Covered by tests/wire_format.rs.
| Value | Description |
|---|---|
PythonTripleQuote |
Python triple-quoted string docstring ("""..."""). |
JsDoc |
JavaScript/TypeScript JSDoc block comment (opens with two stars, closes with star-slash). |
Rustdoc |
Rust /// or //! doc comment. |
GoDoc |
Go doc comment (a comment block immediately preceding a declaration). |
JavaDoc |
Java Javadoc block comment (opens with two stars, closes with star-slash). |
Other |
A language-specific docstring format not covered by the standard variants. — Fields: 0: String |
ExportKind
Section titled “ExportKind”The kind of an export statement found in source code.
Covers named exports, default exports, and re-exports from other modules.
| Value | Description |
|---|---|
Named |
A named export (e.g., export { foo }). |
Default |
A default export (e.g., export default foo). |
ReExport |
A re-export from another module (e.g., export { foo } from 'bar'). |
SymbolKind
Section titled “SymbolKind”The kind of a symbol definition found in source code.
Categorizes symbol definitions such as variables, constants, functions, classes, types, interfaces, enums, and modules.
Wire format (public JSON contract)
Section titled “Wire format (public JSON contract)”Unit variants serialize as a bare string ("Function"); the Other
variant serializes as a single-keyed object ({"Other": "macro"}). DO
NOT add #[serde(tag = "...")]. Covered by tests/wire_format.rs.
| Value | Description |
|---|---|
Variable |
A variable binding. |
Constant |
A constant (immutable binding). |
Function |
A function definition. |
Class |
A class definition. |
Type |
A type alias or typedef. |
Interface |
An interface definition. |
Enum |
An enum definition. |
Module |
A module declaration. |
Other |
A symbol kind not covered by the standard variants. — Fields: 0: String |
DiagnosticSeverity
Section titled “DiagnosticSeverity”Severity level of a diagnostic produced during parsing.
Used to classify parse errors, warnings, and informational messages found in the syntax tree.
| Value | Description |
|---|---|
Error |
A parse error (e.g., an ERROR or MISSING node in the tree). |
Warning |
A warning-level diagnostic. |
Info |
An informational diagnostic. |
Errors
Section titled “Errors”Errors that can occur when using the tree-sitter language pack.
Covers language lookup failures, parse errors, query errors, and I/O issues.
Feature-gated variants are included when config, download, or related
features are enabled.
Matching on Error
Section titled “Matching on Error”The set of variants is not stable: new failure modes are added in minor
releases, and Io, Json, and Toml exist only under certain feature
combinations, so the variant set a downstream crate sees depends on which
features it enables. Downstream matches must therefore carry a _ arm;
#[non_exhaustive] makes the compiler enforce that instead of letting a
feature change silently break a build.
C ABI error codes
Section titled “C ABI error codes”Each variant alef can see carries an explicit alef(error_code = N)
allocation that becomes a member of the generated AlefFfiErrorCode C enum.
These numbers are a public ABI contract: an allocated number is never
reused after its variant is removed, and a variant’s number never changes,
because C callers compare against the value, not the name. New variants take
the next free number. 0-4 are reserved by alef, so allocation starts at 100.
An unannotated variant is emitted as the unknown code rather than as itself,
which silently flattens the taxonomy — annotate every new variant.
| Variant | Description |
|---|---|
LanguageNotFound |
The requested language name (or alias) was not found in the registry. |
DynamicLoad |
A dynamic shared library could not be loaded at runtime. |
NullLanguagePointer |
The tree-sitter language function returned a null pointer for the given language name. |
ParserSetup |
The language could not be applied to the parser (e.g., ABI version mismatch). |
LockPoisoned |
An internal RwLock or Mutex was poisoned by a previous panic. |
Config |
A configuration file or value was invalid or could not be applied. |
ParseFailed |
The tree-sitter parser returned no tree for the given source input. |
ParseTimeout |
The parse was cancelled because it exceeded its configured wall-clock budget. Raised only when a budget is configured — see ProcessConfig.parse_timeout_ms, which defaults to null. |
QueryError |
A tree-sitter query could not be compiled or executed. |
InvalidRange |
A byte range was invalid (e.g., end before start, or out of bounds). |
Download |
A parser download from GitHub releases failed. |
ChecksumMismatch |
The downloaded file’s SHA-256 digest did not match the manifest’s expected value. |
CacheLock |
The cross-process download cache lock file could not be acquired or created. |