Rust Tree-sitter
Rust bindings to the Tree-sitter parsing library.
Basic Usage
First, create a parser:
use ;
let mut parser = new;
Then, add a language as a dependency:
[]
= "0.24"
= "0.23"
To use a language, you assign them to the parser.
parser.set_language.expect;
Now you can parse source code:
let source_code = "fn test() {}";
let mut tree = parser.parse.unwrap;
let root_node = tree.root_node;
assert_eq!;
assert_eq!;
assert_eq!;
Editing
Once you have a syntax tree, you can update it when your source code changes.
Passing in the previous edited tree makes parse run much more quickly:
let new_source_code = "fn test(a: u32) {}";
tree.edit;
let new_tree = parser.parse;
Text Input
The source code to parse can be provided either as a string, a slice, a vector, or as a function that returns a slice. The text can be encoded as either UTF8 or UTF16:
// Store some source code in an array of lines.
let lines = &;
// Parse the source code using a custom callback. The callback is called
// with both a byte offset and a row/column offset.
let tree = parser.parse_with.unwrap;
assert_eq!;
Using Wasm Grammar Files
Requires the feature wasm to be enabled.
First, create a parser with a Wasm store:
use ;
let engine = default;
let store = new.unwrap;
let mut parser = new;
parser.set_wasm_store.unwrap;
Then, load the language from a Wasm file:
const JAVASCRIPT_GRAMMAR: & = include_bytes!;
let mut store = new.unwrap;
let javascript = store
.load_language
.unwrap;
// The language may be loaded from a different WasmStore than the one set on
// the parser but it must use the same underlying WasmEngine.
parser.set_language.unwrap;
Now you can parse source code:
let source_code = "let x = 1;";
let tree = parser.parse.unwrap;
assert_eq!;
Features
- std - This feature is enabled by default and allows
tree-sitterto use the standard library.- Error types implement the
std::error:Errortrait. regexperformance optimizations are enabled.- The DOT graph methods are enabled.
- Error types implement the
- wasm - This feature allows
tree-sitterto be built for Wasm targets using thewasmtime-c-apicrate.