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