cst_construction/
cst_construction.rs

1//! Example demonstrating manual CST construction.
2//!
3//! This example shows how to build a concrete syntax tree manually
4//! using the NodeArena and CstNode types.
5//!
6//! Run with: cargo run --example cst_construction --package sipha-tree
7
8use sipha_core::{span::Span, traits::TokenKind};
9use sipha_tree::{
10    arena::NodeArena,
11    children::NodeChildren,
12    node::{CstKind, CstNode},
13    RawNodeId,
14};
15
16#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
17enum Token {
18    Ident,
19    Plus,
20    Number,
21}
22
23impl TokenKind for Token {
24    fn is_trivia(&self) -> bool {
25        false
26    }
27}
28
29#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
30#[allow(dead_code)]
31enum Rule {
32    Expr,
33    Term,
34}
35
36fn main() {
37    println!("=== CST Construction Example ===\n");
38
39    // Create an arena to store nodes
40    let mut arena: NodeArena<Token, Rule, RawNodeId> = NodeArena::new();
41
42    // Create leaf nodes (tokens)
43    let ident_node = CstNode::create(
44        CstKind::Token(Token::Ident),
45        Span::new(0, 1),
46        NodeChildren::new(),
47    );
48    let ident_id = arena.alloc(ident_node);
49    println!("Created ident node: {:?}", ident_id);
50
51    let plus_node = CstNode::create(
52        CstKind::Token(Token::Plus),
53        Span::new(2, 3),
54        NodeChildren::new(),
55    );
56    let plus_id = arena.alloc(plus_node);
57    println!("Created plus node: {:?}", plus_id);
58
59    let number_node = CstNode::create(
60        CstKind::Token(Token::Number),
61        Span::new(4, 5),
62        NodeChildren::new(),
63    );
64    let number_id = arena.alloc(number_node);
65    println!("Created number node: {:?}", number_id);
66
67    // Create a rule node with children
68    let mut children = NodeChildren::new();
69    children.push(ident_id);
70    children.push(plus_id);
71    children.push(number_id);
72
73    let expr_node = CstNode::create(CstKind::Rule(Rule::Expr), Span::new(0, 5), children);
74    let root_id = arena.alloc(expr_node);
75    println!("Created expr node (root): {:?}", root_id);
76
77    println!("\nTotal nodes in arena: {}", arena.len());
78    println!("\n=== Example Complete ===");
79}