Skip to main content

logicaffeine_compile/optimize/egraph/
mod.rs

1//! The ARCHITECT — equality saturation over a compiler e-graph
2//! (EXODIA Phase 4, sprints 17–22).
3//!
4//! Classic egg-style design: a hash-consed term bank over the shared
5//! [`UnionFind`] (the same engine the kernel's congruence closure uses),
6//! a worklist `rebuild` restoring the congruence invariant after unions,
7//! budgeted saturation with a deterministic rule order, and bottom-up
8//! cost extraction.
9//!
10//! Class facts (scalar kind + integer interval) come from the Oracle and
11//! gate the conditional rewrites: `x / 2^n → x >> n` fires only with a
12//! non-negativity proof, the Group-2 boolean laws fire only on proven
13//! Bools, and EVERYTHING fails closed when no fact is present.
14
15pub mod convert;
16pub mod enode;
17pub mod extract;
18pub mod rules;
19
20pub use enode::CompilerENode;
21
22use std::collections::HashMap;
23
24use logicaffeine_base::union_find::UnionFind;
25
26use crate::optimize::ScalarKind;
27
28pub type NodeId = usize;
29
30/// Saturation stops after this many fixpoint iterations…
31pub const SATURATION_ITERS: usize = 8;
32/// …or when the term bank would exceed this many nodes.
33pub const MAX_NODES: usize = 10_000;
34
35/// Per-class knowledge, seeded from literals and the Oracle.
36///
37/// Facts describe the VALUE of every member of the class (if evaluation
38/// succeeds); merging classes therefore INTERSECTS intervals.
39#[derive(Debug, Clone, Copy, Default)]
40pub struct ClassFact {
41    pub scalar: Option<ScalarKind>,
42    pub range: Option<(i64, i64)>,
43    /// The value (if evaluation succeeds) is a collection — list, text,
44    /// map, or set. Kind facts are mutation-immune (contents change,
45    /// kinds never do), so they merge by OR.
46    pub collection: bool,
47    /// The value is specifically a LIST (implies `collection`).
48    pub list: bool,
49}
50
51pub struct CompilerEGraph {
52    uf: UnionFind,
53    /// Node id → the node as added (children canonical at insert time).
54    nodes: Vec<CompilerENode>,
55    /// Canonical node → its id. Stale keys (whose children later merged)
56    /// are either still-correct or unreachable by canonical lookups.
57    memo: HashMap<CompilerENode, NodeId>,
58    /// Class root → member node ids.
59    class_nodes: HashMap<NodeId, Vec<NodeId>>,
60    /// Child class root → parent node ids (for congruence repair).
61    uses: HashMap<NodeId, Vec<NodeId>>,
62    /// Class root → facts.
63    facts: HashMap<NodeId, ClassFact>,
64    /// Roots whose parents need congruence repair.
65    dirty: Vec<NodeId>,
66}
67
68impl CompilerEGraph {
69    pub fn new() -> Self {
70        CompilerEGraph {
71            uf: UnionFind::new(),
72            nodes: Vec::new(),
73            memo: HashMap::new(),
74            class_nodes: HashMap::new(),
75            uses: HashMap::new(),
76            facts: HashMap::new(),
77            dirty: Vec::new(),
78        }
79    }
80
81    pub fn node_count(&self) -> usize {
82        self.nodes.len()
83    }
84
85    pub fn find(&mut self, id: NodeId) -> NodeId {
86        self.uf.find(id)
87    }
88
89    /// The stored node with children mapped to their CURRENT class roots.
90    pub fn canonical_node(&mut self, id: NodeId) -> CompilerENode {
91        let node = self.nodes[id];
92        node.map_children(|c| self.uf.find(c))
93    }
94
95    /// Member node ids of `id`'s class, in insertion order (deterministic).
96    pub fn class_members(&mut self, id: NodeId) -> Vec<NodeId> {
97        let root = self.find(id);
98        self.class_nodes.get(&root).cloned().unwrap_or_default()
99    }
100
101    /// Hash-consing insert: an existing congruent node is returned instead
102    /// of allocating. Literal leaves seed their own class facts.
103    pub fn add(&mut self, node: CompilerENode) -> NodeId {
104        let canonical = node.map_children(|c| self.uf.find(c));
105        if let Some(&existing) = self.memo.get(&canonical) {
106            return self.uf.find(existing);
107        }
108        let id = self.uf.make_set();
109        debug_assert_eq!(id, self.nodes.len());
110        self.nodes.push(canonical);
111        self.memo.insert(canonical, id);
112        self.class_nodes.insert(id, vec![id]);
113        for child in canonical.children() {
114            self.uses.entry(child).or_default().push(id);
115        }
116        match canonical {
117            CompilerENode::Int(k) => {
118                self.facts.insert(
119                    id,
120                    ClassFact {
121                        scalar: Some(ScalarKind::Int),
122                        range: Some((k, k)),
123                        ..ClassFact::default()
124                    },
125                );
126            }
127            CompilerENode::Bool(_) => {
128                self.facts.insert(
129                    id,
130                    ClassFact {
131                        scalar: Some(ScalarKind::Bool),
132                        ..ClassFact::default()
133                    },
134                );
135            }
136            CompilerENode::Float(_) => {
137                self.facts.insert(
138                    id,
139                    ClassFact {
140                        scalar: Some(ScalarKind::Float),
141                        ..ClassFact::default()
142                    },
143                );
144            }
145            // A slice that evaluates successfully ALWAYS yields a list.
146            CompilerENode::Slice(..) => {
147                self.facts.insert(
148                    id,
149                    ClassFact {
150                        collection: true,
151                        list: true,
152                        ..ClassFact::default()
153                    },
154                );
155            }
156            // A copy that evaluates preserves its operand's kind; the
157            // converter upgrades this when the operand is a proven list.
158            _ => {}
159        }
160        id
161    }
162
163    /// Merge two classes. Facts intersect (both described the same value).
164    /// Returns true if a merge actually happened.
165    pub fn union(&mut self, a: NodeId, b: NodeId) -> bool {
166        let ra = self.uf.find(a);
167        let rb = self.uf.find(b);
168        if ra == rb {
169            return false;
170        }
171        let fa = self.facts.remove(&ra);
172        let fb = self.facts.remove(&rb);
173        self.uf.union(ra, rb);
174        let root = self.uf.find(ra);
175        let loser = if root == ra { rb } else { ra };
176
177        let mut members = self.class_nodes.remove(&loser).unwrap_or_default();
178        self.class_nodes
179            .entry(root)
180            .or_default()
181            .append(&mut members);
182        let mut moved_uses = self.uses.remove(&loser).unwrap_or_default();
183        self.uses.entry(root).or_default().append(&mut moved_uses);
184
185        let merged = match (fa, fb) {
186            (Some(x), Some(y)) => ClassFact {
187                scalar: x.scalar.or(y.scalar),
188                range: match (x.range, y.range) {
189                    (Some((al, ah)), Some((bl, bh))) => {
190                        let lo = al.max(bl);
191                        let hi = ah.min(bh);
192                        debug_assert!(lo <= hi, "contradictory ranges merged — unsound rule?");
193                        if lo <= hi {
194                            Some((lo, hi))
195                        } else {
196                            Some((al, ah))
197                        }
198                    }
199                    (r, None) | (None, r) => r,
200                },
201                // Kind facts are sound statements about the shared value:
202                // either side's proof carries over.
203                collection: x.collection || y.collection,
204                list: x.list || y.list,
205            },
206            (Some(x), None) | (None, Some(x)) => x,
207            (None, None) => ClassFact::default(),
208        };
209        self.facts.insert(root, merged);
210        self.dirty.push(root);
211        true
212    }
213
214    /// Restore the congruence invariant: parents of merged classes are
215    /// re-canonicalized; newly congruent pairs are unioned (worklist).
216    pub fn rebuild(&mut self) {
217        while let Some(r) = self.dirty.pop() {
218            let root = self.uf.find(r);
219            let parents = self.uses.remove(&root).unwrap_or_default();
220            let mut kept: Vec<NodeId> = Vec::with_capacity(parents.len());
221            for p in parents {
222                let canon = self.nodes[p].map_children(|c| self.uf.find(c));
223                if let Some(&q) = self.memo.get(&canon) {
224                    if self.uf.find(q) != self.uf.find(p) {
225                        self.union(p, q);
226                    }
227                }
228                let rep = self.uf.find(p);
229                self.memo.insert(canon, rep);
230                kept.push(p);
231            }
232            let now = self.uf.find(root);
233            self.uses.entry(now).or_default().extend(kept);
234        }
235    }
236
237    // ----- facts ---------------------------------------------------------
238
239    pub fn set_scalar(&mut self, id: NodeId, kind: ScalarKind) {
240        let root = self.find(id);
241        self.facts.entry(root).or_default().scalar = Some(kind);
242    }
243
244    pub fn set_int_range(&mut self, id: NodeId, lo: i64, hi: i64) {
245        let root = self.find(id);
246        let fact = self.facts.entry(root).or_default();
247        fact.scalar = Some(ScalarKind::Int);
248        fact.range = Some((lo, hi));
249    }
250
251    pub fn scalar_of(&mut self, id: NodeId) -> Option<ScalarKind> {
252        let root = self.find(id);
253        self.facts.get(&root).and_then(|f| f.scalar)
254    }
255
256    pub fn int_range(&mut self, id: NodeId) -> Option<(i64, i64)> {
257        let root = self.find(id);
258        self.facts.get(&root).and_then(|f| f.range)
259    }
260
261    /// A PROVEN single value (point interval) — sound grounds for folding.
262    pub fn int_value(&mut self, id: NodeId) -> Option<i64> {
263        match self.int_range(id) {
264            Some((lo, hi)) if lo == hi => Some(lo),
265            _ => None,
266        }
267    }
268
269    pub fn proven_nonneg(&mut self, id: NodeId) -> bool {
270        matches!(self.int_range(id), Some((lo, _)) if lo >= 0)
271    }
272
273    /// Mark the class a proven collection (list/text/map/set).
274    pub fn set_collection(&mut self, id: NodeId) {
275        let root = self.find(id);
276        self.facts.entry(root).or_default().collection = true;
277    }
278
279    /// Mark the class a proven LIST (implies collection).
280    pub fn set_list(&mut self, id: NodeId) {
281        let root = self.find(id);
282        let fact = self.facts.entry(root).or_default();
283        fact.collection = true;
284        fact.list = true;
285    }
286
287    pub fn proven_collection(&mut self, id: NodeId) -> bool {
288        let root = self.find(id);
289        self.facts.get(&root).is_some_and(|f| f.collection)
290    }
291
292    pub fn proven_list(&mut self, id: NodeId) -> bool {
293        let root = self.find(id);
294        self.facts.get(&root).is_some_and(|f| f.list)
295    }
296
297    /// Does the class contain the literal `Bool(b)`?
298    pub fn class_has_bool(&mut self, id: NodeId, b: bool) -> bool {
299        self.class_members(id)
300            .into_iter()
301            .any(|m| self.nodes[m] == CompilerENode::Bool(b))
302    }
303
304    /// Whole-tree totality: the class has at least one member whose op is
305    /// total and whose children are recursively total. A rewrite may only
306    /// DELETE (stop evaluating) a provably total subterm — anything else
307    /// could erase a runtime error or an effect. Bottom-up fixpoint,
308    /// cycle-tolerant (cycles stay "not yet proven" until a leaf grounds
309    /// them).
310    ///
311    /// Totality is FACT-CONDITIONAL where the op's only failure mode is a
312    /// kind error: `Len`/`Copy`/`Contains` never raise over a PROVEN
313    /// collection, and raise a type error over anything unproven — so
314    /// without the fact they stay non-total, exactly like fold.rs's
315    /// fail-closed `expr_is_total`.
316    pub fn provably_total(&mut self, id: NodeId) -> bool {
317        let mut total: HashMap<NodeId, bool> = HashMap::new();
318        loop {
319            let mut changed = false;
320            for n in 0..self.nodes.len() {
321                let node = self.nodes[n];
322                let root = self.uf.find(n);
323                if *total.get(&root).unwrap_or(&false) {
324                    continue;
325                }
326                let op_total = match node {
327                    CompilerENode::Len(c)
328                    | CompilerENode::Copy(c)
329                    | CompilerENode::Contains(c, _) => self.proven_collection(c),
330                    _ => node.op_is_total(),
331                };
332                if op_total
333                    && node
334                        .children()
335                        .iter()
336                        .all(|&c| *total.get(&self.uf.find(c)).unwrap_or(&false))
337                {
338                    total.insert(root, true);
339                    changed = true;
340                }
341            }
342            if !changed {
343                break;
344            }
345        }
346        let root = self.find(id);
347        *total.get(&root).unwrap_or(&false)
348    }
349
350    // ----- saturation ----------------------------------------------------
351
352    /// Budgeted equality saturation: deterministic node order × rule order,
353    /// unions applied immediately, congruence repaired per iteration. Stops
354    /// at fixpoint, iteration cap, or the node-bank cap.
355    pub fn saturate(&mut self, rules: &[rules::Rewrite]) {
356        self.rebuild();
357        'outer: for _ in 0..SATURATION_ITERS {
358            let snapshot = self.nodes.len();
359            let mut changed = false;
360            for id in 0..snapshot {
361                for rule in rules {
362                    if self.nodes.len() + 4 > MAX_NODES {
363                        self.rebuild();
364                        break 'outer;
365                    }
366                    if let Some(replacement) = (rule.apply)(self, id) {
367                        changed |= self.union(id, replacement);
368                    }
369                }
370            }
371            self.rebuild();
372            if !changed && self.nodes.len() == snapshot {
373                break;
374            }
375        }
376    }
377}
378
379impl Default for CompilerEGraph {
380    fn default() -> Self {
381        Self::new()
382    }
383}