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/// Flattening direction for variadic sequence operators.
27///
28/// `Left` folds and flattens through the first child, `Right` through the last,
29/// and `Both` through every nested same-op child. All preserve child order.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum AssocDir {
32    Left,
33    Right,
34    Both,
35}
36
37/// How an AC op's normal form bounds a summand's count (design "three independent axes").
38/// This is a unified axis carried on both `MSet` and `Set` descriptors,
39/// independent of the storage partition: the partition is derived from the clamp (`Idempotent →
40/// Set`; `None` / `Nilpotent → MSet`). See `doc/design/ac-algebraic-properties.md`.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum Clamp {
43    /// No count bound: counts stay in ℕ. Plain AC (`+`, `*`). Stored as `MSet`.
44    None,
45    /// `x∘x = x`: duplicate summands collapse to one (dedup at build via `SetCanon`). `and`, `or`.
46    /// Stored as `Set` (bare children); dedup is the correct build/recanonize canonize rule.
47    Idempotent,
48    /// `x∘x = e` (order 2), or count mod `order` in general: pairs cancel to the unit. `xor`,
49    /// `bvxor`. Requires an `identity`. Stored as `MSet` (NOT `Set`): computing count-mod-n needs
50    /// the true multiplicity, which the `Set` dedup canonize would destroy at build time; the
51    /// mod-n reduction happens during build/recanonization and is also used by completion
52    /// normalization. The NF counts are {0,1} at order 2 but the
53    /// *storage* is MSet regardless of order.
54    ///
55    /// Why `order: u8` and not a node id: the two halves of the law `xⁿ = e` have different
56    /// natures. The order `n` is pure ARITHMETIC — its entire life is being the modulus in
57    /// `count % n` (`clamp_nilpotent`, `MSetCanon::clamp_multiset`); no e-node denotes it,
58    /// so an id type would be a category error. The identity `e` IS a graph entity, and it
59    /// is stored as one — a resolved node id in the egraph's per-op `unit_node` map (as the
60    /// inverse operator is in `inverse_op`), kept OFF this descriptor because `OpKind<S>`
61    /// is generic over sorts only and cannot carry a `Cfg::G`/`Cfg::O`. The parsed
62    /// [`UnitRef`] retained here is resolved immediately by surface registration. `u8` is
63    /// the "orders are tiny" choice (xor = 2); its one known
64    /// limit is foreclosing the `bvadd(N)`-as-nilpotent-`2^N` torsion encoding for N ≥ 8 —
65    /// widen to `u32` (enum field, `MSetClamp`, the two clamp fns, the tag parser) if
66    /// bitvector modeling ever lands. Numbers for laws, ids for entities.
67    Nilpotent { order: u8 },
68}
69
70/// Parsed reference to an operator's identity (unit) element. Surface registration
71/// sort-checks and builds the actual e-node immediately, storing it in the egraph's
72/// per-op `unit_node` map; this descriptor retains the source-level form.
73#[derive(Clone, Debug)]
74pub enum UnitRef {
75    /// A literal unit (`0`, `true`, `#b0000`): its surface token and the sort to parse it at.
76    Lit { token: String },
77    /// A constructed unit (`(zero)`): the parsed surface term, built via the term builder.
78    Ctor { term: crate::ast::Term },
79}
80
81/// Signature and algebraic kind of a registered operator.
82///
83/// The `MSet`/`Set` variants carry the resolved algebra beyond the representation: an optional
84/// `identity` (unit-drop; applies to either representation), `cancellative` flag, and count
85/// clamp. Resolved unit nodes and inverse operator ids need the configured node/op id types,
86/// which `OpKind<S>` cannot carry, so the e-graph stores them in its semi-persistent
87/// `unit_node` and `inverse_op` maps. See `doc/design/ac-algebraic-properties.md`.
88#[derive(Clone, Debug)]
89pub enum OpKind<S: DenseId> {
90    Normal {
91        arg_sorts: Vec<S>,
92    },
93    /// Binary commutative operator. Both argument sorts are equal; the return sort may differ.
94    Commutative {
95        arg_sorts: [S; 2],
96    },
97    /// Associative operator closed over one sort: `arg_sort` equals `OpInfo::return_sort`.
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        match &kind {
659            OpKind::Commutative { arg_sorts } => assert!(
660                arg_sorts[0] == arg_sorts[1],
661                "commutative operator '{name}' must use the same sort for both arguments"
662            ),
663            OpKind::A { arg_sort, .. }
664            | OpKind::MSet { arg_sort, .. }
665            | OpKind::Set { arg_sort, .. } => assert!(
666                *arg_sort == return_sort,
667                "associative operator '{name}' must use the same argument and return sort"
668            ),
669            OpKind::Normal { .. } | OpKind::Lit => {}
670        }
671        if self.builtin_count > 0 && return_sort.to_usize() < self.concrete_sort_count {
672            panic!(
673                "operator '{name}' cannot return concrete sort (index {})",
674                return_sort.to_usize()
675            );
676        }
677        let completion_kind = match kind {
678            OpKind::MSet { .. } => CompletionKind::MSet,
679            OpKind::Set { .. } => CompletionKind::Set,
680            _ => CompletionKind::NotCompletion,
681        };
682        let id = self
683            .map
684            .try_insert(
685                name.to_owned(),
686                OpInfo {
687                    name: name.to_owned(),
688                    return_sort,
689                    kind,
690                    is_constructor: meta.is_constructor,
691                    cost: meta.cost,
692                    unextractable: meta.unextractable,
693                },
694            )
695            .expect("registry id space exhausted for its index word");
696        let (msets, sets) = self.completion_counts();
697        let slot = CompletionSlot {
698            kind: completion_kind,
699            msets: msets + usize::from(completion_kind == CompletionKind::MSet),
700            sets: sets + usize::from(completion_kind == CompletionKind::Set),
701        };
702        let slot_id = self
703            .completion
704            .try_push(slot)
705            .expect("completion table shares the op log's index word");
706        debug_assert_eq!(
707            slot_id.as_usize(),
708            id.as_usize(),
709            "one completion slot per op, pushed in op-id order"
710        );
711        id_at::<O>(id.as_usize())
712    }
713
714    pub fn mark(&mut self, shrink: ShrinkPolicy) -> OpRegistryToken {
715        OpRegistryToken {
716            map: self
717                .map
718                .try_mark(shrink)
719                .expect("mark: frame depth is bounded by the saturation driver"),
720            completion: self
721                .completion
722                .try_mark(shrink)
723                .expect("mark: frame depth is bounded by the saturation driver"),
724        }
725    }
726
727    pub fn restore(&mut self, token: OpRegistryToken) {
728        self.map
729            .try_restore(token.map)
730            .expect("restore: token minted by this container's own mark");
731        self.completion
732            .try_restore(token.completion)
733            .expect("restore: token minted by this container's own mark");
734        debug_assert_eq!(
735            self.completion.len().as_usize(),
736            self.map.log_len().as_usize(),
737            "the completion table is truncated with the op log"
738        );
739    }
740}
741
742// ---------------------------------------------------------------------------
743// Rule registry
744// ---------------------------------------------------------------------------
745
746/// Opaque token for [`RuleRegistry::mark`] / [`RuleRegistry::restore`].
747#[derive(Clone, Copy, Debug)]
748pub struct RuleRegistryToken(MapToken);
749
750/// Metadata for a registered rewrite rule.
751#[derive(Clone, Debug)]
752pub struct RuleInfo {
753    pub name: String,
754    pub lhs: String,
755    pub rhs: String,
756}
757
758/// Append-only rule registry backed by `SpMap`.
759pub struct RuleRegistry<const TRACK: bool> {
760    /// Positions in this log ARE rule ids, so the log's index word is `RuleId`'s — a
761    /// `u16`, since `RuleId` is 15-bit.
762    map: SpMap<String, RuleInfo, <crate::id::RuleId as DenseId>::Index, TRACK>,
763}
764
765impl<const TRACK: bool> Default for RuleRegistry<TRACK> {
766    fn default() -> Self {
767        Self::new()
768    }
769}
770
771impl<const TRACK: bool> RuleRegistry<TRACK> {
772    pub fn new() -> Self {
773        Self { map: SpMap::new() }
774    }
775
776    pub fn register(&mut self, name: &str, lhs: &str, rhs: &str) -> crate::id::RuleId {
777        let id = self
778            .map
779            .try_insert(
780                name.to_owned(),
781                RuleInfo {
782                    name: name.to_owned(),
783                    lhs: lhs.to_owned(),
784                    rhs: rhs.to_owned(),
785                },
786            )
787            .expect("registry id space exhausted for its index word");
788        id_at::<crate::id::RuleId>(id.as_usize())
789    }
790
791    pub fn info(&self, id: crate::id::RuleId) -> &RuleInfo {
792        self.map.get_val(id.to_index())
793    }
794
795    pub fn name(&self, id: crate::id::RuleId) -> &str {
796        self.map.key(id.to_index())
797    }
798
799    pub fn len(&self) -> usize {
800        self.map.log_len().as_usize()
801    }
802
803    pub fn is_empty(&self) -> bool {
804        self.map.is_empty()
805    }
806
807    pub fn id_by_name(&self, name: &str) -> Option<crate::id::RuleId> {
808        self.map
809            .id_of(&name.to_owned())
810            .map(|id| id_at::<crate::id::RuleId>(id.as_usize()))
811    }
812
813    pub fn mark(&mut self, shrink: ShrinkPolicy) -> RuleRegistryToken {
814        RuleRegistryToken(
815            self.map
816                .try_mark(shrink)
817                .expect("mark: frame depth is bounded by the saturation driver"),
818        )
819    }
820
821    pub fn restore(&mut self, token: RuleRegistryToken) {
822        self.map
823            .try_restore(token.0)
824            .expect("restore: token minted by this container's own mark");
825    }
826}
827
828// ---------------------------------------------------------------------------
829// Axiom registry
830// ---------------------------------------------------------------------------
831
832/// Opaque token for [`AxiomRegistry::mark`] / [`AxiomRegistry::restore`].
833#[derive(Clone, Copy, Debug)]
834pub struct AxiomRegistryToken(MapToken);
835
836/// Metadata for a registered axiom (user-asserted equality).
837#[derive(Clone, Debug)]
838pub struct AxiomInfo<G: Copy> {
839    pub name: String,
840    pub lhs: G,
841    pub rhs: G,
842}
843
844/// Append-only axiom registry backed by `SpMap`.
845pub struct AxiomRegistry<G: Copy + DenseId, const TRACK: bool> {
846    /// Positions in this log ARE axiom ids, so the log's index word is `AxiomId`'s — a
847    /// `u16`, since `AxiomId` is 15-bit. Note this is NOT `G::Index`: `G` is the id type
848    /// of the *terms* an axiom relates, not of the axiom.
849    map: SpMap<String, AxiomInfo<G>, <crate::id::AxiomId as DenseId>::Index, TRACK>,
850}
851
852impl<G: Copy + DenseId, const TRACK: bool> Default for AxiomRegistry<G, TRACK> {
853    fn default() -> Self {
854        Self::new()
855    }
856}
857
858impl<G: Copy + DenseId, const TRACK: bool> AxiomRegistry<G, TRACK> {
859    pub fn new() -> Self {
860        Self { map: SpMap::new() }
861    }
862
863    pub fn register(&mut self, name: &str, lhs: G, rhs: G) -> crate::id::AxiomId {
864        let id = self
865            .map
866            .try_insert(
867                name.to_owned(),
868                AxiomInfo {
869                    name: name.to_owned(),
870                    lhs,
871                    rhs,
872                },
873            )
874            .expect("registry id space exhausted for its index word");
875        id_at::<crate::id::AxiomId>(id.as_usize())
876    }
877
878    pub fn info(&self, id: crate::id::AxiomId) -> &AxiomInfo<G> {
879        self.map.get_val(id.to_index())
880    }
881
882    pub fn name(&self, id: crate::id::AxiomId) -> &str {
883        self.map.key(id.to_index())
884    }
885
886    pub fn len(&self) -> usize {
887        self.map.log_len().as_usize()
888    }
889
890    pub fn is_empty(&self) -> bool {
891        self.map.is_empty()
892    }
893
894    pub fn mark(&mut self, shrink: ShrinkPolicy) -> AxiomRegistryToken {
895        AxiomRegistryToken(
896            self.map
897                .try_mark(shrink)
898                .expect("mark: frame depth is bounded by the saturation driver"),
899        )
900    }
901
902    pub fn restore(&mut self, token: AxiomRegistryToken) {
903        self.map
904            .try_restore(token.0)
905            .expect("restore: token minted by this container's own mark");
906    }
907}
908
909#[cfg(test)]
910mod tests {
911    use super::*;
912    use crate::id::{OpId, RuleId, SortId};
913
914    type SR = SortRegistry<SortId, false>;
915    type OR = OpRegistry<OpId, SortId, false>;
916
917    // -- Id-space exhaustion --
918    //
919    // `RuleId` is 15-bit while its log's index word is `u16`, so the log can hold a
920    // position (up to 65534) that no `RuleId` can name. That gap is why the mint has
921    // to be checked before mutation: position 32768 must be rejected without adding
922    // an unnameable registry entry.
923
924    /// `RuleId`'s id bound, asserted rather than assumed: `id_bound()` is a spec
925    /// function, so exec code reads the bound off `try_new`'s boundary.
926    fn rule_id_bound() -> usize {
927        let bound = 1usize << 15; // define_id15!
928        assert!(RuleId::try_new(bound - 1).is_some(), "bound is too high");
929        assert!(RuleId::try_new(bound).is_none(), "bound is too low");
930        bound
931    }
932
933    /// Every position below the id bound mints its own distinct id.
934    #[test]
935    fn rule_registry_fills_its_id_space_without_aliasing() {
936        let bound = rule_id_bound();
937        let mut r: RuleRegistry<false> = RuleRegistry::new();
938        for i in 0..bound {
939            assert_eq!(r.register(&format!("r{i}"), "l", "r").to_usize(), i);
940        }
941        assert_eq!(r.len(), bound);
942        // The last id round-trips, so no earlier entry was overwritten.
943        assert_eq!(
944            r.name(id_at::<RuleId>(bound - 1)),
945            format!("r{}", bound - 1)
946        );
947        assert_eq!(r.id_by_name("r0").unwrap().to_usize(), 0);
948    }
949
950    /// One past the bound panics rather than aliasing rule 0.
951    #[test]
952    #[should_panic(expected = "the id space is exhausted")]
953    fn rule_registry_past_its_id_space_panics() {
954        let bound = rule_id_bound();
955        let mut r: RuleRegistry<false> = RuleRegistry::new();
956        for i in 0..=bound {
957            r.register(&format!("r{i}"), "l", "r");
958        }
959    }
960
961    #[test]
962    fn builtin_sorts() {
963        let mut r = SR::new();
964        r.register_builtins(&["Bool", "Int", "Real"]);
965        assert_eq!(r.name(SortId::new(0)), "Bool");
966        assert_eq!(r.name(SortId::new(1)), "Int");
967        assert_eq!(r.name(SortId::new(2)), "Real");
968        assert!(r.is_builtin(SortId::new(0)));
969        assert!(r.is_builtin(SortId::new(2)));
970        let user = r.intern("BitVec");
971        assert!(!r.is_builtin(user));
972    }
973
974    #[test]
975    fn sort_intern_dedup() {
976        let mut r = SR::new();
977        let a = r.intern("BitVec");
978        let b = r.intern("BitVec");
979        assert_eq!(a, b);
980    }
981
982    #[test]
983    fn canon_class_all_kinds() {
984        let mut sorts = SR::new();
985        let bool_sort = sorts.intern("Bool");
986        let int_sort = sorts.intern("Int");
987
988        let mut ops = OR::new();
989        let lit = ops.register_lit("BLit", bool_sort);
990        let not = ops.register("Not", &[bool_sort], bool_sort);
991        let ite = ops.register("ITE", &[bool_sort, int_sort, int_sort], int_sort);
992        let eq = ops.register_c("Eq", [int_sort, int_sort], bool_sort);
993        let sub = ops.register_a("Sub", int_sort, int_sort, AssocDir::Left);
994        let add = ops.register_mset("Add", int_sort, int_sort);
995        let and = ops.register_set("And", bool_sort, bool_sort);
996
997        assert_eq!(ops.info(lit).canon_class(), ENodeKind::Lit);
998        assert_eq!(ops.info(not).canon_class(), ENodeKind::Plain1);
999        assert_eq!(ops.info(ite).canon_class(), ENodeKind::Plain3);
1000        assert_eq!(ops.info(eq).canon_class(), ENodeKind::SPair);
1001        assert_eq!(ops.info(sub).canon_class(), ENodeKind::Seq);
1002        assert_eq!(ops.info(add).canon_class(), ENodeKind::MSet);
1003        assert_eq!(ops.info(and).canon_class(), ENodeKind::Set);
1004    }
1005
1006    #[test]
1007    fn plain0_for_constants() {
1008        let int_sort = SortId::new(1);
1009        let mut ops = OR::new();
1010        let zero = ops.register("Zero", &[], int_sort);
1011        assert_eq!(ops.info(zero).canon_class(), ENodeKind::Plain0);
1012    }
1013
1014    #[test]
1015    fn plainn_for_high_arity() {
1016        let int_sort = SortId::new(1);
1017        let mut ops = OR::new();
1018        let f = ops.register("F4", &[int_sort; 4], int_sort);
1019        assert_eq!(ops.info(f).canon_class(), ENodeKind::PlainN);
1020    }
1021
1022    #[test]
1023    fn id_by_name() {
1024        let int_sort = SortId::new(1);
1025        let mut ops = OR::new();
1026        let add = ops.register_mset("Add", int_sort, int_sort);
1027        assert_eq!(ops.id_by_name("Add"), Some(add));
1028        assert_eq!(ops.id_by_name("nonexistent"), None);
1029    }
1030
1031    #[test]
1032    #[should_panic(expected = "already registered")]
1033    fn duplicate_name_panics() {
1034        let int_sort = SortId::new(1);
1035        let mut ops = OR::new();
1036        ops.register_mset("Add", int_sort, int_sort);
1037        ops.register_mset("Add", int_sort, int_sort);
1038    }
1039
1040    #[test]
1041    #[should_panic(expected = "must use the same argument and return sort")]
1042    fn associative_signature_mismatch_panics() {
1043        let mut ops = OR::new();
1044        ops.register_a("Bad", SortId::new(0), SortId::new(1), AssocDir::Both);
1045    }
1046
1047    #[test]
1048    #[should_panic(expected = "must use the same argument and return sort")]
1049    fn ac_signature_mismatch_panics() {
1050        let mut ops = OR::new();
1051        ops.register_mset("Bad", SortId::new(0), SortId::new(1));
1052    }
1053
1054    #[test]
1055    #[should_panic(expected = "must use the same sort for both arguments")]
1056    fn commutative_argument_sort_mismatch_panics() {
1057        let mut ops = OR::new();
1058        ops.register_c("Bad", [SortId::new(0), SortId::new(1)], SortId::new(2));
1059    }
1060
1061    #[test]
1062    fn mset_ops_lists_only_mset() {
1063        let mut sorts = SR::new();
1064        let bool_sort = sorts.intern("Bool");
1065        let int_sort = sorts.intern("Int");
1066
1067        let mut ops = OR::new();
1068        ops.register("Not", &[bool_sort], bool_sort); // Normal
1069        ops.register_c("Eq", [int_sort, int_sort], bool_sort); // Commutative
1070        ops.register_a("Sub", int_sort, int_sort, AssocDir::Left); // A
1071        let add = ops.register_mset("Add", int_sort, int_sort); // AC
1072        let mul = ops.register_mset("Mul", int_sort, int_sort); // AC
1073        ops.register_set("And", bool_sort, bool_sort); // ACI — must be excluded
1074
1075        // mset_ops yields exactly the two MSet ids, and is_mset agrees per-op.
1076        let mut mset_ids: Vec<OpId> = ops.mset_ops().collect();
1077        mset_ids.sort();
1078        assert_eq!(mset_ids, vec![add, mul]);
1079
1080        assert!(ops.is_mset(add));
1081        assert!(ops.is_mset(mul));
1082        // ACI is a distinct kind — not AC.
1083        assert!(!ops.is_mset(ops.id_by_name("And").unwrap()));
1084        assert!(!ops.is_mset(ops.id_by_name("Sub").unwrap()));
1085        assert!(!ops.is_mset(ops.id_by_name("Not").unwrap()));
1086    }
1087
1088    #[test]
1089    fn mset_ops_empty_when_none_registered() {
1090        let int_sort = SortId::new(1);
1091        let mut ops = OR::new();
1092        ops.register("F", &[int_sort], int_sort);
1093        assert_eq!(ops.mset_ops().count(), 0);
1094    }
1095
1096    #[test]
1097    fn completion_ops_mset_then_set_in_registration_order() {
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 mul = ops.register_mset("Mul", int_sort, int_sort);
1106        let or = ops.register_set("Or", bool_sort, bool_sort);
1107        ops.register("Not", &[bool_sort], bool_sort); // non-completion op, excluded
1108
1109        // completion_ops = all MSet (registration order) then all Set (registration order).
1110        assert_eq!(ops.completion_ops(), vec![add, mul, and, or]);
1111        assert_eq!(ops.completion_op_count(), 4);
1112        assert_eq!(ops.set_op_count(), 2);
1113        assert_eq!(ops.mset_op_count(), 2);
1114
1115        // column() is the position in that array; non-completion ops have none.
1116        assert_eq!(ops.completion_column(add), Some(0));
1117        assert_eq!(ops.completion_column(mul), Some(1));
1118        assert_eq!(ops.completion_column(and), Some(2));
1119        assert_eq!(ops.completion_column(or), Some(3));
1120        assert_eq!(ops.completion_column(ops.id_by_name("Not").unwrap()), None);
1121
1122        // is_set agrees.
1123        assert!(ops.is_set(and) && ops.is_set(or));
1124        assert!(!ops.is_set(add));
1125    }
1126
1127    /// The column of a registered op is a table read: no call to `completion_ops`, hence no
1128    /// allocation and no rescan of the op map, however many times it is asked. This is the
1129    /// property `EGraph::register_if_fresh` depends on — it asks once per node created.
1130    #[test]
1131    fn completion_column_does_not_rebuild_the_column_array() {
1132        let mut sorts = SR::new();
1133        let bool_sort = sorts.intern("Bool");
1134        let int_sort = sorts.intern("Int");
1135
1136        let mut ops = OR::new();
1137        let add = ops.register_mset("Add", int_sort, int_sort);
1138        let and = ops.register_set("And", bool_sort, bool_sort);
1139        let not = ops.register("Not", &[bool_sort], bool_sort);
1140
1141        let scans = || COMPLETION_OPS_SCANS.with(|n| n.get());
1142        let before = scans();
1143        for _ in 0..1000 {
1144            assert_eq!(ops.completion_column(add), Some(0));
1145            assert_eq!(ops.completion_column(and), Some(1));
1146            assert_eq!(ops.completion_column(not), None);
1147            assert_eq!(ops.completion_op_count(), 2);
1148        }
1149        assert_eq!(
1150            scans(),
1151            before,
1152            "completion_column rebuilt the column array"
1153        );
1154
1155        // The counter does fire for the array itself, so the assertion above is not vacuous.
1156        let _ = ops.completion_ops();
1157        assert_eq!(scans(), before + 1);
1158    }
1159
1160    /// Restore truncates the completion table with the op log: columns and counts after a
1161    /// restore are the ones the surviving ops alone would produce, and ids registered next
1162    /// reuse the freed columns. Registering an MSet op after a Set op is the case that moves
1163    /// existing Set columns, so the table cannot cache columns directly.
1164    #[test]
1165    fn completion_columns_restore_with_the_op_log() {
1166        type TrackedOR = OpRegistry<OpId, SortId, true>;
1167        let mut sorts = SR::new();
1168        let bool_sort = sorts.intern("Bool");
1169        let int_sort = sorts.intern("Int");
1170
1171        let mut ops = TrackedOR::new();
1172        let add = ops.register_mset("Add", int_sort, int_sort);
1173        let and = ops.register_set("And", bool_sort, bool_sort);
1174        assert_eq!(
1175            (ops.completion_column(add), ops.completion_column(and)),
1176            (Some(0), Some(1))
1177        );
1178
1179        let token = ops.mark(ShrinkPolicy::Never);
1180        let mul = ops.register_mset("Mul", int_sort, int_sort);
1181        let or = ops.register_set("Or", bool_sort, bool_sort);
1182        // The new MSet op takes column 1, pushing every Set op up one.
1183        assert_eq!(ops.completion_ops(), vec![add, mul, and, or]);
1184        assert_eq!(ops.completion_column(mul), Some(1));
1185        assert_eq!(ops.completion_column(and), Some(2));
1186        assert_eq!(ops.completion_column(or), Some(3));
1187        assert_eq!(ops.completion_op_count(), 4);
1188
1189        ops.restore(token);
1190        assert_eq!(ops.completion_ops(), vec![add, and]);
1191        assert_eq!(ops.completion_column(add), Some(0));
1192        assert_eq!(ops.completion_column(and), Some(1));
1193        assert_eq!(ops.mset_op_count(), 1);
1194        assert_eq!(ops.set_op_count(), 1);
1195        assert_eq!(ops.completion_op_count(), 2);
1196        // The restored ids are unregistered, so their columns are gone with them.
1197        assert_eq!(ops.completion_column(mul), None);
1198        assert_eq!(ops.completion_column(or), None);
1199
1200        // Registering again after the restore mints the same ids and columns as before.
1201        let mul2 = ops.register_mset("Mul", int_sort, int_sort);
1202        assert_eq!(mul2, mul);
1203        assert_eq!(ops.completion_column(mul2), Some(1));
1204        assert_eq!(ops.completion_column(and), Some(2));
1205    }
1206
1207    #[test]
1208    fn completion_ops_empty_when_none() {
1209        let int_sort = SortId::new(1);
1210        let mut ops = OR::new();
1211        ops.register("F", &[int_sort], int_sort);
1212        assert_eq!(ops.completion_ops(), Vec::<OpId>::new());
1213        assert_eq!(ops.completion_op_count(), 0);
1214    }
1215}