Skip to main content

logicaffeine_compile/optimize/egraph/
convert.rs

1//! AST ⇄ e-graph conversion and the statement-level Architect pass.
2//!
3//! Each expression gets its OWN e-graph (mutation between statements can
4//! never leak equalities), seeded with the Oracle's per-site facts. Two
5//! stability rules keep the seeding sound:
6//!
7//! - **Opaque uniqueness**: every unmodeled subexpression (calls, list
8//!   literals, ranges, …) becomes a FRESH opaque leaf per occurrence —
9//!   two identical calls never unify, so effects are never deduplicated.
10//! - **Fact stability**: Oracle facts are seeded only on subtrees whose
11//!   value cannot change WITHIN one evaluation of the enclosing
12//!   expression — literals, variables (no `Set` can run mid-expression),
13//!   and pure arithmetic over those. A call can write a variable
14//!   mid-expression by lending it to a `mutable` parameter: each read of
15//!   a name the expression writes so is an opaque leaf of its own. `Index`/`Length`/opaque subtrees can
16//!   observe a collection mutated by a sibling call, and two occurrences
17//!   share one e-class, so per-site facts must not be intersected there.
18
19use std::collections::HashMap;
20
21use crate::arena::Arena;
22use crate::ast::stmt::{BinaryOpKind, Expr, Literal, Stmt};
23use crate::intern::{Interner, Symbol};
24use crate::optimize::writes::{pattern_symbols, CalleeGlobals, WriteSet};
25use crate::optimize::OracleFacts;
26
27use super::extract::{best_tree, best_tree_filtered, ExtractTree};
28use super::{rules, CompilerEGraph, CompilerENode, NodeId};
29
30pub struct Converter<'a> {
31    pub eg: CompilerEGraph,
32    opaques: Vec<&'a Expr<'a>>,
33    symbols: HashMap<u32, Symbol>,
34    /// Length-range facts staged on Len nodes — applied only when the
35    /// WHOLE converted expression is opaque-free (no call can mutate the
36    /// collection mid-evaluation, so the statement-entry snapshot holds
37    /// for every occurrence).
38    pending_len_facts: Vec<(NodeId, (i64, i64))>,
39    saw_opaque: bool,
40    /// CURRENT version per symbol index (cross-statement runs): a `Set`
41    /// or rebinding bumps its target, so equality never leaks across a
42    /// write. Absent = version 0.
43    versions: HashMap<u32, u32>,
44    /// Symbols read AS COLLECTIONS so far (the collection child of
45    /// Len/Index/Slice/Copy/Contains): any collection mutation bumps them
46    /// ALL — aliasing between collections is invisible here, so contents
47    /// equalities die wholesale while scalar equalities survive.
48    coll_read_vars: std::collections::HashSet<u32>,
49    /// Symbol indices whose VALUE facts (scalar value-kind, integer range,
50    /// length range) must NOT be applied: variables mutated inside the
51    /// enclosing loop. The Oracle records facts per OCCURRENCE, and a loop
52    /// guard like `d * d <= i` carries `d`'s FIRST-ITERATION range — sound to
53    /// read point-wise (v1 does), UNSOUND as a universal e-graph rewrite
54    /// (`d * d → 4` collapsed primes). KIND facts (is-collection) stay; they
55    /// are mutation-immune.
56    suppressed: std::collections::HashSet<u32>,
57    /// Symbol indices the expression being converted writes while it is evaluated (a binding a call lends to a
58    /// `mutable` parameter, the root of a lent element or field): every read of one is a fresh opaque leaf, so
59    /// no two reads of it unify and none takes a fact from before the write.
60    volatile: std::collections::HashSet<u32>,
61}
62
63/// The symbol indices evaluating `exprs` may write: what their calls lend to `mutable` parameters.
64fn written_while_evaluating<'e, 'a: 'e>(
65    exprs: impl IntoIterator<Item = &'e Expr<'a>>,
66) -> std::collections::HashSet<u32> {
67    exprs
68        .into_iter()
69        .flat_map(|e| WriteSet::of_expr(e).symbols().collect::<Vec<_>>())
70        .map(|s| s.index() as u32)
71        .collect()
72}
73
74impl<'a> Converter<'a> {
75    pub fn new() -> Self {
76        Converter {
77            eg: CompilerEGraph::new(),
78            opaques: Vec::new(),
79            symbols: HashMap::new(),
80            pending_len_facts: Vec::new(),
81            saw_opaque: false,
82            versions: HashMap::new(),
83            coll_read_vars: std::collections::HashSet::new(),
84            suppressed: std::collections::HashSet::new(),
85            volatile: std::collections::HashSet::new(),
86        }
87    }
88
89    fn version_of(&self, ix: u32) -> u32 {
90        self.versions.get(&ix).copied().unwrap_or(0)
91    }
92
93    /// Rebinding / mutation: later reads see a FRESH version.
94    fn bump(&mut self, sym: Symbol) {
95        *self.versions.entry(sym.index() as u32).or_insert(0) += 1;
96    }
97
98    /// A collection's CONTENTS changed somewhere: every symbol ever read
99    /// as a collection gets a fresh version (aliases are indistinguishable
100    /// at this level).
101    fn bump_collection_reads(&mut self) {
102        let vars: Vec<u32> = self.coll_read_vars.iter().copied().collect();
103        for ix in vars {
104            *self.versions.entry(ix).or_insert(0) += 1;
105        }
106    }
107
108    fn note_collection_read(&mut self, collection: &Expr) {
109        if let Expr::Identifier(sym) = collection {
110            self.coll_read_vars.insert(sym.index() as u32);
111        }
112    }
113
114    /// True if `expr` references any suppressed (loop-mutated) variable. Such an
115    /// expression's Oracle facts are a single-iteration snapshot, so they must
116    /// not seed a universal rewrite. Recursive; cheap-exits when nothing is
117    /// suppressed (the common, non-loop case).
118    fn mentions_suppressed(&self, expr: &Expr) -> bool {
119        if self.suppressed.is_empty() {
120            return false;
121        }
122        match expr {
123            Expr::Identifier(sym) => self.suppressed.contains(&(sym.index() as u32)),
124            Expr::BinaryOp { left, right, .. } => {
125                self.mentions_suppressed(left) || self.mentions_suppressed(right)
126            }
127            Expr::Not { operand } => self.mentions_suppressed(operand),
128            Expr::Index { collection, index } => {
129                self.mentions_suppressed(collection) || self.mentions_suppressed(index)
130            }
131            Expr::Length { collection } => self.mentions_suppressed(collection),
132            Expr::Copy { expr } => self.mentions_suppressed(expr),
133            Expr::Slice {
134                collection,
135                start,
136                end,
137            } => {
138                self.mentions_suppressed(collection)
139                    || self.mentions_suppressed(start)
140                    || self.mentions_suppressed(end)
141            }
142            Expr::Contains { collection, value } => {
143                self.mentions_suppressed(collection) || self.mentions_suppressed(value)
144            }
145            _ => false,
146        }
147    }
148
149    /// Stage opaque-free-gated facts now that conversion is complete.
150    pub fn finish_facts(&mut self) {
151        if !self.saw_opaque {
152            for (id, (lo, hi)) in std::mem::take(&mut self.pending_len_facts) {
153                self.eg.set_int_range(id, lo, hi);
154            }
155        }
156    }
157
158    fn opaque(&mut self, expr: &'a Expr<'a>) -> (NodeId, bool) {
159        self.saw_opaque = true;
160        let ix = self.opaques.len() as u32;
161        self.opaques.push(expr);
162        let id = self.eg.add(CompilerENode::Opaque(ix));
163        // A list literal is opaque (effects in its items stay verbatim),
164        // but its VALUE is unconditionally a list.
165        if matches!(expr, Expr::List(_)) {
166            self.eg.set_list(id);
167        }
168        (id, false)
169    }
170
171    /// Returns (class, stable). `stable` = the subtree's value cannot
172    /// change within one evaluation of the enclosing expression.
173    pub fn to_node(&mut self, expr: &'a Expr<'a>, facts: Option<&OracleFacts>) -> (NodeId, bool) {
174        let (id, stable) = match expr {
175            Expr::Literal(Literal::Number(n)) => (self.eg.add(CompilerENode::Int(*n)), true),
176            Expr::Literal(Literal::Boolean(b)) => (self.eg.add(CompilerENode::Bool(*b)), true),
177            Expr::Literal(Literal::Float(f)) => {
178                (self.eg.add(CompilerENode::Float(f.to_bits())), true)
179            }
180            Expr::Identifier(sym) if self.volatile.contains(&(sym.index() as u32)) => {
181                self.opaque(expr)
182            }
183            Expr::Identifier(sym) => {
184                let ix = sym.index() as u32;
185                self.symbols.insert(ix, *sym);
186                let v = self.version_of(ix);
187                let id = self.eg.add(CompilerENode::Var(ix, v));
188                // KIND facts are mutation-immune (contents change, kinds
189                // never do) — seed them unconditionally.
190                if let Some(f) = facts {
191                    if f.expr_is_tracked_collection(expr) {
192                        self.eg.set_collection(id);
193                    }
194                }
195                (id, true)
196            }
197            // ExactDivide (exact Rational division) has no integer e-node model and must
198            // NEVER be floor-folded by the e-graph — treat the whole division as an opaque
199            // leaf so the optimizer leaves it verbatim for the runtime.
200            Expr::BinaryOp {
201                op: BinaryOpKind::ExactDivide,
202                ..
203            } => self.opaque(expr),
204            // Sequence concatenation has no arithmetic e-node model — leave it opaque so the
205            // optimizer never tries to fold it.
206            Expr::BinaryOp {
207                op: BinaryOpKind::SeqConcat,
208                ..
209            } => self.opaque(expr),
210            // Tolerant float comparison: opaque — no algebraic rewrites apply.
211            Expr::BinaryOp {
212                op: BinaryOpKind::ApproxEq,
213                ..
214            } => self.opaque(expr),
215            // `&`/`|` are type-dispatched (Int bitwise / Set ops): opaque to
216            // the numeric e-graph.
217            Expr::BinaryOp {
218                op: BinaryOpKind::BitAnd | BinaryOpKind::BitOr,
219                ..
220            } => self.opaque(expr),
221            // `**` has no e-node model (BigInt-promoting / Float): opaque.
222            Expr::BinaryOp {
223                op: BinaryOpKind::Pow,
224                ..
225            } => self.opaque(expr),
226            // `//` floors toward -inf (distinct from `Div`'s truncation) and can promote
227            // to BigInt — no e-node model, so it stays opaque (never algebraically rewritten).
228            Expr::BinaryOp {
229                op: BinaryOpKind::FloorDivide,
230                ..
231            } => self.opaque(expr),
232            Expr::BinaryOp { op, left, right } => {
233                let (l, ls) = self.to_node(left, facts);
234                let (r, rs) = self.to_node(right, facts);
235                let node = match op {
236                    BinaryOpKind::Add => CompilerENode::Add(l, r),
237                    BinaryOpKind::Subtract => CompilerENode::Sub(l, r),
238                    BinaryOpKind::Multiply => CompilerENode::Mul(l, r),
239                    BinaryOpKind::Divide => CompilerENode::Div(l, r),
240                    BinaryOpKind::ExactDivide => {
241                        unreachable!("ExactDivide handled by the opaque arm above")
242                    }
243                    BinaryOpKind::Pow => unreachable!("Pow handled by the opaque arm above"),
244                    BinaryOpKind::FloorDivide => {
245                        unreachable!("FloorDivide handled by the opaque arm above")
246                    }
247                    BinaryOpKind::ApproxEq => {
248                        unreachable!("ApproxEq handled by the opaque arm above")
249                    }
250                    BinaryOpKind::BitAnd | BinaryOpKind::BitOr => {
251                        unreachable!("BitAnd/BitOr handled by the opaque arm above")
252                    }
253                    BinaryOpKind::Modulo => CompilerENode::Mod(l, r),
254                    BinaryOpKind::Eq => CompilerENode::Eq(l, r),
255                    BinaryOpKind::NotEq => CompilerENode::Ne(l, r),
256                    BinaryOpKind::Lt => CompilerENode::Lt(l, r),
257                    BinaryOpKind::Gt => CompilerENode::Gt(l, r),
258                    BinaryOpKind::LtEq => CompilerENode::Le(l, r),
259                    BinaryOpKind::GtEq => CompilerENode::Ge(l, r),
260                    BinaryOpKind::And => CompilerENode::And(l, r),
261                    BinaryOpKind::Or => CompilerENode::Or(l, r),
262                    BinaryOpKind::Concat => CompilerENode::Concat(l, r),
263                    BinaryOpKind::SeqConcat => {
264                        unreachable!("SeqConcat handled by the opaque arm above")
265                    }
266                    BinaryOpKind::BitXor => CompilerENode::BitXor(l, r),
267                    BinaryOpKind::Shl => CompilerENode::Shl(l, r),
268                    BinaryOpKind::Shr => CompilerENode::Shr(l, r),
269                };
270                (self.eg.add(node), ls && rs)
271            }
272            Expr::Not { operand } => {
273                let (o, os) = self.to_node(operand, facts);
274                (self.eg.add(CompilerENode::Not(o)), os)
275            }
276            Expr::Index { collection, index } => {
277                self.note_collection_read(collection);
278                let (c, _) = self.to_node(collection, facts);
279                let (i, _) = self.to_node(index, facts);
280                // Collection contents can change under a sibling call.
281                (self.eg.add(CompilerENode::Index(c, i)), false)
282            }
283            Expr::Length { collection } => {
284                self.note_collection_read(collection);
285                let (c, _) = self.to_node(collection, facts);
286                let id = self.eg.add(CompilerENode::Len(c));
287                // Length-range facts hold at statement entry; they apply
288                // only if NO opaque (call) can mutate mid-evaluation —
289                // staged here, applied by finish_facts().
290                if let Some(f) = facts {
291                    if !self.mentions_suppressed(collection) {
292                        if let Some((lo, hi)) = f.expr_len_range(collection) {
293                            self.pending_len_facts.push((id, (lo, hi)));
294                        }
295                    }
296                }
297                (id, false)
298            }
299            Expr::Copy { expr: inner } => {
300                self.note_collection_read(inner);
301                let (c, _) = self.to_node(inner, facts);
302                let id = self.eg.add(CompilerENode::Copy(c));
303                // Copy preserves its operand's kind.
304                if self.eg.proven_list(c) {
305                    self.eg.set_list(id);
306                } else if self.eg.proven_collection(c) {
307                    self.eg.set_collection(id);
308                }
309                (id, false)
310            }
311            Expr::Slice {
312                collection,
313                start,
314                end,
315            } => {
316                self.note_collection_read(collection);
317                let (c, _) = self.to_node(collection, facts);
318                let (s, _) = self.to_node(start, facts);
319                let (e, _) = self.to_node(end, facts);
320                (self.eg.add(CompilerENode::Slice(c, s, e)), false)
321            }
322            Expr::Contains { collection, value } => {
323                self.note_collection_read(collection);
324                let (c, _) = self.to_node(collection, facts);
325                let (v, _) = self.to_node(value, facts);
326                (self.eg.add(CompilerENode::Contains(c, v)), false)
327            }
328            other => self.opaque(other),
329        };
330        if stable {
331            if let Some(f) = facts {
332                if !self.mentions_suppressed(expr) {
333                    if let Some(k) = f.expr_scalar(expr) {
334                        self.eg.set_scalar(id, k);
335                    }
336                    if let Some((lo, hi)) = f.expr_int_range(expr) {
337                        self.eg.set_int_range(id, lo, hi);
338                    }
339                }
340            }
341        }
342        (id, stable)
343    }
344
345    pub fn tree_to_expr(&self, t: &ExtractTree, arena: &'a Arena<Expr<'a>>) -> &'a Expr<'a> {
346        let bin = |op: BinaryOpKind, s: &Self| -> &'a Expr<'a> {
347            arena.alloc(Expr::BinaryOp {
348                op,
349                left: s.tree_to_expr(&t.children[0], arena),
350                right: s.tree_to_expr(&t.children[1], arena),
351            })
352        };
353        match t.node {
354            CompilerENode::Int(n) => arena.alloc(Expr::Literal(Literal::Number(n))),
355            CompilerENode::Bool(b) => arena.alloc(Expr::Literal(Literal::Boolean(b))),
356            CompilerENode::Float(bits) => {
357                arena.alloc(Expr::Literal(Literal::Float(f64::from_bits(bits))))
358            }
359            CompilerENode::Var(ix, _) => arena.alloc(Expr::Identifier(self.symbols[&ix])),
360            CompilerENode::Opaque(ix) => self.opaques[ix as usize],
361            CompilerENode::Not(_) => arena.alloc(Expr::Not {
362                operand: self.tree_to_expr(&t.children[0], arena),
363            }),
364            CompilerENode::Len(_) => arena.alloc(Expr::Length {
365                collection: self.tree_to_expr(&t.children[0], arena),
366            }),
367            CompilerENode::Index(..) => arena.alloc(Expr::Index {
368                collection: self.tree_to_expr(&t.children[0], arena),
369                index: self.tree_to_expr(&t.children[1], arena),
370            }),
371            CompilerENode::Copy(_) => arena.alloc(Expr::Copy {
372                expr: self.tree_to_expr(&t.children[0], arena),
373            }),
374            CompilerENode::Slice(..) => arena.alloc(Expr::Slice {
375                collection: self.tree_to_expr(&t.children[0], arena),
376                start: self.tree_to_expr(&t.children[1], arena),
377                end: self.tree_to_expr(&t.children[2], arena),
378            }),
379            CompilerENode::Contains(..) => arena.alloc(Expr::Contains {
380                collection: self.tree_to_expr(&t.children[0], arena),
381                value: self.tree_to_expr(&t.children[1], arena),
382            }),
383            CompilerENode::Add(..) => bin(BinaryOpKind::Add, self),
384            CompilerENode::Sub(..) => bin(BinaryOpKind::Subtract, self),
385            CompilerENode::Mul(..) => bin(BinaryOpKind::Multiply, self),
386            CompilerENode::Div(..) => bin(BinaryOpKind::Divide, self),
387            CompilerENode::Mod(..) => bin(BinaryOpKind::Modulo, self),
388            CompilerENode::Shl(..) => bin(BinaryOpKind::Shl, self),
389            CompilerENode::Shr(..) => bin(BinaryOpKind::Shr, self),
390            CompilerENode::BitXor(..) => bin(BinaryOpKind::BitXor, self),
391            CompilerENode::BitAnd(..) => bin(BinaryOpKind::BitAnd, self),
392            CompilerENode::BitOr(..) => bin(BinaryOpKind::BitOr, self),
393            CompilerENode::And(..) => bin(BinaryOpKind::And, self),
394            CompilerENode::Or(..) => bin(BinaryOpKind::Or, self),
395            CompilerENode::Eq(..) => bin(BinaryOpKind::Eq, self),
396            CompilerENode::Ne(..) => bin(BinaryOpKind::NotEq, self),
397            CompilerENode::Lt(..) => bin(BinaryOpKind::Lt, self),
398            CompilerENode::Le(..) => bin(BinaryOpKind::LtEq, self),
399            CompilerENode::Gt(..) => bin(BinaryOpKind::Gt, self),
400            CompilerENode::Ge(..) => bin(BinaryOpKind::GtEq, self),
401            CompilerENode::Concat(..) => bin(BinaryOpKind::Concat, self),
402        }
403    }
404}
405
406/// Structural equality over the MODELED fragment (bit-exact floats);
407/// anything else compares by pointer (opaques re-emit the original).
408fn expr_struct_eq(a: &Expr, b: &Expr) -> bool {
409    if std::ptr::eq(a, b) {
410        return true;
411    }
412    match (a, b) {
413        (Expr::Literal(Literal::Number(x)), Expr::Literal(Literal::Number(y))) => x == y,
414        (Expr::Literal(Literal::Boolean(x)), Expr::Literal(Literal::Boolean(y))) => x == y,
415        (Expr::Literal(Literal::Float(x)), Expr::Literal(Literal::Float(y))) => {
416            x.to_bits() == y.to_bits()
417        }
418        (Expr::Identifier(x), Expr::Identifier(y)) => x == y,
419        (
420            Expr::BinaryOp {
421                op: oa,
422                left: la,
423                right: ra,
424            },
425            Expr::BinaryOp {
426                op: ob,
427                left: lb,
428                right: rb,
429            },
430        ) => oa == ob && expr_struct_eq(la, lb) && expr_struct_eq(ra, rb),
431        (Expr::Not { operand: x }, Expr::Not { operand: y }) => expr_struct_eq(x, y),
432        (Expr::Length { collection: x }, Expr::Length { collection: y }) => expr_struct_eq(x, y),
433        (
434            Expr::Index {
435                collection: ca,
436                index: ia,
437            },
438            Expr::Index {
439                collection: cb,
440                index: ib,
441            },
442        ) => expr_struct_eq(ca, cb) && expr_struct_eq(ia, ib),
443        (Expr::Copy { expr: a }, Expr::Copy { expr: b }) => expr_struct_eq(a, b),
444        (
445            Expr::Slice {
446                collection: ca,
447                start: sa,
448                end: ea,
449            },
450            Expr::Slice {
451                collection: cb,
452                start: sb,
453                end: eb,
454            },
455        ) => expr_struct_eq(ca, cb) && expr_struct_eq(sa, sb) && expr_struct_eq(ea, eb),
456        (
457            Expr::Contains {
458                collection: ca,
459                value: va,
460            },
461            Expr::Contains {
462                collection: cb,
463                value: vb,
464            },
465        ) => expr_struct_eq(ca, cb) && expr_struct_eq(va, vb),
466        _ => false,
467    }
468}
469
470/// Does the expression contain anything the e-graph can act on?
471fn worth_modeling(expr: &Expr) -> bool {
472    match expr {
473        Expr::BinaryOp { .. } | Expr::Not { .. } => true,
474        // A bare `length of xs` / `item i of xs` has nothing to improve,
475        // but the same reads over a COPY or SLICE are fusion's home turf.
476        Expr::Index { collection, index } => {
477            fusable(collection) || worth_modeling(collection) || worth_modeling(index)
478        }
479        Expr::Length { collection } => fusable(collection) || worth_modeling(collection),
480        Expr::Copy { expr } => fusable(expr) || worth_modeling(expr),
481        Expr::Slice {
482            collection,
483            start,
484            end,
485        } => worth_modeling(collection) || worth_modeling(start) || worth_modeling(end),
486        Expr::Contains { collection, value } => worth_modeling(collection) || worth_modeling(value),
487        _ => false,
488    }
489}
490
491/// Operands whose shape the fusion algebra can act on directly.
492fn fusable(expr: &Expr) -> bool {
493    matches!(expr, Expr::Copy { .. } | Expr::Slice { .. })
494}
495
496/// Saturate ONE expression against the rule set and extract the cheapest
497/// equivalent. Returns the original pointer when nothing improved.
498pub fn simplify_expr<'a>(
499    expr: &'a Expr<'a>,
500    facts: &OracleFacts,
501    rule_set: &[rules::Rewrite],
502    arena: &'a Arena<Expr<'a>>,
503) -> &'a Expr<'a> {
504    simplify_expr_in(
505        expr,
506        facts,
507        rule_set,
508        arena,
509        &std::collections::HashSet::new(),
510    )
511}
512
513/// As [`simplify_expr`], but suppresses value facts for the `suppressed`
514/// (loop-mutated) symbols — their Oracle per-occurrence range is iteration-
515/// specific and may not seed a universal rewrite.
516fn simplify_expr_in<'a>(
517    expr: &'a Expr<'a>,
518    facts: &OracleFacts,
519    rule_set: &[rules::Rewrite],
520    arena: &'a Arena<Expr<'a>>,
521    suppressed: &std::collections::HashSet<u32>,
522) -> &'a Expr<'a> {
523    if !worth_modeling(expr) {
524        return expr;
525    }
526    let mut cv = Converter::new();
527    cv.suppressed = suppressed.clone();
528    cv.volatile = written_while_evaluating([expr]);
529    let (root, _) = cv.to_node(expr, Some(facts));
530    cv.finish_facts();
531    cv.eg.saturate(rule_set);
532    let tree = best_tree(&mut cv.eg, root);
533    let rebuilt = cv.tree_to_expr(&tree, arena);
534    if expr_struct_eq(rebuilt, expr) {
535        expr
536    } else {
537        rebuilt
538    }
539}
540
541/// The Architect statement pass: STRAIGHT-LINE RUNS of simple statements
542/// share one e-graph (a Let merges its variable with its defining
543/// expression's class, so later statements extract against everything
544/// proven so far — the GVN replacement); everything else falls back to
545/// per-expression graphs and ENDS the run. Versioning makes mutation
546/// kills structural.
547pub fn egraph_stmts<'a>(
548    stmts: Vec<Stmt<'a>>,
549    expr_arena: &'a Arena<Expr<'a>>,
550    stmt_arena: &'a Arena<Stmt<'a>>,
551    interner: &mut Interner,
552) -> Vec<Stmt<'a>> {
553    let facts = crate::optimize::oracle_analyze_with(&stmts, interner);
554    let rule_set = rules::all();
555    let globals = CalleeGlobals::of_program(&stmts);
556    walk_stmts(
557        stmts,
558        &facts,
559        &rule_set,
560        expr_arena,
561        stmt_arena,
562        &std::collections::HashSet::new(),
563        &globals,
564    )
565}
566
567/// Statements a cross-statement run can model EXACTLY (effects and kills
568/// understood). Anything else flushes the run.
569fn run_modeled(s: &Stmt, globals: &CalleeGlobals) -> bool {
570    let shape = matches!(
571        s,
572        Stmt::Let { .. }
573            | Stmt::Set { .. }
574            | Stmt::Show { .. }
575            | Stmt::RuntimeAssert { .. }
576            | Stmt::Return { .. }
577            | Stmt::Push { .. }
578            | Stmt::SetIndex { .. }
579            | Stmt::Call { .. }
580    );
581    // A call into a callee holding raw foreign code may rewrite any name: no version bookkeeping
582    // can express that, so such a statement ends the run.
583    shape && !(globals.opaque && WriteSet::of_stmt(s).has_calls())
584}
585
586/// One extraction site inside a run: the converted root, the VERSION
587/// SNAPSHOT it may reference, the opaque indices it owns, and the
588/// original expression (the fallback and the no-change comparator).
589struct SiteRec<'a> {
590    root: NodeId,
591    ctx: HashMap<u32, u32>,
592    opq: (usize, usize),
593    original: &'a Expr<'a>,
594}
595
596fn walk_stmts<'a>(
597    stmts: Vec<Stmt<'a>>,
598    facts: &OracleFacts,
599    rule_set: &[rules::Rewrite],
600    expr_arena: &'a Arena<Expr<'a>>,
601    stmt_arena: &'a Arena<Stmt<'a>>,
602    suppressed: &std::collections::HashSet<u32>,
603    globals: &CalleeGlobals,
604) -> Vec<Stmt<'a>> {
605    let mut out: Vec<Stmt<'a>> = Vec::new();
606    let mut run: Vec<Stmt<'a>> = Vec::new();
607    for s in stmts {
608        if run_modeled(&s, globals) {
609            run.push(s);
610        } else {
611            flush_run(
612                &mut run, &mut out, facts, rule_set, expr_arena, suppressed, globals,
613            );
614            out.push(walk_stmt(
615                s, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
616            ));
617        }
618    }
619    flush_run(
620        &mut run, &mut out, facts, rule_set, expr_arena, suppressed, globals,
621    );
622    out
623}
624
625/// Convert a run's expression sites into ONE shared graph (with version
626/// bookkeeping per statement), saturate once, then rebuild every
627/// statement from its site's filtered extraction.
628fn flush_run<'a>(
629    run: &mut Vec<Stmt<'a>>,
630    out: &mut Vec<Stmt<'a>>,
631    facts: &OracleFacts,
632    rule_set: &[rules::Rewrite],
633    expr_arena: &'a Arena<Expr<'a>>,
634    suppressed: &std::collections::HashSet<u32>,
635    globals: &CalleeGlobals,
636) {
637    if run.is_empty() {
638        return;
639    }
640    let stmts = std::mem::take(run);
641    let mut cv = Converter::new();
642    cv.suppressed = suppressed.clone();
643    let mut sites: Vec<SiteRec<'a>> = Vec::new();
644    // Per statement: the site indices feeding its rebuild, in field order.
645    let mut plans: Vec<Vec<usize>> = Vec::with_capacity(stmts.len());
646
647    let convert_site =
648        |cv: &mut Converter<'a>, sites: &mut Vec<SiteRec<'a>>, e: &'a Expr<'a>| -> usize {
649            let opq_start = cv.opaques.len();
650            let (root, _) = cv.to_node(e, Some(facts));
651            let opq_end = cv.opaques.len();
652            sites.push(SiteRec {
653                root,
654                ctx: cv.versions.clone(),
655                opq: (opq_start, opq_end),
656                original: e,
657            });
658            sites.len() - 1
659        };
660
661    for s in &stmts {
662        let mut plan: Vec<usize> = Vec::new();
663        // A call anywhere in the statement may assign any callee-written global: later reads see a
664        // FRESH version, so nothing computed from the pre-call value is reused past it.
665        if WriteSet::of_stmt(s).has_calls() {
666            for g in &globals.symbols {
667                cv.bump(*g);
668            }
669        }
670        // A name a call in the statement writes mid-evaluation is read as its own opaque leaf here, and holds a
671        // fresh version from here on; a lent element or field changes its collection's contents.
672        cv.volatile =
673            written_while_evaluating(logicaffeine_language::ast_depth::stmt_expr_children(s));
674        if !cv.volatile.is_empty() {
675            let written: Vec<u32> = cv.volatile.iter().copied().collect();
676            for ix in written {
677                *cv.versions.entry(ix).or_insert(0) += 1;
678            }
679            cv.bump_collection_reads();
680        }
681        match s {
682            Stmt::Let { var, value, .. } => {
683                let site = convert_site(&mut cv, &mut sites, value);
684                plan.push(site);
685                let had_opaques = sites[site].opq.0 != sites[site].opq.1;
686                cv.bump(*var);
687                if !had_opaques {
688                    let ix = var.index() as u32;
689                    cv.symbols.insert(ix, *var);
690                    let v = cv.version_of(ix);
691                    let vnode = cv.eg.add(CompilerENode::Var(ix, v));
692                    let root = sites[site].root;
693                    cv.eg.union(vnode, root);
694                } else {
695                    // The binding's value went through a call — its
696                    // collection arguments may have been resized.
697                    cv.bump_collection_reads();
698                }
699            }
700            Stmt::Set { target, value } => {
701                let site = convert_site(&mut cv, &mut sites, value);
702                plan.push(site);
703                let had_opaques = sites[site].opq.0 != sites[site].opq.1;
704                cv.bump(*target);
705                if !had_opaques {
706                    let ix = target.index() as u32;
707                    cv.symbols.insert(ix, *target);
708                    let v = cv.version_of(ix);
709                    let vnode = cv.eg.add(CompilerENode::Var(ix, v));
710                    let root = sites[site].root;
711                    cv.eg.union(vnode, root);
712                } else {
713                    cv.bump_collection_reads();
714                }
715            }
716            Stmt::Show { object, .. } => {
717                plan.push(convert_site(&mut cv, &mut sites, object));
718                // Show stringifies arbitrary values through an opaque-free
719                // read — no kills.
720            }
721            Stmt::RuntimeAssert { condition, .. } => {
722                plan.push(convert_site(&mut cv, &mut sites, condition));
723            }
724            Stmt::Return { value } => {
725                if let Some(v) = value {
726                    plan.push(convert_site(&mut cv, &mut sites, v));
727                }
728            }
729            Stmt::Push { value, collection } => {
730                plan.push(convert_site(&mut cv, &mut sites, value));
731                // Contents change: every collection read goes stale.
732                if let Expr::Identifier(sym) = collection {
733                    cv.bump(*sym);
734                }
735                cv.bump_collection_reads();
736            }
737            Stmt::SetIndex {
738                collection,
739                index,
740                value,
741            } => {
742                plan.push(convert_site(&mut cv, &mut sites, index));
743                plan.push(convert_site(&mut cv, &mut sites, value));
744                if let Expr::Identifier(sym) = collection {
745                    cv.bump(*sym);
746                }
747                cv.bump_collection_reads();
748            }
749            Stmt::Call { args, .. } => {
750                for a in args {
751                    plan.push(convert_site(&mut cv, &mut sites, a));
752                }
753                // The callee may resize any collection it can reach.
754                cv.bump_collection_reads();
755            }
756            _ => unreachable!("run_modeled admitted an unhandled statement"),
757        }
758        plans.push(plan);
759    }
760
761    cv.finish_facts();
762    cv.eg.saturate(rule_set);
763
764    let extract = |cv: &mut Converter<'a>, site: usize| -> &'a Expr<'a> {
765        let rec = &sites[site];
766        if !worth_modeling(rec.original) {
767            return rec.original;
768        }
769        let ctx = rec.ctx.clone();
770        let (lo, hi) = rec.opq;
771        let admissible = move |n: &CompilerENode| match *n {
772            CompilerENode::Var(ix, v) => ctx.get(&ix).copied().unwrap_or(0) == v,
773            CompilerENode::Opaque(j) => (lo..hi).contains(&(j as usize)),
774            _ => true,
775        };
776        match best_tree_filtered(&mut cv.eg, rec.root, &admissible) {
777            Some(tree) => {
778                let rebuilt = cv.tree_to_expr(&tree, expr_arena);
779                if expr_struct_eq(rebuilt, rec.original) {
780                    rec.original
781                } else {
782                    rebuilt
783                }
784            }
785            None => rec.original,
786        }
787    };
788
789    for (s, plan) in stmts.into_iter().zip(plans) {
790        let rebuilt = match s {
791            Stmt::Let {
792                var,
793                ty,
794                value: _,
795                mutable,
796            } => Stmt::Let {
797                var,
798                ty,
799                value: extract(&mut cv, plan[0]),
800                mutable,
801            },
802            Stmt::Set { target, value: _ } => Stmt::Set {
803                target,
804                value: extract(&mut cv, plan[0]),
805            },
806            Stmt::Show {
807                object: _,
808                recipient,
809            } => Stmt::Show {
810                object: extract(&mut cv, plan[0]),
811                recipient,
812            },
813            Stmt::RuntimeAssert {
814                condition: _,
815                hard,
816                dim,
817                reason,
818            } => Stmt::RuntimeAssert {
819                condition: extract(&mut cv, plan[0]),
820                hard,
821                dim,
822                reason,
823            },
824            Stmt::Return { value } => Stmt::Return {
825                value: value.map(|_| extract(&mut cv, plan[0])),
826            },
827            Stmt::Push {
828                value: _,
829                collection,
830            } => Stmt::Push {
831                value: extract(&mut cv, plan[0]),
832                collection,
833            },
834            Stmt::SetIndex {
835                collection,
836                index: _,
837                value: _,
838            } => Stmt::SetIndex {
839                collection,
840                index: extract(&mut cv, plan[0]),
841                value: extract(&mut cv, plan[1]),
842            },
843            Stmt::Call { function, args } => Stmt::Call {
844                function,
845                args: (0..args.len()).map(|k| extract(&mut cv, plan[k])).collect(),
846            },
847            other => other,
848        };
849        out.push(rebuilt);
850    }
851}
852
853fn walk_block<'a>(
854    block: &'a [Stmt<'a>],
855    facts: &OracleFacts,
856    rule_set: &[rules::Rewrite],
857    expr_arena: &'a Arena<Expr<'a>>,
858    stmt_arena: &'a Arena<Stmt<'a>>,
859    suppressed: &std::collections::HashSet<u32>,
860    globals: &CalleeGlobals,
861) -> &'a [Stmt<'a>] {
862    let walked = walk_stmts(
863        block.to_vec(),
864        facts,
865        rule_set,
866        expr_arena,
867        stmt_arena,
868        suppressed,
869        globals,
870    );
871    stmt_arena.alloc_slice(walked)
872}
873
874fn walk_stmt<'a>(
875    stmt: Stmt<'a>,
876    facts: &OracleFacts,
877    rule_set: &[rules::Rewrite],
878    expr_arena: &'a Arena<Expr<'a>>,
879    stmt_arena: &'a Arena<Stmt<'a>>,
880    suppressed: &std::collections::HashSet<u32>,
881    globals: &CalleeGlobals,
882) -> Stmt<'a> {
883    let se = |e: &'a Expr<'a>| simplify_expr_in(e, facts, rule_set, expr_arena, suppressed);
884    match stmt {
885        Stmt::Let {
886            var,
887            ty,
888            value,
889            mutable,
890        } => Stmt::Let {
891            var,
892            ty,
893            value: se(value),
894            mutable,
895        },
896        Stmt::Set { target, value } => Stmt::Set {
897            target,
898            value: se(value),
899        },
900        Stmt::If {
901            cond,
902            then_block,
903            else_block,
904        } => Stmt::If {
905            cond: se(cond),
906            then_block: walk_block(
907                then_block, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
908            ),
909            else_block: else_block.map(|b| {
910                walk_block(
911                    b, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
912                )
913            }),
914        },
915        Stmt::While {
916            cond,
917            body,
918            decreasing,
919        } => {
920            // Inside the loop, every variable the body mutates is loop-variant;
921            // its Oracle per-occurrence facts (a single-iteration snapshot) must
922            // not seed a universal rewrite — `cond` is re-evaluated each pass.
923            let body_writes = WriteSet::of_block(body).with_callee_globals(globals);
924            if body_writes.is_opaque() {
925                // Foreign code in the body may rewrite anything: no fact is a loop invariant here.
926                return Stmt::While {
927                    cond,
928                    body,
929                    decreasing,
930                };
931            }
932            let mut inner = suppressed.clone();
933            inner.extend(body_writes.symbols().map(|sym| sym.index() as u32));
934            Stmt::While {
935                cond: simplify_expr_in(cond, facts, rule_set, expr_arena, &inner),
936                body: walk_block(
937                    body, facts, rule_set, expr_arena, stmt_arena, &inner, globals,
938                ),
939                decreasing,
940            }
941        }
942        Stmt::Repeat {
943            pattern,
944            iterable,
945            body,
946        } => {
947            // `iterable` is evaluated ONCE in the outer context; the body runs
948            // per element, so loop-mutated vars are suppressed within it.
949            let body_writes = WriteSet::of_block(body).with_callee_globals(globals);
950            if body_writes.is_opaque() {
951                return Stmt::Repeat {
952                    pattern,
953                    iterable,
954                    body,
955                };
956            }
957            let mut inner = suppressed.clone();
958            inner.extend(body_writes.symbols().map(|sym| sym.index() as u32));
959            for sym in pattern_symbols(&pattern) {
960                inner.insert(sym.index() as u32);
961            }
962            Stmt::Repeat {
963                pattern,
964                iterable: se(iterable),
965                body: walk_block(
966                    body, facts, rule_set, expr_arena, stmt_arena, &inner, globals,
967                ),
968            }
969        }
970        Stmt::FunctionDef {
971            name,
972            params,
973            generics,
974            body,
975            return_type,
976            is_native,
977            native_path,
978            is_exported,
979            export_target,
980            opt_flags,
981        } => Stmt::FunctionDef {
982            name,
983            params,
984            generics,
985            body: walk_block(
986                body, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
987            ),
988            return_type,
989            is_native,
990            native_path,
991            is_exported,
992            export_target,
993            opt_flags,
994        },
995        Stmt::Show { object, recipient } => Stmt::Show {
996            object: se(object),
997            recipient,
998        },
999        Stmt::Return { value } => Stmt::Return {
1000            value: value.map(se),
1001        },
1002        Stmt::RuntimeAssert {
1003            condition,
1004            hard,
1005            dim,
1006            reason,
1007        } => Stmt::RuntimeAssert {
1008            condition: se(condition),
1009            hard,
1010            dim,
1011            reason: reason.map(|r| se(r)),
1012        },
1013        Stmt::Push { value, collection } => Stmt::Push {
1014            value: se(value),
1015            collection,
1016        },
1017        Stmt::SetField {
1018            object,
1019            field,
1020            value,
1021        } => Stmt::SetField {
1022            object,
1023            field,
1024            value: se(value),
1025        },
1026        Stmt::SetIndex {
1027            collection,
1028            index,
1029            value,
1030        } => Stmt::SetIndex {
1031            collection,
1032            index: se(index),
1033            value: se(value),
1034        },
1035        Stmt::Call { function, args } => Stmt::Call {
1036            function,
1037            args: args.into_iter().map(se).collect(),
1038        },
1039        Stmt::Give { object, recipient } => Stmt::Give {
1040            object: se(object),
1041            recipient: se(recipient),
1042        },
1043        Stmt::Inspect {
1044            target,
1045            arms,
1046            has_otherwise,
1047        } => Stmt::Inspect {
1048            target: se(target),
1049            arms: arms
1050                .into_iter()
1051                .map(|arm| crate::ast::stmt::MatchArm {
1052                    enum_name: arm.enum_name,
1053                    variant: arm.variant,
1054                    bindings: arm.bindings,
1055                    body: walk_block(
1056                        arm.body, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
1057                    ),
1058                })
1059                .collect(),
1060            has_otherwise,
1061        },
1062        Stmt::Pop { collection, into } => Stmt::Pop {
1063            collection: se(collection),
1064            into,
1065        },
1066        Stmt::Add { value, collection } => Stmt::Add {
1067            value: se(value),
1068            collection: se(collection),
1069        },
1070        Stmt::Remove { value, collection } => Stmt::Remove {
1071            value: se(value),
1072            collection: se(collection),
1073        },
1074        Stmt::Zone {
1075            name,
1076            capacity,
1077            source_file,
1078            body,
1079        } => Stmt::Zone {
1080            name,
1081            capacity,
1082            source_file,
1083            body: walk_block(
1084                body, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
1085            ),
1086        },
1087        Stmt::Concurrent { tasks } => Stmt::Concurrent {
1088            tasks: walk_block(
1089                tasks, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
1090            ),
1091        },
1092        Stmt::Parallel { tasks } => Stmt::Parallel {
1093            tasks: walk_block(
1094                tasks, facts, rule_set, expr_arena, stmt_arena, suppressed, globals,
1095            ),
1096        },
1097        Stmt::WriteFile { content, path } => Stmt::WriteFile {
1098            content: se(content),
1099            path: se(path),
1100        },
1101        Stmt::SendMessage {
1102            message,
1103            destination,
1104            compression,
1105            cached,
1106            unchecked,
1107            layout,
1108            shared,
1109            computed,
1110            indexed,
1111            deduped,
1112            unreliable,
1113        } => Stmt::SendMessage {
1114            message: se(message),
1115            destination: se(destination),
1116            compression,
1117            cached,
1118            unchecked,
1119            layout,
1120            shared,
1121            computed,
1122            indexed,
1123            deduped,
1124            unreliable,
1125        },
1126        Stmt::StreamMessage {
1127            values,
1128            destination,
1129        } => Stmt::StreamMessage {
1130            values: se(values),
1131            destination: se(destination),
1132        },
1133        Stmt::IncreaseCrdt {
1134            object,
1135            field,
1136            amount,
1137        } => Stmt::IncreaseCrdt {
1138            object: se(object),
1139            field,
1140            amount: se(amount),
1141        },
1142        Stmt::DecreaseCrdt {
1143            object,
1144            field,
1145            amount,
1146        } => Stmt::DecreaseCrdt {
1147            object: se(object),
1148            field,
1149            amount: se(amount),
1150        },
1151        Stmt::Sleep { milliseconds } => Stmt::Sleep {
1152            milliseconds: se(milliseconds),
1153        },
1154        Stmt::MergeCrdt { source, target } => Stmt::MergeCrdt {
1155            source: se(source),
1156            target: se(target),
1157        },
1158        Stmt::JoinCrdt { source, target } => Stmt::JoinCrdt {
1159            source: se(source),
1160            target: se(target),
1161        },
1162        other => other,
1163    }
1164}