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

# Language API

> API reference for the Language struct

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

```rust theme={null}
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.

<ParamField path="builder" type="LanguageFn" required>
  A function that returns a pointer to the language's internal structure
</ParamField>

```rust theme={null}
use tree_sitter::Language;

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

## Language Information

### name

```rust theme={null}
pub fn name(&self) -> Option<&'static str>
```

Get the name of this language. Returns `None` for older parsers that don't include name metadata.

```rust theme={null}
if let Some(name) = language.name() {
    println!("Language: {}", name);
}
```

### abi\_version

```rust theme={null}
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.

```rust theme={null}
let version = language.abi_version();
println!("ABI version: {}", version);
```

### metadata

```rust theme={null}
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.

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

## Node Types

### node\_kind\_count

```rust theme={null}
pub fn node_kind_count(&self) -> usize
```

Get the number of distinct node types in this language.

### node\_kind\_for\_id

```rust theme={null}
pub fn node_kind_for_id(&self, id: u16) -> Option<&'static str>
```

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

<ParamField path="id" type="u16" required>
  The numerical id of the node kind
</ParamField>

**Returns:** `Some(&str)` with the node kind name, or `None` if the id is invalid.

### id\_for\_node\_kind

```rust theme={null}
pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16
```

Get the numeric id for the given node kind.

<ParamField path="kind" type="&str" required>
  The name of the node kind
</ParamField>

<ParamField path="named" type="bool" required>
  Whether to look for a named or anonymous node kind
</ParamField>

**Returns:** The numerical id, or 0 if the kind doesn't exist.

### node\_kind\_is\_named

```rust theme={null}
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).

<ParamField path="id" type="u16" required>
  The numerical id of the node kind
</ParamField>

### node\_kind\_is\_visible

```rust theme={null}
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

```rust theme={null}
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

```rust theme={null}
pub fn field_count(&self) -> usize
```

Get the number of distinct field names in this language.

### field\_name\_for\_id

```rust theme={null}
pub fn field_name_for_id(&self, field_id: u16) -> Option<&'static str>
```

Get the field name for the given numerical id.

<ParamField path="field_id" type="u16" required>
  The numerical id of the field
</ParamField>

**Returns:** `Some(&str)` with the field name, or `None` if the id is invalid.

### field\_id\_for\_name

```rust theme={null}
pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId>
```

Get the numerical id for the given field name.

<ParamField path="field_name" type="impl AsRef<[u8]>" required>
  The name of the field
</ParamField>

**Returns:** `Some(FieldId)` if the field exists, or `None` if it doesn't.

```rust theme={null}
if let Some(field_id) = language.field_id_for_name("name") {
    println!("Field 'name' has id: {:?}", field_id);
}
```

## Supertypes

### supertypes

```rust theme={null}
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

```rust theme={null}
pub fn subtypes_for_supertype(&self, supertype: u16) -> &[u16]
```

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

<ParamField path="supertype" type="u16" required>
  The id of the supertype
</ParamField>

**Returns:** A slice of subtype symbol ids.

## Parse States

### parse\_state\_count

```rust theme={null}
pub fn parse_state_count(&self) -> usize
```

Get the number of valid states in this language.

### next\_state

```rust theme={null}
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.

<ParamField path="state" type="u16" required>
  The current parse state
</ParamField>

<ParamField path="id" type="u16" required>
  The grammar symbol id
</ParamField>

**Returns:** The next parse state id.

```rust theme={null}
let state = language.next_state(node.parse_state(), node.grammar_id());
```

## Lookahead

### lookahead\_iterator

```rust theme={null}
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.

<ParamField path="state" type="u16" required>
  The parse state to create the iterator for
</ParamField>

**Returns:** `Some(LookaheadIterator)` if the state is valid, or `None` otherwise.

```rust theme={null}
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

```rust theme={null}
pub fn current_symbol(&self) -> u16
```

Get the current symbol of the lookahead iterator.

### current\_symbol\_name

```rust theme={null}
pub fn current_symbol_name(&self) -> &'static str
```

Get the current symbol name of the lookahead iterator.

### language

```rust theme={null}
pub fn language(&self) -> LanguageRef<'_>
```

Get the current language of the lookahead iterator.

### reset

```rust theme={null}
pub fn reset(&mut self, language: &Language, state: u16) -> bool
```

Reset the lookahead iterator to a different language and state.

<ParamField path="language" type="&Language" required>
  The language to use
</ParamField>

<ParamField path="state" type="u16" required>
  The parse state
</ParamField>

**Returns:** `true` if the reset was successful, `false` otherwise.

### reset\_state

```rust theme={null}
pub fn reset_state(&mut self, state: u16) -> bool
```

Reset the lookahead iterator to another state in the same language.

<ParamField path="state" type="u16" required>
  The parse state
</ParamField>

**Returns:** `true` if the reset was successful, `false` otherwise.

### iter\_names

```rust theme={null}
pub fn iter_names(&mut self) -> impl Iterator<Item = &'static str> + '_
```

Iterate over symbol names.

```rust theme={null}
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:

```rust theme={null}
for symbol_id in lookahead {
    println!("Symbol id: {}", symbol_id);
}
```

## LanguageMetadata

Metadata associated with a language, including semantic version information.

```rust theme={null}
pub struct LanguageMetadata {
    pub major_version: u8,
    pub minor_version: u8,
    pub patch_version: u8,
}
```

<ParamField path="major_version" type="u8">
  The major version number
</ParamField>

<ParamField path="minor_version" type="u8">
  The minor version number
</ParamField>

<ParamField path="patch_version" type="u8">
  The patch version number
</ParamField>

## Examples

### Inspecting a Language

```rust theme={null}
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

```rust theme={null}
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

```rust theme={null}
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);
    }
}
```
