willbooster-tree-sitter
Rust bindings to this fork of the Tree-sitter parsing library. The crate keeps the library name
tree_sitter, so depending on it under the name tree-sitter (as below) needs no code changes.
Basic Usage
First, create a parser:
use ;
let mut parser = new;
Then, add a language as a dependency:
[]
= { = "willbooster-tree-sitter", = "2" }
= { = "willbooster-tree-sitter-rust", = "3" }
The grammar must be one generated by the CLI of this runtime's major version. The library rejects every other parser:
the ones upstream grammar crates ship, and the willbooster-tree-sitter-* releases generated for runtime 1, such as
willbooster-tree-sitter-rust 2. Cargo cannot detect the mismatch, because a grammar crate does not depend on the
runtime; it shows as an error from set_language.
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 that the CLI of this runtime's major version built from a parser it generated
(tree-sitter generate, then tree-sitter build --wasm); other Wasm files are rejected like other parsers:
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.