Skip to main content
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:

Set the language

Assign a language grammar to the parser. In this example, we’ll use Rust:

Parse source code

Now parse some source code:

Inspect the tree

Access the syntax tree structure:
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:

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

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:
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:
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