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.

This guide walks you through parsing your first source code file with Tree-sitter. We’ll use real examples from the Tree-sitter codebase to show you the basics.
Make sure you’ve installed Tree-sitter before starting this guide.

Choose your language

Create a parser

First, import the necessary types and create a parser:
use tree_sitter::{Parser, Language};

let mut parser = Parser::new();

Set the language

Assign a language grammar to the parser. In this example, we’ll use Rust:
parser.set_language(&tree_sitter_rust::LANGUAGE.into())
    .expect("Error loading Rust grammar");

Parse source code

Now parse some source code:
let source_code = "fn test() {}";
let tree = parser.parse(source_code, None).unwrap();
let root_node = tree.root_node();

assert_eq!(root_node.kind(), "source_file");
assert_eq!(root_node.start_position().column, 0);
assert_eq!(root_node.end_position().column, 12);

Inspect the tree

Access the syntax tree structure:
println!("Root node kind: {}", root_node.kind());
println!("Start position: {:?}", root_node.start_position());
println!("End position: {:?}", root_node.end_position());
println!("S-expression: {}", root_node.to_sexp());
The to_sexp() method returns a string representation of the tree in S-expression format, which is useful for debugging.

Parse from multiple lines

You can parse source code from custom data structures using a callback:
use tree_sitter::Point;

// Store source code in an array of lines
let lines = &[
    "pub fn foo() {",
    "  1",
    "}",
];

// Parse using a custom callback
let tree = parser.parse_with(&mut |_byte: usize, position: Point| -> &[u8] {
    let row = position.row as usize;
    let column = position.column as usize;
    if row < lines.len() {
        if column < lines[row].as_bytes().len() {
            &lines[row].as_bytes()[column..]
        } else {
            b"\n"
        }
    } else {
        &[]
    }
}, None).unwrap();

assert_eq!(
  tree.root_node().to_sexp(),
  "(source_file (function_item (visibility_modifier) (identifier) (parameters) (block (number_literal))))"
);

Working with syntax nodes

Syntax nodes are the building blocks of the syntax tree. Here’s how to work with them:

Node types and positions

let source_code = "fn test() {}";
let tree = parser.parse(source_code, None).unwrap();
let root_node = tree.root_node();

// Get node type
println!("Type: {}", root_node.kind());

// Get positions (zero-based)
println!("Start byte: {}", root_node.start_byte());
println!("End byte: {}", root_node.end_byte());
println!("Start position: {:?}", root_node.start_position());
println!("End position: {:?}", root_node.end_position());
// Access all children
let child_count = root_node.child_count();
for i in 0..child_count {
    let child = root_node.child(i).unwrap();
    println!("Child {}: {}", i, child.kind());
}

// Access named children only (skip tokens like punctuation)
let named_child_count = root_node.named_child_count();
for i in 0..named_child_count {
    let child = root_node.named_child(i).unwrap();
    println!("Named child {}: {}", i, child.kind());
}

// Navigate siblings and parent
if let Some(next_sibling) = root_node.next_sibling() {
    println!("Next sibling: {}", next_sibling.kind());
}
Use the “named” variants of navigation methods (named_child, next_named_sibling, etc.) to work with the tree as an abstract syntax tree, skipping punctuation tokens.

Incremental parsing

One of Tree-sitter’s key features is efficient incremental parsing. When source code changes, you can update the tree instead of reparsing from scratch:
use tree_sitter::{InputEdit, Point};

let source_code = "fn test() {}";
let mut tree = parser.parse(source_code, None).unwrap();

// The source code changed from "fn test() {}" to "fn test(a: u32) {}"
let new_source_code = "fn test(a: u32) {}";

// Tell the tree about the edit
tree.edit(&InputEdit {
  start_byte: 8,
  old_end_byte: 8,
  new_end_byte: 14,
  start_position: Point::new(0, 8),
  old_end_position: Point::new(0, 8),
  new_end_position: Point::new(0, 14),
});

// Reparse with the old tree for efficiency
let new_tree = parser.parse(new_source_code, Some(&tree));
Incremental parsing is significantly faster than reparsing from scratch. Tree-sitter reuses unchanged portions of the tree, making it ideal for text editors and other real-time applications.

Using Wasm grammars (Rust)

You can load language grammars compiled to WebAssembly:
use tree_sitter::{Parser, WasmStore};
use tree_sitter::wasmtime::Engine;

// Create a Wasm engine and store
let engine = Engine::default();
let mut store = WasmStore::new(&engine).unwrap();

let mut parser = Parser::new();
parser.set_wasm_store(store).unwrap();

// Load a language from a Wasm file
const JAVASCRIPT_GRAMMAR: &[u8] = include_bytes!("path/to/tree-sitter-javascript.wasm");

let mut store = WasmStore::new(&engine).unwrap();
let javascript = store
    .load_language("javascript", JAVASCRIPT_GRAMMAR)
    .unwrap();

parser.set_language(&javascript).unwrap();

// Now parse JavaScript code
let source_code = "let x = 1;";
let tree = parser.parse(source_code, None).unwrap();
The wasm feature must be enabled in your Cargo.toml to use Wasm grammars.

Next steps

Using parsers

Learn advanced parsing techniques and tree traversal

Queries

Use Tree-sitter queries to search and analyze syntax trees

Creating parsers

Write your own grammar to parse custom languages

CLI reference

Explore CLI commands for testing and debugging grammars