Skip to main content

logicaffeine_language/
session.rs

1//! Session Manager for Incremental Evaluation
2//!
3//! Provides a REPL-style interface for parsing sentences one at a time
4//! while maintaining persistent discourse state across turns.
5//!
6//! # Example
7//!
8//! ```
9//! use logicaffeine_language::Session;
10//!
11//! let mut session = Session::new();
12//! let out1 = session.eval("The boys lifted the piano.").unwrap();
13//! let out2 = session.eval("They smiled.").unwrap();  // "They" resolves to "the boys"
14//! ```
15
16use crate::analysis;
17use crate::arena_ctx::AstContext;
18use crate::drs::WorldState;
19use crate::error::ParseError;
20use crate::lexer::Lexer;
21use crate::mwe;
22use crate::parser::Parser;
23use crate::registry::SymbolRegistry;
24use crate::semantics;
25use crate::OutputFormat;
26use logicaffeine_base::Arena;
27use logicaffeine_base::Interner;
28
29/// A persistent session for incremental sentence evaluation.
30///
31/// Maintains discourse state across multiple `eval()` calls, enabling
32/// cross-sentence anaphora resolution and temporal ordering.
33pub struct Session {
34    /// Persistent discourse state (DRS tree, referents, modal contexts)
35    world_state: WorldState,
36
37    /// Symbol interner for string interning across all sentences
38    interner: Interner,
39
40    /// Symbol registry for transpilation
41    registry: SymbolRegistry,
42
43    /// MWE trie for multi-word expression detection
44    mwe_trie: mwe::MweTrie,
45
46    /// Accumulated transpiled outputs from each sentence
47    history: Vec<String>,
48
49    /// Output format for transpilation
50    format: OutputFormat,
51}
52
53impl Default for Session {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59impl Session {
60    /// Create a new session with default settings.
61    pub fn new() -> Self {
62        Session {
63            world_state: WorldState::new(),
64            interner: Interner::new(),
65            registry: SymbolRegistry::new(),
66            mwe_trie: mwe::build_mwe_trie(),
67            history: Vec::new(),
68            format: OutputFormat::Unicode,
69        }
70    }
71
72    /// Switch the output format mid-session.
73    ///
74    /// Affects only how subsequent sentences are rendered; discourse state
75    /// (referents, event counters) is untouched, so a session switched to
76    /// LaTeX renders exactly as one that used LaTeX from the start.
77    pub fn set_format(&mut self, format: OutputFormat) {
78        self.format = format;
79    }
80
81    /// Create a new session with a specific output format.
82    pub fn with_format(format: OutputFormat) -> Self {
83        Session {
84            world_state: WorldState::new(),
85            interner: Interner::new(),
86            registry: SymbolRegistry::new(),
87            mwe_trie: mwe::build_mwe_trie(),
88            history: Vec::new(),
89            format,
90        }
91    }
92
93    /// Evaluate a single sentence, updating the session state.
94    ///
95    /// Returns the transpiled logic for just this sentence.
96    /// Pronouns in this sentence can resolve to entities from previous sentences.
97    pub fn eval(&mut self, input: &str) -> Result<String, ParseError> {
98        // Generate event variable for this turn
99        let event_var_name = self.world_state.next_event_var();
100        let event_var_symbol = self.interner.intern(&event_var_name);
101
102        // Tokenize
103        let mut lexer = Lexer::new(input, &mut self.interner);
104        let tokens = lexer.tokenize();
105
106        // Apply MWE collapsing
107        let tokens = mwe::apply_mwe_pipeline(tokens, &self.mwe_trie, &mut self.interner);
108
109        // Pass 1: Discovery - scan for type definitions
110        let type_registry = {
111            let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut self.interner);
112            discovery.run()
113        };
114
115        // Create arenas for this parse (fresh each sentence)
116        let expr_arena = Arena::new();
117        let term_arena = Arena::new();
118        let np_arena = Arena::new();
119        let sym_arena = Arena::new();
120        let role_arena = Arena::new();
121        let pp_arena = Arena::new();
122
123        let ast_ctx = AstContext::new(
124            &expr_arena,
125            &term_arena,
126            &np_arena,
127            &sym_arena,
128            &role_arena,
129            &pp_arena,
130        );
131
132        // Pass 2: Parse with WorldState (DRS persists across sentences)
133        let mut parser = Parser::new(
134            tokens,
135            &mut self.world_state,
136            &mut self.interner,
137            ast_ctx,
138            type_registry,
139        );
140        parser.set_discourse_event_var(event_var_symbol);
141
142        // Swap DRS from WorldState into Parser at start
143        parser.swap_drs_with_world_state();
144        let ast = parser.parse()?;
145        // Swap DRS back to WorldState at end
146        parser.swap_drs_with_world_state();
147
148        // Mark sentence boundary - collect telescope candidates for cross-sentence anaphora
149        self.world_state.end_sentence();
150
151        // Apply semantic axioms
152        let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut self.interner);
153
154        // Transpile
155        let output = ast.transpile(&mut self.registry, &self.interner, self.format);
156
157        // Store in history
158        self.history.push(output.clone());
159
160        Ok(output)
161    }
162
163    /// Get the full accumulated logic from all sentences.
164    ///
165    /// Includes temporal ordering constraints (Precedes relations).
166    pub fn history(&self) -> String {
167        if self.history.is_empty() {
168            return String::new();
169        }
170
171        let event_history = self.world_state.event_history();
172        let mut precedes = Vec::new();
173        for i in 0..event_history.len().saturating_sub(1) {
174            precedes.push(format!(
175                "Precedes({}, {})",
176                event_history[i],
177                event_history[i + 1]
178            ));
179        }
180
181        if precedes.is_empty() {
182            self.history.join(" ∧ ")
183        } else {
184            format!("{} ∧ {}", self.history.join(" ∧ "), precedes.join(" ∧ "))
185        }
186    }
187
188    /// Get the number of sentences processed.
189    pub fn turn_count(&self) -> usize {
190        self.history.len()
191    }
192
193    /// Get direct access to the world state (for advanced use).
194    pub fn world_state(&self) -> &WorldState {
195        &self.world_state
196    }
197
198    /// Get mutable access to the world state (for advanced use).
199    pub fn world_state_mut(&mut self) -> &mut WorldState {
200        &mut self.world_state
201    }
202
203    /// Reset the session to initial state.
204    pub fn reset(&mut self) {
205        self.world_state = WorldState::new();
206        self.history.clear();
207        // Keep interner and registry - symbols are still valid
208    }
209}
210
211#[cfg(test)]
212#[path = "../../logicaffeine_tests/unit/logicaffeine_language/session/tests.rs"]
213mod tests;