Skip to main content

logicaffeine_language/
arena_ctx.rs

1//! Arena context for AST allocation.
2//!
3//! This module provides [`AstContext`], a collection of typed arenas used during
4//! parsing to allocate AST nodes. All nodes are bump-allocated for efficiency,
5//! with the `'a` lifetime tracking the arena's scope.
6//!
7//! The context contains separate arenas for:
8//! - Logical expressions ([`LogicExpr`])
9//! - Terms ([`Term`])
10//! - Noun phrases ([`NounPhrase`])
11//! - Symbols, thematic roles, and prepositional phrases
12//! - Imperative statements (optional, for LOGOS mode)
13
14use crate::ast::{
15    AspectOperator, Expr, LogicExpr, ModalVector, NounPhrase, QuantifierKind, Stmt,
16    TemporalOperator, Term, ThematicRole, TypeExpr, VoiceOperator,
17};
18use crate::token::TokenType;
19use logicaffeine_base::Arena;
20use logicaffeine_base::Symbol;
21
22/// Collection of typed arenas for AST allocation during parsing.
23///
24/// The context holds references to multiple arenas, each specialized for
25/// a particular AST node type. This separation allows efficient allocation
26/// while maintaining type safety.
27///
28/// # Modes
29///
30/// The context supports two modes:
31/// - **Declarative** (default): For natural language parsing to logic
32/// - **Imperative**: Adds statement and expression arenas for LOGOS programs
33#[derive(Clone, Copy)]
34pub struct AstContext<'a> {
35    /// Arena for logical expressions ([`LogicExpr`]).
36    pub exprs: &'a Arena<LogicExpr<'a>>,
37    /// Arena for first-order terms ([`Term`]).
38    pub terms: &'a Arena<Term<'a>>,
39    /// Arena for noun phrases ([`NounPhrase`]).
40    pub nps: &'a Arena<NounPhrase<'a>>,
41    /// Arena for interned symbols.
42    pub syms: &'a Arena<Symbol>,
43    /// Arena for thematic role assignments.
44    pub roles: &'a Arena<(ThematicRole, Term<'a>)>,
45    /// Arena for prepositional phrase modifiers.
46    pub pps: &'a Arena<&'a LogicExpr<'a>>,
47    /// Optional arena for imperative statements (LOGOS mode).
48    pub stmts: Option<&'a Arena<Stmt<'a>>>,
49    /// Optional arena for imperative expressions (LOGOS mode).
50    pub imperative_exprs: Option<&'a Arena<Expr<'a>>>,
51    /// Optional arena for type expressions (LOGOS mode).
52    pub type_exprs: Option<&'a Arena<TypeExpr<'a>>>,
53}
54
55impl<'a> AstContext<'a> {
56    /// Creates a new context for declarative (natural language) parsing.
57    pub fn new(
58        exprs: &'a Arena<LogicExpr<'a>>,
59        terms: &'a Arena<Term<'a>>,
60        nps: &'a Arena<NounPhrase<'a>>,
61        syms: &'a Arena<Symbol>,
62        roles: &'a Arena<(ThematicRole, Term<'a>)>,
63        pps: &'a Arena<&'a LogicExpr<'a>>,
64    ) -> Self {
65        AstContext {
66            exprs,
67            terms,
68            nps,
69            syms,
70            roles,
71            pps,
72            stmts: None,
73            imperative_exprs: None,
74            type_exprs: None,
75        }
76    }
77
78    /// Creates a context with imperative statement arenas for LOGOS programs.
79    pub fn with_imperative(
80        exprs: &'a Arena<LogicExpr<'a>>,
81        terms: &'a Arena<Term<'a>>,
82        nps: &'a Arena<NounPhrase<'a>>,
83        syms: &'a Arena<Symbol>,
84        roles: &'a Arena<(ThematicRole, Term<'a>)>,
85        pps: &'a Arena<&'a LogicExpr<'a>>,
86        stmts: &'a Arena<Stmt<'a>>,
87        imperative_exprs: &'a Arena<Expr<'a>>,
88    ) -> Self {
89        AstContext {
90            exprs,
91            terms,
92            nps,
93            syms,
94            roles,
95            pps,
96            stmts: Some(stmts),
97            imperative_exprs: Some(imperative_exprs),
98            type_exprs: None,
99        }
100    }
101
102    /// Creates a context with type expression arena for typed LOGOS programs.
103    pub fn with_types(
104        exprs: &'a Arena<LogicExpr<'a>>,
105        terms: &'a Arena<Term<'a>>,
106        nps: &'a Arena<NounPhrase<'a>>,
107        syms: &'a Arena<Symbol>,
108        roles: &'a Arena<(ThematicRole, Term<'a>)>,
109        pps: &'a Arena<&'a LogicExpr<'a>>,
110        stmts: &'a Arena<Stmt<'a>>,
111        imperative_exprs: &'a Arena<Expr<'a>>,
112        type_exprs: &'a Arena<TypeExpr<'a>>,
113    ) -> Self {
114        AstContext {
115            exprs,
116            terms,
117            nps,
118            syms,
119            roles,
120            pps,
121            stmts: Some(stmts),
122            imperative_exprs: Some(imperative_exprs),
123            type_exprs: Some(type_exprs),
124        }
125    }
126
127    /// Allocates an imperative statement.
128    ///
129    /// # Panics
130    /// Panics if imperative arenas were not initialized.
131    pub fn alloc_stmt(&self, stmt: Stmt<'a>) -> &'a Stmt<'a> {
132        self.stmts
133            .expect("imperative arenas not initialized")
134            .alloc(stmt)
135    }
136
137    /// Allocates an imperative expression.
138    ///
139    /// # Panics
140    /// Panics if imperative arenas were not initialized.
141    pub fn alloc_imperative_expr(&self, expr: Expr<'a>) -> &'a Expr<'a> {
142        self.imperative_exprs
143            .expect("imperative arenas not initialized")
144            .alloc(expr)
145    }
146
147    /// Allocates a type expression.
148    ///
149    /// # Panics
150    /// Panics if type expression arena was not initialized.
151    pub fn alloc_type_expr(&self, ty: TypeExpr<'a>) -> &'a TypeExpr<'a> {
152        self.type_exprs
153            .expect("type_exprs arena not initialized")
154            .alloc(ty)
155    }
156
157    /// Allocates a slice of type expressions.
158    ///
159    /// # Panics
160    /// Panics if type expression arena was not initialized.
161    pub fn alloc_type_exprs<I>(&self, types: I) -> &'a [TypeExpr<'a>]
162    where
163        I: IntoIterator<Item = TypeExpr<'a>>,
164        I::IntoIter: ExactSizeIterator,
165    {
166        self.type_exprs
167            .expect("type_exprs arena not initialized")
168            .alloc_slice(types)
169    }
170
171    /// Allocates a logical expression.
172    pub fn alloc_expr(&self, expr: LogicExpr<'a>) -> &'a LogicExpr<'a> {
173        self.exprs.alloc(expr)
174    }
175
176    /// Allocates a first-order term.
177    pub fn alloc_term(&self, term: Term<'a>) -> &'a Term<'a> {
178        self.terms.alloc(term)
179    }
180
181    /// Allocates a slice of terms from an iterator.
182    pub fn alloc_terms<I>(&self, terms: I) -> &'a [Term<'a>]
183    where
184        I: IntoIterator<Item = Term<'a>>,
185        I::IntoIter: ExactSizeIterator,
186    {
187        self.terms.alloc_slice(terms)
188    }
189
190    /// Allocates a noun phrase.
191    pub fn alloc_np(&self, np: NounPhrase<'a>) -> &'a NounPhrase<'a> {
192        self.nps.alloc(np)
193    }
194
195    /// Allocates a slice of symbols from an iterator.
196    pub fn alloc_syms<I>(&self, syms: I) -> &'a [Symbol]
197    where
198        I: IntoIterator<Item = Symbol>,
199        I::IntoIter: ExactSizeIterator,
200    {
201        self.syms.alloc_slice(syms)
202    }
203
204    /// Allocates a slice of thematic role assignments.
205    pub fn alloc_roles<I>(&self, roles: I) -> &'a [(ThematicRole, Term<'a>)]
206    where
207        I: IntoIterator<Item = (ThematicRole, Term<'a>)>,
208        I::IntoIter: ExactSizeIterator,
209    {
210        self.roles.alloc_slice(roles)
211    }
212
213    /// Allocates a slice of prepositional phrase modifiers.
214    pub fn alloc_pps<I>(&self, pps: I) -> &'a [&'a LogicExpr<'a>]
215    where
216        I: IntoIterator<Item = &'a LogicExpr<'a>>,
217        I::IntoIter: ExactSizeIterator,
218    {
219        self.pps.alloc_slice(pps)
220    }
221
222    /// Creates an atomic predicate: `P(t1, t2, ...)`.
223    pub fn predicate(&self, name: Symbol, args: &'a [Term<'a>]) -> &'a LogicExpr<'a> {
224        self.exprs.alloc(LogicExpr::Predicate {
225            name,
226            args,
227            world: None,
228        })
229    }
230
231    /// Creates a binary operation: `left op right`.
232    #[inline(always)]
233    pub fn binary(
234        &self,
235        left: &'a LogicExpr<'a>,
236        op: TokenType,
237        right: &'a LogicExpr<'a>,
238    ) -> &'a LogicExpr<'a> {
239        self.exprs.alloc(LogicExpr::BinaryOp { left, op, right })
240    }
241
242    /// Creates a unary operation: `op operand`.
243    #[inline(always)]
244    pub fn unary(&self, op: TokenType, operand: &'a LogicExpr<'a>) -> &'a LogicExpr<'a> {
245        self.exprs.alloc(LogicExpr::UnaryOp { op, operand })
246    }
247
248    /// Creates a quantified formula: `∀x.body` or `∃x.body`.
249    #[inline(always)]
250    pub fn quantifier(
251        &self,
252        kind: QuantifierKind,
253        variable: Symbol,
254        body: &'a LogicExpr<'a>,
255        island_id: u32,
256    ) -> &'a LogicExpr<'a> {
257        self.exprs.alloc(LogicExpr::Quantifier {
258            kind,
259            variable,
260            body,
261            island_id,
262        })
263    }
264
265    /// Creates a temporal operator: `PAST(body)` or `FUTURE(body)`.
266    #[inline(always)]
267    pub fn temporal(
268        &self,
269        operator: TemporalOperator,
270        body: &'a LogicExpr<'a>,
271    ) -> &'a LogicExpr<'a> {
272        self.exprs.alloc(LogicExpr::Temporal { operator, body })
273    }
274
275    /// Creates an aspectual operator: `PROG(body)`, `PERF(body)`, etc.
276    #[inline(always)]
277    pub fn aspectual(
278        &self,
279        operator: AspectOperator,
280        body: &'a LogicExpr<'a>,
281    ) -> &'a LogicExpr<'a> {
282        self.exprs.alloc(LogicExpr::Aspectual { operator, body })
283    }
284
285    /// Creates a voice operator: `PASSIVE(body)`.
286    #[inline(always)]
287    pub fn voice(&self, operator: VoiceOperator, body: &'a LogicExpr<'a>) -> &'a LogicExpr<'a> {
288        self.exprs.alloc(LogicExpr::Voice { operator, body })
289    }
290
291    /// Creates a modal operator: `□operand` or `◇operand`.
292    #[inline(always)]
293    pub fn modal(&self, vector: ModalVector, operand: &'a LogicExpr<'a>) -> &'a LogicExpr<'a> {
294        self.exprs.alloc(LogicExpr::Modal { vector, operand })
295    }
296}
297
298#[cfg(test)]
299#[path = "../../logicaffeine_tests/unit/logicaffeine_language/arena_ctx/tests.rs"]
300mod tests;