Skip to main content

semi_persistent_egraph/
registry.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Sort and operator registries.
4
5use crate::containers::AppendOnlyVec;
6use crate::containers::DenseId;
7use crate::containers::IndexLike;
8use crate::containers::MapToken;
9use crate::containers::ShrinkPolicy;
10use crate::containers::SpMap;
11use crate::containers::VecToken;
12use crate::id::{ENodeKind, id_at};
13
14/// Opaque token for [`SortRegistry::mark`] / [`SortRegistry::restore`].
15#[derive(Clone, Copy, Debug)]
16pub struct SortRegistryToken(MapToken);
17
18/// Opaque token for [`OpRegistry::mark`] / [`OpRegistry::restore`]. Bundles the op log's
19/// token with the completion table's, so the two are always marked and truncated together.
20#[derive(Clone, Copy, Debug)]
21pub struct OpRegistryToken {
22    map: MapToken,
23    completion: VecToken,
24}
25
26/// Source spelling retained for associative-only operators.
27///
28/// All three variants currently use the same flat, order-preserving `Seq`
29/// representation and matching semantics. The value records whether the
30/// declaration used `:assoc-left`, `:assoc-right`, or `:assoc`; no production
31/// path branches on it after registration.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum AssocDir {
34    Left,
35    Right,
36    Both,
37}
38
39/// How an AC op's normal form bounds a summand's count (design "three independent axes").
40/// This is a unified axis carried on both `MSet` and `Set` descriptors,
41/// independent of the storage partition: the partition is derived from the clamp (`Idempotent →
42/// Set`; `None` / `Nilpotent → MSet`). See `doc/design/ac-algebraic-properties.md`.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum Clamp {
45    /// No count bound: counts stay in ℕ. Plain AC (`+`, `*`). Stored as `MSet`.
46    None,
47    /// `x∘x = x`: duplicate summands collapse to one (dedup at build via `SetCanon`). `and`, `or`.
48    /// Stored as `Set` (bare children); dedup is the correct build/recanonize canonize rule.
49    Idempotent,
50    /// `x∘x = e` (order 2), or count mod `order` in general: pairs cancel to the unit. `xor`,
51    /// `bvxor`. Requires an `identity`. Stored as `MSet` (NOT `Set`): computing count-mod-n needs
52    /// the true multiplicity, which the `Set` dedup canonize would destroy at build time; the
53    /// mod-n reduction happens during build/recanonization and is also used by completion
54    /// normalization. The NF counts are {0,1} at order 2 but the
55    /// *storage* is MSet regardless of order.
56    ///
57    /// Why `order: u8` and not a node id: the two halves of the law `xⁿ = e` have different
58    /// natures. The order `n` is pure ARITHMETIC — its entire life is being the modulus in
59    /// `count % n` (`clamp_nilpotent`, `MSetCanon::clamp_multiset`); no e-node denotes it,
60    /// so an id type would be a category error. The identity `e` IS a graph entity, and it
61    /// is stored as one — a resolved node id in the egraph's per-op `unit_node` map (as the
62    /// inverse operator is in `inverse_op`), kept OFF this descriptor because `OpKind<S>`
63    /// is generic over sorts only and cannot carry a `Cfg::G`/`Cfg::O`. The parsed
64    /// [`UnitRef`] retained here is resolved immediately by surface registration. `u8` is
65    /// the "orders are tiny" choice (xor = 2); its one known
66    /// limit is foreclosing the `bvadd(N)`-as-nilpotent-`2^N` torsion encoding for N ≥ 8 —
67    /// widen to `u32` (enum field, `MSetClamp`, the two clamp fns, the tag parser) if
68    /// bitvector modeling ever lands. Numbers for laws, ids for entities.
69    Nilpotent { order: u8 },
70}
71
72/// Parsed reference to an operator's identity (unit) element. Surface registration
73/// sort-checks and builds the actual e-node immediately, storing it in the egraph's
74/// per-op `unit_node` map; this descriptor retains the source-level form.
75#[derive(Clone, Debug)]
76pub enum UnitRef {
77    /// A literal unit (`0`, `true`, `#b0000`): its surface token and the sort to parse it at.
78    Lit { token: String },
79    /// A constructed unit (`(zero)`): the parsed surface term, built via the term builder.
80    Ctor { term: crate::ast::Term },
81}
82
83/// Signature and algebraic kind of a registered operator.
84///
85/// The `MSet`/`Set` variants carry the resolved algebra beyond the representation: an optional
86/// `identity` (unit-drop; applies to either representation), `cancellative` flag, and count
87/// clamp. Resolved unit nodes and inverse operator ids need the configured node/op id types,
88/// which `OpKind<S>` cannot carry, so the e-graph stores them in its semi-persistent
89/// `unit_node` and `inverse_op` maps. See `doc/design/ac-algebraic-properties.md`.
90#[derive(Clone, Debug)]
91pub enum OpKind<S: DenseId> {
92    Normal {
93        arg_sorts: Vec<S>,
94    },
95    Commutative {
96        arg_sorts: [S; 2],
97    },
98    A {
99        arg_sort: S,
100        dir: AssocDir,
101    },
102    /// Associative-commutative, multiset child representation (`(G, mult)`, ℕ counts). Holds
103    /// `clamp ∈ {None, Nilpotent}` — plain AC (`None`) or nilpotent (`Nilpotent`, which is stored
104    /// MSet so build/recanonization can compute the mod-n reduction from true multiplicities). Never
105    /// `Idempotent` (that is the `Set` partition).
106    MSet {
107        arg_sort: S,
108        clamp: Clamp,
109        identity: Option<UnitRef>,
110        cancellative: bool,
111    },
112    /// Associative-commutative with {0,1}-bounded counts, set child representation (bare `G`).
113    /// `clamp` is always `Idempotent` here (dedup is the build/recanonize canonize rule); the
114    /// field is kept for uniformity with `MSet` and the `op_clamp` read.
115    Set {
116        arg_sort: S,
117        clamp: Clamp,
118        identity: Option<UnitRef>,
119        cancellative: bool,
120    },
121    Lit,
122}
123
124/// Non-algebraic registration metadata for an operator: whether it was declared as a
125/// constructor, and the two extraction knobs. Separate from [`OpKind`], which carries only
126/// the algebraic shape. The surface layer parses this straight out of a declaration's tag
127/// list (`ast::Command::Function`, `ast::Variant`) and hands it to
128/// [`OpRegistry::register_kind_meta`], so there is one representation from parse to registry.
129///
130/// `Default` is the undeclared case: a plain `(function …)` — not a constructor, cost 1,
131/// extractable. Cost 1 is what the extractor charged for every node before per-op costs
132/// existed, so a program that declares no `:cost` extracts exactly as it did before.
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134pub struct OpMeta {
135    /// Declared with `(constructor …)`, or a `(datatype …)` variant. A constructor is a term
136    /// former: it behaves like a function for congruence and matching, and additionally
137    /// stamps [`FLAG_CONSTRUCTOR`](crate::node_types::FLAG_CONSTRUCTOR) on its nodes.
138    pub is_constructor: bool,
139    /// Per-node extraction cost (`:cost n`). The cost of a term is the sum over its nodes,
140    /// with an AC child of multiplicity k counted k times.
141    pub cost: u32,
142    /// `:unextractable` — the extractor never selects a node of this op.
143    pub unextractable: bool,
144}
145
146impl Default for OpMeta {
147    fn default() -> Self {
148        Self {
149            is_constructor: false,
150            cost: 1,
151            unextractable: false,
152        }
153    }
154}
155
156/// Metadata for a registered operator.
157#[derive(Clone, Debug)]
158pub struct OpInfo<S: DenseId> {
159    pub name: String,
160    pub return_sort: S,
161    pub kind: OpKind<S>,
162    pub is_constructor: bool,
163    /// Per-node extraction cost, default 1. See [`OpMeta::cost`].
164    pub cost: u32,
165    /// Excluded from extraction. See [`OpMeta::unextractable`].
166    pub unextractable: bool,
167}
168
169impl<S: DenseId> OpInfo<S> {
170    pub fn canon_class(&self) -> ENodeKind {
171        match &self.kind {
172            OpKind::Normal { arg_sorts } => match arg_sorts.len() {
173                0 => ENodeKind::Plain0,
174                1 => ENodeKind::Plain1,
175                2 => ENodeKind::Plain2,
176                3 => ENodeKind::Plain3,
177                _ => ENodeKind::PlainN,
178            },
179            OpKind::Commutative { .. } => ENodeKind::SPair,
180            OpKind::A { .. } => ENodeKind::Seq,
181            OpKind::MSet { .. } => ENodeKind::MSet,
182            OpKind::Set { .. } => ENodeKind::Set,
183            OpKind::Lit => ENodeKind::Lit,
184        }
185    }
186}
187
188/// Append-only sort registry backed by `SpMap`.
189#[derive(Debug)]
190pub struct SortRegistry<S: DenseId, const TRACK: bool> {
191    /// Positions in this log ARE sort ids, so the log's index word is the id's.
192    map: SpMap<String, (), S::Index, TRACK>,
193    builtin_count: usize,
194    concrete_count: usize,
195    _phantom: core::marker::PhantomData<S>,
196}
197
198impl<S: DenseId, const TRACK: bool> Default for SortRegistry<S, TRACK> {
199    fn default() -> Self {
200        Self::new()
201    }
202}
203
204impl<S: DenseId, const TRACK: bool> SortRegistry<S, TRACK> {
205    pub fn new() -> Self {
206        Self {
207            map: SpMap::new(),
208            builtin_count: 0,
209            concrete_count: 0,
210            _phantom: core::marker::PhantomData,
211        }
212    }
213
214    pub fn register_builtins(&mut self, sort_names: &[&str]) {
215        assert!(
216            self.map.is_empty(),
217            "register_builtins must be called on empty registry"
218        );
219        for name in sort_names {
220            self.map
221                .try_insert(name.to_string(), ())
222                .expect("registry id space exhausted for its index word");
223        }
224        self.builtin_count = self.map.len();
225        self.concrete_count = self.map.len();
226    }
227
228    pub fn intern(&mut self, name: &str) -> S {
229        if let Some(id) = self.map.id_of(&name.to_owned()) {
230            // A position already in the log came from `sort_id` below, so it is in
231            // range; re-checking costs nothing on this path and keeps one spelling.
232            return id_at::<S>(id.as_usize());
233        }
234        let id = self
235            .map
236            .try_insert(name.to_owned(), ())
237            .expect("registry id space exhausted for its index word");
238        id_at::<S>(id.as_usize())
239    }
240
241    pub fn name(&self, id: S) -> &str {
242        self.map.key(id.to_index())
243    }
244
245    pub fn is_builtin(&self, id: S) -> bool {
246        id.to_usize() < self.builtin_count
247    }
248
249    pub fn is_concrete(&self, id: S) -> bool {
250        id.to_usize() < self.concrete_count
251    }
252
253    pub fn concrete_count(&self) -> usize {
254        self.concrete_count
255    }
256
257    pub fn is_empty(&self) -> bool {
258        self.map.is_empty()
259    }
260
261    pub fn len(&self) -> usize {
262        self.map.log_len().as_usize()
263    }
264
265    pub fn id_by_name(&self, name: &str) -> Option<S> {
266        self.map
267            .id_of(&name.to_owned())
268            .map(|id| id_at::<S>(id.as_usize()))
269    }
270
271    pub fn mark(&mut self, shrink: ShrinkPolicy) -> SortRegistryToken {
272        SortRegistryToken(
273            self.map
274                .try_mark(shrink)
275                .expect("mark: frame depth is bounded by the saturation driver"),
276        )
277    }
278
279    pub fn restore(&mut self, token: SortRegistryToken) {
280        self.map
281            .try_restore(token.0)
282            .expect("restore: token minted by this container's own mark");
283    }
284}
285
286/// Which completion segment an op belongs to: the two segments of the completion column
287/// order (MSet first, then Set), plus "neither".
288#[derive(Clone, Copy, Debug, PartialEq, Eq)]
289enum CompletionKind {
290    NotCompletion,
291    MSet,
292    Set,
293}
294
295/// One op's completion bookkeeping, precomputed at registration.
296///
297/// A column index cannot be stored directly because registering an MSet op shifts every
298/// Set column up by one (the MSet segment precedes the Set segment), so a stored column
299/// would need rewriting on each later registration. The *running counts* do not have that
300/// problem: `msets`/`sets` count the ops of each kind registered up to and including this
301/// one, they are fixed the moment the entry is pushed, and both the totals (the last
302/// entry's counts) and a column (a total plus a rank) read off them in O(1).
303#[derive(Clone, Copy, Debug)]
304struct CompletionSlot {
305    kind: CompletionKind,
306    /// MSet ops registered up to and including this op.
307    msets: usize,
308    /// Set ops registered up to and including this op.
309    sets: usize,
310}
311
312#[cfg(test)]
313thread_local! {
314    /// Calls to [`OpRegistry::completion_ops`] on this thread. Lets a test pin that
315    /// `completion_column` answers out of the completion table instead of rebuilding the
316    /// column array per call, which is the regression this counter exists to catch (tests
317    /// run one per thread, so the count is per test).
318    static COMPLETION_OPS_SCANS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
319}
320
321/// Append-only operator registry backed by `SpMap`.
322#[derive(Debug)]
323pub struct OpRegistry<O: DenseId, S: DenseId, const TRACK: bool> {
324    /// Positions in this log ARE op ids, so the log's index word is the id's.
325    map: SpMap<String, OpInfo<S>, O::Index, TRACK>,
326    /// Completion bookkeeping per op, one entry per op id ([`CompletionSlot`]).
327    ///
328    /// `insert` pushes exactly one entry per op, so entry `i` describes op `i`, and the
329    /// registry's token bundle marks and restores this vector with the op log: a restore
330    /// truncates both at the same length, leaving the counts describing exactly the
331    /// surviving ops. [`completion_column`](OpRegistry::completion_column) is a read out of
332    /// this table rather than a scan of the op map, because the node-creation path calls it
333    /// once per fresh node.
334    completion: AppendOnlyVec<CompletionSlot, O::Index, TRACK>,
335    builtin_count: usize,
336    concrete_sort_count: usize,
337    _phantom: core::marker::PhantomData<O>,
338}
339
340impl<O: crate::DenseId, S: DenseId, const TRACK: bool> Default for OpRegistry<O, S, TRACK> {
341    fn default() -> Self {
342        Self::new()
343    }
344}
345
346impl<O: crate::DenseId, S: DenseId, const TRACK: bool> OpRegistry<O, S, TRACK> {
347    pub fn new() -> Self {
348        Self {
349            map: SpMap::new(),
350            completion: AppendOnlyVec::new(),
351            builtin_count: 0,
352            concrete_sort_count: 0,
353            _phantom: core::marker::PhantomData,
354        }
355    }
356
357    /// Register builtin ops from a LitModel. Must be called before any user ops.
358    /// Each LitOpDesc becomes a real OpId with OpKind::Normal.
359    /// The OpId indices match LitModel::ops() indices for eval lookup.
360    pub fn register_builtins<
361        L: crate::literal::LitVal,
362        M: crate::lit_model::LitModel<Value = L>,
363    >(
364        &mut self,
365        model: &M,
366        sorts: &SortRegistry<S, TRACK>,
367    ) {
368        assert!(
369            self.map.is_empty(),
370            "register_builtins must be called on empty registry"
371        );
372        for op_desc in model.ops() {
373            let arg_sorts: Vec<S> = op_desc
374                .arg_sorts
375                .iter()
376                .map(|name| {
377                    sorts.id_by_name(name).unwrap_or_else(|| {
378                        panic!("unknown sort '{name}' in LitOpDesc '{}'", op_desc.name)
379                    })
380                })
381                .collect();
382            let ret_sort = sorts.id_by_name(op_desc.ret_sort).unwrap_or_else(|| {
383                panic!(
384                    "unknown sort '{}' in LitOpDesc '{}'",
385                    op_desc.ret_sort, op_desc.name
386                )
387            });
388            self.insert(
389                op_desc.name,
390                ret_sort,
391                OpKind::Normal { arg_sorts },
392                OpMeta::default(),
393            );
394        }
395        // Auto-register a LitNode op for each concrete sort.
396        for sort_desc in model.sorts() {
397            let sort_id = sorts.id_by_name(sort_desc.name).unwrap();
398            let lit_name = format!("@{}", sort_desc.name);
399            self.insert(&lit_name, sort_id, OpKind::Lit, OpMeta::default());
400        }
401        self.builtin_count = self.map.log_len().as_usize();
402        self.concrete_sort_count = sorts.concrete_count();
403    }
404
405    /// Is this a builtin op (from LitModel)?
406    pub fn is_builtin(&self, id: O) -> bool {
407        id.to_usize() < self.builtin_count
408    }
409
410    /// Is this a primitive op (from LitModel::ops(), not a @-prefixed lit wrap)?
411    pub fn is_prim_op(&self, id: O) -> bool {
412        self.is_builtin(id) && !matches!(self.map.get_val(id.to_index()).kind, OpKind::Lit)
413    }
414
415    pub fn register(&mut self, name: &str, arg_sorts: &[S], return_sort: S) -> O {
416        self.insert(
417            name,
418            return_sort,
419            OpKind::Normal {
420                arg_sorts: arg_sorts.to_vec(),
421            },
422            OpMeta::default(),
423        )
424    }
425
426    pub fn register_c(&mut self, name: &str, arg_sorts: [S; 2], return_sort: S) -> O {
427        self.insert(
428            name,
429            return_sort,
430            OpKind::Commutative { arg_sorts },
431            OpMeta::default(),
432        )
433    }
434
435    pub fn register_a(&mut self, name: &str, arg_sort: S, return_sort: S, dir: AssocDir) -> O {
436        self.insert(
437            name,
438            return_sort,
439            OpKind::A { arg_sort, dir },
440            OpMeta::default(),
441        )
442    }
443
444    /// Register a plain AC (multiset) op: no identity, not cancellative. Richer algebra
445    /// (identity/cancellative) is set via the property-tag resolver (`register_with_algebra`).
446    pub fn register_mset(&mut self, name: &str, arg_sort: S, return_sort: S) -> O {
447        self.insert(
448            name,
449            return_sort,
450            OpKind::MSet {
451                arg_sort,
452                clamp: Clamp::None,
453                identity: None,
454                cancellative: false,
455            },
456            OpMeta::default(),
457        )
458    }
459
460    /// Register a plain ACI (idempotent set) op: no identity, not cancellative. This is the
461    /// `Clamp::Idempotent` case; nilpotent (MSet) comes via the property-tag resolver.
462    pub fn register_set(&mut self, name: &str, arg_sort: S, return_sort: S) -> O {
463        self.insert(
464            name,
465            return_sort,
466            OpKind::Set {
467                arg_sort,
468                clamp: Clamp::Idempotent,
469                identity: None,
470                cancellative: false,
471            },
472            OpMeta::default(),
473        )
474    }
475
476    pub fn register_lit(&mut self, name: &str, return_sort: S) -> O {
477        self.insert(name, return_sort, OpKind::Lit, OpMeta::default())
478    }
479
480    /// Register an op from a fully-resolved `OpKind`. Used by the property-tag resolver
481    /// (`sortcheck`), which builds the `MSet`/`Set` descriptor (clamp/identity/cancellative)
482    /// from the parsed tag set. The plain `register_mset`/`register_set` are the default-filled
483    /// special cases of this.
484    pub fn register_kind(&mut self, name: &str, return_sort: S, kind: OpKind<S>) -> O {
485        self.insert(name, return_sort, kind, OpMeta::default())
486    }
487
488    /// Register an op from a fully-resolved `OpKind` plus its non-algebraic metadata
489    /// (constructor-ness, `:cost`, `:unextractable`). This is the surface layer's single
490    /// registration entry point: `sortcheck::register_op` builds both descriptors from the
491    /// declaration and calls this, so constructor-ness is registration-time data rather than
492    /// a post-hoc mutation (the backing `SpMap` is append-only and has no `get_mut`).
493    pub fn register_kind_meta(
494        &mut self,
495        name: &str,
496        return_sort: S,
497        kind: OpKind<S>,
498        meta: OpMeta,
499    ) -> O {
500        self.insert(name, return_sort, kind, meta)
501    }
502
503    pub fn info(&self, id: O) -> &OpInfo<S> {
504        self.map.get_val(id.to_index())
505    }
506
507    /// The names of every registered op, in op-id order — the same order as
508    /// [`meta_table`](Self::meta_table) and `EGraph::op_node_counts`, so the three index
509    /// together.
510    pub fn names(&self) -> impl Iterator<Item = &str> + '_ {
511        self.map.iter().map(|(_, i)| i.name.as_str())
512    }
513
514    /// The non-algebraic metadata ([`OpMeta`]) of every registered op, in op-id order. Lets a
515    /// consumer index by op id instead of calling [`info`](Self::info) per node; the extractor
516    /// hoists this out of its fixpoint loop, where the per-node lookup would otherwise repeat
517    /// on every pass.
518    pub fn meta_table(&self) -> Vec<OpMeta> {
519        self.map
520            .iter()
521            .map(|(_, i)| OpMeta {
522                is_constructor: i.is_constructor,
523                cost: i.cost,
524                unextractable: i.unextractable,
525            })
526            .collect()
527    }
528
529    /// Is this op associative-commutative (`OpKind::MSet`)? Note this is `false`
530    /// for ACI ops, which are a distinct kind.
531    pub fn is_mset(&self, id: O) -> bool {
532        matches!(self.map.get_val(id.to_index()).kind, OpKind::MSet { .. })
533    }
534
535    /// Iterator over the ids of all registered AC ops. Used by AC congruence
536    /// completion to drive the per-AC-op critical-pair pass (see
537    /// `doc/design/ac-congruence-completeness.md`). Excludes ACI ops.
538    pub fn mset_ops(&self) -> impl Iterator<Item = O> + '_ {
539        self.ops_of_kind(CompletionKind::MSet)
540    }
541
542    /// The ids of the ops in one completion segment, in registration order.
543    fn ops_of_kind(&self, kind: CompletionKind) -> impl Iterator<Item = O> + '_ {
544        self.completion
545            .as_slice()
546            .iter()
547            .enumerate()
548            .filter(move |(_, slot)| slot.kind == kind)
549            .map(|(i, _)| id_at::<O>(i))
550    }
551
552    /// The number of MSet and of Set ops registered, read off the last completion slot:
553    /// every slot carries the running counts, so the totals survive a `restore` truncation
554    /// without a rescan.
555    fn completion_counts(&self) -> (usize, usize) {
556        match self.completion.as_slice().last() {
557            Some(slot) => (slot.msets, slot.sets),
558            None => (0, 0),
559        }
560    }
561
562    /// Number of registered `OpKind::MSet` ops (excludes Set). Completion supports
563    /// multiple symbols through one per-op column in each allocated class row.
564    pub fn mset_op_count(&self) -> usize {
565        self.completion_counts().0
566    }
567
568    /// Is this op a `Set` (idempotent) op? Nilpotent ops use `MSet`.
569    pub fn is_set(&self, id: O) -> bool {
570        matches!(self.map.get_val(id.to_index()).kind, OpKind::Set { .. })
571    }
572
573    /// Iterator over the ids of all registered `Set` ops (idempotent), in
574    /// registration order. The Set analogue of [`mset_ops`](Self::mset_ops).
575    pub fn set_ops(&self) -> impl Iterator<Item = O> + '_ {
576        self.ops_of_kind(CompletionKind::Set)
577    }
578
579    /// Number of registered `Set` ops.
580    pub fn set_op_count(&self) -> usize {
581        self.completion_counts().1
582    }
583
584    /// The ordered list of *completion* ops (MSet then Set, each in registration order). This
585    /// is the column → op reference array for the per-op `min_monomial` pool (design "the
586    /// column → op reference array"): `completion_ops()[k]` is the op owning pool column `k`,
587    /// and its length is the fixed row width `nb_completion`. Registration order is stable
588    /// (the backing `SpMap` is append-only, never renumbered), so a column's meaning is fixed
589    /// for the run.
590    ///
591    /// Allocates and scans every op, so it is for per-round callers (the pool builder); a
592    /// single op's column comes from [`completion_column`](Self::completion_column), which
593    /// does neither.
594    pub fn completion_ops(&self) -> Vec<O> {
595        #[cfg(test)]
596        COMPLETION_OPS_SCANS.with(|n| n.set(n.get() + 1));
597        let mut v: Vec<O> = self.mset_ops().collect();
598        v.extend(self.set_ops());
599        v
600    }
601
602    /// Number of completion ops (`nb_completion` = MSet + Set), the `min_monomial` pool row
603    /// width.
604    pub fn completion_op_count(&self) -> usize {
605        let (msets, sets) = self.completion_counts();
606        msets + sets
607    }
608
609    /// The pool column index of a completion op, or `None` if `id` is not an MSet/Set op.
610    ///
611    /// One indexed read of the per-op completion table plus, for a Set op, the MSet
612    /// total: no allocation and no scan of the op map, because
613    /// `EGraph::register_if_fresh` calls this once per node the engine creates.
614    /// The former implementation scanned the registry; current constant-factor
615    /// comparisons belong in the Criterion registration/completion workload.
616    pub fn completion_column(&self, id: O) -> Option<usize> {
617        let slot = self.completion.as_slice().get(id.to_usize())?;
618        match slot.kind {
619            CompletionKind::NotCompletion => None,
620            // Registration order within a segment is the column order, and `msets`/`sets`
621            // count this op too, so its rank in its segment is the count minus one.
622            CompletionKind::MSet => Some(slot.msets - 1),
623            CompletionKind::Set => Some(self.completion_counts().0 + slot.sets - 1),
624        }
625    }
626
627    pub fn id_by_name(&self, name: &str) -> Option<O> {
628        self.map
629            .id_of(&name.to_owned())
630            .map(|id| id_at::<O>(id.as_usize()))
631    }
632
633    pub fn lit_op_for_sort(&self, sort: S) -> Option<O> {
634        self.map
635            .iter()
636            .enumerate()
637            .find(|(_, (_, info))| matches!(info.kind, OpKind::Lit) && info.return_sort == sort)
638            .map(|(i, _)| id_at::<O>(i))
639    }
640
641    /// Find a unary op that takes `from` and returns `to` (e.g. ILit: IBig → IExpr).
642    pub fn find_lift_op(&self, from: S, to: S) -> Option<O> {
643        self.map
644            .iter()
645            .enumerate()
646            .find(|(_, (_, info))| {
647                info.return_sort == to
648                    && matches!(&info.kind, OpKind::Normal { arg_sorts } if arg_sorts.len() == 1 && arg_sorts[0] == from)
649            })
650            .map(|(i, _)| id_at::<O>(i))
651    }
652
653    fn insert(&mut self, name: &str, return_sort: S, kind: OpKind<S>, meta: OpMeta) -> O {
654        assert!(
655            !self.map.contains_key(&name.to_owned()),
656            "operator '{name}' already registered"
657        );
658        if self.builtin_count > 0 && return_sort.to_usize() < self.concrete_sort_count {
659            panic!(
660                "operator '{name}' cannot return concrete sort (index {})",
661                return_sort.to_usize()
662            );
663        }
664        let completion_kind = match kind {
665            OpKind::MSet { .. } => CompletionKind::MSet,
666            OpKind::Set { .. } => CompletionKind::Set,
667            _ => CompletionKind::NotCompletion,
668        };
669        let id = self
670            .map
671            .try_insert(
672                name.to_owned(),
673                OpInfo {
674                    name: name.to_owned(),
675                    return_sort,
676                    kind,
677                    is_constructor: meta.is_constructor,
678                    cost: meta.cost,
679                    unextractable: meta.unextractable,
680                },
681            )
682            .expect("registry id space exhausted for its index word");
683        let (msets, sets) = self.completion_counts();
684        let slot = CompletionSlot {
685            kind: completion_kind,
686            msets: msets + usize::from(completion_kind == CompletionKind::MSet),
687            sets: sets + usize::from(completion_kind == CompletionKind::Set),
688        };
689        let slot_id = self
690            .completion
691            .try_push(slot)
692            .expect("completion table shares the op log's index word");
693        debug_assert_eq!(
694            slot_id.as_usize(),
695            id.as_usize(),
696            "one completion slot per op, pushed in op-id order"
697        );
698        id_at::<O>(id.as_usize())
699    }
700
701    pub fn mark(&mut self, shrink: ShrinkPolicy) -> OpRegistryToken {
702        OpRegistryToken {
703            map: self
704                .map
705                .try_mark(shrink)
706                .expect("mark: frame depth is bounded by the saturation driver"),
707            completion: self
708                .completion
709                .try_mark(shrink)
710                .expect("mark: frame depth is bounded by the saturation driver"),
711        }
712    }
713
714    pub fn restore(&mut self, token: OpRegistryToken) {
715        self.map
716            .try_restore(token.map)
717            .expect("restore: token minted by this container's own mark");
718        self.completion
719            .try_restore(token.completion)
720            .expect("restore: token minted by this container's own mark");
721        debug_assert_eq!(
722            self.completion.len().as_usize(),
723            self.map.log_len().as_usize(),
724            "the completion table is truncated with the op log"
725        );
726    }
727}
728
729// ---------------------------------------------------------------------------
730// Rule registry
731// ---------------------------------------------------------------------------
732
733/// Opaque token for [`RuleRegistry::mark`] / [`RuleRegistry::restore`].
734#[derive(Clone, Copy, Debug)]
735pub struct RuleRegistryToken(MapToken);
736
737/// Metadata for a registered rewrite rule.
738#[derive(Clone, Debug)]
739pub struct RuleInfo {
740    pub name: String,
741    pub lhs: String,
742    pub rhs: String,
743}
744
745/// Append-only rule registry backed by `SpMap`.
746pub struct RuleRegistry<const TRACK: bool> {
747    /// Positions in this log ARE rule ids, so the log's index word is `RuleId`'s — a
748    /// `u16`, since `RuleId` is 15-bit.
749    map: SpMap<String, RuleInfo, <crate::id::RuleId as DenseId>::Index, TRACK>,
750}
751
752impl<const TRACK: bool> Default for RuleRegistry<TRACK> {
753    fn default() -> Self {
754        Self::new()
755    }
756}
757
758impl<const TRACK: bool> RuleRegistry<TRACK> {
759    pub fn new() -> Self {
760        Self { map: SpMap::new() }
761    }
762
763    pub fn register(&mut self, name: &str, lhs: &str, rhs: &str) -> crate::id::RuleId {
764        let id = self
765            .map
766            .try_insert(
767                name.to_owned(),
768                RuleInfo {
769                    name: name.to_owned(),
770                    lhs: lhs.to_owned(),
771                    rhs: rhs.to_owned(),
772                },
773            )
774            .expect("registry id space exhausted for its index word");
775        id_at::<crate::id::RuleId>(id.as_usize())
776    }
777
778    pub fn info(&self, id: crate::id::RuleId) -> &RuleInfo {
779        self.map.get_val(id.to_index())
780    }
781
782    pub fn name(&self, id: crate::id::RuleId) -> &str {
783        self.map.key(id.to_index())
784    }
785
786    pub fn len(&self) -> usize {
787        self.map.log_len().as_usize()
788    }
789
790    pub fn is_empty(&self) -> bool {
791        self.map.is_empty()
792    }
793
794    pub fn id_by_name(&self, name: &str) -> Option<crate::id::RuleId> {
795        self.map
796            .id_of(&name.to_owned())
797            .map(|id| id_at::<crate::id::RuleId>(id.as_usize()))
798    }
799
800    pub fn mark(&mut self, shrink: ShrinkPolicy) -> RuleRegistryToken {
801        RuleRegistryToken(
802            self.map
803                .try_mark(shrink)
804                .expect("mark: frame depth is bounded by the saturation driver"),
805        )
806    }
807
808    pub fn restore(&mut self, token: RuleRegistryToken) {
809        self.map
810            .try_restore(token.0)
811            .expect("restore: token minted by this container's own mark");
812    }
813}
814
815// ---------------------------------------------------------------------------
816// Axiom registry
817// ---------------------------------------------------------------------------
818
819/// Opaque token for [`AxiomRegistry::mark`] / [`AxiomRegistry::restore`].
820#[derive(Clone, Copy, Debug)]
821pub struct AxiomRegistryToken(MapToken);
822
823/// Metadata for a registered axiom (user-asserted equality).
824#[derive(Clone, Debug)]
825pub struct AxiomInfo<G: Copy> {
826    pub name: String,
827    pub lhs: G,
828    pub rhs: G,
829}
830
831/// Append-only axiom registry backed by `SpMap`.
832pub struct AxiomRegistry<G: Copy + DenseId, const TRACK: bool> {
833    /// Positions in this log ARE axiom ids, so the log's index word is `AxiomId`'s — a
834    /// `u16`, since `AxiomId` is 15-bit. Note this is NOT `G::Index`: `G` is the id type
835    /// of the *terms* an axiom relates, not of the axiom.
836    map: SpMap<String, AxiomInfo<G>, <crate::id::AxiomId as DenseId>::Index, TRACK>,
837}
838
839impl<G: Copy + DenseId, const TRACK: bool> Default for AxiomRegistry<G, TRACK> {
840    fn default() -> Self {
841        Self::new()
842    }
843}
844
845impl<G: Copy + DenseId, const TRACK: bool> AxiomRegistry<G, TRACK> {
846    pub fn new() -> Self {
847        Self { map: SpMap::new() }
848    }
849
850    pub fn register(&mut self, name: &str, lhs: G, rhs: G) -> crate::id::AxiomId {
851        let id = self
852            .map
853            .try_insert(
854                name.to_owned(),
855                AxiomInfo {
856                    name: name.to_owned(),
857                    lhs,
858                    rhs,
859                },
860            )
861            .expect("registry id space exhausted for its index word");
862        id_at::<crate::id::AxiomId>(id.as_usize())
863    }
864
865    pub fn info(&self, id: crate::id::AxiomId) -> &AxiomInfo<G> {
866        self.map.get_val(id.to_index())
867    }
868
869    pub fn name(&self, id: crate::id::AxiomId) -> &str {
870        self.map.key(id.to_index())
871    }
872
873    pub fn len(&self) -> usize {
874        self.map.log_len().as_usize()
875    }
876
877    pub fn is_empty(&self) -> bool {
878        self.map.is_empty()
879    }
880
881    pub fn mark(&mut self, shrink: ShrinkPolicy) -> AxiomRegistryToken {
882        AxiomRegistryToken(
883            self.map
884                .try_mark(shrink)
885                .expect("mark: frame depth is bounded by the saturation driver"),
886        )
887    }
888
889    pub fn restore(&mut self, token: AxiomRegistryToken) {
890        self.map
891            .try_restore(token.0)
892            .expect("restore: token minted by this container's own mark");
893    }
894}
895
896#[cfg(test)]
897mod tests {
898    use super::*;
899    use crate::id::{OpId, RuleId, SortId};
900
901    type SR = SortRegistry<SortId, false>;
902    type OR = OpRegistry<OpId, SortId, false>;
903
904    // -- Id-space exhaustion --
905    //
906    // `RuleId` is 15-bit while its log's index word is `u16`, so the log can hold a
907    // position (up to 65534) that no `RuleId` can name. That gap is why the mint has
908    // to be checked before mutation: position 32768 must be rejected without adding
909    // an unnameable registry entry.
910
911    /// `RuleId`'s id bound, asserted rather than assumed: `id_bound()` is a spec
912    /// function, so exec code reads the bound off `try_new`'s boundary.
913    fn rule_id_bound() -> usize {
914        let bound = 1usize << 15; // define_id15!
915        assert!(RuleId::try_new(bound - 1).is_some(), "bound is too high");
916        assert!(RuleId::try_new(bound).is_none(), "bound is too low");
917        bound
918    }
919
920    /// Every position below the id bound mints its own distinct id.
921    #[test]
922    fn rule_registry_fills_its_id_space_without_aliasing() {
923        let bound = rule_id_bound();
924        let mut r: RuleRegistry<false> = RuleRegistry::new();
925        for i in 0..bound {
926            assert_eq!(r.register(&format!("r{i}"), "l", "r").to_usize(), i);
927        }
928        assert_eq!(r.len(), bound);
929        // The last id round-trips, so no earlier entry was overwritten.
930        assert_eq!(
931            r.name(id_at::<RuleId>(bound - 1)),
932            format!("r{}", bound - 1)
933        );
934        assert_eq!(r.id_by_name("r0").unwrap().to_usize(), 0);
935    }
936
937    /// One past the bound panics rather than aliasing rule 0.
938    #[test]
939    #[should_panic(expected = "the id space is exhausted")]
940    fn rule_registry_past_its_id_space_panics() {
941        let bound = rule_id_bound();
942        let mut r: RuleRegistry<false> = RuleRegistry::new();
943        for i in 0..=bound {
944            r.register(&format!("r{i}"), "l", "r");
945        }
946    }
947
948    #[test]
949    fn builtin_sorts() {
950        let mut r = SR::new();
951        r.register_builtins(&["Bool", "Int", "Real"]);
952        assert_eq!(r.name(SortId::new(0)), "Bool");
953        assert_eq!(r.name(SortId::new(1)), "Int");
954        assert_eq!(r.name(SortId::new(2)), "Real");
955        assert!(r.is_builtin(SortId::new(0)));
956        assert!(r.is_builtin(SortId::new(2)));
957        let user = r.intern("BitVec");
958        assert!(!r.is_builtin(user));
959    }
960
961    #[test]
962    fn sort_intern_dedup() {
963        let mut r = SR::new();
964        let a = r.intern("BitVec");
965        let b = r.intern("BitVec");
966        assert_eq!(a, b);
967    }
968
969    #[test]
970    fn canon_class_all_kinds() {
971        let mut sorts = SR::new();
972        let bool_sort = sorts.intern("Bool");
973        let int_sort = sorts.intern("Int");
974
975        let mut ops = OR::new();
976        let lit = ops.register_lit("BLit", bool_sort);
977        let not = ops.register("Not", &[bool_sort], bool_sort);
978        let ite = ops.register("ITE", &[bool_sort, int_sort, int_sort], int_sort);
979        let eq = ops.register_c("Eq", [int_sort, int_sort], bool_sort);
980        let sub = ops.register_a("Sub", int_sort, int_sort, AssocDir::Left);
981        let add = ops.register_mset("Add", int_sort, int_sort);
982        let and = ops.register_set("And", bool_sort, bool_sort);
983
984        assert_eq!(ops.info(lit).canon_class(), ENodeKind::Lit);
985        assert_eq!(ops.info(not).canon_class(), ENodeKind::Plain1);
986        assert_eq!(ops.info(ite).canon_class(), ENodeKind::Plain3);
987        assert_eq!(ops.info(eq).canon_class(), ENodeKind::SPair);
988        assert_eq!(ops.info(sub).canon_class(), ENodeKind::Seq);
989        assert_eq!(ops.info(add).canon_class(), ENodeKind::MSet);
990        assert_eq!(ops.info(and).canon_class(), ENodeKind::Set);
991    }
992
993    #[test]
994    fn plain0_for_constants() {
995        let int_sort = SortId::new(1);
996        let mut ops = OR::new();
997        let zero = ops.register("Zero", &[], int_sort);
998        assert_eq!(ops.info(zero).canon_class(), ENodeKind::Plain0);
999    }
1000
1001    #[test]
1002    fn plainn_for_high_arity() {
1003        let int_sort = SortId::new(1);
1004        let mut ops = OR::new();
1005        let f = ops.register("F4", &[int_sort; 4], int_sort);
1006        assert_eq!(ops.info(f).canon_class(), ENodeKind::PlainN);
1007    }
1008
1009    #[test]
1010    fn id_by_name() {
1011        let int_sort = SortId::new(1);
1012        let mut ops = OR::new();
1013        let add = ops.register_mset("Add", int_sort, int_sort);
1014        assert_eq!(ops.id_by_name("Add"), Some(add));
1015        assert_eq!(ops.id_by_name("nonexistent"), None);
1016    }
1017
1018    #[test]
1019    #[should_panic(expected = "already registered")]
1020    fn duplicate_name_panics() {
1021        let int_sort = SortId::new(1);
1022        let mut ops = OR::new();
1023        ops.register_mset("Add", int_sort, int_sort);
1024        ops.register_mset("Add", int_sort, int_sort);
1025    }
1026
1027    #[test]
1028    fn mset_ops_lists_only_mset() {
1029        let mut sorts = SR::new();
1030        let bool_sort = sorts.intern("Bool");
1031        let int_sort = sorts.intern("Int");
1032
1033        let mut ops = OR::new();
1034        ops.register("Not", &[bool_sort], bool_sort); // Normal
1035        ops.register_c("Eq", [int_sort, int_sort], bool_sort); // Commutative
1036        ops.register_a("Sub", int_sort, int_sort, AssocDir::Left); // A
1037        let add = ops.register_mset("Add", int_sort, int_sort); // AC
1038        let mul = ops.register_mset("Mul", int_sort, int_sort); // AC
1039        ops.register_set("And", bool_sort, bool_sort); // ACI — must be excluded
1040
1041        // mset_ops yields exactly the two MSet ids, and is_mset agrees per-op.
1042        let mut mset_ids: Vec<OpId> = ops.mset_ops().collect();
1043        mset_ids.sort();
1044        assert_eq!(mset_ids, vec![add, mul]);
1045
1046        assert!(ops.is_mset(add));
1047        assert!(ops.is_mset(mul));
1048        // ACI is a distinct kind — not AC.
1049        assert!(!ops.is_mset(ops.id_by_name("And").unwrap()));
1050        assert!(!ops.is_mset(ops.id_by_name("Sub").unwrap()));
1051        assert!(!ops.is_mset(ops.id_by_name("Not").unwrap()));
1052    }
1053
1054    #[test]
1055    fn mset_ops_empty_when_none_registered() {
1056        let int_sort = SortId::new(1);
1057        let mut ops = OR::new();
1058        ops.register("F", &[int_sort], int_sort);
1059        assert_eq!(ops.mset_ops().count(), 0);
1060    }
1061
1062    #[test]
1063    fn completion_ops_mset_then_set_in_registration_order() {
1064        let mut sorts = SR::new();
1065        let bool_sort = sorts.intern("Bool");
1066        let int_sort = sorts.intern("Int");
1067
1068        let mut ops = OR::new();
1069        let add = ops.register_mset("Add", int_sort, int_sort);
1070        let and = ops.register_set("And", bool_sort, bool_sort);
1071        let mul = ops.register_mset("Mul", int_sort, int_sort);
1072        let or = ops.register_set("Or", bool_sort, bool_sort);
1073        ops.register("Not", &[bool_sort], bool_sort); // non-completion op, excluded
1074
1075        // completion_ops = all MSet (registration order) then all Set (registration order).
1076        assert_eq!(ops.completion_ops(), vec![add, mul, and, or]);
1077        assert_eq!(ops.completion_op_count(), 4);
1078        assert_eq!(ops.set_op_count(), 2);
1079        assert_eq!(ops.mset_op_count(), 2);
1080
1081        // column() is the position in that array; non-completion ops have none.
1082        assert_eq!(ops.completion_column(add), Some(0));
1083        assert_eq!(ops.completion_column(mul), Some(1));
1084        assert_eq!(ops.completion_column(and), Some(2));
1085        assert_eq!(ops.completion_column(or), Some(3));
1086        assert_eq!(ops.completion_column(ops.id_by_name("Not").unwrap()), None);
1087
1088        // is_set agrees.
1089        assert!(ops.is_set(and) && ops.is_set(or));
1090        assert!(!ops.is_set(add));
1091    }
1092
1093    /// The column of a registered op is a table read: no call to `completion_ops`, hence no
1094    /// allocation and no rescan of the op map, however many times it is asked. This is the
1095    /// property `EGraph::register_if_fresh` depends on — it asks once per node created.
1096    #[test]
1097    fn completion_column_does_not_rebuild_the_column_array() {
1098        let mut sorts = SR::new();
1099        let bool_sort = sorts.intern("Bool");
1100        let int_sort = sorts.intern("Int");
1101
1102        let mut ops = OR::new();
1103        let add = ops.register_mset("Add", int_sort, int_sort);
1104        let and = ops.register_set("And", bool_sort, bool_sort);
1105        let not = ops.register("Not", &[bool_sort], bool_sort);
1106
1107        let scans = || COMPLETION_OPS_SCANS.with(|n| n.get());
1108        let before = scans();
1109        for _ in 0..1000 {
1110            assert_eq!(ops.completion_column(add), Some(0));
1111            assert_eq!(ops.completion_column(and), Some(1));
1112            assert_eq!(ops.completion_column(not), None);
1113            assert_eq!(ops.completion_op_count(), 2);
1114        }
1115        assert_eq!(
1116            scans(),
1117            before,
1118            "completion_column rebuilt the column array"
1119        );
1120
1121        // The counter does fire for the array itself, so the assertion above is not vacuous.
1122        let _ = ops.completion_ops();
1123        assert_eq!(scans(), before + 1);
1124    }
1125
1126    /// Restore truncates the completion table with the op log: columns and counts after a
1127    /// restore are the ones the surviving ops alone would produce, and ids registered next
1128    /// reuse the freed columns. Registering an MSet op after a Set op is the case that moves
1129    /// existing Set columns, so the table cannot cache columns directly.
1130    #[test]
1131    fn completion_columns_restore_with_the_op_log() {
1132        type TrackedOR = OpRegistry<OpId, SortId, true>;
1133        let mut sorts = SR::new();
1134        let bool_sort = sorts.intern("Bool");
1135        let int_sort = sorts.intern("Int");
1136
1137        let mut ops = TrackedOR::new();
1138        let add = ops.register_mset("Add", int_sort, int_sort);
1139        let and = ops.register_set("And", bool_sort, bool_sort);
1140        assert_eq!(
1141            (ops.completion_column(add), ops.completion_column(and)),
1142            (Some(0), Some(1))
1143        );
1144
1145        let token = ops.mark(ShrinkPolicy::Never);
1146        let mul = ops.register_mset("Mul", int_sort, int_sort);
1147        let or = ops.register_set("Or", bool_sort, bool_sort);
1148        // The new MSet op takes column 1, pushing every Set op up one.
1149        assert_eq!(ops.completion_ops(), vec![add, mul, and, or]);
1150        assert_eq!(ops.completion_column(mul), Some(1));
1151        assert_eq!(ops.completion_column(and), Some(2));
1152        assert_eq!(ops.completion_column(or), Some(3));
1153        assert_eq!(ops.completion_op_count(), 4);
1154
1155        ops.restore(token);
1156        assert_eq!(ops.completion_ops(), vec![add, and]);
1157        assert_eq!(ops.completion_column(add), Some(0));
1158        assert_eq!(ops.completion_column(and), Some(1));
1159        assert_eq!(ops.mset_op_count(), 1);
1160        assert_eq!(ops.set_op_count(), 1);
1161        assert_eq!(ops.completion_op_count(), 2);
1162        // The restored ids are unregistered, so their columns are gone with them.
1163        assert_eq!(ops.completion_column(mul), None);
1164        assert_eq!(ops.completion_column(or), None);
1165
1166        // Registering again after the restore mints the same ids and columns as before.
1167        let mul2 = ops.register_mset("Mul", int_sort, int_sort);
1168        assert_eq!(mul2, mul);
1169        assert_eq!(ops.completion_column(mul2), Some(1));
1170        assert_eq!(ops.completion_column(and), Some(2));
1171    }
1172
1173    #[test]
1174    fn completion_ops_empty_when_none() {
1175        let int_sort = SortId::new(1);
1176        let mut ops = OR::new();
1177        ops.register("F", &[int_sort], int_sort);
1178        assert_eq!(ops.completion_ops(), Vec::<OpId>::new());
1179        assert_eq!(ops.completion_op_count(), 0);
1180    }
1181}