logicaffeine_compile/analysis/
escape.rs1use crate::ast::stmt::{Expr, Stmt, StmtId};
28use crate::intern::{Interner, Symbol};
29use crate::token::Span;
30use std::collections::HashMap;
31
32#[derive(Debug, Clone)]
34pub struct EscapeError {
35 pub kind: EscapeErrorKind,
36 pub span: Span,
37}
38
39#[derive(Debug, Clone)]
40pub enum EscapeErrorKind {
41 ReturnEscape { variable: String, zone_name: String },
43 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#[derive(Debug)]
92pub struct EscapeFinding {
93 pub stmt_index: usize,
94 pub trail: Vec<StmtId>,
95 pub error: EscapeError,
96}
97
98struct 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 zone_depth: HashMap<Symbol, usize>,
117 current_depth: usize,
119 zone_stack: Vec<Symbol>,
121 interner: &'a Interner,
123}
124
125impl<'a> EscapeChecker<'a> {
126 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 pub fn check_program(&mut self, stmts: &[Stmt<'_>]) -> Result<(), EscapeError> {
138 self.check_block(stmts).map_err(|traced| traced.error)
139 }
140
141 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 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 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 self.current_depth += 1;
179 self.zone_stack.push(*name);
180
181 let body_result = self.check_block(body);
183
184 self.zone_stack.pop();
187 self.current_depth -= 1;
188 body_result?;
189 }
190
191 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 self.zone_depth.insert(*var, self.current_depth);
203 }
204
205 Stmt::Return { value: Some(expr) } => {
206 self.check_no_escape(expr, 0)?;
208 }
209
210 Stmt::Set { target, value } => {
211 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 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 Stmt::During { body, .. } => {
244 self.check_block(body)?;
245 }
246
247 Stmt::Escape { .. } => {}
249
250 _ => {}
252 }
253 Ok(())
254 }
255
256 fn check_no_escape(&self, expr: &Expr<'_>, max_depth: usize) -> Result<(), EscapeError> {
258 match expr {
259 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 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 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 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 }
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 Expr::Literal(_) => {}
416 }
417 Ok(())
418 }
419
420 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 _ => 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;