Skip to main content

logicaffeine_compile/optimize/
supercompile.rs

1//! Supercompiler — a unified optimization pass that subsumes constant folding,
2//! propagation, dead code elimination, and compile-time function evaluation
3//! in a single framework.
4//!
5//! The supercompiler performs online partial evaluation via:
6//!   1. **Driving** — symbolic execution one step at a time, maintaining an
7//!      abstract store mapping variables to known values
8//!   2. **Folding** — memoizing function evaluation results to avoid
9//!      recomputation and detect infinite recursion
10//!   3. **Generalization** — widening variables modified in loops to ensure
11//!      termination of the analysis
12//!
13//! Scope: pure integer/boolean code only. Collections, IO, and escape blocks
14//! are treated conservatively (passed through unchanged).
15
16use std::collections::HashMap;
17
18use super::capture::{self, EntryBinders};
19use super::writes::{CalleeGlobals, WriteSet};
20use crate::arena::Arena;
21use crate::ast::stmt::{BinaryOpKind, Block, Expr, Literal, Stmt};
22use crate::intern::{Interner, Symbol};
23
24const MAX_INLINE_DEPTH: usize = 64;
25const MAX_INLINE_STEPS: usize = 10_000;
26
27#[derive(Debug, Clone)]
28enum Value {
29    Int(i64),
30    Float(f64),
31    Bool(bool),
32    Text(Symbol),
33    Nothing,
34    /// A statically-known array (a `Seq`/`List` built from literals under constant-trip loops). Its presence
35    /// in the store lets a matmul/reduction over it be *executed at compile time* — the loops and the array
36    /// itself vanish, leaving only the result constants. A `Seq` value never propagates as a literal (only its
37    /// elements do, via `Index` folding).
38    Seq(Vec<Value>),
39}
40
41impl PartialEq for Value {
42    fn eq(&self, other: &Self) -> bool {
43        match (self, other) {
44            (Value::Int(a), Value::Int(b)) => a == b,
45            (Value::Float(a), Value::Float(b)) => a.to_bits() == b.to_bits(),
46            (Value::Bool(a), Value::Bool(b)) => a == b,
47            (Value::Text(a), Value::Text(b)) => a == b,
48            (Value::Nothing, Value::Nothing) => true,
49            (Value::Seq(a), Value::Seq(b)) => a == b,
50            _ => false,
51        }
52    }
53}
54
55impl Eq for Value {}
56
57impl std::hash::Hash for Value {
58    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
59        std::mem::discriminant(self).hash(state);
60        match self {
61            Value::Int(n) => n.hash(state),
62            Value::Float(f) => f.to_bits().hash(state),
63            Value::Bool(b) => b.hash(state),
64            Value::Text(s) => s.hash(state),
65            Value::Nothing => {}
66            Value::Seq(v) => v.hash(state),
67        }
68    }
69}
70
71struct FuncDef<'a> {
72    params: Vec<Symbol>,
73    body: Block<'a>,
74}
75
76#[derive(Clone)]
77struct Configuration<'a> {
78    expr: &'a Expr<'a>,
79}
80
81struct History<'a> {
82    entries: Vec<Configuration<'a>>,
83}
84
85impl<'a> History<'a> {
86    fn new() -> Self {
87        Self {
88            entries: Vec::new(),
89        }
90    }
91
92    fn push(&mut self, config: Configuration<'a>) {
93        if self.entries.len() >= 16 {
94            self.entries.remove(0);
95        }
96        self.entries.push(config);
97    }
98
99    fn check_embedding(&self, new_expr: &Expr<'a>) -> Option<&Configuration<'a>> {
100        self.entries.iter().find(|c| embeds(c.expr, new_expr))
101    }
102}
103
104struct SuperEnv<'a> {
105    store: HashMap<Symbol, Value>,
106    funcs: HashMap<Symbol, FuncDef<'a>>,
107    memo: HashMap<(Symbol, Vec<Value>), Option<Value>>,
108    steps: usize,
109    history: History<'a>,
110    /// Whether ARRAY supercompilation (Value::Seq tracking, Index folding, concrete static-loop execution) is
111    /// enabled for THIS program. Off unless the whole program is in the pure static-array fragment
112    /// ([`is_pure_static_array_program`]) — so a program that Pops/slices/aliases an array, calls a native or
113    /// user function, or takes runtime input is driven EXACTLY as the original supercompiler (no perturbation,
114    /// no unsound stale-array fold). Confines the tensor fold to the fragment it soundly models.
115    array_fold: bool,
116    /// Globals that some function mutates (writes without declaring locally). A `Call` can change any of these
117    /// under the driver, so they are dropped from `store` at every call site — otherwise a global written by a
118    /// callee would be folded to its stale pre-call value (the `Set counter` in `bump` soundness bug). Opaque
119    /// (a callee runs foreign code) means a call may write anything: the whole store is dropped.
120    callee_globals: CalleeGlobals,
121}
122
123impl<'a> SuperEnv<'a> {
124    fn new() -> Self {
125        Self {
126            store: HashMap::new(),
127            funcs: HashMap::new(),
128            memo: HashMap::new(),
129            steps: 0,
130            history: History::new(),
131            array_fold: false,
132            callee_globals: CalleeGlobals::default(),
133        }
134    }
135
136    /// Everything a statement or block may write ([`WriteSet`]) — its binders, assignments, in-place
137    /// mutations, what it lends, and the callee-written globals when it calls anything.
138    fn writes_of(&self, written: WriteSet) -> WriteSet {
139        written.with_callee_globals(&self.callee_globals)
140    }
141}
142
143/// Drop from `store` every name `written` may change — all of them when foreign code ran.
144fn forget(store: &mut HashMap<Symbol, Value>, written: &WriteSet) {
145    if written.is_opaque() {
146        store.clear();
147    } else {
148        for sym in written.symbols() {
149            store.remove(&sym);
150        }
151    }
152}
153
154/// Whether this evaluator can run a body: only the statement and expression shapes it executes. Whether running it
155/// is sound is [`super::purity::Purity`]'s question, which every caller asks too. `pub(crate)` so the run-path
156/// memoizer ([`super::memoize_run`]) transforms only the shapes this evaluator agrees on.
157pub(crate) fn evaluable_body(stmts: &[Stmt]) -> bool {
158    stmts.iter().all(is_pure_stmt)
159}
160
161fn is_pure_stmt(stmt: &Stmt) -> bool {
162    match stmt {
163        Stmt::Let { value, .. } => is_pure_expr(value),
164        Stmt::Set { value, .. } => is_pure_expr(value),
165        Stmt::Return { value } => value.map_or(true, is_pure_expr),
166        Stmt::If {
167            cond,
168            then_block,
169            else_block,
170        } => {
171            is_pure_expr(cond)
172                && evaluable_body(then_block)
173                && else_block.map_or(true, |eb| evaluable_body(eb))
174        }
175        Stmt::While { cond, body, .. } => is_pure_expr(cond) && evaluable_body(body),
176        Stmt::Call { .. } => true,
177        _ => false,
178    }
179}
180
181fn is_pure_expr(expr: &Expr) -> bool {
182    match expr {
183        Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone => true,
184        Expr::BinaryOp { left, right, .. } => is_pure_expr(left) && is_pure_expr(right),
185        Expr::Not { operand } => is_pure_expr(operand),
186        Expr::Call { args, .. } => args.iter().all(|a| is_pure_expr(a)),
187        Expr::Length { collection } => is_pure_expr(collection),
188        Expr::FieldAccess { object, .. } => is_pure_expr(object),
189        Expr::Index { collection, index } => is_pure_expr(collection) && is_pure_expr(index),
190        _ => false,
191    }
192}
193
194fn collect_pure_funcs<'a>(stmts: &[Stmt<'a>], interner: &Interner) -> HashMap<Symbol, FuncDef<'a>> {
195    let purity = super::purity::Purity::of_program(stmts, interner);
196    let mut funcs = HashMap::new();
197    for stmt in stmts {
198        if let Stmt::FunctionDef {
199            name,
200            params,
201            body,
202            is_native,
203            ..
204        } = stmt
205        {
206            // A function with a `mutable` parameter writes its caller's binding: its answer is
207            // not the whole of what a call to it does, so it is never evaluated to a value.
208            if *is_native
209                || params
210                    .iter()
211                    .any(|(_, ty)| matches!(ty, crate::ast::stmt::TypeExpr::Mutable { .. }))
212            {
213                continue;
214            }
215            if purity.is_pure(*name) && evaluable_body(body) {
216                let param_syms: Vec<Symbol> = params.iter().map(|(s, _)| *s).collect();
217                funcs.insert(
218                    *name,
219                    FuncDef {
220                        params: param_syms,
221                        body,
222                    },
223                );
224            }
225        }
226    }
227    funcs
228}
229
230// =============================================================================
231// Value-level evaluation (for inline evaluation of pure functions)
232// =============================================================================
233
234fn eval_expr_to_value(
235    expr: &Expr,
236    locals: &HashMap<Symbol, Value>,
237    funcs: &HashMap<Symbol, FuncDef>,
238    memo: &mut HashMap<(Symbol, Vec<Value>), Option<Value>>,
239    steps: &mut usize,
240    depth: usize,
241) -> Option<Value> {
242    if *steps >= MAX_INLINE_STEPS || depth >= MAX_INLINE_DEPTH {
243        return None;
244    }
245    *steps += 1;
246
247    match expr {
248        Expr::Literal(Literal::Number(n)) => Some(Value::Int(*n)),
249        Expr::Literal(Literal::Float(f)) => Some(Value::Float(*f)),
250        Expr::Literal(Literal::Boolean(b)) => Some(Value::Bool(*b)),
251        Expr::Literal(Literal::Text(s)) => Some(Value::Text(*s)),
252        Expr::Literal(Literal::Nothing) => Some(Value::Nothing),
253        Expr::Identifier(sym) => locals.get(sym).cloned(),
254        Expr::BinaryOp { op, left, right } => {
255            let lv = eval_expr_to_value(left, locals, funcs, memo, steps, depth)?;
256            let rv = eval_expr_to_value(right, locals, funcs, memo, steps, depth)?;
257            eval_binop(*op, &lv, &rv)
258        }
259        Expr::Not { operand } => {
260            if let Value::Bool(b) = eval_expr_to_value(operand, locals, funcs, memo, steps, depth)?
261            {
262                Some(Value::Bool(!b))
263            } else {
264                None
265            }
266        }
267        Expr::Call { function, args } => {
268            let func = funcs.get(function)?;
269            if args.len() != func.params.len() {
270                return None;
271            }
272            let mut arg_vals = Vec::with_capacity(args.len());
273            for arg in args {
274                arg_vals.push(eval_expr_to_value(arg, locals, funcs, memo, steps, depth)?);
275            }
276
277            let memo_key = (*function, arg_vals.clone());
278            if let Some(cached) = memo.get(&memo_key) {
279                return cached.clone();
280            }
281
282            // Mark as in-progress to detect infinite recursion
283            memo.insert(memo_key.clone(), None);
284
285            let mut call_locals = HashMap::new();
286            for (param, val) in func.params.iter().zip(arg_vals.iter()) {
287                call_locals.insert(*param, val.clone());
288            }
289
290            let result =
291                eval_block_to_value(func.body, &mut call_locals, funcs, memo, steps, depth + 1);
292            memo.insert(memo_key, result.clone());
293            result
294        }
295        _ => None,
296    }
297}
298
299fn eval_binop(op: BinaryOpKind, lv: &Value, rv: &Value) -> Option<Value> {
300    match (op, lv, rv) {
301        // Constant-fold integer arithmetic ONLY when the result fits i64; on overflow
302        // return None so the now-exact runtime computes the promoted (BigInt) value.
303        // The folder must never bake a WRAPPED constant the runtime would not produce.
304        (BinaryOpKind::Add, Value::Int(a), Value::Int(b)) => a.checked_add(*b).map(Value::Int),
305        (BinaryOpKind::Subtract, Value::Int(a), Value::Int(b)) => a.checked_sub(*b).map(Value::Int),
306        (BinaryOpKind::Multiply, Value::Int(a), Value::Int(b)) => a.checked_mul(*b).map(Value::Int),
307        (BinaryOpKind::Divide, Value::Int(a), Value::Int(b)) if *b != 0 => {
308            a.checked_div(*b).map(Value::Int)
309        }
310        (BinaryOpKind::Modulo, Value::Int(a), Value::Int(b)) if *b != 0 => {
311            a.checked_rem(*b).map(Value::Int)
312        }
313        (BinaryOpKind::Shl, Value::Int(a), Value::Int(b)) if *b >= 0 && *b < 64 => {
314            Some(Value::Int(a.wrapping_shl(*b as u32)))
315        }
316        (BinaryOpKind::Shr, Value::Int(a), Value::Int(b)) if *b >= 0 && *b < 64 => {
317            Some(Value::Int(a.wrapping_shr(*b as u32)))
318        }
319        (BinaryOpKind::BitXor, Value::Int(a), Value::Int(b)) => Some(Value::Int(a ^ b)),
320        (BinaryOpKind::And, Value::Int(a), Value::Int(b)) => Some(Value::Int(a & b)),
321        (BinaryOpKind::Or, Value::Int(a), Value::Int(b)) => Some(Value::Int(a | b)),
322        (BinaryOpKind::Eq, Value::Int(a), Value::Int(b)) => Some(Value::Bool(a == b)),
323        (BinaryOpKind::NotEq, Value::Int(a), Value::Int(b)) => Some(Value::Bool(a != b)),
324        (BinaryOpKind::Lt, Value::Int(a), Value::Int(b)) => Some(Value::Bool(a < b)),
325        (BinaryOpKind::Gt, Value::Int(a), Value::Int(b)) => Some(Value::Bool(a > b)),
326        (BinaryOpKind::LtEq, Value::Int(a), Value::Int(b)) => Some(Value::Bool(a <= b)),
327        (BinaryOpKind::GtEq, Value::Int(a), Value::Int(b)) => Some(Value::Bool(a >= b)),
328        (BinaryOpKind::Add, Value::Float(a), Value::Float(b)) => Some(Value::Float(a + b)),
329        (BinaryOpKind::Subtract, Value::Float(a), Value::Float(b)) => Some(Value::Float(a - b)),
330        (BinaryOpKind::Multiply, Value::Float(a), Value::Float(b)) => Some(Value::Float(a * b)),
331        (BinaryOpKind::Divide, Value::Float(a), Value::Float(b)) if *b != 0.0 => {
332            Some(Value::Float(a / b))
333        }
334        // Exponentiation: Float `a ** b` via powf (softmax's `e^x`); exact Int power that fits i64.
335        (BinaryOpKind::Pow, Value::Float(a), Value::Float(b)) => Some(Value::Float(a.powf(*b))),
336        (BinaryOpKind::Pow, Value::Int(a), Value::Int(b)) if *b >= 0 && *b <= 63 => {
337            a.checked_pow(*b as u32).map(Value::Int)
338        }
339        (BinaryOpKind::Lt, Value::Float(a), Value::Float(b)) => Some(Value::Bool(a < b)),
340        (BinaryOpKind::Gt, Value::Float(a), Value::Float(b)) => Some(Value::Bool(a > b)),
341        (BinaryOpKind::LtEq, Value::Float(a), Value::Float(b)) => Some(Value::Bool(a <= b)),
342        (BinaryOpKind::GtEq, Value::Float(a), Value::Float(b)) => Some(Value::Bool(a >= b)),
343        (BinaryOpKind::And, Value::Bool(a), Value::Bool(b)) => Some(Value::Bool(*a && *b)),
344        (BinaryOpKind::Or, Value::Bool(a), Value::Bool(b)) => Some(Value::Bool(*a || *b)),
345        (BinaryOpKind::Eq, Value::Text(a), Value::Text(b)) => Some(Value::Bool(a == b)),
346        (BinaryOpKind::NotEq, Value::Text(a), Value::Text(b)) => Some(Value::Bool(a != b)),
347        _ => None,
348    }
349}
350
351enum EvalResult {
352    Continue,
353    Return(Value),
354}
355
356fn eval_block_to_value(
357    stmts: &[Stmt],
358    locals: &mut HashMap<Symbol, Value>,
359    funcs: &HashMap<Symbol, FuncDef>,
360    memo: &mut HashMap<(Symbol, Vec<Value>), Option<Value>>,
361    steps: &mut usize,
362    depth: usize,
363) -> Option<Value> {
364    for stmt in stmts {
365        match eval_stmt_to_value(stmt, locals, funcs, memo, steps, depth)? {
366            EvalResult::Continue => {}
367            EvalResult::Return(v) => return Some(v),
368        }
369    }
370    Some(Value::Nothing)
371}
372
373fn eval_stmt_to_value(
374    stmt: &Stmt,
375    locals: &mut HashMap<Symbol, Value>,
376    funcs: &HashMap<Symbol, FuncDef>,
377    memo: &mut HashMap<(Symbol, Vec<Value>), Option<Value>>,
378    steps: &mut usize,
379    depth: usize,
380) -> Option<EvalResult> {
381    if *steps >= MAX_INLINE_STEPS {
382        return None;
383    }
384    *steps += 1;
385
386    match stmt {
387        Stmt::Let { var, value, .. } => {
388            let v = eval_expr_to_value(value, locals, funcs, memo, steps, depth)?;
389            locals.insert(*var, v);
390            Some(EvalResult::Continue)
391        }
392        Stmt::Set { target, value } => {
393            let v = eval_expr_to_value(value, locals, funcs, memo, steps, depth)?;
394            locals.insert(*target, v);
395            Some(EvalResult::Continue)
396        }
397        Stmt::Return { value } => {
398            if let Some(v) = value {
399                let result = eval_expr_to_value(v, locals, funcs, memo, steps, depth)?;
400                Some(EvalResult::Return(result))
401            } else {
402                Some(EvalResult::Return(Value::Nothing))
403            }
404        }
405        Stmt::If {
406            cond,
407            then_block,
408            else_block,
409        } => {
410            let cv = eval_expr_to_value(cond, locals, funcs, memo, steps, depth)?;
411            if let Value::Bool(b) = cv {
412                if b {
413                    for s in *then_block {
414                        match eval_stmt_to_value(s, locals, funcs, memo, steps, depth)? {
415                            EvalResult::Continue => {}
416                            EvalResult::Return(v) => return Some(EvalResult::Return(v)),
417                        }
418                    }
419                } else if let Some(eb) = else_block {
420                    for s in *eb {
421                        match eval_stmt_to_value(s, locals, funcs, memo, steps, depth)? {
422                            EvalResult::Continue => {}
423                            EvalResult::Return(v) => return Some(EvalResult::Return(v)),
424                        }
425                    }
426                }
427                Some(EvalResult::Continue)
428            } else {
429                None
430            }
431        }
432        Stmt::While { cond, body, .. } => {
433            loop {
434                let cv = eval_expr_to_value(cond, locals, funcs, memo, steps, depth)?;
435                match cv {
436                    Value::Bool(false) => break,
437                    Value::Bool(true) => {
438                        for s in *body {
439                            match eval_stmt_to_value(s, locals, funcs, memo, steps, depth)? {
440                                EvalResult::Continue => {}
441                                EvalResult::Return(v) => return Some(EvalResult::Return(v)),
442                            }
443                        }
444                    }
445                    _ => return None,
446                }
447            }
448            Some(EvalResult::Continue)
449        }
450        _ => None,
451    }
452}
453
454// =============================================================================
455// AST-level supercompilation (driving + constant propagation + inline)
456// =============================================================================
457
458fn value_to_literal(val: &Value) -> Option<Literal> {
459    match val {
460        Value::Int(n) => Some(Literal::Number(*n)),
461        Value::Float(f) => Some(Literal::Float(*f)),
462        Value::Bool(b) => Some(Literal::Boolean(*b)),
463        Value::Text(s) => Some(Literal::Text(*s)),
464        Value::Nothing => Some(Literal::Nothing),
465        Value::Seq(_) => None,
466    }
467}
468
469fn value_to_expr<'a>(val: &Value, arena: &'a Arena<Expr<'a>>) -> &'a Expr<'a> {
470    match value_to_literal(val) {
471        Some(lit) => arena.alloc(Expr::Literal(lit)),
472        None => unreachable!(),
473    }
474}
475
476fn expr_to_value(expr: &Expr, store: &HashMap<Symbol, Value>) -> Option<Value> {
477    match expr {
478        Expr::Literal(Literal::Number(n)) => Some(Value::Int(*n)),
479        Expr::Literal(Literal::Float(f)) => Some(Value::Float(*f)),
480        Expr::Literal(Literal::Boolean(b)) => Some(Value::Bool(*b)),
481        Expr::Literal(Literal::Text(s)) => Some(Value::Text(*s)),
482        Expr::Literal(Literal::Nothing) => Some(Value::Nothing),
483        Expr::Identifier(sym) => store.get(sym).cloned(),
484        // `item i of A` over a statically-known `Seq` + a known 1-based index → the element.
485        Expr::Index { collection, index } => {
486            let seq = match expr_to_value(collection, store)? {
487                Value::Seq(v) => v,
488                _ => return None,
489            };
490            let i = match expr_to_value(index, store)? {
491                Value::Int(n) => n,
492                _ => return None,
493            };
494            (i >= 1 && (i as usize) <= seq.len()).then(|| seq[(i - 1) as usize].clone())
495        }
496        Expr::Length { collection } => match expr_to_value(collection, store)? {
497            Value::Seq(v) => Some(Value::Int(v.len() as i64)),
498            _ => None,
499        },
500        _ => None,
501    }
502}
503
504fn try_eval_expr<'a>(expr: &'a Expr<'a>, env: &mut SuperEnv<'a>, depth: usize) -> Option<Value> {
505    eval_expr_to_value(
506        expr,
507        &env.store,
508        &env.funcs,
509        &mut env.memo,
510        &mut env.steps,
511        depth,
512    )
513}
514
515/// A call's arguments, driven with the pre-call store — except each one at a `mutable` parameter
516/// position ([`crate::analysis::callgraph::lent_positions`]), which is the place the callee writes
517/// and stays as written. The call writes every binding it lends, so each leaves the abstract store:
518/// a later read of one is never folded to its value from before the call.
519fn drive_call_arguments<'a>(
520    function: Symbol,
521    args: &[&'a Expr<'a>],
522    env: &mut SuperEnv<'a>,
523    expr_arena: &'a Arena<Expr<'a>>,
524    depth: usize,
525) -> Vec<&'a Expr<'a>> {
526    let lent = crate::analysis::callgraph::lent_positions(function);
527    let driven = args
528        .iter()
529        .enumerate()
530        .map(|(i, a)| {
531            if lent.contains(&i) {
532                *a
533            } else {
534                drive_expr(a, env, expr_arena, depth)
535            }
536        })
537        .collect();
538    for at in lent {
539        if let Some(root) = args.get(at).and_then(|a| lent_root(a)) {
540            env.store.remove(&root);
541        }
542    }
543    driven
544}
545
546/// The binding a lent place is rooted at: the binding itself, or the record or list a field or
547/// an element of it belongs to.
548fn lent_root(place: &Expr) -> Option<Symbol> {
549    match place {
550        Expr::Identifier(sym) => Some(*sym),
551        Expr::FieldAccess { object, .. } => lent_root(object),
552        Expr::Index { collection, .. } => lent_root(collection),
553        _ => None,
554    }
555}
556
557fn drive_expr<'a>(
558    expr: &'a Expr<'a>,
559    env: &mut SuperEnv<'a>,
560    expr_arena: &'a Arena<Expr<'a>>,
561    depth: usize,
562) -> &'a Expr<'a> {
563    if depth >= MAX_INLINE_DEPTH {
564        return expr;
565    }
566
567    match expr {
568        Expr::Identifier(sym) => {
569            if let Some(val) = env.store.get(sym) {
570                // Only propagate Copy-type values (Int, Float, Bool, Nothing).
571                // Text values are owned (String) in generated Rust — propagating
572                // them changes move semantics and can eliminate use-after-move errors.
573                match val {
574                    Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Nothing => {
575                        if let Some(lit) = value_to_literal(val) {
576                            return expr_arena.alloc(Expr::Literal(lit));
577                        }
578                    }
579                    Value::Text(s) => {
580                        return expr_arena.alloc(Expr::Literal(Literal::Text(*s)));
581                    }
582                    // A `Seq` value never propagates as a literal (only its elements do, via `Index` folding) —
583                    // leave the identifier in place.
584                    Value::Seq(_) => {}
585                }
586            }
587            expr
588        }
589        Expr::BinaryOp { op, left, right } => {
590            let dl = drive_expr(left, env, expr_arena, depth);
591            let dr = drive_expr(right, env, expr_arena, depth);
592            // Try value-level evaluation
593            if let (Some(lv), Some(rv)) =
594                (expr_to_value(dl, &env.store), expr_to_value(dr, &env.store))
595            {
596                if let Some(result) = eval_binop(*op, &lv, &rv) {
597                    return value_to_expr(&result, expr_arena);
598                }
599            }
600            if std::ptr::eq(dl, *left) && std::ptr::eq(dr, *right) {
601                expr
602            } else {
603                expr_arena.alloc(Expr::BinaryOp {
604                    op: *op,
605                    left: dl,
606                    right: dr,
607                })
608            }
609        }
610        Expr::Not { operand } => {
611            let d = drive_expr(operand, env, expr_arena, depth);
612            if let Expr::Literal(Literal::Boolean(b)) = d {
613                return expr_arena.alloc(Expr::Literal(Literal::Boolean(!b)));
614            }
615            if std::ptr::eq(d, *operand) {
616                expr
617            } else {
618                expr_arena.alloc(Expr::Not { operand: d })
619            }
620        }
621        Expr::Call { function, args } => {
622            let driven_args = drive_call_arguments(*function, args, env, expr_arena, depth);
623            // Don't replace calls in the AST — preserve function call sites.
624            // Call evaluation is done at the store level in drive_stmt for Let/Set.
625            let changed = driven_args
626                .iter()
627                .zip(args.iter())
628                .any(|(d, o)| !std::ptr::eq(*d, *o));
629            if changed {
630                expr_arena.alloc(Expr::Call {
631                    function: *function,
632                    args: driven_args,
633                })
634            } else {
635                expr
636            }
637        }
638        Expr::Length { collection } => {
639            // A statically-known `Seq`'s length is a constant (array-fold programs only).
640            if env.array_fold {
641                if let Some(val) = expr_to_value(expr, &env.store) {
642                    if let Some(lit) = value_to_literal(&val) {
643                        return expr_arena.alloc(Expr::Literal(lit));
644                    }
645                }
646            }
647            let d = drive_expr(collection, env, expr_arena, depth);
648            if std::ptr::eq(d, *collection) {
649                expr
650            } else {
651                expr_arena.alloc(Expr::Length { collection: d })
652            }
653        }
654        // Index over a statically-known array folds to the element literal — ONLY for array-fold programs (the
655        // array is being constant-folded away entirely). For every other program the read is left untouched, so
656        // the affine / oracle-bounds / BCE array passes see exactly what they did before.
657        Expr::Index { .. } => {
658            if env.array_fold {
659                if let Some(val) = expr_to_value(expr, &env.store) {
660                    if let Some(lit) = value_to_literal(&val) {
661                        return expr_arena.alloc(Expr::Literal(lit));
662                    }
663                }
664            }
665            expr
666        }
667        Expr::Slice { .. } => expr,
668        Expr::Contains { collection, value } => {
669            let dc = drive_expr(collection, env, expr_arena, depth);
670            let dv = drive_expr(value, env, expr_arena, depth);
671            if std::ptr::eq(dc, *collection) && std::ptr::eq(dv, *value) {
672                expr
673            } else {
674                expr_arena.alloc(Expr::Contains {
675                    collection: dc,
676                    value: dv,
677                })
678            }
679        }
680        Expr::FieldAccess { object, field } => {
681            let d = drive_expr(object, env, expr_arena, depth);
682            if std::ptr::eq(d, *object) {
683                expr
684            } else {
685                expr_arena.alloc(Expr::FieldAccess {
686                    object: d,
687                    field: *field,
688                })
689            }
690        }
691        Expr::OptionSome { value } => {
692            let d = drive_expr(value, env, expr_arena, depth);
693            if std::ptr::eq(d, *value) {
694                expr
695            } else {
696                expr_arena.alloc(Expr::OptionSome { value: d })
697            }
698        }
699        Expr::Copy { expr: inner } => {
700            let d = drive_expr(inner, env, expr_arena, depth);
701            if std::ptr::eq(d, *inner) {
702                expr
703            } else {
704                expr_arena.alloc(Expr::Copy { expr: d })
705            }
706        }
707        Expr::Give { value } => {
708            let d = drive_expr(value, env, expr_arena, depth);
709            if std::ptr::eq(d, *value) {
710                expr
711            } else {
712                expr_arena.alloc(Expr::Give { value: d })
713            }
714        }
715        Expr::List(elems) => {
716            let driven: Vec<&'a Expr<'a>> = elems
717                .iter()
718                .map(|e| drive_expr(e, env, expr_arena, depth))
719                .collect();
720            let changed = driven
721                .iter()
722                .zip(elems.iter())
723                .any(|(d, o)| !std::ptr::eq(*d, *o));
724            if changed {
725                expr_arena.alloc(Expr::List(driven))
726            } else {
727                expr
728            }
729        }
730        Expr::Tuple(elems) => {
731            let driven: Vec<&'a Expr<'a>> = elems
732                .iter()
733                .map(|e| drive_expr(e, env, expr_arena, depth))
734                .collect();
735            let changed = driven
736                .iter()
737                .zip(elems.iter())
738                .any(|(d, o)| !std::ptr::eq(*d, *o));
739            if changed {
740                expr_arena.alloc(Expr::Tuple(driven))
741            } else {
742                expr
743            }
744        }
745        // Leaves and complex expressions passed through
746        _ => expr,
747    }
748}
749
750/// Drive `block`, a block nested in the statement being driven, against a copy of the store without
751/// the names it binds on entry (`binders`). The store it leaves is the one it started from, less
752/// everything the block may write, with what the block assigns to names it never declares — the
753/// enclosing scope's bindings — at the values the drive gave them. A name the block declares ends with
754/// the block, whatever it held there.
755fn drive_nested_block<'a>(
756    block: &'a [Stmt<'a>],
757    binders: &[Symbol],
758    env: &mut SuperEnv<'a>,
759    expr_arena: &'a Arena<Expr<'a>>,
760    stmt_arena: &'a Arena<Stmt<'a>>,
761    interner: &mut Interner,
762    depth: usize,
763) -> &'a [Stmt<'a>] {
764    let outer = env.store.clone();
765    for b in binders {
766        env.store.remove(b);
767    }
768    let driven = drive_block(block, env, expr_arena, stmt_arena, interner, depth);
769    let inner = std::mem::take(&mut env.store);
770    let written = env.writes_of(WriteSet::of_block(block));
771    let mut after = outer;
772    forget(&mut after, &written);
773    if !written.is_opaque() {
774        let declared = capture::frame_names(binders, block);
775        for sym in written.reassigned() {
776            if declared.contains(&sym) {
777                continue;
778            }
779            if let Some(value) = inner.get(&sym) {
780                after.insert(sym, value.clone());
781            }
782        }
783    }
784    env.store = after;
785    driven
786}
787
788fn drive_stmt<'a>(
789    stmt: Stmt<'a>,
790    env: &mut SuperEnv<'a>,
791    expr_arena: &'a Arena<Expr<'a>>,
792    stmt_arena: &'a Arena<Stmt<'a>>,
793    interner: &mut Interner,
794    depth: usize,
795) -> Option<Stmt<'a>> {
796    // Every name a statement binds where it stands takes a new value there, and nothing an earlier
797    // binding of the name gave it survives: a `Let` forgets its name once it has read its value, and a
798    // statement driven through unchanged forgets everything it may write, its binders included. A
799    // block nested in the statement starts without the names it binds on entry.
800    let entry = EntryBinders::of(&stmt);
801    match stmt {
802        Stmt::Let {
803            var,
804            ty,
805            value,
806            mutable,
807        } => {
808            let driven = drive_expr(value, env, expr_arena, depth);
809            // A `Let` shadows every earlier binding of its name, known or not.
810            env.store.remove(&var);
811            if env.array_fold {
812                // Resolve to a store value when statically known: a `new Seq`, a leaf literal, a pure
813                // arithmetic/array-read/builtin expression (`eval_static` — folds a reduction's
814                // `denom = sqrt(ss/n + eps)`), or a pure call. Text on a MUTABLE binding is left owned;
815                // everything else is output-safe (`Set` overwrites, a `While` widens). Lets a following
816                // constant-trip loop run concretely.
817                let resolved = if let Some(seq) = new_seq_value(driven, interner) {
818                    Some(seq)
819                } else if let Some(v) = expr_to_value(driven, &env.store) {
820                    Some(v)
821                } else {
822                    let mut s = 0usize;
823                    if let Some(v) = eval_static(driven, &env.store, interner, &mut s) {
824                        Some(v)
825                    } else if !mutable {
826                        try_eval_expr(driven, env, depth)
827                    } else {
828                        None
829                    }
830                };
831                if let Some(val) = resolved {
832                    if !(mutable && matches!(val, Value::Text(_))) {
833                        env.store.insert(var, val);
834                    }
835                }
836            } else if !mutable {
837                // Original behavior: track only immutable scalar bindings (literals / pure calls).
838                if let Some(val) = expr_to_value(driven, &env.store) {
839                    env.store.insert(var, val);
840                } else if let Some(val) = try_eval_expr(driven, env, depth) {
841                    env.store.insert(var, val);
842                }
843            }
844            Some(Stmt::Let {
845                var,
846                ty,
847                value: driven,
848                mutable,
849            })
850        }
851        Stmt::Set { target, value } => {
852            let driven = drive_expr(value, env, expr_arena, depth);
853            // Update store if we can resolve the new value
854            if let Some(val) = expr_to_value(driven, &env.store) {
855                env.store.insert(target, val);
856            } else {
857                // Value is unknown; remove from store
858                env.store.remove(&target);
859            }
860            Some(Stmt::Set {
861                target,
862                value: driven,
863            })
864        }
865        Stmt::If {
866            cond,
867            then_block,
868            else_block,
869        } => {
870            let driven_cond = drive_expr(cond, env, expr_arena, depth);
871            // If condition is known, eliminate dead branch
872            if let Expr::Literal(Literal::Boolean(b)) = driven_cond {
873                if *b {
874                    // Take then branch only
875                    let driven_then = drive_nested_block(
876                        then_block,
877                        entry.of_block(then_block),
878                        env,
879                        expr_arena,
880                        stmt_arena,
881                        interner,
882                        depth,
883                    );
884                    Some(Stmt::If {
885                        cond: driven_cond,
886                        then_block: driven_then,
887                        else_block: None,
888                    })
889                } else {
890                    // Take else branch only
891                    if let Some(eb) = else_block {
892                        let driven_else = drive_nested_block(
893                            eb,
894                            entry.of_block(eb),
895                            env,
896                            expr_arena,
897                            stmt_arena,
898                            interner,
899                            depth,
900                        );
901                        Some(Stmt::If {
902                            cond: driven_cond,
903                            then_block: stmt_arena.alloc_slice(vec![]),
904                            else_block: Some(driven_else),
905                        })
906                    } else {
907                        None // Entire If eliminated
908                    }
909                }
910            } else {
911                // Condition unknown: drive both branches from the same store, then join.
912                let snapshot = env.store.clone();
913                let driven_then = drive_nested_block(
914                    then_block,
915                    entry.of_block(then_block),
916                    env,
917                    expr_arena,
918                    stmt_arena,
919                    interner,
920                    depth,
921                );
922                let then_store = std::mem::replace(&mut env.store, snapshot);
923                let driven_else = else_block.map(|eb| {
924                    drive_nested_block(
925                        eb,
926                        entry.of_block(eb),
927                        env,
928                        expr_arena,
929                        stmt_arena,
930                        interner,
931                        depth,
932                    )
933                });
934                let else_store = env.store.clone();
935
936                // Join: keep only values that agree in both branches
937                let mut joined = HashMap::new();
938                for (sym, then_val) in &then_store {
939                    if let Some(else_val) = else_store.get(sym) {
940                        if then_val == else_val {
941                            joined.insert(*sym, then_val.clone());
942                        }
943                    }
944                }
945                env.store = joined;
946
947                Some(Stmt::If {
948                    cond: driven_cond,
949                    then_block: driven_then,
950                    else_block: driven_else,
951                })
952            }
953        }
954        Stmt::While {
955            cond,
956            body,
957            decreasing,
958        } => {
959            // Concrete-execution fast path for a fully-static ARRAY-building loop (a fill / matmul / reduction
960            // nest). The ordinary driver widens modified vars and never runs the loop; here, if the loop
961            // mutates an array and every read resolves against the current store, we EXECUTE it to completion,
962            // updating the store with the concrete post-loop array values — so the reads AFTER it fold to
963            // constants. The loop is KEPT in the residual (sound: the runtime array is still built the same
964            // way); it becomes dead once all its reads fold and DCE removes it. Confined to array loops, so
965            // pure-scalar loops keep their exact widening behavior.
966            if env.array_fold && loop_touches_array(body) {
967                let snap = env.store.clone();
968                let mut steps = 0usize;
969                if run_static_loop(cond, body, &mut env.store, interner, &mut steps).is_some() {
970                    return Some(Stmt::While {
971                        cond,
972                        body,
973                        decreasing,
974                    });
975                }
976                env.store = snap; // not fully static (or over budget) — fall back to widening
977            }
978
979            // `run_static_loop` above could NOT fully execute this loop (array_fold off, the loop
980            // doesn't touch an array, or a read/stmt was unresolvable — e.g. fannkuch's outer loop
981            // allocates a fresh `perm` each iteration). On that fallback path we WIDEN everything the
982            // body may write — every name it binds or assigns, every array or record it writes in place
983            // (`perm1` rotated through `Set item i of perm1` must not keep its `[0,1,2,…]` value), every
984            // binding it lends, every global a callee it or its condition calls writes — and drive the body
985            // once.
986            let written = env.writes_of(WriteSet::of_stmt(&stmt));
987            let snapshot = env.store.clone();
988
989            // Snapshot configuration before entering loop
990            let pre_config = Configuration { expr: cond };
991
992            forget(&mut env.store, &written);
993
994            let driven_cond = drive_expr(cond, env, expr_arena, depth);
995            // While-false elimination: if condition is statically false, remove loop
996            if let Expr::Literal(Literal::Boolean(false)) = driven_cond {
997                env.store = snapshot;
998                return None;
999            }
1000
1001            // Check embedding: if the driven condition embeds in a historical one,
1002            // the whistle blows — use MSG to generalize and widen precisely.
1003            if let Some(prev) = env.history.check_embedding(driven_cond) {
1004                let generalized = msg(prev.expr, driven_cond, expr_arena, interner);
1005                // Remove store entries for MSG-introduced variables to ensure termination
1006                for i in 0..generalized.num_substitutions {
1007                    let name = format!("__msg_{}", i);
1008                    let sym = interner.intern(&name);
1009                    env.store.remove(&sym);
1010                }
1011            }
1012
1013            // Push configuration to history
1014            env.history.push(pre_config);
1015
1016            let driven_body = drive_block(body, env, expr_arena, stmt_arena, interner, depth);
1017
1018            // After the loop, what the body never writes keeps its value from before it.
1019            let mut post_loop_store = snapshot;
1020            forget(&mut post_loop_store, &written);
1021            env.store = post_loop_store;
1022
1023            Some(Stmt::While {
1024                cond: driven_cond,
1025                body: driven_body,
1026                decreasing,
1027            })
1028        }
1029        Stmt::Repeat {
1030            pattern,
1031            iterable,
1032            body,
1033        } => {
1034            let driven_iter = drive_expr(iterable, env, expr_arena, depth);
1035            // Each iteration starts without the loop's binders and without anything an earlier iteration
1036            // (or the iterable's evaluation) wrote.
1037            let evaluated = env.writes_of(WriteSet::of_expr(iterable));
1038            let written = env.writes_of(WriteSet::of_block(body));
1039            forget(&mut env.store, &evaluated);
1040            forget(&mut env.store, &written);
1041            let driven_body = drive_nested_block(
1042                body,
1043                entry.of_block(body),
1044                env,
1045                expr_arena,
1046                stmt_arena,
1047                interner,
1048                depth,
1049            );
1050            // The body was driven ONCE, but the loop runs any number of times, none included: nothing it
1051            // writes holds its single-drive value afterward — neither a collection it pushes to (`Repeat for
1052            // i from 1 to 10: Push 0 to nums` must not fold `length of nums` to 1) nor a name it sets (a
1053            // loop over an empty list leaves it as it was).
1054            forget(&mut env.store, &written);
1055            Some(Stmt::Repeat {
1056                pattern,
1057                iterable: driven_iter,
1058                body: driven_body,
1059            })
1060        }
1061        Stmt::Show { object, recipient } => {
1062            let driven = drive_expr(object, env, expr_arena, depth);
1063            Some(Stmt::Show {
1064                object: driven,
1065                recipient,
1066            })
1067        }
1068        Stmt::Return { value } => {
1069            let driven = value.map(|v| drive_expr(v, env, expr_arena, depth));
1070            Some(Stmt::Return { value: driven })
1071        }
1072        Stmt::Call { function, args } => {
1073            // Arguments are evaluated with the PRE-call store (they see the current values)...
1074            let driven_args = drive_call_arguments(function, &args, env, expr_arena, depth);
1075            // ...then the call can mutate any global some function writes — drop those from the abstract store
1076            // so a later read of one is NOT folded to its stale pre-call value.
1077            if env.callee_globals.opaque {
1078                env.store.clear();
1079            } else if !env.callee_globals.is_empty() {
1080                let globals: Vec<Symbol> = env.callee_globals.symbols.iter().copied().collect();
1081                for g in globals {
1082                    env.store.remove(&g);
1083                }
1084            }
1085            Some(Stmt::Call {
1086                function,
1087                args: driven_args,
1088            })
1089        }
1090        Stmt::Push { value, collection } => {
1091            let driven_val = drive_expr(value, env, expr_arena, depth);
1092            if let Expr::Identifier(sym) = collection {
1093                // Append to a statically-known array when the pushed value is known; otherwise the array
1094                // becomes runtime-opaque (invalidate). The statement itself is KEPT (builds the runtime array).
1095                match (env.store.get(sym), expr_to_value(driven_val, &env.store)) {
1096                    (Some(Value::Seq(_)), Some(elem)) => {
1097                        if let Some(Value::Seq(seq)) = env.store.get_mut(sym) {
1098                            seq.push(elem);
1099                        }
1100                    }
1101                    _ => {
1102                        env.store.remove(sym);
1103                    }
1104                }
1105            }
1106            Some(Stmt::Push {
1107                value: driven_val,
1108                collection,
1109            })
1110        }
1111        Stmt::SetIndex {
1112            collection,
1113            index,
1114            value,
1115        } => {
1116            // `Set item i of A to v`: update a statically-known array in place when i and v are known;
1117            // otherwise invalidate. The statement is KEPT (the runtime array is still written). Index and value
1118            // are NOT driven — codegen peephole patterns depend on the original variable names.
1119            if let Expr::Identifier(sym) = collection {
1120                let iv = expr_to_value(index, &env.store);
1121                let vv = expr_to_value(value, &env.store);
1122                match (env.store.get(sym), iv, vv) {
1123                    (Some(Value::Seq(_)), Some(Value::Int(i)), Some(v)) if i >= 1 => {
1124                        if let Some(Value::Seq(seq)) = env.store.get_mut(sym) {
1125                            let idx = (i - 1) as usize;
1126                            if idx >= seq.len() {
1127                                seq.resize(idx + 1, Value::Nothing);
1128                            }
1129                            seq[idx] = v;
1130                        }
1131                    }
1132                    _ => {
1133                        env.store.remove(sym);
1134                    }
1135                }
1136            }
1137            Some(Stmt::SetIndex {
1138                collection,
1139                index,
1140                value,
1141            })
1142        }
1143        Stmt::SetField {
1144            object,
1145            field,
1146            value,
1147        } => {
1148            let dv = drive_expr(value, env, expr_arena, depth);
1149            if let Expr::Identifier(sym) = object {
1150                env.store.remove(sym);
1151            }
1152            Some(Stmt::SetField {
1153                object,
1154                field,
1155                value: dv,
1156            })
1157        }
1158        Stmt::RuntimeAssert {
1159            condition,
1160            hard,
1161            dim,
1162            reason,
1163        } => {
1164            let driven = drive_expr(condition, env, expr_arena, depth);
1165            Some(Stmt::RuntimeAssert {
1166                condition: driven,
1167                hard,
1168                dim,
1169                reason,
1170            })
1171        }
1172        Stmt::FunctionDef {
1173            name,
1174            params,
1175            generics,
1176            body,
1177            return_type,
1178            is_native,
1179            native_path,
1180            is_exported,
1181            export_target,
1182            opt_flags,
1183        } => {
1184            // Drive inside function body with fresh store
1185            let snapshot = env.store.clone();
1186            env.store.clear();
1187            let driven_body = drive_block(body, env, expr_arena, stmt_arena, interner, depth);
1188            env.store = snapshot;
1189            Some(Stmt::FunctionDef {
1190                name,
1191                params,
1192                generics,
1193                body: driven_body,
1194                return_type,
1195                is_native,
1196                native_path,
1197                is_exported,
1198                export_target,
1199                opt_flags,
1200            })
1201        }
1202        // A `Splice` is a transparent desugar container (its `Let`s leak to the enclosing scope). For array-fold
1203        // programs we drive its body against the SAME store so tensor-sugar loops (which land inside Splices)
1204        // fold even before splice-fusion flattens them; otherwise it passes through unchanged (original).
1205        Stmt::Splice { body } if env.array_fold => {
1206            let driven = drive_block(body, env, expr_arena, stmt_arena, interner, depth);
1207            Some(Stmt::Splice { body: driven })
1208        }
1209        // Zone blocks: pass through unchanged. Propagating inside zones can
1210        // eliminate zone escape patterns that the Rust compiler needs to detect. Everything else passes
1211        // through undriven too. Either way nothing it may write — a name an `Inspect` arm sets, the
1212        // binding `Pop … into` fills — keeps a value from before it.
1213        other => {
1214            let written = env.writes_of(WriteSet::of_stmt(&other));
1215            forget(&mut env.store, &written);
1216            Some(other)
1217        }
1218    }
1219}
1220
1221fn drive_block<'a>(
1222    block: &'a [Stmt<'a>],
1223    env: &mut SuperEnv<'a>,
1224    expr_arena: &'a Arena<Expr<'a>>,
1225    stmt_arena: &'a Arena<Stmt<'a>>,
1226    interner: &mut Interner,
1227    depth: usize,
1228) -> &'a [Stmt<'a>] {
1229    let mut result = Vec::with_capacity(block.len());
1230    for stmt in block.iter().cloned() {
1231        if let Some(driven) = drive_stmt(stmt, env, expr_arena, stmt_arena, interner, depth) {
1232            result.push(driven);
1233        }
1234    }
1235    stmt_arena.alloc_slice(result)
1236}
1237
1238// =============================================================================
1239// Public API
1240// =============================================================================
1241
1242pub fn supercompile_stmts<'a>(
1243    stmts: Vec<Stmt<'a>>,
1244    expr_arena: &'a Arena<Expr<'a>>,
1245    stmt_arena: &'a Arena<Stmt<'a>>,
1246    interner: &mut Interner,
1247) -> Vec<Stmt<'a>> {
1248    let funcs = collect_pure_funcs(&stmts, interner);
1249    let mut env = SuperEnv::new();
1250    // Array supercompilation only engages for a WHOLE program in the pure static-array fragment — everything
1251    // else is driven exactly as the original supercompiler (sound + byte-identical, no perturbation of the
1252    // array/codegen passes and no unsound stale-array fold across ops we don't model, e.g. Pop).
1253    env.array_fold = is_pure_static_array_program(&stmts, interner);
1254    env.funcs = funcs;
1255    env.callee_globals = CalleeGlobals::of_program(&stmts);
1256
1257    let mut result = Vec::with_capacity(stmts.len());
1258    for stmt in stmts {
1259        if let Some(driven) = drive_stmt(stmt, &mut env, expr_arena, stmt_arena, interner, 0) {
1260            result.push(driven);
1261        }
1262    }
1263    result
1264}
1265
1266/// Whether the WHOLE program is in the fragment array supercompilation soundly models: only
1267/// `Let`/`Set`/`Push`/`Set item`/`While`/`If`/`Show`/`Splice`/`Return` statements, over
1268/// literal/identifier/arithmetic/`Index`/`Length`/`new Seq`/pure-math-builtin expressions. Anything else — a
1269/// native or user function, `Pop`/`slice`/`remove`/`add`/aliasing, a `Repeat`, runtime input via `parseInt`,
1270/// … — makes the program INELIGIBLE, so the supercompiler behaves exactly as before for it.
1271fn is_pure_static_array_program(stmts: &[Stmt], interner: &Interner) -> bool {
1272    stmts.iter().all(|s| stmt_in_fragment(s, interner))
1273}
1274
1275fn stmt_in_fragment(stmt: &Stmt, interner: &Interner) -> bool {
1276    match stmt {
1277        Stmt::Let { value, .. } | Stmt::Set { value, .. } => expr_in_fragment(value, interner),
1278        Stmt::Push { value, collection } => {
1279            expr_in_fragment(value, interner) && expr_in_fragment(collection, interner)
1280        }
1281        Stmt::SetIndex {
1282            collection,
1283            index,
1284            value,
1285        } => {
1286            expr_in_fragment(collection, interner)
1287                && expr_in_fragment(index, interner)
1288                && expr_in_fragment(value, interner)
1289        }
1290        Stmt::While { cond, body, .. } => {
1291            expr_in_fragment(cond, interner) && is_pure_static_array_program(body, interner)
1292        }
1293        Stmt::If {
1294            cond,
1295            then_block,
1296            else_block,
1297        } => {
1298            expr_in_fragment(cond, interner)
1299                && is_pure_static_array_program(then_block, interner)
1300                && else_block.map_or(true, |eb| is_pure_static_array_program(eb, interner))
1301        }
1302        Stmt::Show { object, .. } => expr_in_fragment(object, interner),
1303        Stmt::Splice { body } => is_pure_static_array_program(body, interner),
1304        Stmt::Return { value } => value.map_or(true, |v| expr_in_fragment(v, interner)),
1305        _ => false, // FunctionDef, Pop, RemoveFrom, SetAdd, Repeat, Call, Zone, … → not in the fragment
1306    }
1307}
1308
1309fn expr_in_fragment(expr: &Expr, interner: &Interner) -> bool {
1310    match expr {
1311        Expr::Literal(_) | Expr::Identifier(_) => true,
1312        Expr::BinaryOp { left, right, .. } => {
1313            expr_in_fragment(left, interner) && expr_in_fragment(right, interner)
1314        }
1315        Expr::Not { operand } => expr_in_fragment(operand, interner),
1316        Expr::Index { collection, index } => {
1317            expr_in_fragment(collection, interner) && expr_in_fragment(index, interner)
1318        }
1319        Expr::Length { collection } => expr_in_fragment(collection, interner),
1320        Expr::New { .. } => true,
1321        // Only the pure math builtins the reductions use — NOT native (`parseInt`) or user functions.
1322        Expr::Call { function, args } => {
1323            matches!(
1324                interner.resolve(*function),
1325                "sqrt" | "max" | "min" | "round" | "floor" | "ceil" | "abs"
1326            ) && args.iter().all(|a| expr_in_fragment(a, interner))
1327        }
1328        _ => false, // Slice, Contains, SeqConcat, List, Tuple, closures, … → not in the fragment
1329    }
1330}
1331
1332/// Homeomorphic embedding check: `e1 ◁ e2`.
1333///
1334/// Returns true if `e1` is homeomorphically embedded in `e2`, meaning `e1` can
1335/// be obtained from `e2` by erasing some constructors (diving) or both share
1336/// the same constructor with all children embedded (coupling).
1337pub fn embeds<'a>(e1: &Expr<'a>, e2: &Expr<'a>) -> bool {
1338    match (e1, e2) {
1339        // Coupling: same constructor, all children embed
1340        (
1341            Expr::BinaryOp {
1342                op: op1,
1343                left: l1,
1344                right: r1,
1345            },
1346            Expr::BinaryOp {
1347                op: op2,
1348                left: l2,
1349                right: r2,
1350            },
1351        ) if op1 == op2 => embeds(l1, l2) && embeds(r1, r2),
1352        (
1353            Expr::Call {
1354                function: f1,
1355                args: a1,
1356            },
1357            Expr::Call {
1358                function: f2,
1359                args: a2,
1360            },
1361        ) if f1 == f2 && a1.len() == a2.len() => {
1362            a1.iter().zip(a2.iter()).all(|(x, y)| embeds(x, y))
1363        }
1364        (Expr::Not { operand: e1_inner }, Expr::Not { operand: e2_inner }) => {
1365            embeds(e1_inner, e2_inner)
1366        }
1367        // Base: literals and identifiers embed in themselves
1368        (Expr::Literal(l1), Expr::Literal(l2)) => l1 == l2,
1369        (Expr::Identifier(s1), Expr::Identifier(s2)) => s1 == s2,
1370        // Diving: e1 embeds in a subterm of e2
1371        (_, Expr::BinaryOp { left, right, .. }) => embeds(e1, left) || embeds(e1, right),
1372        (_, Expr::Call { args, .. }) => args.iter().any(|a| embeds(e1, a)),
1373        (_, Expr::Not { operand }) => embeds(e1, operand),
1374        _ => false,
1375    }
1376}
1377
1378/// Result of Most Specific Generalization (MSG).
1379pub struct MsgResult<'a> {
1380    /// The generalized expression with fresh variables replacing differing parts.
1381    pub expr: &'a Expr<'a>,
1382    /// Number of fresh variables (substitutions) introduced.
1383    pub num_substitutions: usize,
1384}
1385
1386/// Compute the Most Specific Generalization (MSG) of two expressions.
1387///
1388/// Given `e1` and `e2`, finds the most specific expression `g` such that
1389/// both `e1` and `e2` are instances of `g`. Differing subexpressions are
1390/// replaced with fresh variables named `__msg_0`, `__msg_1`, etc.
1391pub fn msg<'a>(
1392    e1: &'a Expr<'a>,
1393    e2: &'a Expr<'a>,
1394    arena: &'a Arena<Expr<'a>>,
1395    interner: &mut Interner,
1396) -> MsgResult<'a> {
1397    let mut counter = 0;
1398    let expr = msg_inner(e1, e2, arena, interner, &mut counter);
1399    MsgResult {
1400        expr,
1401        num_substitutions: counter,
1402    }
1403}
1404
1405fn msg_inner<'a>(
1406    e1: &'a Expr<'a>,
1407    e2: &'a Expr<'a>,
1408    arena: &'a Arena<Expr<'a>>,
1409    interner: &mut Interner,
1410    counter: &mut usize,
1411) -> &'a Expr<'a> {
1412    match (e1, e2) {
1413        // Same literal or same identifier → preserve
1414        (Expr::Literal(l1), Expr::Literal(l2)) if l1 == l2 => e1,
1415        (Expr::Identifier(s1), Expr::Identifier(s2)) if s1 == s2 => e1,
1416        // Same BinaryOp constructor → recurse into children
1417        (
1418            Expr::BinaryOp {
1419                op: op1,
1420                left: l1,
1421                right: r1,
1422            },
1423            Expr::BinaryOp {
1424                op: op2,
1425                left: l2,
1426                right: r2,
1427            },
1428        ) if op1 == op2 => {
1429            let left = msg_inner(l1, l2, arena, interner, counter);
1430            let right = msg_inner(r1, r2, arena, interner, counter);
1431            arena.alloc(Expr::BinaryOp {
1432                op: *op1,
1433                left,
1434                right,
1435            })
1436        }
1437        // Same Call constructor → recurse into args
1438        (
1439            Expr::Call {
1440                function: f1,
1441                args: a1,
1442            },
1443            Expr::Call {
1444                function: f2,
1445                args: a2,
1446            },
1447        ) if f1 == f2 && a1.len() == a2.len() => {
1448            let args: Vec<&'a Expr<'a>> = a1
1449                .iter()
1450                .zip(a2.iter())
1451                .map(|(x, y)| msg_inner(x, y, arena, interner, counter))
1452                .collect();
1453            arena.alloc(Expr::Call {
1454                function: *f1,
1455                args,
1456            })
1457        }
1458        // Same Not constructor → recurse
1459        (Expr::Not { operand: e1_inner }, Expr::Not { operand: e2_inner }) => {
1460            let inner = msg_inner(e1_inner, e2_inner, arena, interner, counter);
1461            arena.alloc(Expr::Not { operand: inner })
1462        }
1463        // Differing → introduce fresh variable
1464        _ => {
1465            let name = format!("__msg_{}", counter);
1466            *counter += 1;
1467            let sym = interner.intern(&name);
1468            arena.alloc(Expr::Identifier(sym))
1469        }
1470    }
1471}
1472
1473// =============================================================================
1474// Static array evaluation — the machinery that folds a constant-data tensor op
1475// (matmul / reduction over literal-filled arrays) to its result constants.
1476// =============================================================================
1477
1478/// `Let A be a new Seq/List/Vec` → a statically-known (empty) array value.
1479fn new_seq_value(driven: &Expr, interner: &Interner) -> Option<Value> {
1480    if let Expr::New { type_name, .. } = driven {
1481        if matches!(interner.resolve(*type_name), "Seq" | "List" | "Vec") {
1482            return Some(Value::Seq(Vec::new()));
1483        }
1484    }
1485    None
1486}
1487
1488/// Whether a loop body reads OR writes an array — the gate for attempting concrete execution. Pure-scalar
1489/// loops (no array touch) keep their exact widening behavior; a loop that merely MIGHT be static is still safe
1490/// to attempt, because `run_static_loop` bails (and the caller restores) the moment a read/write can't resolve.
1491fn loop_touches_array(body: &[Stmt]) -> bool {
1492    body.iter().any(stmt_touches_array)
1493}
1494
1495fn stmt_touches_array(stmt: &Stmt) -> bool {
1496    match stmt {
1497        Stmt::Push { .. } | Stmt::SetIndex { .. } => true,
1498        Stmt::Let { value, .. } | Stmt::Set { value, .. } => expr_reads_array(value),
1499        Stmt::Return { value } => value.map_or(false, expr_reads_array),
1500        Stmt::While { cond, body, .. } => expr_reads_array(cond) || loop_touches_array(body),
1501        Stmt::Repeat { body, .. } => loop_touches_array(body),
1502        Stmt::If {
1503            cond,
1504            then_block,
1505            else_block,
1506        } => {
1507            expr_reads_array(cond)
1508                || loop_touches_array(then_block)
1509                || else_block.map_or(false, |eb| loop_touches_array(eb))
1510        }
1511        _ => false,
1512    }
1513}
1514
1515fn expr_reads_array(expr: &Expr) -> bool {
1516    match expr {
1517        Expr::Index { .. } | Expr::Length { .. } => true,
1518        Expr::BinaryOp { left, right, .. } => expr_reads_array(left) || expr_reads_array(right),
1519        Expr::Not { operand } => expr_reads_array(operand),
1520        Expr::Call { args, .. } => args.iter().any(|a| expr_reads_array(a)),
1521        _ => false,
1522    }
1523}
1524
1525/// Concretely execute a constant-trip loop over the store (arrays included) to completion. Returns `Some(())`
1526/// with the store holding the post-loop values, or `None` (leaving the store partially mutated — the caller
1527/// restores its snapshot) if any read is unknown or the step budget is exceeded.
1528fn run_static_loop(
1529    cond: &Expr,
1530    body: &[Stmt],
1531    store: &mut HashMap<Symbol, Value>,
1532    interner: &Interner,
1533    steps: &mut usize,
1534) -> Option<()> {
1535    loop {
1536        *steps += 1;
1537        if *steps > MAX_INLINE_STEPS {
1538            return None;
1539        }
1540        match eval_static(cond, store, interner, steps)? {
1541            Value::Bool(true) => {
1542                for s in body {
1543                    exec_static_stmt(s, store, interner, steps)?;
1544                }
1545            }
1546            Value::Bool(false) => return Some(()),
1547            _ => return None,
1548        }
1549    }
1550}
1551
1552/// Concretely execute one statement over the store. Only effect-free, statically-resolvable forms are handled;
1553/// anything else (a `Show`, a `Return`, an unresolved read) returns `None` to abort the concrete run.
1554fn exec_static_stmt(
1555    stmt: &Stmt,
1556    store: &mut HashMap<Symbol, Value>,
1557    interner: &Interner,
1558    steps: &mut usize,
1559) -> Option<()> {
1560    *steps += 1;
1561    if *steps > MAX_INLINE_STEPS {
1562        return None;
1563    }
1564    match stmt {
1565        Stmt::Let { var, value, .. } => {
1566            let v = eval_static(value, store, interner, steps)?;
1567            store.insert(*var, v);
1568            Some(())
1569        }
1570        Stmt::Set { target, value } => {
1571            let v = eval_static(value, store, interner, steps)?;
1572            store.insert(*target, v);
1573            Some(())
1574        }
1575        Stmt::Push { value, collection } => {
1576            let sym = as_ident_sym(collection)?;
1577            let v = eval_static(value, store, interner, steps)?;
1578            match store.get_mut(&sym) {
1579                Some(Value::Seq(seq)) => {
1580                    seq.push(v);
1581                    Some(())
1582                }
1583                _ => None,
1584            }
1585        }
1586        Stmt::SetIndex {
1587            collection,
1588            index,
1589            value,
1590        } => {
1591            let sym = as_ident_sym(collection)?;
1592            let i = as_int_val(eval_static(index, store, interner, steps)?)?;
1593            if i < 1 {
1594                return None;
1595            }
1596            let v = eval_static(value, store, interner, steps)?;
1597            match store.get_mut(&sym) {
1598                Some(Value::Seq(seq)) => {
1599                    let idx = (i - 1) as usize;
1600                    if idx >= seq.len() {
1601                        seq.resize(idx + 1, Value::Nothing);
1602                    }
1603                    seq[idx] = v;
1604                    Some(())
1605                }
1606                _ => None,
1607            }
1608        }
1609        Stmt::If {
1610            cond,
1611            then_block,
1612            else_block,
1613        } => match eval_static(cond, store, interner, steps)? {
1614            Value::Bool(true) => {
1615                for s in *then_block {
1616                    exec_static_stmt(s, store, interner, steps)?;
1617                }
1618                Some(())
1619            }
1620            Value::Bool(false) => {
1621                if let Some(eb) = else_block {
1622                    for s in *eb {
1623                        exec_static_stmt(s, store, interner, steps)?;
1624                    }
1625                }
1626                Some(())
1627            }
1628            _ => None,
1629        },
1630        Stmt::While { cond, body, .. } => run_static_loop(cond, body, store, interner, steps),
1631        _ => None,
1632    }
1633}
1634
1635/// A pure concrete evaluator over `Value` (arrays included): literals, identifiers, arithmetic, array reads,
1636/// and the pure math builtins the reductions use (`sqrt`/`max`/`min`/`round`/`floor`/`ceil`/`abs`). Returns
1637/// `None` for anything it cannot fully resolve.
1638fn eval_static(
1639    expr: &Expr,
1640    store: &HashMap<Symbol, Value>,
1641    interner: &Interner,
1642    steps: &mut usize,
1643) -> Option<Value> {
1644    *steps += 1;
1645    if *steps > MAX_INLINE_STEPS {
1646        return None;
1647    }
1648    match expr {
1649        Expr::Literal(Literal::Number(n)) => Some(Value::Int(*n)),
1650        Expr::Literal(Literal::Float(f)) => Some(Value::Float(*f)),
1651        Expr::Literal(Literal::Boolean(b)) => Some(Value::Bool(*b)),
1652        Expr::Literal(Literal::Text(s)) => Some(Value::Text(*s)),
1653        Expr::Literal(Literal::Nothing) => Some(Value::Nothing),
1654        Expr::Identifier(sym) => store.get(sym).cloned(),
1655        Expr::BinaryOp { op, left, right } => {
1656            let l = eval_static(left, store, interner, steps)?;
1657            let r = eval_static(right, store, interner, steps)?;
1658            eval_binop(*op, &l, &r)
1659        }
1660        Expr::Not { operand } => match eval_static(operand, store, interner, steps)? {
1661            Value::Bool(b) => Some(Value::Bool(!b)),
1662            _ => None,
1663        },
1664        Expr::Index { collection, index } => {
1665            let seq = match eval_static(collection, store, interner, steps)? {
1666                Value::Seq(v) => v,
1667                _ => return None,
1668            };
1669            let i = as_int_val(eval_static(index, store, interner, steps)?)?;
1670            (i >= 1 && (i as usize) <= seq.len()).then(|| seq[(i - 1) as usize].clone())
1671        }
1672        Expr::Length { collection } => match eval_static(collection, store, interner, steps)? {
1673            Value::Seq(v) => Some(Value::Int(v.len() as i64)),
1674            _ => None,
1675        },
1676        Expr::Call { function, args } => {
1677            let mut vals = Vec::with_capacity(args.len());
1678            for a in args.iter() {
1679                vals.push(eval_static(a, store, interner, steps)?);
1680            }
1681            eval_static_builtin(interner.resolve(*function), &vals)
1682        }
1683        _ => None,
1684    }
1685}
1686
1687/// The pure math builtins the reduction desugars use. Semantics mirror the runtime (`f64` libm + `round`
1688/// half-away-from-zero), so a folded constant equals what the tier would compute.
1689fn eval_static_builtin(name: &str, vals: &[Value]) -> Option<Value> {
1690    match (name, vals) {
1691        ("sqrt", [Value::Float(x)]) => Some(Value::Float(x.sqrt())),
1692        ("sqrt", [Value::Int(x)]) => Some(Value::Float((*x as f64).sqrt())),
1693        ("max", [Value::Float(a), Value::Float(b)]) => Some(Value::Float(a.max(*b))),
1694        ("max", [Value::Int(a), Value::Int(b)]) => Some(Value::Int((*a).max(*b))),
1695        ("min", [Value::Float(a), Value::Float(b)]) => Some(Value::Float(a.min(*b))),
1696        ("min", [Value::Int(a), Value::Int(b)]) => Some(Value::Int((*a).min(*b))),
1697        ("round", [Value::Float(x)]) => Some(Value::Float(x.round())),
1698        ("floor", [Value::Float(x)]) => Some(Value::Float(x.floor())),
1699        ("ceil", [Value::Float(x)]) => Some(Value::Float(x.ceil())),
1700        ("abs", [Value::Int(x)]) => Some(Value::Int(x.abs())),
1701        ("abs", [Value::Float(x)]) => Some(Value::Float(x.abs())),
1702        _ => None,
1703    }
1704}
1705
1706fn as_ident_sym(expr: &Expr) -> Option<Symbol> {
1707    if let Expr::Identifier(s) = expr {
1708        Some(*s)
1709    } else {
1710        None
1711    }
1712}
1713
1714fn as_int_val(v: Value) -> Option<i64> {
1715    if let Value::Int(n) = v {
1716        Some(n)
1717    } else {
1718        None
1719    }
1720}