Skip to main content

logicaffeine_compile/analysis/
escape.rs

1//! Escape analysis for zone safety.
2//!
3//! Implements the zone containment rule: values can enter
4//! zones but cannot escape. This pass checks for obvious violations before
5//! code generation, providing Socratic error messages.
6//!
7//! # The Zone Rule
8//!
9//! Variables defined inside a zone are deallocated when the zone ends.
10//! Returning or assigning them to outer variables would create dangling
11//! references. This pass catches these common patterns with friendly errors.
12//!
13//! # Example
14//!
15//! ```text
16//! Zone "temp":
17//!     Let x be 5.
18//!     Return x.        ← Error: x cannot escape zone "temp"
19//! ```
20//!
21//! # Limitations
22//!
23//! More complex escape patterns (e.g., through closures or indirect references)
24//! are caught by Rust's borrow checker at compile time. This pass catches the
25//! common cases with better LOGOS-specific error messages.
26
27use crate::ast::stmt::{Expr, Stmt, StmtId};
28use crate::intern::{Interner, Symbol};
29use crate::token::Span;
30use std::collections::HashMap;
31
32/// Error type for escape violations
33#[derive(Debug, Clone)]
34pub struct EscapeError {
35    pub kind: EscapeErrorKind,
36    pub span: Span,
37}
38
39#[derive(Debug, Clone)]
40pub enum EscapeErrorKind {
41    /// Variable cannot escape zone via return
42    ReturnEscape { variable: String, zone_name: String },
43    /// Variable cannot escape zone via assignment to outer variable
44    AssignmentEscape {
45        variable: String,
46        target: String,
47        zone_name: String,
48    },
49}
50
51impl std::fmt::Display for EscapeError {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match &self.kind {
54            EscapeErrorKind::ReturnEscape {
55                variable,
56                zone_name,
57            } => {
58                write!(
59                    f,
60                    "Reference '{}' cannot escape zone '{}'.\n\n\
61                    Variables allocated inside a zone are deallocated when the zone ends.\n\
62                    Returning them would create a dangling reference.\n\n\
63                    Tip: Copy the data if you need it outside the zone.",
64                    variable, zone_name
65                )
66            }
67            EscapeErrorKind::AssignmentEscape {
68                variable,
69                target,
70                zone_name,
71            } => {
72                write!(
73                    f,
74                    "Reference '{}' cannot escape zone '{}' via assignment to '{}'.\n\n\
75                    Variables allocated inside a zone are deallocated when the zone ends.\n\
76                    Assigning them to outer scope variables would create a dangling reference.\n\n\
77                    Tip: Copy the data if you need it outside the zone.",
78                    variable, zone_name, target
79                )
80            }
81        }
82    }
83}
84
85impl std::error::Error for EscapeError {}
86
87/// Tracks the "zone depth" of variables for escape analysis
88/// One escape finding: the top-level statement it belongs to (mapping onto
89/// `Parser::stmt_spans()`), and the erring statement with each one around it,
90/// innermost first (for `Parser::nested_stmt_spans()`).
91#[derive(Debug)]
92pub struct EscapeFinding {
93    pub stmt_index: usize,
94    pub trail: Vec<StmtId>,
95    pub error: EscapeError,
96}
97
98/// An escape error on its way out of the statements it was found in, naming
99/// each one as it passes, innermost first.
100struct Traced {
101    error: EscapeError,
102    trail: Vec<StmtId>,
103}
104
105impl From<EscapeError> for Traced {
106    fn from(error: EscapeError) -> Self {
107        Traced {
108            error,
109            trail: Vec::new(),
110        }
111    }
112}
113
114pub struct EscapeChecker<'a> {
115    /// Maps variable symbols to their zone depth (0 = global/outside all zones)
116    zone_depth: HashMap<Symbol, usize>,
117    /// Current zone depth (increases when entering zones)
118    current_depth: usize,
119    /// Stack of zone names for error messages
120    zone_stack: Vec<Symbol>,
121    /// String interner for resolving symbols
122    interner: &'a Interner,
123}
124
125impl<'a> EscapeChecker<'a> {
126    /// Create a new escape checker
127    pub fn new(interner: &'a Interner) -> Self {
128        Self {
129            zone_depth: HashMap::new(),
130            current_depth: 0,
131            zone_stack: Vec::new(),
132            interner,
133        }
134    }
135
136    /// Check a program (list of statements) for escape violations
137    pub fn check_program(&mut self, stmts: &[Stmt<'_>]) -> Result<(), EscapeError> {
138        self.check_block(stmts).map_err(|traced| traced.error)
139    }
140
141    /// Collect every escape finding with its statements, continuing past failures.
142    pub fn check_program_collect(&mut self, stmts: &[Stmt<'_>]) -> Vec<EscapeFinding> {
143        stmts
144            .iter()
145            .enumerate()
146            .filter_map(|(index, stmt)| {
147                self.check_stmt(stmt)
148                    .err()
149                    .map(|Traced { error, trail }| EscapeFinding {
150                        stmt_index: index,
151                        trail,
152                        error,
153                    })
154            })
155            .collect()
156    }
157
158    /// Check a block of statements
159    fn check_block(&mut self, stmts: &[Stmt<'_>]) -> Result<(), Traced> {
160        for stmt in stmts {
161            self.check_stmt(stmt)?;
162        }
163        Ok(())
164    }
165
166    /// Check a single statement for escape violations
167    fn check_stmt(&mut self, stmt: &Stmt<'_>) -> Result<(), Traced> {
168        self.check_stmt_kind(stmt).map_err(|mut traced| {
169            traced.trail.push(StmtId::of(stmt));
170            traced
171        })
172    }
173
174    fn check_stmt_kind(&mut self, stmt: &Stmt<'_>) -> Result<(), Traced> {
175        match stmt {
176            Stmt::Zone { name, body, .. } => {
177                // Enter zone: increase depth
178                self.current_depth += 1;
179                self.zone_stack.push(*name);
180
181                // Check body statements
182                let body_result = self.check_block(body);
183
184                // Exit zone: decrease depth — on a finding too, so the
185                // statements after it are checked at their own depth.
186                self.zone_stack.pop();
187                self.current_depth -= 1;
188                body_result?;
189            }
190
191            // A function body is its own scope: its zones and their values
192            // are checked where they are written, and its names end with it.
193            Stmt::FunctionDef { body, .. } => {
194                let outer = self.zone_depth.clone();
195                let body_result = self.check_block(body);
196                self.zone_depth = outer;
197                body_result?;
198            }
199
200            Stmt::Let { var, .. } => {
201                // Register variable at current depth
202                self.zone_depth.insert(*var, self.current_depth);
203            }
204
205            Stmt::Return { value: Some(expr) } => {
206                // Return escapes all zones (target depth = 0)
207                self.check_no_escape(expr, 0)?;
208            }
209
210            Stmt::Set { target, value } => {
211                // Assignment: check if value escapes to target's depth
212                let target_depth = self.zone_depth.get(target).copied().unwrap_or(0);
213                self.check_no_escape_with_target(value, target_depth, *target)?;
214            }
215
216            // Recurse into nested blocks
217            Stmt::If {
218                then_block,
219                else_block,
220                ..
221            } => {
222                self.check_block(then_block)?;
223                if let Some(else_b) = else_block {
224                    self.check_block(else_b)?;
225                }
226            }
227
228            Stmt::While { body, .. } => {
229                self.check_block(body)?;
230            }
231
232            Stmt::Repeat { body, .. } => {
233                self.check_block(body)?;
234            }
235
236            Stmt::Inspect { arms, .. } => {
237                for arm in arms {
238                    self.check_block(arm.body)?;
239                }
240            }
241
242            // A `During` span is scope-transparent: its body runs in place, where it is written.
243            Stmt::During { body, .. } => {
244                self.check_block(body)?;
245            }
246
247            // Escape blocks are opaque — the Rust compiler handles zone safety for raw code
248            Stmt::Escape { .. } => {}
249
250            // Other statements don't introduce escape risks
251            _ => {}
252        }
253        Ok(())
254    }
255
256    /// Check that an expression doesn't escape to a shallower depth
257    fn check_no_escape(&self, expr: &Expr<'_>, max_depth: usize) -> Result<(), EscapeError> {
258        match expr {
259            // A view's holes are evaluated where the view renders; its handler blocks are
260            // closures (checked when called, like a block closure).
261            // A page query reads the DOM; only its selector expression can escape a zone.
262            Expr::Dom(q) => {
263                if let Some(sel) = q.selector() {
264                    self.check_no_escape(sel, max_depth)?;
265                }
266            }
267            Expr::View(v) => {
268                for e in v.exprs_and_blocks().0 {
269                    self.check_no_escape(e, max_depth)?;
270                }
271            }
272            Expr::Identifier(sym) => {
273                if let Some(&depth) = self.zone_depth.get(sym) {
274                    if depth > max_depth && depth > 0 {
275                        // This variable was defined in a deeper zone
276                        let zone_name = self
277                            .zone_stack
278                            .get(depth - 1)
279                            .map(|s| self.interner.resolve(*s).to_string())
280                            .unwrap_or_else(|| "unknown".to_string());
281                        let var_name = self.interner.resolve(*sym).to_string();
282                        return Err(EscapeError {
283                            kind: EscapeErrorKind::ReturnEscape {
284                                variable: var_name,
285                                zone_name,
286                            },
287                            span: Span::default(),
288                        });
289                    }
290                }
291            }
292
293            // Recurse into compound expressions
294            Expr::BinaryOp { left, right, .. } => {
295                self.check_no_escape(left, max_depth)?;
296                self.check_no_escape(right, max_depth)?;
297            }
298
299            Expr::Call { args, .. } => {
300                for arg in args {
301                    self.check_no_escape(arg, max_depth)?;
302                }
303            }
304
305            Expr::FieldAccess { object, .. } => {
306                self.check_no_escape(object, max_depth)?;
307            }
308
309            Expr::Index { collection, index } => {
310                self.check_no_escape(collection, max_depth)?;
311                self.check_no_escape(index, max_depth)?;
312            }
313
314            Expr::Slice {
315                collection,
316                start,
317                end,
318            } => {
319                self.check_no_escape(collection, max_depth)?;
320                self.check_no_escape(start, max_depth)?;
321                self.check_no_escape(end, max_depth)?;
322            }
323
324            Expr::Copy { expr }
325            | Expr::Give { value: expr }
326            | Expr::Length { collection: expr }
327            | Expr::Not { operand: expr } => {
328                self.check_no_escape(expr, max_depth)?;
329            }
330
331            Expr::List(items) | Expr::Tuple(items) => {
332                for item in items {
333                    self.check_no_escape(item, max_depth)?;
334                }
335            }
336
337            Expr::Range { start, end } => {
338                self.check_no_escape(start, max_depth)?;
339                self.check_no_escape(end, max_depth)?;
340            }
341
342            Expr::New { init_fields, .. } => {
343                for (_, expr) in init_fields {
344                    self.check_no_escape(expr, max_depth)?;
345                }
346            }
347
348            Expr::NewVariant { fields, .. } => {
349                for (_, expr) in fields {
350                    self.check_no_escape(expr, max_depth)?;
351                }
352            }
353
354            Expr::ManifestOf { zone } => {
355                self.check_no_escape(zone, max_depth)?;
356            }
357
358            Expr::ChunkAt { index, zone } => {
359                self.check_no_escape(index, max_depth)?;
360                self.check_no_escape(zone, max_depth)?;
361            }
362
363            Expr::Contains { collection, value } => {
364                self.check_no_escape(collection, max_depth)?;
365                self.check_no_escape(value, max_depth)?;
366            }
367
368            Expr::Union { left, right } | Expr::Intersection { left, right } => {
369                self.check_no_escape(left, max_depth)?;
370                self.check_no_escape(right, max_depth)?;
371            }
372
373            Expr::WithCapacity { value, capacity } => {
374                self.check_no_escape(value, max_depth)?;
375                self.check_no_escape(capacity, max_depth)?;
376            }
377
378            Expr::OptionSome { value } => {
379                self.check_no_escape(value, max_depth)?;
380            }
381            Expr::OptionNone => {}
382
383            // Escape expressions are opaque — the Rust compiler handles zone safety for raw code
384            Expr::Escape { .. } => {}
385
386            Expr::Closure { body, .. } => {
387                match body {
388                    crate::ast::stmt::ClosureBody::Expression(expr) => {
389                        self.check_no_escape(expr, max_depth)?;
390                    }
391                    crate::ast::stmt::ClosureBody::Block(_) => {
392                        // Block closures don't escape zone values through their definition.
393                        // The closure body is a separate scope; zone safety for the body
394                        // is checked when the closure is called, not when it's defined.
395                    }
396                }
397            }
398
399            Expr::CallExpr { callee, args } => {
400                self.check_no_escape(callee, max_depth)?;
401                for arg in args {
402                    self.check_no_escape(arg, max_depth)?;
403                }
404            }
405
406            Expr::InterpolatedString(parts) => {
407                for part in parts {
408                    if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
409                        self.check_no_escape(value, max_depth)?;
410                    }
411                }
412            }
413
414            // Literals are always safe
415            Expr::Literal(_) => {}
416        }
417        Ok(())
418    }
419
420    /// Check that an expression doesn't escape via assignment
421    fn check_no_escape_with_target(
422        &self,
423        expr: &Expr<'_>,
424        max_depth: usize,
425        target: Symbol,
426    ) -> Result<(), EscapeError> {
427        match expr {
428            Expr::Identifier(sym) => {
429                if let Some(&depth) = self.zone_depth.get(sym) {
430                    if depth > max_depth && depth > 0 {
431                        let zone_name = self
432                            .zone_stack
433                            .get(depth - 1)
434                            .map(|s| self.interner.resolve(*s).to_string())
435                            .unwrap_or_else(|| "unknown".to_string());
436                        let var_name = self.interner.resolve(*sym).to_string();
437                        let target_name = self.interner.resolve(target).to_string();
438                        return Err(EscapeError {
439                            kind: EscapeErrorKind::AssignmentEscape {
440                                variable: var_name,
441                                target: target_name,
442                                zone_name,
443                            },
444                            span: Span::default(),
445                        });
446                    }
447                }
448            }
449            // For compound expressions, use the simpler check (return style error)
450            _ => self.check_no_escape(expr, max_depth)?,
451        }
452        Ok(())
453    }
454}
455
456#[cfg(test)]
457#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/escape/tests.rs"]
458mod tests;