docs(bindings): Add "Using WASM Grammar files" section to binding_rust (#4235)

This commit is contained in:
June Gschwantner 2025-03-06 23:15:21 +01:00 committed by GitHub
parent a00fab7dc4
commit 0b28226615
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -105,6 +105,49 @@ assert_eq!(
);
```
## Using WASM Grammar Files
> Requires the feature **wasm** to be enabled.
First, create a parser with a WASM store:
```rust
use tree_sitter::{wasmtime::Engine, Parser, WasmStore};
let engine = Engine::default();
let store = WasmStore::new(&engine).unwrap();
let mut parser = Parser::new();
parser.set_wasm_store(store).unwrap();
```
Then, load the language from a WASM file:
```rust
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();
// 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(&javascript).unwrap();
```
Now you can parse source code:
```rust
let source_code = "let x = 1;";
let tree = parser.parse(source_code, None).unwrap();
assert_eq!(
tree.root_node().to_sexp(),
"(program (lexical_declaration (variable_declarator name: (identifier) value: (number))))"
);
```
[tree-sitter]: https://github.com/tree-sitter/tree-sitter
## Features