panache_parser/syntax/
json.rs1use serde_json::{Value, json};
2
3use super::{SyntaxElement, SyntaxNode, SyntaxToken};
4
5fn range_to_json(range: rowan::TextRange) -> Value {
6 json!({
7 "start": u32::from(range.start()),
8 "end": u32::from(range.end())
9 })
10}
11
12fn token_to_json(token: SyntaxToken) -> Value {
13 json!({
14 "kind": format!("{:?}", token.kind()),
15 "range": range_to_json(token.text_range()),
16 "text": token.text(),
17 })
18}
19
20fn element_to_json(element: SyntaxElement) -> Value {
21 match element {
22 rowan::NodeOrToken::Node(node) => cst_to_json(&node),
23 rowan::NodeOrToken::Token(token) => token_to_json(token),
24 }
25}
26
27pub fn cst_to_json(node: &SyntaxNode) -> Value {
28 let children: Vec<Value> = node.children_with_tokens().map(element_to_json).collect();
29
30 json!({
31 "kind": format!("{:?}", node.kind()),
32 "range": range_to_json(node.text_range()),
33 "children": children,
34 })
35}