Skip to main content

semi_persistent_egraph/
apply.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Compiled RHS terms and apply function.
4//!
5//! All variable references use the typed dense ids from LHS resolve
6//! for O(1) lookup into Match / MatchSet. The apply function walks
7//! the compiled RHS tree bottom-up, building e-graph terms via `eg.add()`.
8
9use crate::ast::{GlobalVarId, LitValVarId, MsetVarId, MultVarId, SeqVarId, SetVarId, VarId};
10use crate::containers::DenseId;
11use crate::resolve::{RRhsChild, RRhsTerm};
12
13// ---------------------------------------------------------------------------
14// Compiled RHS types
15// ---------------------------------------------------------------------------
16
17/// Instruction that produces one `Cfg::G` when evaluated against a Match.
18#[derive(Clone, Debug)]
19pub enum RhsOp<O, V> {
20    /// Fetch bound e-node id from match.
21    FetchNode(VarId),
22    /// Create literal node via `eg.add_lit()`.
23    Lit(O, V),
24    /// Reconstruct `@sort(val)` lit node from a bound LitValVarId.
25    LitVar(O, LitValVarId),
26    /// Reconstruct an `@i64(k)` lit node from a bound AC multiplicity variable.
27    MultVar(O, MultVarId),
28    /// Build `(op args...)` via `eg.add()`. Args may expand to multiple children.
29    App { op: O, args: Vec<RhsArg<O, V>> },
30    /// Evaluate a prim op on bound lit values or multiplicities, intern result.
31    PrimApp {
32        op: O,
33        args: Vec<crate::resolve::RPrimArg>,
34    },
35    /// Fetch a global e-class id from the runtime global bindings.
36    FetchGlobal(GlobalVarId),
37}
38
39/// An argument to `App` — produces one or many children.
40#[derive(Clone, Debug)]
41pub enum RhsArg<O, V> {
42    /// Single child.
43    One(RhsOp<O, V>),
44    /// One child contributed `mult` times (variadic ops only). Multiplicity 0
45    /// omits the child without evaluating it, so nothing is materialized.
46    OneMult {
47        body: Box<RhsOp<O, V>>,
48        mult: crate::resolve::ResolvedMultExpr,
49    },
50    /// Splice sequence rest into children.
51    SpliceSeq(SeqVarId),
52    /// Splice set rest into children.
53    SpliceSet(SetVarId),
54    /// Splice multiset rest into children (each element repeated by its multiplicity).
55    SpliceMset(MsetVarId),
56    /// Set comprehension: map body over set rest.
57    SetComp {
58        body: Box<RhsOp<O, V>>,
59        var: VarId,
60        source: SetVarId,
61        filter: Option<Box<RhsOp<O, V>>>,
62    },
63    /// Multiset comprehension: map body over mset rest, with output multiplicity.
64    MsetComp {
65        body: Box<RhsOp<O, V>>,
66        mult: crate::resolve::ResolvedMultExpr,
67        var: VarId,
68        mult_var: MultVarId,
69        source: MsetVarId,
70        filter: Option<Box<RhsOp<O, V>>>,
71    },
72    /// Sequence comprehension: map body over seq rest.
73    SeqComp {
74        body: Box<RhsOp<O, V>>,
75        var: VarId,
76        source: SeqVarId,
77        filter: Option<Box<RhsOp<O, V>>>,
78    },
79}
80
81// ---------------------------------------------------------------------------
82// Compile: RRhsTerm → RhsOp (all IDs already resolved)
83// ---------------------------------------------------------------------------
84
85pub fn compile_rhs<O: Clone, S, V: Clone>(term: &RRhsTerm<O, S, V>) -> RhsOp<O, V> {
86    match term {
87        RRhsTerm::Var(vid) => RhsOp::FetchNode(*vid),
88        RRhsTerm::Lit { op, value, .. } => RhsOp::Lit(op.clone(), value.clone()),
89        RRhsTerm::LitVar { op, val } => RhsOp::LitVar(op.clone(), *val),
90        RRhsTerm::MultVar { op, var } => RhsOp::MultVar(op.clone(), *var),
91        RRhsTerm::App { op, children } => {
92            let args: Vec<RhsArg<O, V>> = children.iter().map(|c| compile_rhs_arg(c)).collect();
93            RhsOp::App {
94                op: op.clone(),
95                args,
96            }
97        }
98        RRhsTerm::PrimApp { op, args, .. } => RhsOp::PrimApp {
99            op: op.clone(),
100            args: args.clone(),
101        },
102        RRhsTerm::FetchGlobal(gid) => RhsOp::FetchGlobal(*gid),
103    }
104}
105
106fn compile_rhs_arg<O: Clone, S, V: Clone>(child: &RRhsChild<O, S, V>) -> RhsArg<O, V> {
107    match child {
108        RRhsChild::Term(t) => RhsArg::One(compile_rhs(t)),
109        RRhsChild::TermMult { body, mult } => RhsArg::OneMult {
110            body: Box::new(compile_rhs(body)),
111            mult: mult.clone(),
112        },
113        RRhsChild::SpliceSeq(id) => RhsArg::SpliceSeq(*id),
114        RRhsChild::SpliceSet(id) => RhsArg::SpliceSet(*id),
115        RRhsChild::SpliceMset(id) => RhsArg::SpliceMset(*id),
116        RRhsChild::SetComp {
117            body,
118            var,
119            source,
120            filter,
121        } => RhsArg::SetComp {
122            body: Box::new(compile_rhs(body)),
123            var: *var,
124            source: *source,
125            filter: filter.as_ref().map(|f| Box::new(compile_rhs(f))),
126        },
127        RRhsChild::MsetComp {
128            body,
129            mult,
130            var,
131            mult_var,
132            source,
133            filter,
134        } => RhsArg::MsetComp {
135            body: Box::new(compile_rhs(body)),
136            mult: mult.clone(),
137            var: *var,
138            mult_var: *mult_var,
139            source: *source,
140            filter: filter.as_ref().map(|f| Box::new(compile_rhs(f))),
141        },
142        RRhsChild::SeqComp {
143            body,
144            var,
145            source,
146            filter,
147        } => RhsArg::SeqComp {
148            body: Box::new(compile_rhs(body)),
149            var: *var,
150            source: *source,
151            filter: filter.as_ref().map(|f| Box::new(compile_rhs(f))),
152        },
153    }
154}
155
156// ---------------------------------------------------------------------------
157// Compiled actions and rules
158// ---------------------------------------------------------------------------
159
160#[derive(Clone, Debug)]
161pub enum CompiledAction<O, V> {
162    Union(crate::id::RuleId, RhsOp<O, V>, RhsOp<O, V>),
163    Insert(RhsOp<O, V>),
164    Set {
165        func: O,
166        args: Vec<RhsOp<O, V>>,
167        value: RhsOp<O, V>,
168    },
169    Subsume(crate::ast::VarId),
170}
171
172/// Identifier of a declared ruleset: its index in the program's declaration order. `None`
173/// wherever a `RulesetId` is optional means the default ruleset — the one an untagged rule
174/// joins and a bare `(run N)` runs.
175pub type RulesetId = u32;
176
177#[derive(Clone, Debug)]
178pub struct PreparedRule<O, S, V> {
179    pub rule_id: crate::id::RuleId,
180    pub query: crate::resolve::ResolvedQuery<O, S, V>,
181    pub actions: Vec<CompiledAction<O, V>>,
182    /// The ruleset this rule belongs to (`:ruleset name`), or `None` for the default one.
183    /// The saturation driver runs the rules whose ruleset equals the one asked for.
184    pub ruleset: Option<RulesetId>,
185}
186
187// ---------------------------------------------------------------------------
188// Install-time multiplicity-width validation
189// ---------------------------------------------------------------------------
190
191/// Reject a rule whose surface multiplicity literals do not fit the configured
192/// [`EGraphConfig::M`], naming the offending value.
193///
194/// Multiplicity literals are parsed and resolved at the `u64` surface width, which is
195/// independent of the width a given config stores. The two use sites cannot both fail
196/// gracefully at match/apply time:
197///
198/// * on the **RHS** (`MsetComp`'s output multiplicity), `n` says how many copies of the
199///   body to emit; there is no error channel inside `apply`, and emitting fewer copies
200///   than asked would silently change what the rule means.
201/// * on the **LHS** (`RMult::Exact` and a `RMult::Var` bound), a literal above the
202///   stored width can never equal a stored multiplicity, so the pattern is dead — sound,
203///   but silently so, which is exactly the failure that hides a mis-sized config.
204///
205/// Checking once at install turns both into one diagnosable error, and is what licenses
206/// the `expect` at the RHS narrowing site.
207pub fn check_mult_literals<Cfg: crate::config::EGraphConfig, O, S, V>(
208    rule: &PreparedRule<O, S, V>,
209) -> Result<(), u64> {
210    for atom in &rule.query.atoms {
211        let elems: &[(crate::resolve::PatVar, crate::resolve::RMult)] = match atom {
212            crate::resolve::RAtom::ACExact { elems, .. }
213            | crate::resolve::RAtom::ACSub { elems, .. } => elems,
214            _ => continue,
215        };
216        for (_, m) in elems {
217            match m {
218                crate::resolve::RMult::Exact(n) => check_one::<Cfg>(*n)?,
219                crate::resolve::RMult::Var {
220                    constraint: Some((_, n)),
221                    ..
222                } => check_one::<Cfg>(*n)?,
223                crate::resolve::RMult::Var { .. } => {}
224            }
225        }
226    }
227    for (_, lo, hi) in &rule.query.mult_intervals {
228        check_one::<Cfg>(*lo)?;
229        // An open upper bound is `u64::MAX`, not a literal the rule spelled out; only a
230        // bound the author actually wrote can be too wide for the configuration.
231        if *hi != u64::MAX {
232            check_one::<Cfg>(*hi)?;
233        }
234    }
235    for action in &rule.actions {
236        match action {
237            CompiledAction::Union(_, a, b) => {
238                check_op_mults::<Cfg, _, _>(a)?;
239                check_op_mults::<Cfg, _, _>(b)?;
240            }
241            CompiledAction::Insert(t) => check_op_mults::<Cfg, _, _>(t)?,
242            CompiledAction::Set { args, value, .. } => {
243                for a in args {
244                    check_op_mults::<Cfg, _, _>(a)?;
245                }
246                check_op_mults::<Cfg, _, _>(value)?;
247            }
248            CompiledAction::Subsume(_) => {}
249        }
250    }
251    Ok(())
252}
253
254#[inline]
255fn check_one<Cfg: crate::config::EGraphConfig>(n: u64) -> Result<(), u64> {
256    match <Cfg::M as MultiplicityLike>::try_from_u64(n) {
257        Some(_) => Ok(()),
258        None => Err(n),
259    }
260}
261
262fn check_op_mults<Cfg: crate::config::EGraphConfig, O, V>(op: &RhsOp<O, V>) -> Result<(), u64> {
263    let args = match op {
264        RhsOp::App { args, .. } => args,
265        _ => return Ok(()),
266    };
267    for arg in args {
268        match arg {
269            RhsArg::One(inner) => check_op_mults::<Cfg, _, _>(inner)?,
270            RhsArg::OneMult { body, mult } => {
271                // A literal count above the stored width can never be
272                // represented; multiplicity 0 is legal here (omission).
273                if let crate::resolve::ResolvedMultExpr::Lit(n) = mult
274                    && *n > 0
275                {
276                    check_one::<Cfg>(*n)?;
277                }
278                check_op_mults::<Cfg, _, _>(body)?;
279            }
280            RhsArg::MsetComp {
281                body, mult, filter, ..
282            } => {
283                if let crate::resolve::ResolvedMultExpr::Lit(n) = mult {
284                    check_one::<Cfg>(*n)?;
285                }
286                check_op_mults::<Cfg, _, _>(body)?;
287                if let Some(f) = filter {
288                    check_op_mults::<Cfg, _, _>(f)?;
289                }
290            }
291            RhsArg::SetComp { body, filter, .. } | RhsArg::SeqComp { body, filter, .. } => {
292                check_op_mults::<Cfg, _, _>(body)?;
293                if let Some(f) = filter {
294                    check_op_mults::<Cfg, _, _>(f)?;
295                }
296            }
297            RhsArg::SpliceSeq(_) | RhsArg::SpliceSet(_) | RhsArg::SpliceMset(_) => {}
298        }
299    }
300    Ok(())
301}
302
303pub fn compile_action<O: Clone, S, V: Clone>(
304    action: &crate::resolve::ResolvedAction<O, S, V>,
305    rule_id: crate::id::RuleId,
306) -> CompiledAction<O, V> {
307    use crate::resolve::ResolvedAction;
308    match action {
309        ResolvedAction::Union(a, b) => {
310            CompiledAction::Union(rule_id, compile_rhs(a), compile_rhs(b))
311        }
312        ResolvedAction::Insert(t) => CompiledAction::Insert(compile_rhs(t)),
313        ResolvedAction::Set { func, args, value } => CompiledAction::Set {
314            func: func.clone(),
315            args: args.iter().map(|a| compile_rhs(a)).collect(),
316            value: compile_rhs(value),
317        },
318    }
319}
320
321/// Compile a `(rewrite LHS RHS :when [guards...])` into a `PreparedRule`.
322pub fn compile_rewrite<O, S, L, M, const TRACK: bool>(
323    name: &str,
324    lhs_src: &str,
325    rhs_src: &str,
326    lhs: &crate::surface_ast::SurfacePattern,
327    rhs: &crate::ast::RhsTerm,
328    when: &[crate::surface_ast::SurfacePattern],
329    subsume: bool,
330    ops: &crate::registry::OpRegistry<O, S, TRACK>,
331    sorts: &crate::registry::SortRegistry<S, TRACK>,
332    rules: &mut crate::registry::RuleRegistry<TRACK>,
333    model: &M,
334    globals: &crate::resolve::GlobalCtx<S, impl Copy>,
335) -> Result<PreparedRule<O, S, L>, crate::resolve::ResolveError>
336where
337    O: crate::DenseId + std::hash::Hash + Copy,
338    S: crate::DenseId + Copy,
339    L: crate::literal::LitVal,
340    M: crate::lit_model::LitModel<Value = L>,
341{
342    let rule_id = rules.register(name, lhs_src, rhs_src);
343    let mut body = vec![lhs.clone()];
344    body.extend_from_slice(when);
345    let fq = crate::sortcheck::flatten_surface(&body, ops).map_err(|e| {
346        crate::resolve::ResolveError {
347            msg: e,
348            span: crate::ast::Span::Dummy,
349            extra_spans: Vec::new(),
350        }
351    })?;
352    let root_name = &fq.root_vars[0];
353    let rq = crate::resolve::resolve(&fq, ops, sorts, model, globals)?;
354
355    let root_vid = rq
356        .shape
357        .find_var(root_name)
358        .expect("root var must be in shape");
359    let mut vs = rq.var_sorts.clone();
360    let mut shape = rq.shape.clone();
361    let root_sort = vs[root_vid.idx()];
362    let resolved_rhs = crate::resolve::resolve_rhs(
363        rhs, root_sort, ops, sorts, model, &mut vs, &mut shape, globals,
364    )?;
365    let compiled_rhs = compile_rhs(&resolved_rhs);
366
367    let mut actions = vec![CompiledAction::Union(
368        rule_id,
369        RhsOp::FetchNode(root_vid),
370        compiled_rhs,
371    )];
372    if subsume {
373        actions.push(CompiledAction::Subsume(root_vid));
374    }
375
376    Ok(PreparedRule {
377        rule_id,
378        query: rq,
379        actions,
380        ruleset: None,
381    })
382}
383
384/// Compile a `(rule (body...) (head...))` into a `PreparedRule`.
385pub fn compile_rule<O, S, L, M, const TRACK: bool>(
386    name: &str,
387    body: &[crate::surface_ast::SurfacePattern],
388    head: &[crate::ast::Action],
389    ops: &crate::registry::OpRegistry<O, S, TRACK>,
390    sorts: &crate::registry::SortRegistry<S, TRACK>,
391    rules: &mut crate::registry::RuleRegistry<TRACK>,
392    model: &M,
393    globals: &crate::resolve::GlobalCtx<S, impl Copy>,
394) -> Result<PreparedRule<O, S, L>, crate::resolve::ResolveError>
395where
396    O: crate::DenseId + std::hash::Hash + Copy,
397    S: crate::DenseId + Copy,
398    L: crate::literal::LitVal,
399    M: crate::lit_model::LitModel<Value = L>,
400{
401    let rule_id = rules.register(name, "", "");
402    let fq =
403        crate::sortcheck::flatten_surface(body, ops).map_err(|e| crate::resolve::ResolveError {
404            msg: e,
405            span: crate::ast::Span::Dummy,
406            extra_spans: Vec::new(),
407        })?;
408    let rq = crate::resolve::resolve(&fq, ops, sorts, model, globals)?;
409
410    let mut vs = rq.var_sorts.clone();
411    let mut shape = rq.shape.clone();
412    let mut actions = Vec::with_capacity(head.len());
413    for a in head {
414        let ra =
415            crate::resolve::resolve_action(a, ops, sorts, model, &mut vs, &mut shape, globals)?;
416        actions.push(compile_action(&ra, rule_id));
417    }
418
419    Ok(PreparedRule {
420        rule_id,
421        query: rq,
422        actions,
423        ruleset: None,
424    })
425}
426
427// ---------------------------------------------------------------------------
428// Eval: execute compiled RHS against a Match and e-graph
429// ---------------------------------------------------------------------------
430
431use crate::EGraphConfig;
432use crate::canon::{MSetCanon, VarCanon};
433use crate::egraph::EGraph;
434use crate::ematch::{MatchPool, run_query_scheduled_into};
435use crate::index::IndexStore;
436use crate::literal::LitVal;
437use crate::multiplicity::MultiplicityLike;
438use smallvec::SmallVec;
439
440/// Inline capacity for a node's child list during RHS instantiation.
441///
442/// 16 rather than the 4 of `leapfrog::CursorVec`, because the two lists have
443/// different length distributions. A cursor vector holds one entry per query
444/// atom; a child list holds one per *child*, and a variadic RHS that splices a
445/// rest variable (`(add (mul y x) ..r)`) produces as many children as the
446/// matched node had. The capacity 16 is a historical AC-workload tuning choice;
447/// it is not a portable knee. Beyond the inline capacity the list spills to the
448/// heap and stays correct. Retuning requires the Criterion rule-application
449/// workload and its allocation counters.
450type ChildVec<Cfg> = SmallVec<[<Cfg as EGraphConfig>::G; 16]>;
451
452/// Inline capacity for a primitive application's argument list. Primitives here
453/// are arithmetic and comparison, so two covers all of them.
454const PRIM_ARGS: usize = 2;
455
456/// A bound AC multiplicity read as an i64 literal value. Resolution only admits
457/// multiplicity variables in i64 positions, so the model must carry an i64
458/// sort; a count above `i64::MAX` cannot arise from a real node's children.
459fn mult_as_lit<L: LitVal, M: crate::lit_model::LitModel<Value = L>>(model: &M, k: u64) -> L {
460    let desc = model
461        .sorts()
462        .iter()
463        .find(|s| s.name == "i64")
464        .expect("multiplicity in RHS: model has no i64 sort");
465    (desc.parse)(&k.to_string()).expect("multiplicity in RHS does not fit i64")
466}
467
468pub fn eval<Cfg, L, M, V, S: Copy, const T: bool, const P: bool>(
469    op: &RhsOp<Cfg::O, L>,
470    m: &mut V,
471    eg: &mut EGraph<Cfg, L, T, P>,
472    model: &M,
473    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
474) -> Cfg::G
475where
476    Cfg: EGraphConfig,
477    L: LitVal,
478    M: crate::lit_model::LitModel<Value = L>,
479    V: crate::ematch::MatchView<Cfg>,
480    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
481{
482    match op {
483        RhsOp::FetchNode(vid) => eg.find(m.get(*vid)),
484        RhsOp::FetchGlobal(gid) => eg.find(globals.binding(*gid)),
485        RhsOp::Lit(op, val) => {
486            let id = eg.lits_mut().intern(val.clone());
487            eg.add_lit(*op, id)
488        }
489        RhsOp::LitVar(op, lvid) => {
490            let val_id = m.get_lit_val(*lvid);
491            eg.add_lit(*op, val_id)
492        }
493        RhsOp::MultVar(op, mid) => {
494            let val = mult_as_lit(model, m.get_mult(*mid).to_u64());
495            let id = eg.lits_mut().intern(val);
496            eg.add_lit(*op, id)
497        }
498        RhsOp::App { op: o, args } => {
499            let mut children = ChildVec::<Cfg>::new();
500            for arg in args {
501                eval_arg(arg, m, eg, model, globals, &mut children);
502            }
503            eg.add(*o, &children)
504        }
505        RhsOp::PrimApp { op, args } => {
506            // Gather bound lit values (or multiplicities as i64) from the match
507            let raw_vals: SmallVec<[L; PRIM_ARGS]> = args
508                .iter()
509                .map(|arg| match arg {
510                    crate::resolve::RPrimArg::LitVal(vid) => {
511                        let lit_val_id = m.get_lit_val(*vid);
512                        eg.lits().get(lit_val_id).clone()
513                    }
514                    crate::resolve::RPrimArg::Mult(mid) => {
515                        mult_as_lit(model, m.get_mult(*mid).to_u64())
516                    }
517                })
518                .collect();
519            let refs: SmallVec<[&L; PRIM_ARGS]> = raw_vals.iter().collect();
520            let prim = &model.ops()[op.to_usize()];
521            let result = (prim.eval)(&refs);
522            let result_id = eg.lits_mut().intern(result);
523            // Find the @-prefixed lit op for the return sort
524            let lit_op = eg
525                .ops()
526                .lit_op_for_sort(eg.ops().info(*op).return_sort)
527                .expect("no lit op for prim op return sort");
528            eg.add_lit(lit_op, result_id)
529        }
530    }
531}
532
533fn eval_arg<Cfg, L, M, V, S: Copy, const T: bool, const P: bool>(
534    arg: &RhsArg<Cfg::O, L>,
535    m: &mut V,
536    eg: &mut EGraph<Cfg, L, T, P>,
537    model: &M,
538    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
539    out: &mut ChildVec<Cfg>,
540) where
541    Cfg: EGraphConfig,
542    L: LitVal,
543    M: crate::lit_model::LitModel<Value = L>,
544    V: crate::ematch::MatchView<Cfg>,
545    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
546{
547    match arg {
548        // A bound node used directly as a child needs no canonicalization here:
549        // `out` is `EGraph::add`'s child slice and `add` canonicalizes every
550        // child itself — which is also why the splice arms below hand it raw
551        // match bindings. Going through `eval` would `find` each child twice.
552        RhsArg::One(RhsOp::FetchNode(vid)) => out.push(m.get(*vid)),
553        RhsArg::One(RhsOp::FetchGlobal(gid)) => out.push(globals.binding(*gid)),
554        RhsArg::One(inner) => out.push(eval(inner, m, eg, model, globals)),
555        RhsArg::OneMult { body, mult } => {
556            // Multiplicity 0 omits the child without evaluating it, so an
557            // omitted term is never materialized (the k-1 = 0 case of a
558            // multiplicity variant). Underflow and division by zero were rejected
559            // at install by the interval check; the checked ops here are the
560            // second line, like the checked literal primitives.
561            let k = eval_mult_expr::<Cfg, V>(mult, m);
562            if k > 0 {
563                let id = eval(body, m, eg, model, globals);
564                for _ in 0..k {
565                    out.push(id);
566                }
567            }
568        }
569        RhsArg::SpliceSeq(sid) => out.extend_from_slice(m.seq_slice(*sid)),
570        RhsArg::SpliceSet(sid) => out.extend_from_slice(m.set_slice(*sid)),
571        RhsArg::SpliceMset(mid) => {
572            for c in m.mset_slice(*mid) {
573                let id = Cfg::mset_child_id(c);
574                let mult = Cfg::mset_child_mult(c);
575                // A repetition count, not a stored multiplicity: widening to
576                // `usize` is lossless for every supported width.
577                for _ in 0..mult.to_usize() {
578                    out.push(id);
579                }
580            }
581        }
582        RhsArg::SeqComp {
583            body,
584            var,
585            source,
586            filter,
587        } => {
588            let slice = m.seq_slice(*source).to_vec();
589            for elem in slice {
590                m.set(*var, elem);
591                if let Some(f) = filter {
592                    let g = eval(f, m, eg, model, globals);
593                    if !check_filter_truthy(eg, model, g) {
594                        continue;
595                    }
596                }
597                out.push(eval(body, m, eg, model, globals));
598            }
599            m.clear(*var);
600        }
601        RhsArg::SetComp {
602            body,
603            var,
604            source,
605            filter,
606        } => {
607            let slice = m.set_slice(*source).to_vec();
608            for elem in slice {
609                m.set(*var, elem);
610                if let Some(f) = filter {
611                    let g = eval(f, m, eg, model, globals);
612                    if !check_filter_truthy(eg, model, g) {
613                        continue;
614                    }
615                }
616                out.push(eval(body, m, eg, model, globals));
617            }
618            m.clear(*var);
619        }
620        RhsArg::MsetComp {
621            body,
622            mult: out_mult,
623            var,
624            mult_var,
625            source,
626            filter,
627        } => {
628            let slice = m.mset_slice(*source).to_vec();
629            for c in &slice {
630                let id = Cfg::mset_child_id(c);
631                let src_mult = Cfg::mset_child_mult(c);
632                m.set(*var, id);
633                m.set_mult(*mult_var, src_mult);
634                if let Some(f) = filter {
635                    let g = eval(f, m, eg, model, globals);
636                    if !check_filter_truthy(eg, model, g) {
637                        continue;
638                    }
639                }
640                let result = eval(body, m, eg, model, globals);
641                // The surface literal is narrowed to the configured width here
642                // rather than being truncated. Emitting `n` duplicate children
643                // that canonicalisation folds back into a multiplicity of `n`
644                // only makes sense if `n` is representable, so an unrepresentable
645                // literal is a rule error, not a silently smaller multiplicity.
646                // `check_mult_literals` rejects such rules at install time, which
647                // is why this is an `expect` rather than a propagated error.
648                let n = eval_mult_expr::<Cfg, V>(out_mult, m);
649                let n: Cfg::M =
650                    Cfg::M::try_from_u64(n).expect("RHS multiplicity exceeds the configured width");
651                for _ in 0..n.to_usize() {
652                    out.push(result);
653                }
654            }
655            m.clear(*var);
656        }
657    }
658}
659
660/// Evaluate an RHS multiplicity expression over the match's bound
661/// multiplicities, in checked u64 arithmetic. Underflow and division by zero
662/// are rejected statically at rule install ([`check_rhs_mult_exprs`]); the
663/// checked ops here are the second line, and panic like the checked literal
664/// primitives do.
665fn eval_mult_expr<Cfg, V>(e: &crate::resolve::ResolvedMultExpr, m: &V) -> u64
666where
667    Cfg: EGraphConfig,
668    V: crate::ematch::MatchView<Cfg>,
669{
670    use crate::resolve::{MultPrimOp as P, ResolvedMultExpr as E};
671    match e {
672        E::Lit(n) => *n,
673        E::Var(v) => m.get_mult(*v).to_u64(),
674        E::Prim { op, args } => {
675            let a = eval_mult_expr::<Cfg, V>(&args[0], m);
676            let b = eval_mult_expr::<Cfg, V>(&args[1], m);
677            match op {
678                P::Add => a
679                    .checked_add(b)
680                    .expect("u64::+ overflow in RHS multiplicity"),
681                P::Sub => a
682                    .checked_sub(b)
683                    .expect("u64::- underflow in RHS multiplicity"),
684                P::Mul => a
685                    .checked_mul(b)
686                    .expect("u64::* overflow in RHS multiplicity"),
687                P::Div => a
688                    .checked_div(b)
689                    .expect("u64::/ by zero in RHS multiplicity"),
690                P::Rem => a
691                    .checked_rem(b)
692                    .expect("u64::% by zero in RHS multiplicity"),
693                P::Min => a.min(b),
694                P::Max => a.max(b),
695            }
696        }
697    }
698}
699
700/// Interval bounds of an RHS multiplicity expression, from the rule's LHS
701/// multiplicity constraints (`ResolvedQuery::mult_intervals`; an unannotated
702/// `x:k` is `[1, u64::MAX]`). Errors on the two expressions that could be
703/// *wrong* at runtime rather than merely large: a subtraction that cannot be
704/// proved non-negative, and a division or remainder whose divisor could be
705/// zero. Additions and products saturate in the bound computation; a runtime
706/// overflow still traps in [`eval_mult_expr`].
707fn mult_expr_bounds(
708    e: &crate::resolve::ResolvedMultExpr,
709    intervals: &[(crate::ast::MultVarId, u64, u64)],
710) -> Result<(u64, u64), String> {
711    use crate::resolve::{MultPrimOp as P, ResolvedMultExpr as E};
712    Ok(match e {
713        E::Lit(n) => (*n, *n),
714        E::Var(v) => intervals
715            .iter()
716            .find(|(id, _, _)| id == v)
717            .map(|(_, lo, hi)| (*lo, *hi))
718            .unwrap_or((1, u64::MAX)),
719        E::Prim { op, args } => {
720            let (lo_a, hi_a) = mult_expr_bounds(&args[0], intervals)?;
721            let (lo_b, hi_b) = mult_expr_bounds(&args[1], intervals)?;
722            match op {
723                P::Add => (lo_a.saturating_add(lo_b), hi_a.saturating_add(hi_b)),
724                P::Sub => {
725                    if lo_a < hi_b {
726                        return Err(format!(
727                            "u64::- can underflow: the left side is at least {lo_a} but \
728                             the right side can reach {hi_b}; constrain the multiplicity \
729                             on the LHS (e.g. `x:k>=2`) so the subtraction cannot go \
730                             negative"
731                        ));
732                    }
733                    (lo_a - hi_b, hi_a.saturating_sub(lo_b))
734                }
735                P::Mul => (lo_a.saturating_mul(lo_b), hi_a.saturating_mul(hi_b)),
736                P::Div | P::Rem => {
737                    if lo_b == 0 {
738                        return Err(format!(
739                            "{} divisor can be zero; constrain it on the LHS",
740                            op.name()
741                        ));
742                    }
743                    match op {
744                        P::Div => (lo_a / hi_b.max(1), hi_a / lo_b),
745                        _ => (0, hi_b - 1),
746                    }
747                }
748                P::Min => (lo_a.min(lo_b), hi_a.min(hi_b)),
749                P::Max => (lo_a.max(lo_b), hi_a.max(hi_b)),
750            }
751        }
752    })
753}
754
755/// Static safety check for every RHS multiplicity expression in a rule's
756/// actions, against the rule's LHS multiplicity intervals. Rejection here is
757/// what licenses the `expect`s in `eval_mult_expr` for underflow and
758/// division by zero; overflow stays a runtime trap because any expression
759/// over an unbounded `k` could overflow and rejecting them all would ban
760/// `k+1`.
761pub fn check_rhs_mult_exprs<O, S, V>(rule: &PreparedRule<O, S, V>) -> Result<(), String> {
762    fn walk_op<O, V>(
763        op: &RhsOp<O, V>,
764        intervals: &[(crate::ast::MultVarId, u64, u64)],
765    ) -> Result<(), String> {
766        let RhsOp::App { args, .. } = op else {
767            return Ok(());
768        };
769        for arg in args {
770            match arg {
771                RhsArg::One(inner) => walk_op(inner, intervals)?,
772                RhsArg::OneMult { body, mult } => {
773                    mult_expr_bounds(mult, intervals)?;
774                    walk_op(body, intervals)?;
775                }
776                RhsArg::MsetComp {
777                    body, mult, filter, ..
778                } => {
779                    mult_expr_bounds(mult, intervals)?;
780                    walk_op(body, intervals)?;
781                    if let Some(f) = filter {
782                        walk_op(f, intervals)?;
783                    }
784                }
785                RhsArg::SetComp { body, filter, .. } | RhsArg::SeqComp { body, filter, .. } => {
786                    walk_op(body, intervals)?;
787                    if let Some(f) = filter {
788                        walk_op(f, intervals)?;
789                    }
790                }
791                RhsArg::SpliceSeq(_) | RhsArg::SpliceSet(_) | RhsArg::SpliceMset(_) => {}
792            }
793        }
794        Ok(())
795    }
796    let iv = &rule.query.mult_intervals;
797    for action in &rule.actions {
798        match action {
799            CompiledAction::Union(_, a, b) => {
800                walk_op(a, iv)?;
801                walk_op(b, iv)?;
802            }
803            CompiledAction::Insert(t) => walk_op(t, iv)?,
804            CompiledAction::Set { args, value, .. } => {
805                for a in args {
806                    walk_op(a, iv)?;
807                }
808                walk_op(value, iv)?;
809            }
810            CompiledAction::Subsume(_) => {}
811        }
812    }
813    Ok(())
814}
815
816fn check_filter_truthy<Cfg, L, M, const T: bool, const P: bool>(
817    eg: &EGraph<Cfg, L, T, P>,
818    _model: &M,
819    id: Cfg::G,
820) -> bool
821where
822    Cfg: EGraphConfig,
823    L: LitVal,
824    M: crate::lit_model::LitModel<Value = L>,
825    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
826{
827    match eg.get_lit_val(id) {
828        Some(val) => M::is_truthy(val),
829        None => false,
830    }
831}
832
833pub fn apply_action<Cfg, L, M, V, S: Copy, const T: bool, const P: bool>(
834    action: &CompiledAction<Cfg::O, L>,
835    m: &mut V,
836    eg: &mut EGraph<Cfg, L, T, P>,
837    model: &M,
838    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
839) -> usize
840where
841    Cfg: EGraphConfig,
842    L: LitVal,
843    M: crate::lit_model::LitModel<Value = L>,
844    V: crate::ematch::MatchView<Cfg>,
845    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
846{
847    match action {
848        CompiledAction::Union(rule_id, a, b) => {
849            let va = eval(a, m, eg, model, globals);
850            let vb = eval(b, m, eg, model, globals);
851            if eg.find(va) != eg.find(vb) {
852                if P {
853                    eg.merge_justified(
854                        va,
855                        vb,
856                        crate::union_find::Justification::Rewrite { rule_id: *rule_id },
857                    );
858                } else {
859                    eg.merge(va, vb);
860                }
861                1
862            } else {
863                0
864            }
865        }
866        CompiledAction::Insert(t) => {
867            eval(t, m, eg, model, globals);
868            1
869        }
870        CompiledAction::Set {
871            func: _,
872            args: _,
873            value: _,
874        } => {
875            todo!("lattice set not yet implemented")
876        }
877        CompiledAction::Subsume(var) => {
878            let node = m.get(*var);
879            eg.subsume(node);
880            1
881        }
882    }
883}
884
885pub fn apply_rule<Cfg, L, M, S, const T: bool, const P: bool>(
886    rule: &PreparedRule<Cfg::O, S, L>,
887    eg: &mut EGraph<Cfg, L, T, P>,
888    index: &IndexStore<Cfg>,
889    stats: &crate::schedule::IndexStats<Cfg::O>,
890    model: &M,
891    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
892) -> usize
893where
894    Cfg: EGraphConfig,
895    S: crate::DenseId,
896    L: LitVal,
897    M: crate::lit_model::LitModel<Value = L>,
898    crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
899{
900    apply_rule_pooled(
901        rule,
902        eg,
903        index,
904        stats,
905        model,
906        globals,
907        &mut MatchPool::new(),
908    )
909}
910
911/// [`apply_rule`] with a caller-owned match buffer.
912///
913/// The naive driver calls this with one pool for the whole saturation, so the
914/// per-match allocations happen in the first round and are recycled thereafter.
915/// See [`MatchPool`].
916pub fn apply_rule_pooled<Cfg, L, M, S, const T: bool, const P: bool>(
917    rule: &PreparedRule<Cfg::O, S, L>,
918    eg: &mut EGraph<Cfg, L, T, P>,
919    index: &IndexStore<Cfg>,
920    stats: &crate::schedule::IndexStats<Cfg::O>,
921    model: &M,
922    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
923    pool: &mut MatchPool<Cfg>,
924) -> usize
925where
926    Cfg: EGraphConfig,
927    S: crate::DenseId,
928    L: LitVal,
929    M: crate::lit_model::LitModel<Value = L>,
930    crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
931{
932    let vindex = crate::index::VariantIndex::naive(index);
933    let sampler = crate::index::IndexSampler::new(eg, vindex);
934    let plan = crate::schedule::schedule_with_stats_sampled(&rule.query, stats, &sampler);
935    run_query_scheduled_into(&rule.query, &plan, eg, &vindex, globals, pool);
936    let mut changes = 0;
937    for j in 0..pool.len() {
938        let mut row = pool.row_mut(j);
939        for action in &rule.actions {
940            changes += apply_action(action, &mut row, eg, model, globals);
941        }
942    }
943    changes
944}
945
946#[cfg(test)]
947mod tests {
948    use super::*;
949
950    use crate::id::{OpId, SortId};
951    use crate::lit_model::LitModel;
952    use crate::literal::{LitValStore, NiraLitVal, NiraModel};
953    use crate::nodes::LitValId;
954    use crate::registry::{AssocDir, OpRegistry, SortRegistry};
955    use crate::resolve::{resolve, resolve_rhs};
956    use crate::sortcheck::flatten_surface as flatten;
957    use crate::test_helpers::{parse_pattern, parse_rhs};
958
959    fn setup() -> (
960        OpRegistry<OpId, SortId, false>,
961        SortRegistry<SortId, false>,
962        LitValStore<NiraLitVal, LitValId, false>,
963    ) {
964        let model = NiraModel;
965        let mut sorts: SortRegistry<SortId, false> = SortRegistry::new();
966        let sort_names: Vec<&str> = model.sorts().iter().map(|s| s.name).collect();
967        sorts.register_builtins(&sort_names);
968        let e = sorts.intern("IExpr");
969        let ibig = sorts.id_by_name("IBig").unwrap();
970        let mut ops = OpRegistry::new();
971        ops.register_builtins(&model, &sorts);
972        ops.register("f", &[e, e], e);
973        ops.register("g", &[e], e);
974        ops.register("a", &[], e);
975        ops.register("b", &[], e);
976        ops.register("c", &[], e);
977        ops.register_a("concat", e, e, AssocDir::Right);
978        ops.register_mset("add", e, e);
979        ops.register_set("union", e, e);
980        ops.register("ILit", &[ibig], e);
981        (
982            ops,
983            sorts,
984            LitValStore::<NiraLitVal, LitValId, false>::new(),
985        )
986    }
987
988    fn lhs_root_sort(
989        rq: &crate::resolve::ResolvedQuery<OpId, SortId, NiraLitVal>,
990        fq: &crate::compile::FlatQuery,
991    ) -> Option<SortId> {
992        let root_vid = rq.shape.find_var(&fq.root_vars[0]).unwrap();
993        rq.var_sorts[root_vid.idx()]
994    }
995
996    fn do_compile(lhs: &str, rhs_src: &str) -> RhsOp<OpId, NiraLitVal> {
997        let (ops, sorts, _) = setup();
998        let model = NiraModel;
999        let pat = parse_pattern(lhs);
1000        let fq = flatten(&[pat], &ops).unwrap();
1001        let rq = resolve(
1002            &fq,
1003            &ops,
1004            &sorts,
1005            &model,
1006            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1007        )
1008        .unwrap();
1009        let root_sort = lhs_root_sort(&rq, &fq);
1010        let ri = rhs_src;
1011        let rhs_ast = parse_rhs(ri);
1012        let mut vs = rq.var_sorts.clone();
1013        let mut shape = rq.shape.clone();
1014        let rhs = resolve_rhs(
1015            &rhs_ast,
1016            root_sort,
1017            &ops,
1018            &sorts,
1019            &model,
1020            &mut vs,
1021            &mut shape,
1022            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1023        )
1024        .unwrap();
1025        compile_rhs(&rhs)
1026    }
1027
1028    #[test]
1029    fn compile_var_is_varid() {
1030        let (ops, sorts, _) = setup();
1031        let model = NiraModel;
1032        let pat = parse_pattern("(f x y)");
1033        let fq = flatten(&[pat], &ops).unwrap();
1034        let rq = resolve(
1035            &fq,
1036            &ops,
1037            &sorts,
1038            &model,
1039            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1040        )
1041        .unwrap();
1042        let root_sort = lhs_root_sort(&rq, &fq);
1043        let ri = "x";
1044        let rhs_ast = parse_rhs(ri);
1045        let mut vs = rq.var_sorts.clone();
1046        let mut shape = rq.shape.clone();
1047        let rhs = resolve_rhs(
1048            &rhs_ast,
1049            root_sort,
1050            &ops,
1051            &sorts,
1052            &model,
1053            &mut vs,
1054            &mut shape,
1055            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1056        )
1057        .unwrap();
1058        let c = compile_rhs(&rhs);
1059        // The compiled term should reference the same VarId the parser assigned to "x"
1060        let x_vid = shape.find_var("x").unwrap();
1061        assert!(matches!(c, RhsOp::FetchNode(v) if v == x_vid));
1062    }
1063
1064    #[test]
1065    fn compile_lit() {
1066        // (ILit 42) in IExpr context
1067        let c = do_compile("(f x y)", "(ILit 42)");
1068        assert!(matches!(c, RhsOp::App { .. }));
1069    }
1070
1071    #[test]
1072    fn compile_app_preserves_varids() {
1073        let (ops, sorts, _) = setup();
1074        let model = NiraModel;
1075        let pat = parse_pattern("(f x y)");
1076        let fq = flatten(&[pat], &ops).unwrap();
1077        let rq = resolve(
1078            &fq,
1079            &ops,
1080            &sorts,
1081            &model,
1082            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1083        )
1084        .unwrap();
1085        let root_sort = lhs_root_sort(&rq, &fq);
1086        let ri = "(f y x)";
1087        let rhs_ast = parse_rhs(ri);
1088        let mut vs = rq.var_sorts.clone();
1089        let mut shape = rq.shape.clone();
1090        let rhs = resolve_rhs(
1091            &rhs_ast,
1092            root_sort,
1093            &ops,
1094            &sorts,
1095            &model,
1096            &mut vs,
1097            &mut shape,
1098            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1099        )
1100        .unwrap();
1101        let c = compile_rhs(&rhs);
1102
1103        let x_vid = shape.find_var("x").unwrap();
1104        let y_vid = shape.find_var("y").unwrap();
1105        match c {
1106            RhsOp::App { args: children, .. } => {
1107                // (f y x) — first child is y, second is x
1108                assert!(matches!(&children[0], RhsArg::One(RhsOp::FetchNode(v)) if *v == y_vid));
1109                assert!(matches!(&children[1], RhsArg::One(RhsOp::FetchNode(v)) if *v == x_vid));
1110            }
1111            _ => panic!("expected App"),
1112        }
1113    }
1114
1115    #[test]
1116    fn compile_splice_seq_typed() {
1117        let c = do_compile("(concat ..pre x ..suf)", "(concat ..pre x ..suf)");
1118        match c {
1119            RhsOp::App { args: children, .. } => {
1120                assert!(matches!(&children[0], RhsArg::SpliceSeq(SeqVarId(0))));
1121                assert!(matches!(&children[1], RhsArg::One(RhsOp::FetchNode(_))));
1122                assert!(matches!(&children[2], RhsArg::SpliceSeq(SeqVarId(1))));
1123            }
1124            _ => panic!("expected App"),
1125        }
1126    }
1127
1128    #[test]
1129    fn compile_splice_mset_typed() {
1130        let c = do_compile("(add x:1 ..rest)", "(add x ..rest)");
1131        match c {
1132            RhsOp::App { args: children, .. } => {
1133                assert!(matches!(&children[0], RhsArg::One(RhsOp::FetchNode(_))));
1134                assert!(matches!(&children[1], RhsArg::SpliceMset(MsetVarId(0))));
1135            }
1136            _ => panic!("expected App"),
1137        }
1138    }
1139
1140    #[test]
1141    fn compile_splice_set_typed() {
1142        let c = do_compile("(union x ..rest)", "(union x ..rest)");
1143        match c {
1144            RhsOp::App { args: children, .. } => {
1145                assert!(matches!(&children[0], RhsArg::One(RhsOp::FetchNode(_))));
1146                assert!(matches!(&children[1], RhsArg::SpliceSet(SetVarId(0))));
1147            }
1148            _ => panic!("expected App"),
1149        }
1150    }
1151
1152    #[test]
1153    fn compile_nested_app() {
1154        let c = do_compile("(f x y)", "(f (g x) y)");
1155        match c {
1156            RhsOp::App { args: children, .. } => {
1157                assert_eq!(children.len(), 2);
1158                assert!(matches!(&children[0], RhsArg::One(RhsOp::App { .. })));
1159                assert!(matches!(&children[1], RhsArg::One(RhsOp::FetchNode(_))));
1160            }
1161            _ => panic!("expected App"),
1162        }
1163    }
1164
1165    #[test]
1166    fn debug_render_full_pipeline() {
1167        let model = NiraModel;
1168        let mut sorts: SortRegistry<SortId, false> = SortRegistry::new();
1169        let sort_names: Vec<&str> = model.sorts().iter().map(|s| s.name).collect();
1170        sorts.register_builtins(&sort_names);
1171        let e = sorts.intern("IExpr");
1172        let mut ops = OpRegistry::new();
1173        ops.register_builtins(&model, &sorts);
1174        let ibig = sorts.id_by_name("IBig").unwrap();
1175        ops.register("f", &[e, e], e);
1176        ops.register("g", &[e], e);
1177        ops.register("h", &[e, e, e], e);
1178        ops.register("inv", &[e], e);
1179        ops.register("a", &[], e);
1180        ops.register("b", &[], e);
1181        ops.register_a("concat", e, e, AssocDir::Right);
1182        ops.register_mset("add", e, e);
1183        ops.register_mset("mul", e, e);
1184        ops.register_set("union", e, e);
1185        ops.register("ILit", &[ibig], e);
1186        let model = NiraModel;
1187
1188        let cases: &[(&str, &str, &str)] = &[
1189            // 1. Plain rewrite: commutativity
1190            ("commute f", "(f x y)", "(f y x)"),
1191            // 2. Nested plain: distribute g into f
1192            ("nested", "(f x (g y))", "(g (f y x))"),
1193            // 3. AC subset + splice: factor out of add
1194            ("AC factor", "(add x:1 y:1 ..rest)", "(add (f x y) ..rest)"),
1195            // 4. ACI subset + splice: de Morgan style (union → add)
1196            (
1197                "ACI de Morgan",
1198                "(inv (union x ..rest))",
1199                "(add (inv x) ..rest)",
1200            ),
1201            // 5. A sliding window + splice: swap adjacent in sequence
1202            (
1203                "A swap adjacent",
1204                "(concat ..pre x y ..suf)",
1205                "(concat ..pre y x ..suf)",
1206            ),
1207            // 6. A prefix + splice
1208            ("A rotate last", "(concat ..pre x)", "(concat x ..pre)"),
1209            // 7. AC exact: normalize binary add
1210            ("AC exact", "(add x:1 y:1)", "(f x y)"),
1211            // 8. ACI two vars + splice
1212            (
1213                "ACI two + rest",
1214                "(union x y ..rest)",
1215                "(union (f x y) ..rest)",
1216            ),
1217            // 9. Literal in RHS
1218            ("literal rhs", "(f x y)", "(ILit 42)"),
1219            // 10. Nullary in RHS
1220            ("nullary rhs", "(f x y)", "(a)"),
1221        ];
1222
1223        for &(label, lhs_src, rhs_src) in cases {
1224            println!("\n{}", "=".repeat(60));
1225            println!("  Rule: {label}");
1226            println!("  LHS:  {lhs_src}");
1227            println!("  RHS:  {rhs_src}");
1228
1229            let pat = parse_pattern(lhs_src);
1230            let fq = flatten(&[pat], &ops).unwrap();
1231
1232            println!("\n  -- Flatten ({} atoms) --", fq.atoms.len(),);
1233            for (i, a) in fq.atoms.iter().enumerate() {
1234                println!("     atom[{i}]: {a:?}");
1235            }
1236
1237            let rq = resolve(
1238                &fq,
1239                &ops,
1240                &sorts,
1241                &model,
1242                &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1243            )
1244            .unwrap();
1245
1246            println!("\n  -- Resolve LHS --");
1247            for (name, id) in rq.shape.vars() {
1248                println!("     {id:?} \"{name}\"");
1249            }
1250            for (i, a) in rq.atoms.iter().enumerate() {
1251                println!("     ratom[{i}]: {a:?}");
1252            }
1253
1254            println!("\n  -- MatchShape --");
1255            if !rq.shape.nodes.is_empty() {
1256                println!("     nodes: {:?}", rq.shape.nodes);
1257            }
1258            if !rq.shape.mults.is_empty() {
1259                println!("     mults: {:?}", rq.shape.mults);
1260            }
1261            if !rq.shape.seqs.is_empty() {
1262                println!("     seqs:  {:?}", rq.shape.seqs);
1263            }
1264            if !rq.shape.sets.is_empty() {
1265                println!("     sets:  {:?}", rq.shape.sets);
1266            }
1267            if !rq.shape.msets.is_empty() {
1268                println!("     msets: {:?}", rq.shape.msets);
1269            }
1270
1271            let root_sort = lhs_root_sort(&rq, &fq);
1272            let ri = rhs_src;
1273            let rhs_ast = parse_rhs(ri);
1274            let mut vs = rq.var_sorts.clone();
1275            let mut shape = rq.shape.clone();
1276            let rhs = resolve_rhs(
1277                &rhs_ast,
1278                root_sort,
1279                &ops,
1280                &sorts,
1281                &model,
1282                &mut vs,
1283                &mut shape,
1284                &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1285            )
1286            .unwrap();
1287
1288            println!("\n  -- Resolved RHS --");
1289            print_rhs("     ", &rhs);
1290
1291            let crhs = compile_rhs(&rhs);
1292            println!("\n  -- Compiled RHS --");
1293            print_compiled("     ", &crhs);
1294        }
1295    }
1296
1297    fn print_rhs(indent: &str, t: &crate::resolve::RRhsTerm<OpId, SortId, NiraLitVal>) {
1298        use crate::resolve::{RRhsChild as RC, RRhsTerm as R};
1299        match t {
1300            R::Var(v) => println!("{indent}Var(VarId({}))", v.idx()),
1301            R::Lit { sort, value, .. } => println!("{indent}Lit(sort={sort:?}, val={value:?})"),
1302            R::App { op, children } => {
1303                println!("{indent}App(op={op:?})");
1304                for (i, c) in children.iter().enumerate() {
1305                    match c {
1306                        RC::Term(t) => {
1307                            println!("{indent}  child[{i}]:");
1308                            print_rhs(&format!("{indent}    "), t);
1309                        }
1310                        RC::TermMult { body, mult } => {
1311                            println!("{indent}  child[{i}] (mult {mult:?}):");
1312                            print_rhs(&format!("{indent}    "), body);
1313                        }
1314                        RC::SpliceSeq(id) => println!("{indent}  child[{i}]: SpliceSeq({:?})", id),
1315                        RC::SpliceSet(id) => println!("{indent}  child[{i}]: SpliceSet({:?})", id),
1316                        RC::SpliceMset(id) => {
1317                            println!("{indent}  child[{i}]: SpliceMset({:?})", id)
1318                        }
1319                        RC::SetComp { var, source, .. } => println!(
1320                            "{indent}  child[{i}]: SetComp(var={}, src={:?})",
1321                            var.idx(),
1322                            source
1323                        ),
1324                        RC::MsetComp { var, source, .. } => println!(
1325                            "{indent}  child[{i}]: MsetComp(var={}, src={:?})",
1326                            var.idx(),
1327                            source
1328                        ),
1329                        RC::SeqComp { var, source, .. } => println!(
1330                            "{indent}  child[{i}]: SeqComp(var={}, src={:?})",
1331                            var.idx(),
1332                            source
1333                        ),
1334                    }
1335                }
1336            }
1337            R::PrimApp { op, args, .. } => {
1338                println!("{indent}PrimApp(op={op:?}, args={args:?})");
1339            }
1340            R::MultVar { op, var } => {
1341                println!("{indent}MultVar(op={op:?}, var={var:?})");
1342            }
1343            R::LitVar { op, val } => {
1344                println!("{indent}LitVar(op={op:?}, val={val:?})");
1345            }
1346            R::FetchGlobal(gid) => {
1347                println!("{indent}FetchGlobal({gid:?})");
1348            }
1349        }
1350    }
1351
1352    fn print_compiled(indent: &str, op: &RhsOp<OpId, NiraLitVal>) {
1353        match op {
1354            RhsOp::FetchNode(v) => println!("{indent}FetchNode(VarId({}))", v.idx()),
1355            RhsOp::Lit(op, id) => println!("{indent}Lit({op:?}, {id:?})"),
1356            RhsOp::App { op: o, args } => {
1357                println!("{indent}App(op={o:?})");
1358                for (i, a) in args.iter().enumerate() {
1359                    match a {
1360                        RhsArg::One(inner) => {
1361                            println!("{indent}  arg[{i}]:");
1362                            print_compiled(&format!("{indent}    "), inner);
1363                        }
1364                        RhsArg::OneMult { body, mult } => {
1365                            println!("{indent}  arg[{i}] (mult {mult:?}):");
1366                            print_compiled(&format!("{indent}    "), body);
1367                        }
1368                        RhsArg::SpliceSeq(s) => {
1369                            println!("{indent}  arg[{i}]: SpliceSeq(SeqVarId({}))", s.idx())
1370                        }
1371                        RhsArg::SpliceSet(s) => {
1372                            println!("{indent}  arg[{i}]: SpliceSet(SetVarId({}))", s.idx())
1373                        }
1374                        RhsArg::SpliceMset(s) => {
1375                            println!("{indent}  arg[{i}]: SpliceMset(MsetVarId({}))", s.idx())
1376                        }
1377                        RhsArg::SetComp { var, source, .. } => println!(
1378                            "{indent}  arg[{i}]: SetComp(var=VarId({}), src=SetVarId({}))",
1379                            var.idx(),
1380                            source.idx()
1381                        ),
1382                        RhsArg::MsetComp { var, source, .. } => println!(
1383                            "{indent}  arg[{i}]: MsetComp(var=VarId({}), src=MsetVarId({}))",
1384                            var.idx(),
1385                            source.idx()
1386                        ),
1387                        RhsArg::SeqComp { var, source, .. } => println!(
1388                            "{indent}  arg[{i}]: SeqComp(var=VarId({}), src=SeqVarId({}))",
1389                            var.idx(),
1390                            source.idx()
1391                        ),
1392                    }
1393                }
1394            }
1395            RhsOp::PrimApp { op, args } => {
1396                println!("{indent}PrimApp(op={op:?}, args={args:?})");
1397            }
1398            RhsOp::LitVar(op, lvid) => {
1399                println!("{indent}LitVar(op={op:?}, val={lvid:?})");
1400            }
1401            RhsOp::MultVar(op, mid) => {
1402                println!("{indent}MultVar(op={op:?}, var={mid:?})");
1403            }
1404            RhsOp::FetchGlobal(gid) => {
1405                println!("{indent}FetchGlobal({gid:?})");
1406            }
1407        }
1408    }
1409
1410    // ===================================================================
1411    // End-to-end: compile_rewrite + apply_rule
1412    // ===================================================================
1413
1414    use crate::egraph::EGraph;
1415    use crate::index::IndexStore;
1416    use crate::nodes::DefaultConfig;
1417
1418    type EG = EGraph<DefaultConfig, NiraLitVal, false, false>;
1419
1420    fn make_eg() -> EG {
1421        let mut eg = EG::from_model(&NiraModel);
1422        let e = eg.intern_sort("IExpr");
1423        eg.register_op2("f", e, e, e);
1424        eg.register_op1("g", e, e);
1425        eg.register_op2("h", e, e, e);
1426        eg.register_op0("a", e);
1427        eg.register_op0("b", e);
1428        eg.register_op0("c", e);
1429        eg.register_a("concat", e, e, AssocDir::Right);
1430        eg.register_mset("add", e, e);
1431        eg.register_set("union", e, e);
1432        eg
1433    }
1434
1435    fn make_eg_with_lits() -> EG {
1436        let mut eg = EG::from_model(&NiraModel);
1437        let e = eg.intern_sort("IExpr");
1438        let ibig = eg.sorts().id_by_name("IBig").unwrap();
1439        eg.register_opn("ILit", &[ibig], e);
1440        eg.register_op2("IAdd", e, e, e);
1441        eg
1442    }
1443
1444    #[test]
1445    fn rewrite_commute_f() {
1446        let mut eg = make_eg();
1447        let mut rules = crate::registry::RuleRegistry::<false>::new();
1448        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1449        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1450        let fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
1451
1452        // Compile: (f x y) → (f y x)
1453        let model = NiraModel;
1454        let lhs = parse_pattern("(f x y)");
1455        let ri = "(f y x)";
1456        let rhs = parse_rhs(ri);
1457        let rule = compile_rewrite(
1458            "test",
1459            "",
1460            "",
1461            &lhs,
1462            &rhs,
1463            &[],
1464            false,
1465            eg.ops(),
1466            eg.sorts(),
1467            &mut rules,
1468            &model,
1469            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1470        )
1471        .unwrap();
1472
1473        // Before: only (f a b) exists
1474        let index = IndexStore::build(&eg);
1475        let changes = apply_rule(
1476            &rule,
1477            &mut eg,
1478            &index,
1479            &crate::schedule::IndexStats::from_index(&index),
1480            &model,
1481            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1482        );
1483        assert!(changes > 0, "expected at least one change");
1484
1485        // After: (f b a) should exist and be merged with (f a b)
1486        let fba = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
1487        assert_eq!(
1488            eg.find(fab),
1489            eg.find(fba),
1490            "(f a b) and (f b a) should be in same e-class"
1491        );
1492    }
1493
1494    #[test]
1495    fn rewrite_nested() {
1496        let mut eg = make_eg();
1497        let mut rules = crate::registry::RuleRegistry::<false>::new();
1498        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1499        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1500        let gb = eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
1501        let _fagb = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, gb]);
1502
1503        // Compile: (f x (g y)) → (g (f y x))
1504        let model = NiraModel;
1505        let lhs = parse_pattern("(f x (g y))");
1506        let ri = "(g (f y x))";
1507        let rhs = parse_rhs(ri);
1508        let rule = compile_rewrite(
1509            "test",
1510            "",
1511            "",
1512            &lhs,
1513            &rhs,
1514            &[],
1515            false,
1516            eg.ops(),
1517            eg.sorts(),
1518            &mut rules,
1519            &model,
1520            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1521        )
1522        .unwrap();
1523
1524        let index = IndexStore::build(&eg);
1525        let changes = apply_rule(
1526            &rule,
1527            &mut eg,
1528            &index,
1529            &crate::schedule::IndexStats::from_index(&index),
1530            &model,
1531            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1532        );
1533        assert!(changes > 0);
1534
1535        // (g (f b a)) should now exist and be merged with (f a (g b))
1536        let fba = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
1537        let g_fba = eg.add(eg.ops().id_by_name("g").unwrap(), &[fba]);
1538        assert_eq!(eg.find(_fagb), eg.find(g_fba));
1539    }
1540
1541    #[test]
1542    fn rewrite_no_match_no_change() {
1543        let mut eg = make_eg();
1544        let mut rules = crate::registry::RuleRegistry::<false>::new();
1545        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1546        let _ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
1547
1548        // Compile: (f x y) → (f y x) — but no f-nodes exist
1549        let model = NiraModel;
1550        let lhs = parse_pattern("(f x y)");
1551        let ri = "(f y x)";
1552        let rhs = parse_rhs(ri);
1553        let rule = compile_rewrite(
1554            "test",
1555            "",
1556            "",
1557            &lhs,
1558            &rhs,
1559            &[],
1560            false,
1561            eg.ops(),
1562            eg.sorts(),
1563            &mut rules,
1564            &model,
1565            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1566        )
1567        .unwrap();
1568
1569        let index = IndexStore::build(&eg);
1570        let changes = apply_rule(
1571            &rule,
1572            &mut eg,
1573            &index,
1574            &crate::schedule::IndexStats::from_index(&index),
1575            &model,
1576            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1577        );
1578        assert_eq!(changes, 0);
1579    }
1580
1581    #[test]
1582    fn rewrite_insert_new_op() {
1583        let mut eg = make_eg();
1584        let mut rules = crate::registry::RuleRegistry::<false>::new();
1585        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1586        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1587        let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
1588
1589        // Compile: (f x y) → (h x y) — creates h-nodes
1590        let model = NiraModel;
1591        let lhs = parse_pattern("(f x y)");
1592        let ri = "(h x y)";
1593        let rhs = parse_rhs(ri);
1594        let rule = compile_rewrite(
1595            "test",
1596            "",
1597            "",
1598            &lhs,
1599            &rhs,
1600            &[],
1601            false,
1602            eg.ops(),
1603            eg.sorts(),
1604            &mut rules,
1605            &model,
1606            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1607        )
1608        .unwrap();
1609
1610        let index = IndexStore::build(&eg);
1611        let changes = apply_rule(
1612            &rule,
1613            &mut eg,
1614            &index,
1615            &crate::schedule::IndexStats::from_index(&index),
1616            &model,
1617            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1618        );
1619        assert!(changes > 0);
1620
1621        // (h a b) should exist and be in same e-class as (f a b)
1622        let hab = eg.add(eg.ops().id_by_name("h").unwrap(), &[a, b]);
1623        assert_eq!(eg.find(_fab), eg.find(hab));
1624    }
1625
1626    // -----------------------------------------------------------------------
1627    // Datalog insert
1628    // -----------------------------------------------------------------------
1629
1630    #[test]
1631    fn rule_datalog_insert() {
1632        // rule: (f x y) => insert (h x y)
1633        // Given (f a b), should create (h a b) as a new e-class (no union).
1634        let mut eg = make_eg();
1635        let mut rules = crate::registry::RuleRegistry::<false>::new();
1636        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1637        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1638        let fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
1639
1640        let model = NiraModel;
1641        let body = vec![parse_pattern("(f x y)")];
1642        let ri = "(h x y)";
1643        let rhs_term = parse_rhs(ri);
1644        let head = vec![crate::ast::Action::Insert(rhs_term)];
1645        let rule = compile_rule(
1646            "test",
1647            &body,
1648            &head,
1649            eg.ops(),
1650            eg.sorts(),
1651            &mut rules,
1652            &model,
1653            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1654        )
1655        .unwrap();
1656
1657        let index = IndexStore::build(&eg);
1658        let changes = apply_rule(
1659            &rule,
1660            &mut eg,
1661            &index,
1662            &crate::schedule::IndexStats::from_index(&index),
1663            &model,
1664            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1665        );
1666        assert_eq!(changes, 1);
1667
1668        // (h a b) should exist but NOT be merged with (f a b)
1669        let hab = eg.add(eg.ops().id_by_name("h").unwrap(), &[a, b]);
1670        assert_ne!(
1671            eg.find(fab),
1672            eg.find(hab),
1673            "insert should not union with the matched node"
1674        );
1675    }
1676
1677    // -----------------------------------------------------------------------
1678    // Rest splicing
1679    // -----------------------------------------------------------------------
1680
1681    #[test]
1682    fn rewrite_a_splice_rest() {
1683        // concat is A (associative). Match prefix, splice rest.
1684        // (concat x ..rest) → (concat x x ..rest)
1685        let mut eg = make_eg();
1686        let mut rules = crate::registry::RuleRegistry::<false>::new();
1687        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1688        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1689        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
1690        let abc = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
1691
1692        let model = NiraModel;
1693        let lhs = parse_pattern("(concat x ..rest)");
1694        let ri = "(concat x x ..rest)";
1695        let rhs = parse_rhs(ri);
1696        let rule = compile_rewrite(
1697            "test",
1698            "",
1699            "",
1700            &lhs,
1701            &rhs,
1702            &[],
1703            false,
1704            eg.ops(),
1705            eg.sorts(),
1706            &mut rules,
1707            &model,
1708            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1709        )
1710        .unwrap();
1711
1712        let index = IndexStore::build(&eg);
1713        let changes = apply_rule(
1714            &rule,
1715            &mut eg,
1716            &index,
1717            &crate::schedule::IndexStats::from_index(&index),
1718            &model,
1719            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1720        );
1721        assert!(changes > 0);
1722
1723        // (concat a a b c) should be merged with (concat a b c)
1724        let aabc = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, a, b, c]);
1725        assert_eq!(eg.find(abc), eg.find(aabc));
1726    }
1727
1728    #[test]
1729    fn rewrite_ac_splice_rest() {
1730        // add is AC. Match one element, splice rest.
1731        // {add x ..rest} → {add (g x) ..rest}
1732        let mut eg = make_eg();
1733        let mut rules = crate::registry::RuleRegistry::<false>::new();
1734        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1735        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1736        let ab = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
1737
1738        let model = NiraModel;
1739        let lhs = parse_pattern("(add x:1 ..rest)");
1740        let ri = "(add (g x) ..rest)";
1741        let rhs = parse_rhs(ri);
1742        let rule = compile_rewrite(
1743            "test",
1744            "",
1745            "",
1746            &lhs,
1747            &rhs,
1748            &[],
1749            false,
1750            eg.ops(),
1751            eg.sorts(),
1752            &mut rules,
1753            &model,
1754            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1755        )
1756        .unwrap();
1757
1758        let index = IndexStore::build(&eg);
1759        let changes = apply_rule(
1760            &rule,
1761            &mut eg,
1762            &index,
1763            &crate::schedule::IndexStats::from_index(&index),
1764            &model,
1765            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1766        );
1767        assert!(changes > 0);
1768
1769        // For match x=a, rest={b}: {add (g a) b} merged with {add a b}
1770        let ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
1771        let ga_b = eg.add(eg.ops().id_by_name("add").unwrap(), &[ga, b]);
1772        assert_eq!(eg.find(ab), eg.find(ga_b));
1773    }
1774
1775    #[test]
1776    fn rewrite_aci_splice_rest() {
1777        // union is ACI. Match one element, splice rest.
1778        // {union x ..rest} → {union (g x) ..rest}
1779        let mut eg = make_eg();
1780        let mut rules = crate::registry::RuleRegistry::<false>::new();
1781        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1782        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1783        let ab = eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b]);
1784
1785        let model = NiraModel;
1786        let lhs = parse_pattern("(union x ..rest)");
1787        let ri = "(union (g x) ..rest)";
1788        let rhs = parse_rhs(ri);
1789        let rule = compile_rewrite(
1790            "test",
1791            "",
1792            "",
1793            &lhs,
1794            &rhs,
1795            &[],
1796            false,
1797            eg.ops(),
1798            eg.sorts(),
1799            &mut rules,
1800            &model,
1801            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1802        )
1803        .unwrap();
1804
1805        let index = IndexStore::build(&eg);
1806        let changes = apply_rule(
1807            &rule,
1808            &mut eg,
1809            &index,
1810            &crate::schedule::IndexStats::from_index(&index),
1811            &model,
1812            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1813        );
1814        assert!(changes > 0);
1815
1816        let ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
1817        let ga_b = eg.add(eg.ops().id_by_name("union").unwrap(), &[ga, b]);
1818        assert_eq!(eg.find(ab), eg.find(ga_b));
1819    }
1820
1821    #[test]
1822    fn constant_fold_iadd() {
1823        use crate::literal::NiraLitVal;
1824        use num_bigint::BigInt;
1825
1826        let mut eg = make_eg_with_lits();
1827        let mut rules = crate::registry::RuleRegistry::<false>::new();
1828        let model = NiraModel;
1829
1830        // Build (IAdd (ILit (@IBig 3)) (ILit (@IBig 5)))
1831        let at_ibig = eg.ops().id_by_name("@IBig").unwrap();
1832        let ilit = eg.ops().id_by_name("ILit").unwrap();
1833        let iadd = eg.ops().id_by_name("IAdd").unwrap();
1834
1835        let v3 = eg.intern_lit(NiraLitVal::Int(BigInt::from(3)));
1836        let n3 = eg.add_lit(at_ibig, v3); // @IBig(3)
1837        let lit3 = eg.add(ilit, &[n3]); // ILit(@IBig(3))
1838
1839        let v5 = eg.intern_lit(NiraLitVal::Int(BigInt::from(5)));
1840        let n5 = eg.add_lit(at_ibig, v5); // @IBig(5)
1841        let lit5 = eg.add(ilit, &[n5]); // ILit(@IBig(5))
1842
1843        let add_node = eg.add(iadd, &[lit3, lit5]); // IAdd(ILit(3), ILit(5))
1844
1845        // Rule: (IAdd (ILit x) (ILit y)) → (ILit (+ x y))
1846        let lhs = parse_pattern("(IAdd (ILit x) (ILit y))");
1847        let ri = "(ILit (+ x y))";
1848        let rhs = parse_rhs(ri);
1849        let rule = compile_rewrite(
1850            "test",
1851            "",
1852            "",
1853            &lhs,
1854            &rhs,
1855            &[],
1856            false,
1857            eg.ops(),
1858            eg.sorts(),
1859            &mut rules,
1860            &model,
1861            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1862        )
1863        .unwrap();
1864
1865        let index = IndexStore::build(&eg);
1866        let changes = apply_rule(
1867            &rule,
1868            &mut eg,
1869            &index,
1870            &crate::schedule::IndexStats::from_index(&index),
1871            &model,
1872            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1873        );
1874        assert!(changes > 0, "constant fold should fire");
1875
1876        // (ILit (@IBig 8)) should now be merged with (IAdd (ILit 3) (ILit 5))
1877        let v8 = eg.intern_lit(NiraLitVal::Int(BigInt::from(8)));
1878        let n8 = eg.add_lit(at_ibig, v8);
1879        let lit8 = eg.add(ilit, &[n8]);
1880        assert_eq!(
1881            eg.find(add_node),
1882            eg.find(lit8),
1883            "(IAdd (ILit 3) (ILit 5)) should be merged with (ILit 8)"
1884        );
1885    }
1886
1887    /// Rewrite on a PROOFS=true e-graph must produce `Rewrite` justifications.
1888    #[test]
1889    fn rewrite_produces_rewrite_justification() {
1890        type Peg = EGraph<DefaultConfig, NiraLitVal, false, true>;
1891        let mut eg = Peg::from_model(&NiraModel);
1892        let mut rules = crate::registry::RuleRegistry::<false>::new();
1893        let e = eg.intern_sort("IExpr");
1894        eg.register_op2("f", e, e, e);
1895        eg.register_op0("a", e);
1896        eg.register_op0("b", e);
1897
1898        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
1899        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
1900        let _fab = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
1901
1902        let model = NiraModel;
1903        let lhs = parse_pattern("(f x y)");
1904        let rhs = parse_rhs("(f y x)");
1905        let rule = compile_rewrite(
1906            "commute-f",
1907            "(f x y)",
1908            "(f y x)",
1909            &lhs,
1910            &rhs,
1911            &[],
1912            false,
1913            eg.ops(),
1914            eg.sorts(),
1915            &mut rules,
1916            &model,
1917            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1918        )
1919        .unwrap();
1920        let rule_id = rule.rule_id;
1921
1922        let index = IndexStore::build(&eg);
1923        let changes = apply_rule(
1924            &rule,
1925            &mut eg,
1926            &index,
1927            &crate::schedule::IndexStats::from_index(&index),
1928            &model,
1929            &crate::resolve::GlobalCtx::<crate::id::SortId, crate::id::ENodeId>::new(),
1930        );
1931        assert!(changes > 0);
1932        eg.rebuild();
1933
1934        let fba = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
1935        let mut buf = crate::union_find::ProofBuf::new();
1936        assert!(eg.explain(_fab, fba, &mut buf));
1937
1938        // At least one step must be a Rewrite with our rule_id
1939        assert!(
1940            buf.steps
1941                .iter()
1942                .any(|&(_, _, j)| j == crate::union_find::Justification::Rewrite { rule_id }),
1943            "expected a Rewrite {{ rule_id: r0 }} step in the proof, got: {:?}",
1944            buf.steps,
1945        );
1946    }
1947}