Deserializer for tree_sitter::Node
.
You can map tree-sitter's parse result to Rust struct/enum with #[derive(serde::Deserialize)]
.
// grammar.js
rules: {
expr: $ => choice($.expr_int, $.expr_bool)
}
#[derive(serde::Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
enum Expr {
ExprInt(i64),
ExprBool(bool),
}
let tree: tree_sitter::Tree = parse("...")?;
serde_tree_sitter::from_tree::<Expr>(tree, src, true)
// grammar.js
rules: {
let: $ => seq('let', $.ident, '=', $.expr),
// ...
}
#[derive(serde::Deserialize, Debug)]
#[serde(rename="let")]
struct Let(Ident, Expr);
rules: {
nums: $ => repeat(seq($.int, ',')),
// ...
}
serde_tree_sitter::from_tree::<Vec<u32>>(tree, src, true)
rules: {
object: $ => seq('{', repeat(seq($.pair, ',')), '}'),
pair: $ => seq(field('key', $.ident), ':', field('value', $.expr),
// ...
}
#[derive(serde::Deserialize, Debug)]
#[serde(rename="object")]
struct Object(Vec<Pair>);
#[derive(serde::Deserialize, Debug)]
#[serde(rename="pair")]
#[serde(rename_all="snake_case")]
struct Pair {
key: String,
value: Expr,
}