Skip to main content

logicaffeine_compile/
repl.rs

1//! `ReplSession` — the replay-based interactive session behind `largo repl`
2//! (and any future notebook surface).
3//!
4//! # Architecture: replay, not a persistent interpreter
5//!
6//! The session accumulates source text — `## ` definition blocks and Main
7//! statements — and on every [`eval`](ReplSession::eval) composes them into
8//! a complete program and re-runs it through
9//! [`interpret_for_ui_with_args`](crate::interpret_for_ui_with_args): the
10//! exact engine behind `largo run --interpret` (VM+JIT, prelude
11//! auto-import, the optimizer, and the debug shadow oracle). Only output
12//! lines past a high-water mark are surfaced, so each eval appears
13//! incremental. This gives zero semantic divergence between the REPL and
14//! real programs by construction, and makes [`source`](ReplSession::source)
15//! a valid, runnable `.lg` program at every moment (`:save` = a program).
16//!
17//! A failing input **rolls back**: the offending chunk is popped and the
18//! high-water mark stays put, so the session never wedges and never
19//! duplicates output.
20//!
21//! # The replay caveat
22//!
23//! Re-running the whole program re-executes side effects. Deterministic
24//! programs are unaffected (their prior output is suppressed by the
25//! high-water mark), but non-deterministic operations — current time,
26//! random numbers, file or network I/O — are re-evaluated on every eval,
27//! so a binding like `Let t be the current time.` drifts across lines.
28//! [`reset`](ReplSession::reset) is the escape hatch; a seeded replay mode
29//! is the growth path.
30
31/// The outcome of one REPL evaluation.
32#[derive(Debug, Default)]
33pub struct ReplOutcome {
34    /// Output lines newly produced by this eval (past the high-water mark).
35    pub new_lines: Vec<String>,
36    /// The error message, if the input failed (the input was rolled back).
37    pub error: Option<String>,
38}
39
40/// A persistent imperative REPL session. See the module docs for the
41/// replay architecture.
42#[derive(Debug, Default)]
43pub struct ReplSession {
44    /// Accumulated `## ` definition blocks (functions, types, policies…).
45    defs: Vec<String>,
46    /// Accumulated Main-body statement chunks.
47    stmts: Vec<String>,
48    /// Output lines already surfaced (the high-water mark).
49    emitted: usize,
50    /// The argv the program's `args()` sees; index 0 is the program name.
51    argv: Vec<String>,
52}
53
54impl ReplSession {
55    /// A fresh session.
56    pub fn new() -> Self {
57        Self {
58            defs: Vec::new(),
59            stmts: Vec::new(),
60            emitted: 0,
61            argv: vec!["repl".to_string()],
62        }
63    }
64
65    /// Evaluate one input chunk (a statement, a multi-statement chunk, or a
66    /// `## ` definition block), returning the new output lines.
67    pub async fn eval(&mut self, input: &str) -> ReplOutcome {
68        let trimmed = input.trim();
69        if trimmed.is_empty() || trimmed == "## Main" {
70            return ReplOutcome::default();
71        }
72        let is_def = trimmed.starts_with("## ");
73        if is_def {
74            self.defs.push(trimmed.to_string());
75        } else {
76            self.stmts.push(trimmed.to_string());
77        }
78
79        let program = self.source();
80        let result = crate::interpret_for_ui_with_args(&program, &self.argv).await;
81        let new_lines: Vec<String> = result
82            .lines
83            .get(self.emitted..)
84            .map(|s| s.to_vec())
85            .unwrap_or_default();
86        match result.error {
87            Some(err) => {
88                // Roll back: the reverted program deterministically reproduces
89                // the old output prefix, so the mark must not advance.
90                if is_def {
91                    self.defs.pop();
92                } else {
93                    self.stmts.pop();
94                }
95                ReplOutcome {
96                    new_lines,
97                    error: Some(err),
98                }
99            }
100            None => {
101                self.emitted = result.lines.len();
102                ReplOutcome {
103                    new_lines,
104                    error: None,
105                }
106            }
107        }
108    }
109
110    /// Synchronous [`eval`](Self::eval) for native callers.
111    pub fn eval_sync(&mut self, input: &str) -> ReplOutcome {
112        futures::executor::block_on(self.eval(input))
113    }
114
115    /// The session as a complete LOGOS program: definitions first, then the
116    /// Main body — always runnable as-is.
117    pub fn source(&self) -> String {
118        let mut out = String::new();
119        for def in &self.defs {
120            out.push_str(def);
121            out.push_str("\n\n");
122        }
123        out.push_str("## Main\n\n");
124        for stmt in &self.stmts {
125            out.push_str(stmt);
126            out.push('\n');
127        }
128        out
129    }
130
131    /// The session's global bindings as `(name, type, value)` rows, sorted
132    /// by name. Unavailable (empty) for concurrent programs — the
133    /// inspection replay runs on the synchronous tree-walker.
134    ///
135    /// NOTE: this **re-executes** the accumulated program (the replay
136    /// architecture) — callers that only need names for completion must use
137    /// [`binding_names`](Self::binding_names), which never executes.
138    pub fn vars(&self) -> Vec<(String, String, String)> {
139        crate::ui_bridge::repl_global_bindings(&self.source(), &self.argv).unwrap_or_default()
140    }
141
142    /// The names this session binds — a pure textual scan (`Let <name> be`,
143    /// `Set <name> to`, `## To <name>`) with **zero execution**, safe to call
144    /// after every keystroke for completion feeds.
145    pub fn binding_names(&self) -> Vec<String> {
146        let mut names: Vec<String> = Vec::new();
147        let mut push = |name: &str| {
148            let name = name.trim();
149            if !name.is_empty() && !names.iter().any(|n| n == name) {
150                names.push(name.to_string());
151            }
152        };
153        for chunk in self.defs.iter().chain(self.stmts.iter()) {
154            for line in chunk.lines() {
155                let t = line.trim_start();
156                if let Some(rest) = t.strip_prefix("Let ") {
157                    if let Some((name, _)) = rest.split_once(" be") {
158                        push(name);
159                    }
160                } else if let Some(rest) = t.strip_prefix("## To ") {
161                    let name: String = rest
162                        .chars()
163                        .take_while(|c| c.is_alphanumeric() || *c == '_')
164                        .collect();
165                    push(&name);
166                }
167            }
168        }
169        names
170    }
171
172    /// Replace the session with the contents of a saved program (the
173    /// inverse of [`source`](Self::source)). Returns the program's full
174    /// output as the outcome.
175    pub fn load_source(&mut self, src: &str) -> ReplOutcome {
176        self.reset();
177
178        // A file with no `## ` headers at all is a bare statement list —
179        // treat the whole thing as the Main body (mirroring the engine's
180        // implicit-main convention) instead of silently loading nothing.
181        let headerless = !src.lines().any(|l| l.starts_with("## "));
182
183        let mut current_def: Option<String> = None;
184        let mut main_body = String::new();
185        let mut in_main = headerless;
186        for line in src.lines() {
187            if line.trim_end() == "## Main" {
188                if let Some(def) = current_def.take() {
189                    self.defs.push(def.trim().to_string());
190                }
191                in_main = true;
192            } else if line.starts_with("## ") {
193                if let Some(def) = current_def.take() {
194                    self.defs.push(def.trim().to_string());
195                }
196                in_main = false;
197                current_def = Some(format!("{line}\n"));
198            } else if in_main {
199                main_body.push_str(line);
200                main_body.push('\n');
201            } else if let Some(def) = current_def.as_mut() {
202                def.push_str(line);
203                def.push('\n');
204            }
205        }
206        if let Some(def) = current_def.take() {
207            self.defs.push(def.trim().to_string());
208        }
209        let main_body = main_body.trim().to_string();
210        if !main_body.is_empty() {
211            self.stmts.push(main_body);
212        }
213
214        let program = self.source();
215        let result =
216            futures::executor::block_on(crate::interpret_for_ui_with_args(&program, &self.argv));
217        match result.error {
218            Some(err) => {
219                self.reset();
220                ReplOutcome {
221                    new_lines: Vec::new(),
222                    error: Some(err),
223                }
224            }
225            None => {
226                self.emitted = result.lines.len();
227                ReplOutcome {
228                    new_lines: result.lines,
229                    error: None,
230                }
231            }
232        }
233    }
234
235    /// Clear the whole session: definitions, statements, and the output
236    /// ledger.
237    pub fn reset(&mut self) {
238        self.defs.clear();
239        self.stmts.clear();
240        self.emitted = 0;
241    }
242}