sipha_parse/state/
builder.rs

1//! Node builder for constructing CST nodes incrementally.
2
3use sipha_core::{span::Span, traits::NodeId, traits::RuleId};
4use sipha_tree::NodeChildren;
5
6use crate::state::ParserState;
7
8/// Helper for constructing CST nodes incrementally.
9pub struct NodeBuilder<R: RuleId, N: NodeId> {
10    rule_id: R,
11    children: NodeChildren<N>,
12    span: Span,
13}
14
15impl<R: RuleId, N: NodeId> NodeBuilder<R, N> {
16    pub(crate) fn new(rule_id: R, span: Span) -> Self {
17        Self {
18            rule_id,
19            children: NodeChildren::new(),
20            span,
21        }
22    }
23
24    /// Append a child node.
25    pub fn node(&mut self, child: N) {
26        self.children.push(child);
27    }
28
29    /// Finalize the node and allocate it inside the arena.
30    pub fn finish<'tokens, 'arena, K, Ctx>(
31        self,
32        state: &mut ParserState<'tokens, 'arena, K, R, N, Ctx>,
33    ) -> N
34    where
35        K: sipha_core::traits::TokenKind,
36        Ctx: sipha_core::traits::GrammarContext,
37    {
38        state.alloc_rule_node(self.rule_id, self.span, self.children)
39    }
40}