Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tree-sitter/tree-sitter/llms.txt

Use this file to discover all available pages before exploring further.

The Language struct defines how to parse a particular programming language. Language instances are typically generated by the Tree-sitter CLI and exported by language-specific crates.

Creating a Language

new

pub fn new(builder: LanguageFn) -> Self
Create a new language from a language function. This is typically called automatically when you use a language from a Tree-sitter grammar crate.
builder
LanguageFn
required
A function that returns a pointer to the language’s internal structure
use tree_sitter::Language;

let language = Language::from(tree_sitter_rust::LANGUAGE);

Language Information

name

pub fn name(&self) -> Option<&'static str>
Get the name of this language. Returns None for older parsers that don’t include name metadata.
if let Some(name) = language.name() {
    println!("Language: {}", name);
}

abi_version

pub fn abi_version(&self) -> usize
Get the ABI version number that indicates which version of the Tree-sitter CLI was used to generate this language.
let version = language.abi_version();
println!("ABI version: {}", version);

metadata

pub fn metadata(&self) -> Option<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. Returns: Some(LanguageMetadata) if metadata is available, or None for older parsers.
if let Some(metadata) = language.metadata() {
    println!("Version: {}.{}.{}",
        metadata.major_version,
        metadata.minor_version,
        metadata.patch_version);
}

Node Types

node_kind_count

pub fn node_kind_count(&self) -> usize
Get the number of distinct node types in this language.

node_kind_for_id

pub fn node_kind_for_id(&self, id: u16) -> Option<&'static str>
Get the name of the node kind for the given numerical id.
id
u16
required
The numerical id of the node kind
Returns: Some(&str) with the node kind name, or None if the id is invalid.

id_for_node_kind

pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16
Get the numeric id for the given node kind.
kind
&str
required
The name of the node kind
named
bool
required
Whether to look for a named or anonymous node kind
Returns: The numerical id, or 0 if the kind doesn’t exist.

node_kind_is_named

pub fn node_kind_is_named(&self, id: u16) -> bool
Check if the node type for the given numerical id is named (as opposed to an anonymous node type).
id
u16
required
The numerical id of the node kind

node_kind_is_visible

pub fn node_kind_is_visible(&self, id: u16) -> bool
Check if the node type for the given numerical id is visible (as opposed to a hidden node type).

node_kind_is_supertype

pub fn node_kind_is_supertype(&self, id: u16) -> bool
Check if the node type for the given numerical id is a supertype.

Fields

field_count

pub fn field_count(&self) -> usize
Get the number of distinct field names in this language.

field_name_for_id

pub fn field_name_for_id(&self, field_id: u16) -> Option<&'static str>
Get the field name for the given numerical id.
field_id
u16
required
The numerical id of the field
Returns: Some(&str) with the field name, or None if the id is invalid.

field_id_for_name

pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId>
Get the numerical id for the given field name.
field_name
impl AsRef<[u8]>
required
The name of the field
Returns: Some(FieldId) if the field exists, or None if it doesn’t.
if let Some(field_id) = language.field_id_for_name("name") {
    println!("Field 'name' has id: {:?}", field_id);
}

Supertypes

supertypes

pub fn supertypes(&self) -> &[u16]
Get a list of all supertype symbols for the language. Returns: A slice of supertype symbol ids.

subtypes_for_supertype

pub fn subtypes_for_supertype(&self, supertype: u16) -> &[u16]
Get a list of all subtype symbols for a given supertype symbol.
supertype
u16
required
The id of the supertype
Returns: A slice of subtype symbol ids.

Parse States

parse_state_count

pub fn parse_state_count(&self) -> usize
Get the number of valid states in this language.

next_state

pub fn next_state(&self, state: u16, id: u16) -> u16
Get the next parse state. Combine this with lookahead_iterator to generate completion suggestions or valid symbols in error nodes.
state
u16
required
The current parse state
id
u16
required
The grammar symbol id
Returns: The next parse state id.
let state = language.next_state(node.parse_state(), node.grammar_id());

Lookahead

lookahead_iterator

pub fn lookahead_iterator(&self, state: u16) -> Option<LookaheadIterator>
Create a new lookahead iterator for this language and parse state. Returns None if state is invalid for this language.
state
u16
required
The parse state to create the iterator for
Returns: Some(LookaheadIterator) if the state is valid, or None otherwise.
if let Some(mut iter) = language.lookahead_iterator(state) {
    for symbol_name in iter.iter_names() {
        println!("Valid symbol: {}", symbol_name);
    }
}
Lookahead iterators can be useful to generate suggestions and improve syntax error diagnostics. To get symbols valid in an ERROR node, use the lookahead iterator on its first leaf node state. For MISSING nodes, a lookahead iterator created on the previous non-extra leaf node may be appropriate.

LookaheadIterator

An iterator over valid symbols in a parse state.

current_symbol

pub fn current_symbol(&self) -> u16
Get the current symbol of the lookahead iterator.

current_symbol_name

pub fn current_symbol_name(&self) -> &'static str
Get the current symbol name of the lookahead iterator.

language

pub fn language(&self) -> LanguageRef<'_>
Get the current language of the lookahead iterator.

reset

pub fn reset(&mut self, language: &Language, state: u16) -> bool
Reset the lookahead iterator to a different language and state.
language
&Language
required
The language to use
state
u16
required
The parse state
Returns: true if the reset was successful, false otherwise.

reset_state

pub fn reset_state(&mut self, state: u16) -> bool
Reset the lookahead iterator to another state in the same language.
state
u16
required
The parse state
Returns: true if the reset was successful, false otherwise.

iter_names

pub fn iter_names(&mut self) -> impl Iterator<Item = &'static str> + '_
Iterate over symbol names.
let mut lookahead = language.lookahead_iterator(state).unwrap();
for name in lookahead.iter_names() {
    println!("Valid: {}", name);
}
The LookaheadIterator also implements the standard Iterator trait, yielding symbol ids:
for symbol_id in lookahead {
    println!("Symbol id: {}", symbol_id);
}

LanguageMetadata

Metadata associated with a language, including semantic version information.
pub struct LanguageMetadata {
    pub major_version: u8,
    pub minor_version: u8,
    pub patch_version: u8,
}
major_version
u8
The major version number
minor_version
u8
The minor version number
patch_version
u8
The patch version number

Examples

Inspecting a Language

let language = Language::from(tree_sitter_rust::LANGUAGE);

println!("Language: {}", language.name().unwrap());
println!("ABI version: {}", language.abi_version());
println!("Node types: {}", language.node_kind_count());
println!("Fields: {}", language.field_count());

if let Some(metadata) = language.metadata() {
    println!("Version: {}.{}.{}",
        metadata.major_version,
        metadata.minor_version,
        metadata.patch_version);
}

Using Lookahead for Completions

fn get_completions(language: &Language, node: Node) -> Vec<String> {
    let state = if node.is_error() {
        // For error nodes, use the first leaf node's state
        let mut cursor = node.walk();
        while cursor.goto_first_child() {}
        cursor.node().parse_state()
    } else {
        node.parse_state()
    };

    if let Some(mut lookahead) = language.lookahead_iterator(state) {
        lookahead.iter_names()
            .map(|s| s.to_string())
            .collect()
    } else {
        Vec::new()
    }
}

Checking Field Existence

let field_names = ["name", "parameters", "body", "return_type"];

for field_name in &field_names {
    if let Some(field_id) = language.field_id_for_name(field_name) {
        println!("Field '{}' exists with id: {:?}", field_name, field_id);
    } else {
        println!("Field '{}' does not exist", field_name);
    }
}