Tree-sitter Rust Grammar for Python

0.24.2 · active · verified Thu Apr 09

tree-sitter-rust provides the official Rust grammar for the Tree-sitter parsing library in Python. It enables fast, incremental parsing of Rust code, generating concrete syntax trees for advanced code analysis, tooling, and editor integrations. The library is actively maintained, with frequent releases to keep up with `tree-sitter` core and Rust language changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Tree-sitter parser with the Rust grammar, parse a simple Rust code snippet, and then inspect the resulting syntax tree's root node and traverse its structure.

import tree_sitter
from tree_sitter import Language, Parser
from tree_sitter_rust import language

# Example Rust code to parse
rust_code = '''
fn main() {
    let message = "Hello, world!";
    println!("{}", message);
}
'''

# 1. Load the Rust language grammar
# The `language` object imported is a callable that returns the actual LanguageFn.
RUST_LANGUAGE = Language(language())

# 2. Create a parser and set its language
parser = Parser()
parser.set_language(RUST_LANGUAGE)

# 3. Parse the code (input must be bytes)
tree = parser.parse(bytes(rust_code, "utf8"))

# 4. Get the root node of the syntax tree
root_node = tree.root_node

print(f"Root node type: {root_node.type}")
print(f"Root node text: {root_node.text}")
print(f"Tree S-expression: {root_node.sexp()}")

# Example of traversing the tree
print("\nWalking the tree nodes:")
cursor = tree.walk()

# Start at the root
def traverse(cursor, indent=0):
    print("  " * indent + f"Node: {cursor.node.type} [start: {cursor.node.start_point}, end: {cursor.node.end_point}]")
    if cursor.goto_first_child():
        traverse(cursor, indent + 1)
        while cursor.goto_next_sibling():
            traverse(cursor, indent + 1)
        cursor.goto_parent() # Go back up after visiting all siblings

traverse(cursor)

view raw JSON →