Skip to main content

semi_persistent_egraph/
interpret.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Layer 7: Command language interpreter.
4//!
5//! Parses and executes egglog programs against the e-graph.
6
7use crate::apply::PreparedRule;
8use crate::canon::{MSetCanon, VarCanon};
9use crate::config::EGraphConfig;
10use crate::containers::DenseId;
11use crate::containers::ShrinkPolicy;
12use crate::egraph::{EGraph, EGraphToken};
13use crate::lit_model::LitModel;
14use crate::literal::LitVal;
15use crate::sortcheck::{CCommand, CTerm};
16use crate::union_find::Justification;
17
18/// Error during interpretation.
19#[derive(Debug)]
20pub enum InterpError {
21    /// Unknown sort name.
22    UnknownSort(String),
23    /// Unknown operator / function name.
24    UnknownOp(String),
25    /// Sort mismatch or arity error in a declaration.
26    DeclError(String),
27    /// Rule compilation failed.
28    CompileError(crate::resolve::ResolveError),
29    /// `(check ...)` assertion failed.
30    CheckFailed(String),
31    /// `(extract ...)` could not produce a term from the named class.
32    ExtractFailed(crate::extract::ExtractError),
33    /// `(pop)` without matching `(push)`.
34    PopWithoutPush,
35}
36
37impl From<crate::resolve::ResolveError> for InterpError {
38    fn from(e: crate::resolve::ResolveError) -> Self {
39        InterpError::CompileError(e)
40    }
41}
42
43impl std::fmt::Display for InterpError {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            InterpError::UnknownSort(s) => write!(f, "unknown sort: {s}"),
47            InterpError::UnknownOp(s) => write!(f, "unknown operator: {s}"),
48            InterpError::DeclError(s) => write!(f, "declaration error: {s}"),
49            InterpError::CompileError(e) => write!(f, "compile error: {e}"),
50            InterpError::CheckFailed(s) => write!(f, "check failed: {s}"),
51            InterpError::ExtractFailed(e) => write!(f, "extract failed: {e}"),
52            InterpError::PopWithoutPush => write!(f, "pop without matching push"),
53        }
54    }
55}
56
57fn parse_au_cycle_mode(value: &str) -> Result<crate::au::space::CycleMode, InterpError> {
58    match value {
59        "sides" => Ok(crate::au::space::CycleMode::AncestorOnly),
60        "sides-current" => Ok(crate::au::space::CycleMode::CurrentInclusive),
61        "pair" => Ok(crate::au::space::CycleMode::Pair),
62        other => Err(InterpError::CheckFailed(format!(
63            "unknown AU cycle mode '{other}' (expected sides, sides-current, or pair)"
64        ))),
65    }
66}
67
68struct Mark<Cfg: EGraphConfig, O> {
69    token: EGraphToken,
70    rules_len: usize,
71    globals_len: usize,
72    _phantom: std::marker::PhantomData<(Cfg, O)>,
73}
74
75/// How AC congruence completion participates in a program run.
76///
77/// - `Off`: canonization and plain congruence only. Checks decide equality of
78///   materialized canonical forms; AC-entailed equalities through erased
79///   intermediate sums are not derived (the documented completeness gap,
80///   `ac-congruence-completeness.md` Part I).
81/// - `Eager`: every rebuild attempts completion (the `--derive-ac-eqs`
82///   behavior). `CompletionOutcome::Converged` reports an unchanged full
83///   implementation round, not a semantic-completeness certificate; the growth
84///   budget can stop earlier with `AbortedGrowthLimit`. Interleaving
85///   completion with saturation rules re-runs it on a growing atom pool every
86///   round. A rule set that continually mints new atoms can prevent the
87///   combined loop from reaching a fixpoint; the node-growth budget may stop an
88///   individual completion rebuild first.
89/// - `Lazy`: saturation runs with completion off; an equality check that plain
90///   congruence cannot decide runs goal-directed completion inside a
91///   semi-persistent transaction shared across consecutive equality checks.
92///   The queried pair is the completion goal: every pass stops with
93///   `CompletionOutcome::GoalMet` the moment the pair joins, a second phase
94///   alternates default-ruleset rule rounds with completion passes when the
95///   graph's own closure does not decide the pair, and the node-growth budget
96///   is checked inside a round's apply loops. The first non-equality-check
97///   command restores the mark, discarding everything the checks derived.
98///   Restore work includes container diff replay/capture-state reconstruction
99///   and incremental or full hash-index repair. Lazy and eager share the
100///   completion implementation, but different stopping points and lazy's
101///   bounded rule/completion alternation mean they are not claimed to be
102///   equivalent decision procedures.
103#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
104pub enum AcMode {
105    #[default]
106    Off,
107    Eager,
108    Lazy,
109}
110
111pub struct Interpreter<
112    Cfg: EGraphConfig,
113    L: LitVal,
114    M: LitModel<Value = L>,
115    const TRACK: bool,
116    const PROOFS: bool,
117> {
118    pub eg: EGraph<Cfg, L, TRACK, PROOFS>,
119    pub model: M,
120    rules: Vec<PreparedRule<Cfg::O, Cfg::S, L>>,
121    globals: crate::resolve::GlobalCtx<Cfg::S, Cfg::G>,
122    marks: Vec<Mark<Cfg, Cfg::O>>,
123    shrink_policy: ShrinkPolicy,
124    strategy: crate::saturate::SaturationStrategy,
125    ac_mode: AcMode,
126    /// Alternation budget for a lazy check's second phase (rule rounds
127    /// interleaved with completion fixpoints inside the transaction).
128    lazy_ac_rounds: usize,
129    /// The shared lazy-check transaction: `Some(mark)` while a run of
130    /// consecutive equality checks accumulates completion state. Closed (and
131    /// the graph restored) by the first non-check command or program end.
132    lazy_txn: Option<EGraphToken>,
133    /// Outcome of the most recent `(run …)` command (iterations, saturated, match steps).
134    /// `None` until the first run. Exposed for diagnostics and benchmarking.
135    last_sat: Option<crate::saturate::SatResult>,
136    /// Wall time of the most recent `(run …)`, measured around the driver call.
137    last_run_time: Option<std::time::Duration>,
138    /// Index build scratch, owned here rather than by the saturation call.
139    ///
140    /// `(run 1)` is one round, so a scratch allocated per call would be built
141    /// and dropped without ever being reused — which is exactly the shape of
142    /// the E6 incremental cycle, twenty `(run 1)`s over one base. Holding it
143    /// here carries the span arenas' allocation and their generation stamp
144    /// across commands. Nothing has to be invalidated between runs, including
145    /// across `(push)`/`(pop)`: a build bumps the stamp and writes only the
146    /// keys its own stream carries, so whatever a previous run left in the
147    /// table reads as empty.
148    index_scratch: crate::index::IndexScratch<Cfg>,
149}
150
151impl<Cfg: EGraphConfig, L: LitVal, M: LitModel<Value = L>, const TRACK: bool, const PROOFS: bool>
152    Interpreter<Cfg, L, M, TRACK, PROOFS>
153where
154    Cfg::O: std::hash::Hash,
155    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
156{
157    pub fn new(model: M) -> Self {
158        let eg = EGraph::from_model(&model);
159        Self {
160            eg,
161            model,
162            rules: Vec::new(),
163            globals: crate::resolve::GlobalCtx::new(),
164            marks: Vec::new(),
165            shrink_policy: ShrinkPolicy::Never,
166            strategy: crate::saturate::SaturationStrategy::default(),
167            ac_mode: AcMode::Off,
168            lazy_ac_rounds: 32,
169            lazy_txn: None,
170            last_sat: None,
171            last_run_time: None,
172            index_scratch: crate::index::IndexScratch::new(),
173        }
174    }
175
176    /// Create an interpreter with pre-built registries (from sortcheck).
177    pub fn with_registries(
178        model: M,
179        sorts: crate::registry::SortRegistry<Cfg::S, TRACK>,
180        ops: crate::registry::OpRegistry<Cfg::O, Cfg::S, TRACK>,
181    ) -> Self {
182        let eg = EGraph::with_registries(sorts, ops);
183        Self {
184            eg,
185            model,
186            rules: Vec::new(),
187            globals: crate::resolve::GlobalCtx::new(),
188            marks: Vec::new(),
189            shrink_policy: ShrinkPolicy::Never,
190            strategy: crate::saturate::SaturationStrategy::default(),
191            ac_mode: AcMode::Off,
192            lazy_ac_rounds: 32,
193            lazy_txn: None,
194            last_sat: None,
195            last_run_time: None,
196            index_scratch: crate::index::IndexScratch::new(),
197        }
198    }
199
200    /// Set the shrink policy used by `push`/`pop`.
201    pub fn set_shrink_policy(&mut self, policy: ShrinkPolicy) {
202        self.shrink_policy = policy;
203    }
204
205    /// Select the saturation strategy used by `(run …)`.
206    pub fn set_strategy(&mut self, strategy: crate::saturate::SaturationStrategy) {
207        self.strategy = strategy;
208    }
209
210    /// Outcome of the most recent `(run …)` command, or `None` if none has run.
211    pub fn last_sat(&self) -> Option<&crate::saturate::SatResult> {
212        self.last_sat.as_ref()
213    }
214
215    /// Wall time of the most recent `(run …)`, or `None` if none has run. Measured around
216    /// the saturation driver only — building the `:until` goal's terms is not included.
217    pub fn last_run_time(&self) -> Option<std::time::Duration> {
218        self.last_run_time
219    }
220
221    /// Enable/disable the AC congruence-completion pass (default off; see
222    /// `EGraph::set_cc`). Equivalent to `set_ac_mode(Eager)` / `set_ac_mode(Off)`.
223    pub fn set_cc(&mut self, enabled: bool) {
224        self.set_ac_mode(if enabled { AcMode::Eager } else { AcMode::Off });
225    }
226
227    /// Select how AC completion participates in the run (see [`AcMode`]).
228    /// `Lazy` keeps the e-graph's completion flag off; completion runs only
229    /// inside the transaction a lazy check opens.
230    pub fn set_ac_mode(&mut self, mode: AcMode) {
231        self.ac_mode = mode;
232        self.eg.set_cc(mode == AcMode::Eager);
233    }
234
235    /// Alternation budget for a lazy check's second phase (default 32 rounds).
236    pub fn set_lazy_ac_rounds(&mut self, rounds: usize) {
237        self.lazy_ac_rounds = rounds;
238    }
239
240    /// Select the merge survivor policy (see `EGraph::set_union_by`).
241    pub fn set_union_by(&mut self, u: crate::egraph::UnionBy) {
242        self.eg.set_union_by(u);
243    }
244
245    /// Open the shared lazy-check transaction if it is not already open: mark
246    /// the graph, then enable completion. Consecutive equality checks keep it
247    /// open and accumulate completion/alternation state; the first non-check
248    /// command (or the end of the program) closes it via `lazy_txn_close`,
249    /// and restore discards everything the checks derived. Restore cost is the
250    /// sum of fork-history walks, diff replay, truncation/regrowth, capture-state
251    /// reconstruction (including bitmap clearing where applicable), and
252    /// incremental or full transient-index repair.
253    fn lazy_txn_open(&mut self) {
254        if self.lazy_txn.is_none() {
255            self.lazy_txn = Some(self.eg.mark(self.shrink_policy));
256            self.eg.set_cc(true);
257        }
258    }
259
260    /// Close the shared lazy-check transaction (no-op when none is open).
261    fn lazy_txn_close(&mut self) {
262        if let Some(token) = self.lazy_txn.take() {
263            self.eg.set_cc(false);
264            self.eg.set_cc_goal(None);
265            self.eg.restore(token);
266        }
267    }
268
269    /// Decide whether `a` and `b` are AC-entailed equal, inside the shared
270    /// semi-persistent transaction (`lazy_txn_open`): every node the decision
271    /// mints is discarded when the transaction closes, and consecutive checks
272    /// continue from the accumulated state instead of re-deriving.
273    ///
274    /// Two phases, both goal-directed: the pair is installed as the
275    /// completion goal (`set_cc_goal`), so every completion pass — including
276    /// the ones inside the alternation — stops mid-closure the moment the
277    /// pair joins. First, one completion rebuild on the current graph — with
278    /// no rules interleaving, the case the conditional termination argument
279    /// (Dickson antichain over a fixed atom pool) targets — searches for pure AC
280    /// congruence consequences. Second, if the pair is still apart and the program has
281    /// rules, the saturation driver runs the default ruleset with the pair as
282    /// its `:until` goal and completion on, so rounds alternate rule matching
283    /// with completion passes, bounded by `lazy_ac_rounds` and by the
284    /// node-growth budget (checked in-round, not only between rounds).
285    ///
286    /// Returns `(equal, inconclusive)`. `inconclusive` means a budget stopped
287    /// the search first. A `false` verdict with `inconclusive == false` reached
288    /// this driver's operational joint fixpoint without joining the pair. It is
289    /// not a semantic non-derivability theorem: matching is over materialized
290    /// nodes, and AC scalar-subterm matching remains incomplete.
291    fn lazy_ac_decide(&mut self, a: Cfg::G, b: Cfg::G) -> (bool, bool) {
292        self.lazy_txn_open();
293        self.eg.set_cc_goal(Some((a, b)));
294        self.eg.rebuild();
295        let mut equal = self.eg.find(a) == self.eg.find(b);
296        let aborted = |eg: &EGraph<Cfg, L, TRACK, PROOFS>| {
297            matches!(
298                eg.completion_outcome(),
299                Some(crate::egraph::CompletionOutcome::AbortedGrowthLimit { .. })
300            )
301        };
302        let mut inconclusive = !equal && aborted(&self.eg);
303        if !equal && !inconclusive && !self.rules.is_empty() {
304            let spec = crate::saturate::RunSpec {
305                limit: self.lazy_ac_rounds,
306                ruleset: None,
307                until: Some(crate::saturate::RunGoal {
308                    left: a,
309                    right: b,
310                    equal: true,
311                }),
312            };
313            let result = match self.strategy {
314                crate::saturate::SaturationStrategy::Naive => self.eg.saturate_spec_in(
315                    &self.rules,
316                    &self.model,
317                    &spec,
318                    &self.globals,
319                    &mut self.index_scratch,
320                ),
321                crate::saturate::SaturationStrategy::SemiNaive => self.eg.saturate_semi_spec_in(
322                    &self.rules,
323                    &self.model,
324                    &spec,
325                    &self.globals,
326                    &mut self.index_scratch,
327                ),
328            };
329            equal = self.eg.find(a) == self.eg.find(b);
330            inconclusive = !equal && (aborted(&self.eg) || !result.saturated);
331        }
332        self.eg.set_cc_goal(None);
333        (equal, inconclusive)
334    }
335
336    /// Enable/disable the runtime reduced-basis invariant checks (default off; see
337    /// `EGraph::set_basis_checks`). Diagnostic only: superlinear brute-force checks.
338    pub fn set_basis_checks(&mut self, enabled: bool) {
339        self.eg.set_basis_checks(enabled);
340    }
341
342    fn alloc_axiom_id(&mut self, lhs: Cfg::G, rhs: Cfg::G) -> crate::id::AxiomId {
343        let name = format!("axiom_{}", self.eg.axioms().len());
344        self.eg.register_axiom(&name, lhs, rhs)
345    }
346
347    fn bind_global(&mut self, name: String, id: Cfg::G, sort: Cfg::S) {
348        self.globals.insert(name, sort, id);
349    }
350
351    /// Look up a global binding by name.
352    pub fn global(&mut self, name: &str) -> Option<(Cfg::G, Cfg::S)> {
353        self.globals
354            .get(name)
355            .map(|(_, sort, id)| (self.eg.find(id), sort))
356    }
357
358    // ── Checked pipeline ──────────────────────────────────────────────
359
360    /// Run a pre-checked program (output of `sortcheck_program`).
361    pub fn run_checked(&mut self, cmds: &[CCommand<Cfg::O, Cfg::S, L>]) -> Result<(), InterpError> {
362        // Each push query already tallies steps in its MatchPool. Arming the
363        // thread-local counter folds that tally in once per query; it does not
364        // add a flag read to every matching step.
365        if cmds.iter().any(|c| matches!(c, CCommand::PrintStats(_))) {
366            crate::ematch::set_match_step_counting(true);
367        }
368        for cmd in cmds {
369            // The lazy-check transaction is shared across a run of consecutive
370            // equality checks (each check continues the accumulated
371            // completion/alternation state instead of re-deriving); any other
372            // command must see the untouched graph, so the transaction closes
373            // first. `(check t)` closes it too: a bare check materializes its
374            // term permanently, which an open transaction would discard.
375            if !matches!(cmd, CCommand::CheckEq(..) | CCommand::CheckNeq(..)) {
376                self.lazy_txn_close();
377            }
378            let r = self.exec_checked(cmd);
379            if r.is_err() {
380                self.lazy_txn_close();
381            }
382            r?;
383        }
384        self.lazy_txn_close();
385        Ok(())
386    }
387
388    /// Reject a rule whose multiplicity literals exceed the configured width, before it
389    /// can be saturated with. See [`crate::apply::check_mult_literals`] for why this has
390    /// to happen at install rather than at match/apply time.
391    fn check_rule_mults(
392        name: &str,
393        rule: &PreparedRule<Cfg::O, Cfg::S, L>,
394    ) -> Result<(), InterpError> {
395        crate::apply::check_mult_literals::<Cfg, _, _, _>(rule).map_err(|n| {
396            InterpError::DeclError(format!(
397                "rule `{name}`: multiplicity literal {n} exceeds the configured \
398                 multiplicity width (EGraphConfig::M holds at most {})",
399                <Cfg::M as crate::multiplicity::MultiplicityLike>::MAX
400            ))
401        })?;
402        crate::apply::check_rhs_mult_exprs(rule)
403            .map_err(|msg| InterpError::DeclError(format!("rule `{name}`: {msg}")))
404    }
405
406    fn exec_checked(&mut self, cmd: &CCommand<Cfg::O, Cfg::S, L>) -> Result<(), InterpError> {
407        match cmd {
408            CCommand::Decl(_) => {
409                // Already registered into egraph during sortcheck. No-op.
410            }
411            CCommand::Let(name, ct) => {
412                let (id, sort) = self.build_cterm(ct);
413                self.bind_global(name.clone(), id, sort);
414            }
415            CCommand::Insert(ct) => {
416                self.build_cterm(ct);
417            }
418            CCommand::Union(a, b) => {
419                let (a_id, _) = self.build_cterm(a);
420                let (b_id, _) = self.build_cterm(b);
421                if PROOFS {
422                    let axiom_id = self.alloc_axiom_id(a_id, b_id);
423                    self.eg
424                        .merge_justified(a_id, b_id, Justification::Axiom { axiom_id });
425                } else {
426                    self.eg.merge(a_id, b_id);
427                }
428                self.eg.rebuild();
429            }
430            CCommand::Check(ct) => {
431                self.build_cterm(ct);
432            }
433            CCommand::CheckEq(a, b) => {
434                let (a_id, _) = self.build_cterm(a);
435                let (b_id, _) = self.build_cterm(b);
436                // Install the goal before any rebuild: with the shared
437                // transaction open, the term-build rebuild runs completion,
438                // and the goal keeps it from running past the answer.
439                if self.ac_mode == AcMode::Lazy {
440                    self.eg.set_cc_goal(Some((a_id, b_id)));
441                }
442                // A budget-limited run can leave congruence work pending even
443                // when both queried terms already hash-cons. Equality commands
444                // are closure boundaries, so node growth is not a sufficient
445                // reason to decide whether to rebuild.
446                self.eg.rebuild();
447                if self.eg.find(a_id) != self.eg.find(b_id) {
448                    if self.ac_mode == AcMode::Lazy {
449                        match self.lazy_ac_decide(a_id, b_id) {
450                            (true, _) => return Ok(()),
451                            (false, aborted) => {
452                                return Err(InterpError::CheckFailed(if aborted {
453                                    "terms are not equal (lazy AC completion hit its growth \
454                                     budget before deciding; inconclusive)"
455                                        .into()
456                                } else {
457                                    "equality was not derived at the lazy AC operational \
458                                     fixpoint"
459                                        .into()
460                                }));
461                            }
462                        }
463                    }
464                    return Err(InterpError::CheckFailed("terms are not equal".into()));
465                }
466                self.eg.set_cc_goal(None);
467            }
468            CCommand::CheckNeq(a, b) => {
469                let (a_id, _) = self.build_cterm(a);
470                let (b_id, _) = self.build_cterm(b);
471                if self.ac_mode == AcMode::Lazy {
472                    self.eg.set_cc_goal(Some((a_id, b_id)));
473                }
474                self.eg.rebuild();
475                if self.eg.find(a_id) == self.eg.find(b_id) {
476                    self.eg.set_cc_goal(None);
477                    return Err(InterpError::CheckFailed("terms are equal".into()));
478                }
479                // Lazy mode searches beyond plain congruence before accepting `!=`:
480                // distinct classes may still join through completion. Reaching the
481                // implemented operational fixpoint without a join is the command's
482                // acceptance criterion, not a semantic non-disequality theorem.
483                if self.ac_mode == AcMode::Lazy {
484                    match self.lazy_ac_decide(a_id, b_id) {
485                        (true, _) => {
486                            return Err(InterpError::CheckFailed(
487                                "terms are equal (derived by lazy AC completion)".into(),
488                            ));
489                        }
490                        (false, true) => {
491                            return Err(InterpError::CheckFailed(
492                                "disequality is inconclusive (lazy AC completion hit its \
493                                 growth or alternation budget before deciding)"
494                                    .into(),
495                            ));
496                        }
497                        (false, false) => {}
498                    }
499                }
500            }
501            CCommand::Extract(ct) => {
502                let (id, _) = self.build_cterm(ct);
503                // Extraction must see pending congruence from a preceding
504                // budget-limited run even when `ct` was already materialized.
505                self.eg.rebuild();
506                // An extract that cannot produce a term is a program error, not a printed
507                // remark: the class is named and the reason distinguished (every node
508                // `:unextractable`, versus no grounded node at all).
509                match crate::extract::extract_best(&self.eg, id) {
510                    Ok(t) => println!("{t}"),
511                    Err(e) => return Err(InterpError::ExtractFailed(e)),
512                }
513            }
514            CCommand::Rewrite {
515                query,
516                rhs_locals,
517                rhs,
518                root_vid,
519                subsume,
520                ruleset,
521            } => {
522                let name = format!("rewrite_{}", self.eg.rules().len());
523                let rule_id = self.eg.register_rule(&name, "", "");
524                let compiled_rhs = crate::apply::compile_rhs(rhs);
525                let mut actions = vec![crate::apply::CompiledAction::Union(
526                    rule_id,
527                    crate::apply::RhsOp::FetchNode(crate::resolve::RhsNodeRef::Query(*root_vid)),
528                    compiled_rhs,
529                )];
530                if *subsume {
531                    actions.push(crate::apply::CompiledAction::Subsume(*root_vid));
532                }
533                let rule = PreparedRule {
534                    rule_id,
535                    query: query.clone(),
536                    rhs_locals: *rhs_locals,
537                    actions,
538                    ruleset: *ruleset,
539                };
540                Self::check_rule_mults(&name, &rule)?;
541                self.rules.push(rule);
542            }
543            CCommand::Rule {
544                query,
545                rhs_locals,
546                actions,
547                ruleset,
548            } => {
549                let name = format!("rule_{}", self.eg.rules().len());
550                let rule_id = self.eg.register_rule(&name, "", "");
551                let compiled: Vec<_> = actions
552                    .iter()
553                    .map(|a| crate::apply::compile_action(a, rule_id))
554                    .collect();
555                let rule = PreparedRule {
556                    rule_id,
557                    query: query.clone(),
558                    rhs_locals: *rhs_locals,
559                    actions: compiled,
560                    ruleset: *ruleset,
561                };
562                Self::check_rule_mults(&name, &rule)?;
563                self.rules.push(rule);
564            }
565            CCommand::Run {
566                ruleset,
567                limit,
568                until,
569            } => {
570                // A `:until` goal is built once. New goal nodes are rebuilt
571                // before timing starts; the driver rebuilds unconditionally
572                // before every goal observation, including when these terms
573                // already existed in a dirty graph.
574                let goal = match until {
575                    None => None,
576                    Some(g) => {
577                        let before = self.eg.node_count();
578                        let (l, _) = self.build_cterm(&g.left);
579                        let (r, _) = self.build_cterm(&g.right);
580                        if self.eg.node_count() > before {
581                            self.eg.rebuild();
582                        }
583                        Some(crate::saturate::RunGoal {
584                            left: l,
585                            right: r,
586                            equal: g.equal,
587                        })
588                    }
589                };
590                let spec = crate::saturate::RunSpec {
591                    limit: *limit as usize,
592                    ruleset: *ruleset,
593                    until: goal,
594                };
595                let t0 = std::time::Instant::now();
596                let result = match self.strategy {
597                    crate::saturate::SaturationStrategy::Naive => self.eg.saturate_spec_in(
598                        &self.rules,
599                        &self.model,
600                        &spec,
601                        &self.globals,
602                        &mut self.index_scratch,
603                    ),
604                    crate::saturate::SaturationStrategy::SemiNaive => {
605                        self.eg.saturate_semi_spec_in(
606                            &self.rules,
607                            &self.model,
608                            &spec,
609                            &self.globals,
610                            &mut self.index_scratch,
611                        )
612                    }
613                };
614                self.last_run_time = Some(t0.elapsed());
615                self.last_sat = Some(result);
616            }
617            CCommand::PrintSize(op) => {
618                let counts = self.eg.op_node_counts();
619                match op {
620                    Some(o) => println!("{}", counts[o.to_usize()]),
621                    None => {
622                        // Ops with no nodes are omitted: the builtin literal and primitive
623                        // ops would otherwise dominate the listing on every program.
624                        let mut total = 0;
625                        for (name, n) in self.eg.ops().names().zip(counts.iter()) {
626                            if *n > 0 {
627                                println!("{name}: {n}");
628                            }
629                            total += n;
630                        }
631                        println!("total: {total}");
632                    }
633                }
634            }
635            CCommand::PrintStats(file) => {
636                let stats = self.stats_snapshot();
637                match file {
638                    None => print!("{}", stats.render_text()),
639                    Some(path) => std::fs::write(path, stats.render_json()).map_err(|e| {
640                        InterpError::DeclError(format!("print-stats :file '{path}': {e}"))
641                    })?,
642                }
643            }
644            CCommand::Push(shrink) => {
645                let policy = if *shrink {
646                    ShrinkPolicy::IfOverallocated {
647                        factor: 4,
648                        headroom: 2,
649                    }
650                } else {
651                    self.shrink_policy
652                };
653                self.marks.push(Mark {
654                    token: self.eg.mark(policy),
655                    rules_len: self.rules.len(),
656                    globals_len: self.globals.len(),
657                    _phantom: std::marker::PhantomData,
658                });
659            }
660            CCommand::AntiUnify {
661                left,
662                right,
663                playouts,
664                algorithm,
665                cycle_mode,
666            } => {
667                let (l_id, _) = self.build_cterm(left);
668                let (r_id, _) = self.build_cterm(right);
669                self.eg.rebuild();
670
671                let alg = match algorithm.as_str() {
672                    "exact" => crate::au::session::AuAlgorithm::Exact,
673                    "uct" => crate::au::session::AuAlgorithm::Uct,
674                    other => {
675                        return Err(InterpError::CheckFailed(format!(
676                            "unknown AU algorithm '{other}' (expected exact or uct)"
677                        )));
678                    }
679                };
680
681                let snap = crate::au::egraph_api::AuSnapshot::new(&self.eg)
682                    .map_err(|e| InterpError::CheckFailed(format!("{e}")))?;
683
684                let config = crate::au::session::AuConfig {
685                    algorithm: alg,
686                    cycle_mode: parse_au_cycle_mode(cycle_mode)?,
687                    playouts: *playouts,
688                    ..Default::default()
689                };
690
691                let result = crate::au::session::anti_unify(&snap, l_id, r_id, &config)
692                    .map_err(|e| InterpError::CheckFailed(format!("{e}")))?;
693
694                let op_namer = |op: &crate::au::terms::TermOp<Cfg::O, Cfg::V>| match op {
695                    crate::au::terms::TermOp::EGraph(o) => self.eg.ops().info(*o).name.clone(),
696                    crate::au::terms::TermOp::Literal(_, v) => {
697                        format!("{}", self.eg.lits().get(*v))
698                    }
699                    crate::au::terms::TermOp::Variants => "Variants".to_string(),
700                };
701                let rendered = result.pretty_print_with(op_namer, 80);
702                let cr = crate::au::session::compression_ratio(
703                    &snap,
704                    snap.class_of(l_id).unwrap(),
705                    snap.class_of(r_id).unwrap(),
706                    result.size,
707                );
708
709                let completion_status = match result.completion {
710                    crate::au::session::Completion::Exact => "exact",
711                    crate::au::session::Completion::BudgetExhausted { .. } => "budget",
712                };
713                println!(
714                    "(anti-unify :size {} :cr {:.4} :completion {}\n  {})",
715                    result.size,
716                    cr,
717                    completion_status,
718                    rendered.replace('\n', "\n  ")
719                );
720            }
721            CCommand::CheckAu {
722                left,
723                right,
724                max_size,
725                playouts,
726                algorithm,
727                cycle_mode,
728            } => {
729                let (l_id, _) = self.build_cterm(left);
730                let (r_id, _) = self.build_cterm(right);
731                self.eg.rebuild();
732
733                let alg = match algorithm.as_str() {
734                    "exact" => crate::au::session::AuAlgorithm::Exact,
735                    "uct" => crate::au::session::AuAlgorithm::Uct,
736                    other => {
737                        return Err(InterpError::CheckFailed(format!(
738                            "unknown AU algorithm '{other}' (expected exact or uct)"
739                        )));
740                    }
741                };
742
743                let snap = crate::au::egraph_api::AuSnapshot::new(&self.eg)
744                    .map_err(|e| InterpError::CheckFailed(format!("{e}")))?;
745
746                let config = crate::au::session::AuConfig {
747                    algorithm: alg,
748                    cycle_mode: parse_au_cycle_mode(cycle_mode)?,
749                    playouts: *playouts,
750                    ..Default::default()
751                };
752
753                let result = crate::au::session::anti_unify(&snap, l_id, r_id, &config)
754                    .map_err(|e| InterpError::CheckFailed(format!("{e}")))?;
755
756                if result.size > *max_size {
757                    return Err(InterpError::CheckFailed(format!(
758                        "anti-unifier size {} exceeds max_size {}",
759                        result.size, max_size
760                    )));
761                }
762            }
763            CCommand::Pop => {
764                let mark = self.marks.pop().ok_or(InterpError::PopWithoutPush)?;
765                self.eg.restore(mark.token);
766                self.rules.truncate(mark.rules_len);
767                self.globals.truncate(mark.globals_len);
768            }
769        }
770        Ok(())
771    }
772
773    /// The numbers `(print-stats)` reports: the graph as it stands now, plus the counters of
774    /// the most recent run (zeroed when no run has happened).
775    fn stats_snapshot(&self) -> RunStats {
776        let sat = self.last_sat.as_ref();
777        RunStats {
778            nodes: self.eg.len(),
779            classes: self.eg.class_count(),
780            iterations: sat.map_or(0, |s| s.iterations),
781            match_steps: sat.map_or(0, |s| s.match_steps),
782            wall_time_ms: self.last_run_time.map_or(0.0, |d| d.as_secs_f64() * 1000.0),
783            saturated: sat.is_some_and(|s| s.saturated),
784            goal_met: sat.is_some_and(|s| s.goal_met),
785        }
786    }
787
788    /// Build a `CTerm` in the e-graph. Apps need no name lookup or sort check;
789    /// `CTerm::Global` intentionally retains and looks up its source name.
790    fn build_cterm(&mut self, ct: &CTerm<Cfg::O, Cfg::S, L>) -> (Cfg::G, Cfg::S) {
791        match ct {
792            CTerm::Lit(val, sort) => {
793                let lit_op = self.eg.ops().lit_op_for_sort(*sort).unwrap();
794                let vid = self.eg.intern_lit(val.clone());
795                let id = self.eg.add_lit(lit_op, vid);
796                (id, *sort)
797            }
798            CTerm::App { op, sort, children } => {
799                let child_ids: Vec<Cfg::G> =
800                    children.iter().map(|c| self.build_cterm(c).0).collect();
801                let id = self.eg.add(*op, &child_ids);
802                (id, *sort)
803            }
804            CTerm::Global(name, sort) => {
805                let (_, _, id) = self.globals.get(name).expect("global not found at runtime");
806                (self.eg.find(id), *sort)
807            }
808        }
809    }
810}
811
812/// The `(print-stats)` reading: e-graph size now, and the last run's counters.
813///
814/// Both renderings are hand-rolled. The text form is for a human reading a terminal; the
815/// JSON form is what the comparison harness parses, and it is small and fixed enough that a
816/// serialization dependency would buy nothing.
817#[derive(Clone, Copy, Debug, PartialEq)]
818pub struct RunStats {
819    pub nodes: usize,
820    pub classes: usize,
821    pub iterations: usize,
822    pub match_steps: u64,
823    pub wall_time_ms: f64,
824    pub saturated: bool,
825    pub goal_met: bool,
826}
827
828impl RunStats {
829    pub fn render_text(&self) -> String {
830        format!(
831            "nodes: {}\nclasses: {}\niterations: {}\nmatch-steps: {}\nwall-time-ms: {:.3}\n\
832             saturated: {}\ngoal-met: {}\n",
833            self.nodes,
834            self.classes,
835            self.iterations,
836            self.match_steps,
837            self.wall_time_ms,
838            self.saturated,
839            self.goal_met,
840        )
841    }
842
843    pub fn render_json(&self) -> String {
844        format!(
845            "{{\"nodes\":{},\"classes\":{},\"iterations\":{},\"match_steps\":{},\
846             \"wall_time_ms\":{:.3},\"saturated\":{},\"goal_met\":{}}}\n",
847            self.nodes,
848            self.classes,
849            self.iterations,
850            self.match_steps,
851            self.wall_time_ms,
852            self.saturated,
853            self.goal_met,
854        )
855    }
856}