logicaffeine-compile 0.9.0

LOGOS compilation pipeline - codegen and interpreter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Native ownership analysis for use-after-move detection.
//!
//! Lightweight data-flow analysis that catches the 90% common ownership errors
//! at check-time (milliseconds), before Rust compilation. This pass tracks
//! `Owned`, `Moved`, and `Borrowed` states through control flow.
//!
//! # State Transitions
//!
//! ```text
//!          Let x be value
//!//!//!           [Owned]
//!          /        \
//!    Give x       Show x
//!        │            │
//!        ▼            ▼
//!    [Moved]     [Borrowed]
//!        │            │
//!    use x?      use x? ✓
//!//!     ERROR: use-after-move
//! ```
//!
//! # Control Flow Awareness
//!
//! The checker handles branches by merging states:
//! - `Moved` in one branch + `Owned` in other = `MaybeMoved`
//! - Using a `MaybeMoved` variable produces an error
//!
//! # Example
//!
//! ```text
//! Let x be 5.
//! Give x to y.
//! Show x to show.  ← Error: Cannot use 'x' after giving it away
//! ```

use std::collections::HashMap;
use crate::ast::stmt::{BinaryOpKind, Literal, Stmt, Expr, TypeExpr};
use crate::intern::{Interner, Symbol};
use crate::token::Span;

/// Ownership state for a variable
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VarState {
    /// Variable is owned and can be used
    Owned,
    /// Variable has been moved (Give)
    Moved,
    /// Variable might be moved (conditional branch)
    MaybeMoved,
    /// Variable is borrowed (Show) - still usable
    Borrowed,
}

/// Error type for ownership violations
#[derive(Debug, Clone)]
pub struct OwnershipError {
    pub kind: OwnershipErrorKind,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub enum OwnershipErrorKind {
    /// Use after move
    UseAfterMove { variable: String },
    /// Use after potential move (in conditional)
    UseAfterMaybeMove { variable: String, branch: String },
    /// Double move
    DoubleMoved { variable: String },
}

impl std::fmt::Display for OwnershipError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            OwnershipErrorKind::UseAfterMove { variable } => {
                write!(f, "Cannot use '{}' after giving it away.\n\n\
                    You transferred ownership of '{}' with Give.\n\
                    Once given, you cannot use it anymore.\n\n\
                    Tip: Use Show instead to lend without giving up ownership.",
                    variable, variable)
            }
            OwnershipErrorKind::UseAfterMaybeMove { variable, branch } => {
                write!(f, "Cannot use '{}' - it might have been given away in {}.\n\n\
                    If the {} branch executes, '{}' will be moved.\n\
                    Using it afterward is not safe.\n\n\
                    Tip: Move the usage inside the branch, or restructure to ensure ownership.",
                    variable, branch, branch, variable)
            }
            OwnershipErrorKind::DoubleMoved { variable } => {
                write!(f, "Cannot give '{}' twice.\n\n\
                    You already transferred ownership of '{}' with Give.\n\
                    You cannot give it again.\n\n\
                    Tip: Consider using Copy to duplicate the value.",
                    variable, variable)
            }
        }
    }
}

impl std::error::Error for OwnershipError {}

/// Ownership checker - tracks variable states through control flow
pub struct OwnershipChecker<'a> {
    /// Maps variable symbols to their current ownership state
    state: HashMap<Symbol, VarState>,
    /// Tracks whether each variable is a Copy type (true = Copy, absent = unknown/Copy)
    types: HashMap<Symbol, bool>,
    /// String interner for resolving symbols
    interner: &'a Interner,
}

impl<'a> OwnershipChecker<'a> {
    pub fn new(interner: &'a Interner) -> Self {
        Self {
            state: HashMap::new(),
            types: HashMap::new(),
            interner,
        }
    }

    /// Access the current variable ownership states.
    pub fn var_states(&self) -> &HashMap<Symbol, VarState> {
        &self.state
    }

    /// Returns true if a symbol is known to be a Copy type.
    /// Unknown types conservatively return true (won't produce false positives).
    fn is_copy_sym(&self, sym: Symbol) -> bool {
        self.types.get(&sym).copied().unwrap_or(true)
    }

    /// Infer whether an expression produces a Copy type.
    /// Conservative: returns true (Copy) when uncertain.
    fn infer_copy_from_expr(&self, expr: &Expr) -> bool {
        match expr {
            Expr::Literal(Literal::Number(_)) => true,
            Expr::Literal(Literal::Float(_)) => true,
            Expr::Literal(Literal::Boolean(_)) => true,
            Expr::Literal(Literal::Nothing) => true,
            Expr::Literal(Literal::Text(_)) => false,
            Expr::Identifier(sym) => self.is_copy_sym(*sym),
            Expr::New { .. } => false,
            Expr::List(_) => false,
            Expr::InterpolatedString(_) => false,
            Expr::Copy { .. } => true,
            Expr::BinaryOp { op: BinaryOpKind::Concat, .. } => false,
            Expr::BinaryOp { .. } => true,
            Expr::Contains { .. } => true,
            Expr::Length { .. } => true,
            _ => true,
        }
    }

    /// After an expression has been validated, walk it to mark non-Copy
    /// function call arguments as Moved.
    fn mark_moves_in_expr(&mut self, expr: &Expr) {
        match expr {
            Expr::Call { args, .. } | Expr::CallExpr { args, .. } => {
                for arg in args.iter() {
                    if let Expr::Identifier(sym) = arg {
                        if !self.is_copy_sym(*sym) {
                            self.state.insert(*sym, VarState::Moved);
                        }
                    }
                    self.mark_moves_in_expr(arg);
                }
            }
            Expr::BinaryOp { left, right, .. } => {
                self.mark_moves_in_expr(left);
                self.mark_moves_in_expr(right);
            }
            Expr::Index { collection, index } => {
                self.mark_moves_in_expr(collection);
                self.mark_moves_in_expr(index);
            }
            Expr::FieldAccess { object, .. } => {
                self.mark_moves_in_expr(object);
            }
            _ => {}
        }
    }

    /// Infer Copy-ness from a TypeExpr (function parameter type annotation).
    /// Conservative: returns true (Copy) when uncertain.
    fn infer_copy_from_type_name(&self, ty: &TypeExpr) -> bool {
        match ty {
            TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
                let name = self.interner.resolve(*sym);
                matches!(name, "Int" | "Nat" | "Float" | "Bool" | "Char" | "Byte")
            }
            TypeExpr::Generic { .. } => false,
            TypeExpr::Function { .. } => true,
            _ => true,
        }
    }

    /// Check a program for ownership violations
    pub fn check_program(&mut self, stmts: &[Stmt<'_>]) -> Result<(), OwnershipError> {
        self.check_block(stmts)
    }

    fn check_block(&mut self, stmts: &[Stmt<'_>]) -> Result<(), OwnershipError> {
        for stmt in stmts {
            self.check_stmt(stmt)?;
        }
        Ok(())
    }

    fn check_stmt(&mut self, stmt: &Stmt<'_>) -> Result<(), OwnershipError> {
        match stmt {
            Stmt::Let { var, value, .. } => {
                // Check the value expression first
                self.check_not_moved(value)?;
                // Mark non-Copy identifiers used as values as Moved
                if let Expr::Identifier(sym) = value {
                    if !self.is_copy_sym(*sym) {
                        self.state.insert(*sym, VarState::Moved);
                    }
                }
                // Mark non-Copy function call arguments as Moved
                self.mark_moves_in_expr(value);
                // Register variable as Owned and track its type
                let is_copy = self.infer_copy_from_expr(value);
                self.state.insert(*var, VarState::Owned);
                self.types.insert(*var, is_copy);
            }

            Stmt::Give { object, .. } => {
                // Check if object is already moved
                if let Expr::Identifier(sym) = object {
                    let current = self.state.get(sym).copied().unwrap_or(VarState::Owned);
                    match current {
                        VarState::Moved => {
                            return Err(OwnershipError {
                                kind: OwnershipErrorKind::DoubleMoved {
                                    variable: self.interner.resolve(*sym).to_string(),
                                },
                                span: Span::default(),
                            });
                        }
                        VarState::MaybeMoved => {
                            return Err(OwnershipError {
                                kind: OwnershipErrorKind::UseAfterMaybeMove {
                                    variable: self.interner.resolve(*sym).to_string(),
                                    branch: "a previous branch".to_string(),
                                },
                                span: Span::default(),
                            });
                        }
                        _ => {
                            self.state.insert(*sym, VarState::Moved);
                        }
                    }
                } else {
                    // For complex expressions, just check they're not moved
                    self.check_not_moved(object)?;
                }
            }

            Stmt::Show { object, .. } => {
                // Check if object is moved before borrowing
                self.check_not_moved(object)?;
                // Mark as borrowed (still usable)
                if let Expr::Identifier(sym) = object {
                    let current = self.state.get(sym).copied();
                    if current == Some(VarState::Owned) || current.is_none() {
                        self.state.insert(*sym, VarState::Borrowed);
                    }
                }
            }

            Stmt::If { then_block, else_block, .. } => {
                // Clone state before branching
                let state_before = self.state.clone();

                // Check then branch
                self.check_block(then_block)?;
                let state_after_then = self.state.clone();

                // Check else branch (if exists)
                let state_after_else = if let Some(else_b) = else_block {
                    self.state = state_before.clone();
                    self.check_block(else_b)?;
                    self.state.clone()
                } else {
                    state_before.clone()
                };

                // Merge states: MaybeMoved if moved in any branch
                self.state = self.merge_states(&state_after_then, &state_after_else);
            }

            Stmt::While { body, .. } => {
                // Clone state before loop
                let state_before = self.state.clone();

                // Check body once
                self.check_block(body)?;
                let state_after_body = self.state.clone();

                // Merge: if moved in body, mark as MaybeMoved
                // (loop might not execute, or might execute multiple times)
                self.state = self.merge_states(&state_before, &state_after_body);
            }

            Stmt::Repeat { body, .. } => {
                // Check body once
                self.check_block(body)?;
            }

            Stmt::Zone { body, .. } => {
                self.check_block(body)?;
            }

            Stmt::Inspect { arms, .. } => {
                if arms.is_empty() {
                    return Ok(());
                }

                // Clone state before branches
                let state_before = self.state.clone();
                let mut branch_states = Vec::new();

                for arm in arms {
                    self.state = state_before.clone();
                    self.check_block(arm.body)?;
                    branch_states.push(self.state.clone());
                }

                // Merge all branch states
                if let Some(first) = branch_states.first() {
                    let mut merged = first.clone();
                    for state in branch_states.iter().skip(1) {
                        merged = self.merge_states(&merged, state);
                    }
                    self.state = merged;
                }
            }

            Stmt::Return { value: Some(expr) } => {
                self.check_not_moved(expr)?;
                self.mark_moves_in_expr(expr);
            }

            Stmt::Return { value: None } => {}

            Stmt::Set { value, .. } => {
                self.check_not_moved(value)?;
                // Mark non-Copy function call arguments as Moved
                self.mark_moves_in_expr(value);
            }

            Stmt::Call { args, .. } => {
                for arg in args.iter() {
                    self.check_not_moved(arg)?;
                }
                // Mark non-Copy identifier arguments as Moved
                for arg in args.iter() {
                    if let Expr::Identifier(sym) = arg {
                        if !self.is_copy_sym(*sym) {
                            self.state.insert(*sym, VarState::Moved);
                        }
                    }
                }
            }

            Stmt::FunctionDef { params, body, .. } => {
                // Save state — function body is a separate scope
                let saved_state = self.state.clone();
                let saved_types = self.types.clone();
                // Register parameters as Owned with inferred Copy-ness
                for (param_sym, param_type) in params.iter() {
                    self.state.insert(*param_sym, VarState::Owned);
                    let is_copy = self.infer_copy_from_type_name(param_type);
                    self.types.insert(*param_sym, is_copy);
                }
                self.check_block(body)?;
                self.state = saved_state;
                self.types = saved_types;
            }

            // Escape blocks are opaque to ownership analysis — the Rust compiler
            // catches use-after-move in the generated code
            Stmt::Escape { .. } => {}

            // Other statements don't affect ownership
            _ => {}
        }
        Ok(())
    }

    /// Check that an expression doesn't reference a moved variable
    fn check_not_moved(&self, expr: &Expr<'_>) -> Result<(), OwnershipError> {
        match expr {
            Expr::InterpolatedString(parts) => {
                for part in parts {
                    if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
                        self.check_not_moved(value)?;
                    }
                }
                Ok(())
            }
            Expr::Identifier(sym) => {
                match self.state.get(sym).copied() {
                    Some(VarState::Moved) => {
                        Err(OwnershipError {
                            kind: OwnershipErrorKind::UseAfterMove {
                                variable: self.interner.resolve(*sym).to_string(),
                            },
                            span: Span::default(),
                        })
                    }
                    Some(VarState::MaybeMoved) => {
                        Err(OwnershipError {
                            kind: OwnershipErrorKind::UseAfterMaybeMove {
                                variable: self.interner.resolve(*sym).to_string(),
                                branch: "a conditional branch".to_string(),
                            },
                            span: Span::default(),
                        })
                    }
                    _ => Ok(())
                }
            }
            Expr::BinaryOp { left, right, .. } => {
                self.check_not_moved(left)?;
                self.check_not_moved(right)?;
                Ok(())
            }
            Expr::FieldAccess { object, .. } => {
                self.check_not_moved(object)
            }
            Expr::Index { collection, index } => {
                self.check_not_moved(collection)?;
                self.check_not_moved(index)?;
                Ok(())
            }
            Expr::Slice { collection, start, end } => {
                self.check_not_moved(collection)?;
                self.check_not_moved(start)?;
                self.check_not_moved(end)?;
                Ok(())
            }
            Expr::Call { args, .. } => {
                for arg in args {
                    self.check_not_moved(arg)?;
                }
                Ok(())
            }
            Expr::List(items) | Expr::Tuple(items) => {
                for item in items {
                    self.check_not_moved(item)?;
                }
                Ok(())
            }
            Expr::Range { start, end } => {
                self.check_not_moved(start)?;
                self.check_not_moved(end)?;
                Ok(())
            }
            Expr::New { init_fields, .. } => {
                for (_, field_expr) in init_fields {
                    self.check_not_moved(field_expr)?;
                }
                Ok(())
            }
            Expr::NewVariant { fields, .. } => {
                for (_, field_expr) in fields {
                    self.check_not_moved(field_expr)?;
                }
                Ok(())
            }
            Expr::Copy { expr } | Expr::Give { value: expr } | Expr::Length { collection: expr }
            | Expr::Not { operand: expr } => {
                self.check_not_moved(expr)
            }
            Expr::ManifestOf { zone } => {
                self.check_not_moved(zone)
            }
            Expr::ChunkAt { index, zone } => {
                self.check_not_moved(index)?;
                self.check_not_moved(zone)
            }
            Expr::Contains { collection, value } => {
                self.check_not_moved(collection)?;
                self.check_not_moved(value)
            }
            Expr::Union { left, right } | Expr::Intersection { left, right } => {
                self.check_not_moved(left)?;
                self.check_not_moved(right)
            }
            Expr::WithCapacity { value, capacity } => {
                self.check_not_moved(value)?;
                self.check_not_moved(capacity)
            }
            Expr::OptionSome { value } => self.check_not_moved(value),
            Expr::OptionNone => Ok(()),

            // Escape expressions are opaque — the Rust compiler handles ownership for raw code
            Expr::Escape { .. } => Ok(()),

            // Closures capture by cloning — no ownership transfer at creation time.
            // We only check the expression body for moved variables; block bodies
            // create their own scope so ownership is handled there.
            Expr::Closure { body, .. } => {
                match body {
                    crate::ast::stmt::ClosureBody::Expression(expr) => {
                        self.check_not_moved(expr)
                    }
                    crate::ast::stmt::ClosureBody::Block(_) => Ok(()),
                }
            }

            Expr::CallExpr { callee, args } => {
                self.check_not_moved(callee)?;
                for arg in args {
                    self.check_not_moved(arg)?;
                }
                Ok(())
            }

            // Literals are always safe
            Expr::Literal(_) => Ok(()),
        }
    }

    /// Merge two branch states - if moved in either, mark as MaybeMoved
    fn merge_states(
        &self,
        state_a: &HashMap<Symbol, VarState>,
        state_b: &HashMap<Symbol, VarState>,
    ) -> HashMap<Symbol, VarState> {
        let mut merged = state_a.clone();

        // Merge keys from state_b
        for (sym, state_b_val) in state_b {
            let state_a_val = state_a.get(sym).copied().unwrap_or(VarState::Owned);

            let merged_val = match (state_a_val, *state_b_val) {
                // Both moved = definitely moved
                (VarState::Moved, VarState::Moved) => VarState::Moved,
                // One moved, one not = maybe moved
                (VarState::Moved, _) | (_, VarState::Moved) => VarState::MaybeMoved,
                // Any maybe moved = maybe moved
                (VarState::MaybeMoved, _) | (_, VarState::MaybeMoved) => VarState::MaybeMoved,
                // Both borrowed = borrowed
                (VarState::Borrowed, VarState::Borrowed) => VarState::Borrowed,
                // Borrowed + Owned = Borrowed (conservative)
                (VarState::Borrowed, _) | (_, VarState::Borrowed) => VarState::Borrowed,
                // Both owned = owned
                (VarState::Owned, VarState::Owned) => VarState::Owned,
            };

            merged.insert(*sym, merged_val);
        }

        // Also check keys only in state_a
        for sym in state_a.keys() {
            if !state_b.contains_key(sym) {
                // Variable exists in one branch but not other - keep state_a value
                // (already in merged)
            }
        }

        merged
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ownership_checker_basic() {
        let interner = Interner::new();
        let checker = OwnershipChecker::new(&interner);
        assert!(checker.state.is_empty());
    }
}