Skip to main content

logicaffeine_compile/analysis/
ownership.rs

1//! Native ownership analysis for use-after-move detection.
2//!
3//! Lightweight data-flow analysis that catches use-after-move at check-time
4//! (milliseconds), before Rust compilation. This pass tracks `Owned`, `Moved`,
5//! and `Borrowed` states through control flow.
6//!
7//! Collections have value semantics in every tier: a call's plain argument and
8//! `Let b be a` each receive a copy, and the caller's value stays usable. Only
9//! GIVING moves — the `Give x to y.` statement, and `give x` as a call argument
10//! (`Call consume with give data.`), which the backend emits as a real move.
11//!
12//! # State Transitions
13//!
14//! ```text
15//!          Let x be value
16//!               │
17//!               ▼
18//!           [Owned] ── f(x) · Let y be x ──▶ [Owned]
19//!          /        \
20//!    Give x       Show x
21//!  … with give x      │
22//!        │            ▼
23//!        ▼       [Borrowed]
24//!    [Moved]          │
25//!        │        use x? ✓
26//!    use x?
27//!        │
28//!     ERROR: use-after-move
29//! ```
30//!
31//! # Control Flow Awareness
32//!
33//! The checker handles branches and loops by merging states:
34//! - `Moved` on one path + `Owned` on another = `MaybeMoved`, remembering whether a branch or a
35//!   loop made the move uncertain
36//! - A loop may run no pass at all, so its body's moves merge with the state before it
37//! - Using a `MaybeMoved` variable produces an error, wherever it is read: an `If` or `While`
38//!   condition, the collection a `Repeat` walks and the value an `Inspect` examines included
39//!
40//! # The Program as Written
41//!
42//! Ownership is a property of the program its author wrote, so every entry point runs this
43//! checker on the freshly-parsed statements, before any rewrite. Once `x` is a known constant,
44//! the optimizer's propagation turns `Give x to p.` into `Give 5 to p.` and `Show x.` into
45//! `Show 5.`, and folding flattens a constant `If` into its body: a checker fed that program
46//! would pass a use after a possible move, or call a possible move certain.
47//!
48//! # Example
49//!
50//! ```text
51//! Let x be 5.
52//! Give x to y.
53//! Show x to show.  ← Error: Cannot use 'x' after giving it away
54//! ```
55
56use crate::ast::stmt::{Expr, Stmt, StmtId};
57use crate::intern::{Interner, Symbol};
58use crate::token::Span;
59use std::collections::HashMap;
60
61/// Ownership state for a variable
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum VarState {
64    /// Variable is owned and can be used
65    Owned,
66    /// Variable has been moved (Give)
67    Moved,
68    /// Variable might be moved: some path through a branch or a loop gave it away
69    MaybeMoved(MaybeGivenIn),
70    /// Variable is borrowed (Show) - still usable
71    Borrowed,
72}
73
74/// Where a value may have been given away: the construct whose paths disagree about it.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum MaybeGivenIn {
77    /// One branch of an `If`, or one arm of an `Inspect`, gives it away and another does not.
78    Branch,
79    /// A loop's body gives it away, and the loop may run no pass at all.
80    Loop,
81}
82
83impl std::fmt::Display for MaybeGivenIn {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.write_str(match self {
86            MaybeGivenIn::Branch => "a conditional branch",
87            MaybeGivenIn::Loop => "a pass through the loop",
88        })
89    }
90}
91
92/// Error type for ownership violations
93#[derive(Debug, Clone)]
94pub struct OwnershipError {
95    pub kind: OwnershipErrorKind,
96    pub span: Span,
97}
98
99#[derive(Debug, Clone)]
100pub enum OwnershipErrorKind {
101    /// Use after move
102    UseAfterMove { variable: String },
103    /// Use after potential move (in a branch or a loop)
104    UseAfterMaybeMove {
105        variable: String,
106        given_in: MaybeGivenIn,
107    },
108    /// Double move
109    DoubleMoved { variable: String },
110}
111
112impl std::fmt::Display for OwnershipError {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        match &self.kind {
115            OwnershipErrorKind::UseAfterMove { variable } => {
116                write!(
117                    f,
118                    "Cannot use '{}' after giving it away.\n\n\
119                    You transferred ownership of '{}' with Give.\n\
120                    Once given, you cannot use it anymore.\n\n\
121                    Tip: Use Show instead to lend without giving up ownership.",
122                    variable, variable
123                )
124            }
125            OwnershipErrorKind::UseAfterMaybeMove { variable, given_in } => {
126                write!(
127                    f,
128                    "Cannot use '{variable}' - it might have been given away in {given_in}.\n\n"
129                )?;
130                match given_in {
131                    MaybeGivenIn::Branch => write!(f,
132                        "If that branch runs, '{variable}' is moved, so using it afterward is not safe.\n\n\
133                        Tip: Move the usage inside the branch, or restructure to ensure ownership."),
134                    MaybeGivenIn::Loop => write!(f,
135                        "If that pass runs, '{variable}' is moved, so using it afterward is not safe.\n\n\
136                        Tip: Give a copy on each pass ('Give a copy of {variable} to ...'), or bind a \
137                        fresh value inside the loop."),
138                }
139            }
140            OwnershipErrorKind::DoubleMoved { variable } => {
141                write!(
142                    f,
143                    "Cannot give '{}' twice.\n\n\
144                    You already transferred ownership of '{}' with Give.\n\
145                    You cannot give it again.\n\n\
146                    Tip: Consider using Copy to duplicate the value.",
147                    variable, variable
148                )
149            }
150        }
151    }
152}
153
154impl std::error::Error for OwnershipError {}
155
156/// Ownership checker - tracks variable states through control flow
157pub struct OwnershipChecker<'a> {
158    /// Maps variable symbols to their current ownership state
159    state: HashMap<Symbol, VarState>,
160    /// String interner for resolving symbols
161    interner: &'a Interner,
162    /// Which top-level statement moved each variable, and the statement that
163    /// did the moving — the cause link that
164    /// [`OwnershipChecker::check_program_collect`] reports for diagnostics.
165    moved_at: HashMap<Symbol, (usize, StmtId)>,
166    /// The top-level statement currently being checked (collect mode).
167    current_top_stmt: usize,
168    /// The innermost statement currently being checked.
169    current_stmt: Option<StmtId>,
170}
171
172/// One ownership finding with its statement coordinates: the top-level
173/// statement that ERRED, and (when known) the one that CAUSED it by moving
174/// the variable — both map 1:1 onto `Parser::stmt_spans()` — plus the exact
175/// statements, nested ones included, for `Parser::nested_stmt_spans()`:
176/// `trail` is the erring statement and each one around it, innermost first,
177/// and `cause` is the statement that gave the value away.
178#[derive(Debug)]
179pub struct OwnershipFinding {
180    pub stmt_index: usize,
181    pub cause_stmt_index: Option<usize>,
182    pub trail: Vec<StmtId>,
183    pub cause: Option<StmtId>,
184    pub error: OwnershipError,
185}
186
187/// An ownership error on its way out of the statements it was found in,
188/// naming each one as it passes, innermost first.
189struct Traced {
190    error: OwnershipError,
191    trail: Vec<StmtId>,
192}
193
194impl From<OwnershipError> for Traced {
195    fn from(error: OwnershipError) -> Self {
196        Traced {
197            error,
198            trail: Vec::new(),
199        }
200    }
201}
202
203impl<'a> OwnershipChecker<'a> {
204    pub fn new(interner: &'a Interner) -> Self {
205        Self {
206            state: HashMap::new(),
207            interner,
208            moved_at: HashMap::new(),
209            current_top_stmt: 0,
210            current_stmt: None,
211        }
212    }
213
214    /// Record a move, remembering which statement performed it.
215    fn mark_moved(&mut self, sym: Symbol) {
216        self.state.insert(sym, VarState::Moved);
217        if let Some(stmt) = self.current_stmt {
218            self.moved_at.insert(sym, (self.current_top_stmt, stmt));
219        }
220    }
221
222    /// The interned symbol behind an error's variable name, if still tracked.
223    fn symbol_for(&self, error: &OwnershipError) -> Option<Symbol> {
224        let name = match &error.kind {
225            OwnershipErrorKind::UseAfterMove { variable }
226            | OwnershipErrorKind::UseAfterMaybeMove { variable, .. }
227            | OwnershipErrorKind::DoubleMoved { variable } => variable,
228        };
229        self.state
230            .keys()
231            .copied()
232            .find(|s| self.interner.resolve(*s) == name)
233    }
234
235    /// Collect EVERY ownership finding instead of bailing at the first.
236    ///
237    /// After each finding the offending variable resets to `Owned`, so one
238    /// use-after-move does not cascade into errors on every later use.
239    /// [`OwnershipChecker::check_program`] keeps the strict fail-fast
240    /// contract for compile paths.
241    pub fn check_program_collect(&mut self, stmts: &[Stmt<'_>]) -> Vec<OwnershipFinding> {
242        let mut findings = Vec::new();
243        for (index, stmt) in stmts.iter().enumerate() {
244            self.current_top_stmt = index;
245            if let Err(Traced { error, trail }) = self.check_stmt(stmt) {
246                let sym = self.symbol_for(&error);
247                let cause = sym.and_then(|s| self.moved_at.get(&s).copied());
248                if let Some(s) = sym {
249                    self.state.insert(s, VarState::Owned);
250                }
251                findings.push(OwnershipFinding {
252                    stmt_index: index,
253                    cause_stmt_index: cause.map(|(top, _)| top),
254                    trail,
255                    cause: cause.map(|(_, stmt)| stmt),
256                    error,
257                });
258            }
259        }
260        findings
261    }
262
263    /// Access the current variable ownership states.
264    pub fn var_states(&self) -> &HashMap<Symbol, VarState> {
265        &self.state
266    }
267
268    /// Mark every value GIVEN inside an expression as Moved: `give x` as a call
269    /// argument hands `x` over (the backend emits a move, not a copy). A plain
270    /// argument is a copy under value semantics and moves nothing.
271    fn mark_gives_in_expr(&mut self, expr: &Expr) {
272        match expr {
273            Expr::Give { value } => {
274                if let Expr::Identifier(sym) = value {
275                    self.mark_moved(*sym);
276                }
277                self.mark_gives_in_expr(value);
278            }
279            Expr::Call { args, .. } | Expr::CallExpr { args, .. } => {
280                for arg in args.iter() {
281                    self.mark_gives_in_expr(arg);
282                }
283            }
284            Expr::BinaryOp { left, right, .. } => {
285                self.mark_gives_in_expr(left);
286                self.mark_gives_in_expr(right);
287            }
288            Expr::Index { collection, index } => {
289                self.mark_gives_in_expr(collection);
290                self.mark_gives_in_expr(index);
291            }
292            Expr::FieldAccess { object, .. } => {
293                self.mark_gives_in_expr(object);
294            }
295            _ => {}
296        }
297    }
298
299    /// Check a program for ownership violations
300    pub fn check_program(&mut self, stmts: &[Stmt<'_>]) -> Result<(), OwnershipError> {
301        self.check_block(stmts).map_err(|traced| traced.error)
302    }
303
304    fn check_block(&mut self, stmts: &[Stmt<'_>]) -> Result<(), Traced> {
305        for stmt in stmts {
306            self.check_stmt(stmt)?;
307        }
308        Ok(())
309    }
310
311    fn check_stmt(&mut self, stmt: &Stmt<'_>) -> Result<(), Traced> {
312        let id = StmtId::of(stmt);
313        let enclosing = self.current_stmt.replace(id);
314        let result = self.check_stmt_kind(stmt);
315        self.current_stmt = enclosing;
316        result.map_err(|mut traced| {
317            traced.trail.push(id);
318            traced
319        })
320    }
321
322    fn check_stmt_kind(&mut self, stmt: &Stmt<'_>) -> Result<(), Traced> {
323        match stmt {
324            Stmt::Let { var, value, .. } => {
325                self.check_not_moved(value)?;
326                self.mark_gives_in_expr(value);
327                self.state.insert(*var, VarState::Owned);
328            }
329
330            Stmt::Give { object, .. } => {
331                // Check if object is already moved
332                if let Expr::Identifier(sym) = object {
333                    let current = self.state.get(sym).copied().unwrap_or(VarState::Owned);
334                    match current {
335                        VarState::Moved => {
336                            return Err(OwnershipError {
337                                kind: OwnershipErrorKind::DoubleMoved {
338                                    variable: self.interner.resolve(*sym).to_string(),
339                                },
340                                span: Span::default(),
341                            }
342                            .into());
343                        }
344                        VarState::MaybeMoved(given_in) => {
345                            return Err(OwnershipError {
346                                kind: OwnershipErrorKind::UseAfterMaybeMove {
347                                    variable: self.interner.resolve(*sym).to_string(),
348                                    given_in,
349                                },
350                                span: Span::default(),
351                            }
352                            .into());
353                        }
354                        _ => {
355                            self.mark_moved(*sym);
356                        }
357                    }
358                } else {
359                    // For complex expressions, just check they're not moved
360                    self.check_not_moved(object)?;
361                }
362            }
363
364            Stmt::Show { object, .. } => {
365                // Check if object is moved before borrowing
366                self.check_not_moved(object)?;
367                // Mark as borrowed (still usable)
368                if let Expr::Identifier(sym) = object {
369                    let current = self.state.get(sym).copied();
370                    if current == Some(VarState::Owned) || current.is_none() {
371                        self.state.insert(*sym, VarState::Borrowed);
372                    }
373                }
374            }
375
376            Stmt::If {
377                cond,
378                then_block,
379                else_block,
380            } => {
381                self.check_not_moved(cond)?;
382                let state_before = self.state.clone();
383
384                self.check_block(then_block)?;
385                let state_after_then = std::mem::replace(&mut self.state, state_before);
386
387                if let Some(else_b) = else_block {
388                    self.check_block(else_b)?;
389                }
390
391                // Merge states: MaybeMoved if moved in any branch
392                self.state =
393                    Self::merge_states(&state_after_then, &self.state, MaybeGivenIn::Branch);
394            }
395
396            Stmt::While { cond, body, .. } => {
397                self.check_not_moved(cond)?;
398                self.check_loop_body(body)?;
399            }
400
401            Stmt::Repeat { iterable, body, .. } => {
402                self.check_not_moved(iterable)?;
403                self.check_loop_body(body)?;
404            }
405
406            Stmt::Zone { body, .. } => {
407                self.check_block(body)?;
408            }
409
410            // A `During` span is scope-transparent: its body runs once, in place.
411            Stmt::During { body, .. } => {
412                self.check_block(body)?;
413            }
414
415            Stmt::Inspect { target, arms, .. } => {
416                self.check_not_moved(target)?;
417                if arms.is_empty() {
418                    return Ok(());
419                }
420
421                // Clone state before branches
422                let state_before = self.state.clone();
423                let mut branch_states = Vec::new();
424
425                for arm in arms {
426                    self.state = state_before.clone();
427                    self.check_block(arm.body)?;
428                    branch_states.push(self.state.clone());
429                }
430
431                // Merge all branch states
432                if let Some(first) = branch_states.first() {
433                    let mut merged = first.clone();
434                    for state in branch_states.iter().skip(1) {
435                        merged = Self::merge_states(&merged, state, MaybeGivenIn::Branch);
436                    }
437                    self.state = merged;
438                }
439            }
440
441            Stmt::Return { value: Some(expr) } => {
442                self.check_not_moved(expr)?;
443                self.mark_gives_in_expr(expr);
444            }
445
446            Stmt::Return { value: None } => {}
447
448            Stmt::Set { value, .. } => {
449                self.check_not_moved(value)?;
450                self.mark_gives_in_expr(value);
451            }
452
453            Stmt::Call { args, .. } => {
454                for arg in args.iter() {
455                    self.check_not_moved(arg)?;
456                }
457                for arg in args.iter() {
458                    self.mark_gives_in_expr(arg);
459                }
460            }
461
462            Stmt::FunctionDef { params, body, .. } => {
463                // Save state — function body is a separate scope
464                let saved_state = self.state.clone();
465                for (param_sym, _) in params.iter() {
466                    self.state.insert(*param_sym, VarState::Owned);
467                }
468                self.check_block(body)?;
469                self.state = saved_state;
470            }
471
472            // Escape blocks are opaque to ownership analysis — the Rust compiler
473            // catches use-after-move in the generated code
474            Stmt::Escape { .. } => {}
475
476            // Other statements don't affect ownership
477            _ => {}
478        }
479        Ok(())
480    }
481
482    /// Check that an expression doesn't reference a moved variable
483    fn check_not_moved(&self, expr: &Expr<'_>) -> Result<(), OwnershipError> {
484        match expr {
485            // A view's holes read where it renders; handler blocks are closures (checked when called).
486            Expr::Dom(q) => match q.selector() {
487                Some(sel) => self.check_not_moved(sel),
488                None => Ok(()),
489            },
490            Expr::View(v) => {
491                for e in v.exprs_and_blocks().0 {
492                    self.check_not_moved(e)?;
493                }
494                Ok(())
495            }
496            Expr::InterpolatedString(parts) => {
497                for part in parts {
498                    if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
499                        self.check_not_moved(value)?;
500                    }
501                }
502                Ok(())
503            }
504            Expr::Identifier(sym) => match self.state.get(sym).copied() {
505                Some(VarState::Moved) => Err(OwnershipError {
506                    kind: OwnershipErrorKind::UseAfterMove {
507                        variable: self.interner.resolve(*sym).to_string(),
508                    },
509                    span: Span::default(),
510                }),
511                Some(VarState::MaybeMoved(given_in)) => Err(OwnershipError {
512                    kind: OwnershipErrorKind::UseAfterMaybeMove {
513                        variable: self.interner.resolve(*sym).to_string(),
514                        given_in,
515                    },
516                    span: Span::default(),
517                }),
518                _ => Ok(()),
519            },
520            Expr::BinaryOp { left, right, .. } => {
521                self.check_not_moved(left)?;
522                self.check_not_moved(right)?;
523                Ok(())
524            }
525            Expr::FieldAccess { object, .. } => self.check_not_moved(object),
526            Expr::Index { collection, index } => {
527                self.check_not_moved(collection)?;
528                self.check_not_moved(index)?;
529                Ok(())
530            }
531            Expr::Slice {
532                collection,
533                start,
534                end,
535            } => {
536                self.check_not_moved(collection)?;
537                self.check_not_moved(start)?;
538                self.check_not_moved(end)?;
539                Ok(())
540            }
541            Expr::Call { args, .. } => {
542                for arg in args {
543                    self.check_not_moved(arg)?;
544                }
545                Ok(())
546            }
547            Expr::List(items) | Expr::Tuple(items) => {
548                for item in items {
549                    self.check_not_moved(item)?;
550                }
551                Ok(())
552            }
553            Expr::Range { start, end } => {
554                self.check_not_moved(start)?;
555                self.check_not_moved(end)?;
556                Ok(())
557            }
558            Expr::New { init_fields, .. } => {
559                for (_, field_expr) in init_fields {
560                    self.check_not_moved(field_expr)?;
561                }
562                Ok(())
563            }
564            Expr::NewVariant { fields, .. } => {
565                for (_, field_expr) in fields {
566                    self.check_not_moved(field_expr)?;
567                }
568                Ok(())
569            }
570            Expr::Copy { expr }
571            | Expr::Give { value: expr }
572            | Expr::Length { collection: expr }
573            | Expr::Not { operand: expr } => self.check_not_moved(expr),
574            Expr::ManifestOf { zone } => self.check_not_moved(zone),
575            Expr::ChunkAt { index, zone } => {
576                self.check_not_moved(index)?;
577                self.check_not_moved(zone)
578            }
579            Expr::Contains { collection, value } => {
580                self.check_not_moved(collection)?;
581                self.check_not_moved(value)
582            }
583            Expr::Union { left, right } | Expr::Intersection { left, right } => {
584                self.check_not_moved(left)?;
585                self.check_not_moved(right)
586            }
587            Expr::WithCapacity { value, capacity } => {
588                self.check_not_moved(value)?;
589                self.check_not_moved(capacity)
590            }
591            Expr::OptionSome { value } => self.check_not_moved(value),
592            Expr::OptionNone => Ok(()),
593
594            // Escape expressions are opaque — the Rust compiler handles ownership for raw code
595            Expr::Escape { .. } => Ok(()),
596
597            // Closures capture by cloning — no ownership transfer at creation time.
598            // We only check the expression body for moved variables; block bodies
599            // create their own scope so ownership is handled there.
600            Expr::Closure { body, .. } => match body {
601                crate::ast::stmt::ClosureBody::Expression(expr) => self.check_not_moved(expr),
602                crate::ast::stmt::ClosureBody::Block(_) => Ok(()),
603            },
604
605            Expr::CallExpr { callee, args } => {
606                self.check_not_moved(callee)?;
607                for arg in args {
608                    self.check_not_moved(arg)?;
609                }
610                Ok(())
611            }
612
613            // Literals are always safe
614            Expr::Literal(_) => Ok(()),
615        }
616    }
617
618    /// A loop may run no pass at all, so what its body gives away may still be there after it:
619    /// the state after the loop is the state before it merged with the state one pass leaves.
620    fn check_loop_body(&mut self, body: &[Stmt<'_>]) -> Result<(), Traced> {
621        let state_before = self.state.clone();
622        self.check_block(body)?;
623        self.state = Self::merge_states(&state_before, &self.state, MaybeGivenIn::Loop);
624        Ok(())
625    }
626
627    /// Merge the states two paths reach where they meet — if moved on one path but not the
628    /// other, the value is MaybeMoved, given away in the construct `given_in` names. A variable
629    /// only one path declares keeps that path's state.
630    fn merge_states(
631        state_a: &HashMap<Symbol, VarState>,
632        state_b: &HashMap<Symbol, VarState>,
633        given_in: MaybeGivenIn,
634    ) -> HashMap<Symbol, VarState> {
635        let mut merged = state_a.clone();
636
637        for (sym, state_b_val) in state_b {
638            let state_a_val = state_a.get(sym).copied().unwrap_or(VarState::Owned);
639
640            let merged_val = match (state_a_val, *state_b_val) {
641                // Both moved = definitely moved
642                (VarState::Moved, VarState::Moved) => VarState::Moved,
643                // Already maybe moved = still maybe moved, where it first became uncertain
644                (VarState::MaybeMoved(earlier), _) | (_, VarState::MaybeMoved(earlier)) => {
645                    VarState::MaybeMoved(earlier)
646                }
647                // One moved, one not = maybe moved, here
648                (VarState::Moved, _) | (_, VarState::Moved) => VarState::MaybeMoved(given_in),
649                // Both borrowed = borrowed
650                (VarState::Borrowed, VarState::Borrowed) => VarState::Borrowed,
651                // Borrowed + Owned = Borrowed (conservative)
652                (VarState::Borrowed, _) | (_, VarState::Borrowed) => VarState::Borrowed,
653                // Both owned = owned
654                (VarState::Owned, VarState::Owned) => VarState::Owned,
655            };
656
657            merged.insert(*sym, merged_val);
658        }
659
660        merged
661    }
662}
663
664#[cfg(test)]
665#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/ownership/tests.rs"]
666mod tests;