semi-persistent-egraph 0.2.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Sort and operator registries.

use crate::containers::AppendOnlyVec;
use crate::containers::DenseId;
use crate::containers::IndexLike;
use crate::containers::MapToken;
use crate::containers::ShrinkPolicy;
use crate::containers::SpMap;
use crate::containers::VecToken;
use crate::id::{ENodeKind, id_at};

/// Opaque token for [`SortRegistry::mark`] / [`SortRegistry::restore`].
#[derive(Clone, Copy, Debug)]
pub struct SortRegistryToken(MapToken);

/// Opaque token for [`OpRegistry::mark`] / [`OpRegistry::restore`]. Bundles the op log's
/// token with the completion table's, so the two are always marked and truncated together.
#[derive(Clone, Copy, Debug)]
pub struct OpRegistryToken {
    map: MapToken,
    completion: VecToken,
}

/// Source spelling retained for associative-only operators.
///
/// All three variants currently use the same flat, order-preserving `Seq`
/// representation and matching semantics. The value records whether the
/// declaration used `:assoc-left`, `:assoc-right`, or `:assoc`; no production
/// path branches on it after registration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AssocDir {
    Left,
    Right,
    Both,
}

/// How an AC op's normal form bounds a summand's count (design "three independent axes").
/// This is a unified axis carried on both `MSet` and `Set` descriptors,
/// independent of the storage partition: the partition is derived from the clamp (`Idempotent →
/// Set`; `None` / `Nilpotent → MSet`). See `doc/design/ac-algebraic-properties.md`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Clamp {
    /// No count bound: counts stay in ℕ. Plain AC (`+`, `*`). Stored as `MSet`.
    None,
    /// `x∘x = x`: duplicate summands collapse to one (dedup at build via `SetCanon`). `and`, `or`.
    /// Stored as `Set` (bare children); dedup is the correct build/recanonize canonize rule.
    Idempotent,
    /// `x∘x = e` (order 2), or count mod `order` in general: pairs cancel to the unit. `xor`,
    /// `bvxor`. Requires an `identity`. Stored as `MSet` (NOT `Set`): computing count-mod-n needs
    /// the true multiplicity, which the `Set` dedup canonize would destroy at build time; the
    /// mod-n reduction happens during build/recanonization and is also used by completion
    /// normalization. The NF counts are {0,1} at order 2 but the
    /// *storage* is MSet regardless of order.
    ///
    /// Why `order: u8` and not a node id: the two halves of the law `xⁿ = e` have different
    /// natures. The order `n` is pure ARITHMETIC — its entire life is being the modulus in
    /// `count % n` (`clamp_nilpotent`, `MSetCanon::clamp_multiset`); no e-node denotes it,
    /// so an id type would be a category error. The identity `e` IS a graph entity, and it
    /// is stored as one — a resolved node id in the egraph's per-op `unit_node` map (as the
    /// inverse operator is in `inverse_op`), kept OFF this descriptor because `OpKind<S>`
    /// is generic over sorts only and cannot carry a `Cfg::G`/`Cfg::O`. The parsed
    /// [`UnitRef`] retained here is resolved immediately by surface registration. `u8` is
    /// the "orders are tiny" choice (xor = 2); its one known
    /// limit is foreclosing the `bvadd(N)`-as-nilpotent-`2^N` torsion encoding for N ≥ 8 —
    /// widen to `u32` (enum field, `MSetClamp`, the two clamp fns, the tag parser) if
    /// bitvector modeling ever lands. Numbers for laws, ids for entities.
    Nilpotent { order: u8 },
}

/// Parsed reference to an operator's identity (unit) element. Surface registration
/// sort-checks and builds the actual e-node immediately, storing it in the egraph's
/// per-op `unit_node` map; this descriptor retains the source-level form.
#[derive(Clone, Debug)]
pub enum UnitRef {
    /// A literal unit (`0`, `true`, `#b0000`): its surface token and the sort to parse it at.
    Lit { token: String },
    /// A constructed unit (`(zero)`): the parsed surface term, built via the term builder.
    Ctor { term: crate::ast::Term },
}

/// Signature and algebraic kind of a registered operator.
///
/// The `MSet`/`Set` variants carry the resolved algebra beyond the representation: an optional
/// `identity` (unit-drop; applies to either representation), `cancellative` flag, and count
/// clamp. Resolved unit nodes and inverse operator ids need the configured node/op id types,
/// which `OpKind<S>` cannot carry, so the e-graph stores them in its semi-persistent
/// `unit_node` and `inverse_op` maps. See `doc/design/ac-algebraic-properties.md`.
#[derive(Clone, Debug)]
pub enum OpKind<S: DenseId> {
    Normal {
        arg_sorts: Vec<S>,
    },
    Commutative {
        arg_sorts: [S; 2],
    },
    A {
        arg_sort: S,
        dir: AssocDir,
    },
    /// Associative-commutative, multiset child representation (`(G, mult)`, ℕ counts). Holds
    /// `clamp ∈ {None, Nilpotent}` — plain AC (`None`) or nilpotent (`Nilpotent`, which is stored
    /// MSet so build/recanonization can compute the mod-n reduction from true multiplicities). Never
    /// `Idempotent` (that is the `Set` partition).
    MSet {
        arg_sort: S,
        clamp: Clamp,
        identity: Option<UnitRef>,
        cancellative: bool,
    },
    /// Associative-commutative with {0,1}-bounded counts, set child representation (bare `G`).
    /// `clamp` is always `Idempotent` here (dedup is the build/recanonize canonize rule); the
    /// field is kept for uniformity with `MSet` and the `op_clamp` read.
    Set {
        arg_sort: S,
        clamp: Clamp,
        identity: Option<UnitRef>,
        cancellative: bool,
    },
    Lit,
}

/// Non-algebraic registration metadata for an operator: whether it was declared as a
/// constructor, and the two extraction knobs. Separate from [`OpKind`], which carries only
/// the algebraic shape. The surface layer parses this straight out of a declaration's tag
/// list (`ast::Command::Function`, `ast::Variant`) and hands it to
/// [`OpRegistry::register_kind_meta`], so there is one representation from parse to registry.
///
/// `Default` is the undeclared case: a plain `(function …)` — not a constructor, cost 1,
/// extractable. Cost 1 is what the extractor charged for every node before per-op costs
/// existed, so a program that declares no `:cost` extracts exactly as it did before.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OpMeta {
    /// Declared with `(constructor …)`, or a `(datatype …)` variant. A constructor is a term
    /// former: it behaves like a function for congruence and matching, and additionally
    /// stamps [`FLAG_CONSTRUCTOR`](crate::node_types::FLAG_CONSTRUCTOR) on its nodes.
    pub is_constructor: bool,
    /// Per-node extraction cost (`:cost n`). The cost of a term is the sum over its nodes,
    /// with an AC child of multiplicity k counted k times.
    pub cost: u32,
    /// `:unextractable` — the extractor never selects a node of this op.
    pub unextractable: bool,
}

impl Default for OpMeta {
    fn default() -> Self {
        Self {
            is_constructor: false,
            cost: 1,
            unextractable: false,
        }
    }
}

/// Metadata for a registered operator.
#[derive(Clone, Debug)]
pub struct OpInfo<S: DenseId> {
    pub name: String,
    pub return_sort: S,
    pub kind: OpKind<S>,
    pub is_constructor: bool,
    /// Per-node extraction cost, default 1. See [`OpMeta::cost`].
    pub cost: u32,
    /// Excluded from extraction. See [`OpMeta::unextractable`].
    pub unextractable: bool,
}

impl<S: DenseId> OpInfo<S> {
    pub fn canon_class(&self) -> ENodeKind {
        match &self.kind {
            OpKind::Normal { arg_sorts } => match arg_sorts.len() {
                0 => ENodeKind::Plain0,
                1 => ENodeKind::Plain1,
                2 => ENodeKind::Plain2,
                3 => ENodeKind::Plain3,
                _ => ENodeKind::PlainN,
            },
            OpKind::Commutative { .. } => ENodeKind::SPair,
            OpKind::A { .. } => ENodeKind::Seq,
            OpKind::MSet { .. } => ENodeKind::MSet,
            OpKind::Set { .. } => ENodeKind::Set,
            OpKind::Lit => ENodeKind::Lit,
        }
    }
}

/// Append-only sort registry backed by `SpMap`.
#[derive(Debug)]
pub struct SortRegistry<S: DenseId, const TRACK: bool> {
    /// Positions in this log ARE sort ids, so the log's index word is the id's.
    map: SpMap<String, (), S::Index, TRACK>,
    builtin_count: usize,
    concrete_count: usize,
    _phantom: core::marker::PhantomData<S>,
}

impl<S: DenseId, const TRACK: bool> Default for SortRegistry<S, TRACK> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: DenseId, const TRACK: bool> SortRegistry<S, TRACK> {
    pub fn new() -> Self {
        Self {
            map: SpMap::new(),
            builtin_count: 0,
            concrete_count: 0,
            _phantom: core::marker::PhantomData,
        }
    }

    pub fn register_builtins(&mut self, sort_names: &[&str]) {
        assert!(
            self.map.is_empty(),
            "register_builtins must be called on empty registry"
        );
        for name in sort_names {
            self.map
                .try_insert(name.to_string(), ())
                .expect("registry id space exhausted for its index word");
        }
        self.builtin_count = self.map.len();
        self.concrete_count = self.map.len();
    }

    pub fn intern(&mut self, name: &str) -> S {
        if let Some(id) = self.map.id_of(&name.to_owned()) {
            // A position already in the log came from `sort_id` below, so it is in
            // range; re-checking costs nothing on this path and keeps one spelling.
            return id_at::<S>(id.as_usize());
        }
        let id = self
            .map
            .try_insert(name.to_owned(), ())
            .expect("registry id space exhausted for its index word");
        id_at::<S>(id.as_usize())
    }

    pub fn name(&self, id: S) -> &str {
        self.map.key(id.to_index())
    }

    pub fn is_builtin(&self, id: S) -> bool {
        id.to_usize() < self.builtin_count
    }

    pub fn is_concrete(&self, id: S) -> bool {
        id.to_usize() < self.concrete_count
    }

    pub fn concrete_count(&self) -> usize {
        self.concrete_count
    }

    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    pub fn len(&self) -> usize {
        self.map.log_len().as_usize()
    }

    pub fn id_by_name(&self, name: &str) -> Option<S> {
        self.map
            .id_of(&name.to_owned())
            .map(|id| id_at::<S>(id.as_usize()))
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> SortRegistryToken {
        SortRegistryToken(
            self.map
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
        )
    }

    pub fn restore(&mut self, token: SortRegistryToken) {
        self.map
            .try_restore(token.0)
            .expect("restore: token minted by this container's own mark");
    }
}

/// Which completion segment an op belongs to: the two segments of the completion column
/// order (MSet first, then Set), plus "neither".
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CompletionKind {
    NotCompletion,
    MSet,
    Set,
}

/// One op's completion bookkeeping, precomputed at registration.
///
/// A column index cannot be stored directly because registering an MSet op shifts every
/// Set column up by one (the MSet segment precedes the Set segment), so a stored column
/// would need rewriting on each later registration. The *running counts* do not have that
/// problem: `msets`/`sets` count the ops of each kind registered up to and including this
/// one, they are fixed the moment the entry is pushed, and both the totals (the last
/// entry's counts) and a column (a total plus a rank) read off them in O(1).
#[derive(Clone, Copy, Debug)]
struct CompletionSlot {
    kind: CompletionKind,
    /// MSet ops registered up to and including this op.
    msets: usize,
    /// Set ops registered up to and including this op.
    sets: usize,
}

#[cfg(test)]
thread_local! {
    /// Calls to [`OpRegistry::completion_ops`] on this thread. Lets a test pin that
    /// `completion_column` answers out of the completion table instead of rebuilding the
    /// column array per call, which is the regression this counter exists to catch (tests
    /// run one per thread, so the count is per test).
    static COMPLETION_OPS_SCANS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
}

/// Append-only operator registry backed by `SpMap`.
#[derive(Debug)]
pub struct OpRegistry<O: DenseId, S: DenseId, const TRACK: bool> {
    /// Positions in this log ARE op ids, so the log's index word is the id's.
    map: SpMap<String, OpInfo<S>, O::Index, TRACK>,
    /// Completion bookkeeping per op, one entry per op id ([`CompletionSlot`]).
    ///
    /// `insert` pushes exactly one entry per op, so entry `i` describes op `i`, and the
    /// registry's token bundle marks and restores this vector with the op log: a restore
    /// truncates both at the same length, leaving the counts describing exactly the
    /// surviving ops. [`completion_column`](OpRegistry::completion_column) is a read out of
    /// this table rather than a scan of the op map, because the node-creation path calls it
    /// once per fresh node.
    completion: AppendOnlyVec<CompletionSlot, O::Index, TRACK>,
    builtin_count: usize,
    concrete_sort_count: usize,
    _phantom: core::marker::PhantomData<O>,
}

impl<O: crate::DenseId, S: DenseId, const TRACK: bool> Default for OpRegistry<O, S, TRACK> {
    fn default() -> Self {
        Self::new()
    }
}

impl<O: crate::DenseId, S: DenseId, const TRACK: bool> OpRegistry<O, S, TRACK> {
    pub fn new() -> Self {
        Self {
            map: SpMap::new(),
            completion: AppendOnlyVec::new(),
            builtin_count: 0,
            concrete_sort_count: 0,
            _phantom: core::marker::PhantomData,
        }
    }

    /// Register builtin ops from a LitModel. Must be called before any user ops.
    /// Each LitOpDesc becomes a real OpId with OpKind::Normal.
    /// The OpId indices match LitModel::ops() indices for eval lookup.
    pub fn register_builtins<
        L: crate::literal::LitVal,
        M: crate::lit_model::LitModel<Value = L>,
    >(
        &mut self,
        model: &M,
        sorts: &SortRegistry<S, TRACK>,
    ) {
        assert!(
            self.map.is_empty(),
            "register_builtins must be called on empty registry"
        );
        for op_desc in model.ops() {
            let arg_sorts: Vec<S> = op_desc
                .arg_sorts
                .iter()
                .map(|name| {
                    sorts.id_by_name(name).unwrap_or_else(|| {
                        panic!("unknown sort '{name}' in LitOpDesc '{}'", op_desc.name)
                    })
                })
                .collect();
            let ret_sort = sorts.id_by_name(op_desc.ret_sort).unwrap_or_else(|| {
                panic!(
                    "unknown sort '{}' in LitOpDesc '{}'",
                    op_desc.ret_sort, op_desc.name
                )
            });
            self.insert(
                op_desc.name,
                ret_sort,
                OpKind::Normal { arg_sorts },
                OpMeta::default(),
            );
        }
        // Auto-register a LitNode op for each concrete sort.
        for sort_desc in model.sorts() {
            let sort_id = sorts.id_by_name(sort_desc.name).unwrap();
            let lit_name = format!("@{}", sort_desc.name);
            self.insert(&lit_name, sort_id, OpKind::Lit, OpMeta::default());
        }
        self.builtin_count = self.map.log_len().as_usize();
        self.concrete_sort_count = sorts.concrete_count();
    }

    /// Is this a builtin op (from LitModel)?
    pub fn is_builtin(&self, id: O) -> bool {
        id.to_usize() < self.builtin_count
    }

    /// Is this a primitive op (from LitModel::ops(), not a @-prefixed lit wrap)?
    pub fn is_prim_op(&self, id: O) -> bool {
        self.is_builtin(id) && !matches!(self.map.get_val(id.to_index()).kind, OpKind::Lit)
    }

    pub fn register(&mut self, name: &str, arg_sorts: &[S], return_sort: S) -> O {
        self.insert(
            name,
            return_sort,
            OpKind::Normal {
                arg_sorts: arg_sorts.to_vec(),
            },
            OpMeta::default(),
        )
    }

    pub fn register_c(&mut self, name: &str, arg_sorts: [S; 2], return_sort: S) -> O {
        self.insert(
            name,
            return_sort,
            OpKind::Commutative { arg_sorts },
            OpMeta::default(),
        )
    }

    pub fn register_a(&mut self, name: &str, arg_sort: S, return_sort: S, dir: AssocDir) -> O {
        self.insert(
            name,
            return_sort,
            OpKind::A { arg_sort, dir },
            OpMeta::default(),
        )
    }

    /// Register a plain AC (multiset) op: no identity, not cancellative. Richer algebra
    /// (identity/cancellative) is set via the property-tag resolver (`register_with_algebra`).
    pub fn register_mset(&mut self, name: &str, arg_sort: S, return_sort: S) -> O {
        self.insert(
            name,
            return_sort,
            OpKind::MSet {
                arg_sort,
                clamp: Clamp::None,
                identity: None,
                cancellative: false,
            },
            OpMeta::default(),
        )
    }

    /// Register a plain ACI (idempotent set) op: no identity, not cancellative. This is the
    /// `Clamp::Idempotent` case; nilpotent (MSet) comes via the property-tag resolver.
    pub fn register_set(&mut self, name: &str, arg_sort: S, return_sort: S) -> O {
        self.insert(
            name,
            return_sort,
            OpKind::Set {
                arg_sort,
                clamp: Clamp::Idempotent,
                identity: None,
                cancellative: false,
            },
            OpMeta::default(),
        )
    }

    pub fn register_lit(&mut self, name: &str, return_sort: S) -> O {
        self.insert(name, return_sort, OpKind::Lit, OpMeta::default())
    }

    /// Register an op from a fully-resolved `OpKind`. Used by the property-tag resolver
    /// (`sortcheck`), which builds the `MSet`/`Set` descriptor (clamp/identity/cancellative)
    /// from the parsed tag set. The plain `register_mset`/`register_set` are the default-filled
    /// special cases of this.
    pub fn register_kind(&mut self, name: &str, return_sort: S, kind: OpKind<S>) -> O {
        self.insert(name, return_sort, kind, OpMeta::default())
    }

    /// Register an op from a fully-resolved `OpKind` plus its non-algebraic metadata
    /// (constructor-ness, `:cost`, `:unextractable`). This is the surface layer's single
    /// registration entry point: `sortcheck::register_op` builds both descriptors from the
    /// declaration and calls this, so constructor-ness is registration-time data rather than
    /// a post-hoc mutation (the backing `SpMap` is append-only and has no `get_mut`).
    pub fn register_kind_meta(
        &mut self,
        name: &str,
        return_sort: S,
        kind: OpKind<S>,
        meta: OpMeta,
    ) -> O {
        self.insert(name, return_sort, kind, meta)
    }

    pub fn info(&self, id: O) -> &OpInfo<S> {
        self.map.get_val(id.to_index())
    }

    /// The names of every registered op, in op-id order — the same order as
    /// [`meta_table`](Self::meta_table) and `EGraph::op_node_counts`, so the three index
    /// together.
    pub fn names(&self) -> impl Iterator<Item = &str> + '_ {
        self.map.iter().map(|(_, i)| i.name.as_str())
    }

    /// The non-algebraic metadata ([`OpMeta`]) of every registered op, in op-id order. Lets a
    /// consumer index by op id instead of calling [`info`](Self::info) per node; the extractor
    /// hoists this out of its fixpoint loop, where the per-node lookup would otherwise repeat
    /// on every pass.
    pub fn meta_table(&self) -> Vec<OpMeta> {
        self.map
            .iter()
            .map(|(_, i)| OpMeta {
                is_constructor: i.is_constructor,
                cost: i.cost,
                unextractable: i.unextractable,
            })
            .collect()
    }

    /// Is this op associative-commutative (`OpKind::MSet`)? Note this is `false`
    /// for ACI ops, which are a distinct kind.
    pub fn is_mset(&self, id: O) -> bool {
        matches!(self.map.get_val(id.to_index()).kind, OpKind::MSet { .. })
    }

    /// Iterator over the ids of all registered AC ops. Used by AC congruence
    /// completion to drive the per-AC-op critical-pair pass (see
    /// `doc/design/ac-congruence-completeness.md`). Excludes ACI ops.
    pub fn mset_ops(&self) -> impl Iterator<Item = O> + '_ {
        self.ops_of_kind(CompletionKind::MSet)
    }

    /// The ids of the ops in one completion segment, in registration order.
    fn ops_of_kind(&self, kind: CompletionKind) -> impl Iterator<Item = O> + '_ {
        self.completion
            .as_slice()
            .iter()
            .enumerate()
            .filter(move |(_, slot)| slot.kind == kind)
            .map(|(i, _)| id_at::<O>(i))
    }

    /// The number of MSet and of Set ops registered, read off the last completion slot:
    /// every slot carries the running counts, so the totals survive a `restore` truncation
    /// without a rescan.
    fn completion_counts(&self) -> (usize, usize) {
        match self.completion.as_slice().last() {
            Some(slot) => (slot.msets, slot.sets),
            None => (0, 0),
        }
    }

    /// Number of registered `OpKind::MSet` ops (excludes Set). Completion supports
    /// multiple symbols through one per-op column in each allocated class row.
    pub fn mset_op_count(&self) -> usize {
        self.completion_counts().0
    }

    /// Is this op a `Set` (idempotent) op? Nilpotent ops use `MSet`.
    pub fn is_set(&self, id: O) -> bool {
        matches!(self.map.get_val(id.to_index()).kind, OpKind::Set { .. })
    }

    /// Iterator over the ids of all registered `Set` ops (idempotent), in
    /// registration order. The Set analogue of [`mset_ops`](Self::mset_ops).
    pub fn set_ops(&self) -> impl Iterator<Item = O> + '_ {
        self.ops_of_kind(CompletionKind::Set)
    }

    /// Number of registered `Set` ops.
    pub fn set_op_count(&self) -> usize {
        self.completion_counts().1
    }

    /// The ordered list of *completion* ops (MSet then Set, each in registration order). This
    /// is the column → op reference array for the per-op `min_monomial` pool (design "the
    /// column → op reference array"): `completion_ops()[k]` is the op owning pool column `k`,
    /// and its length is the fixed row width `nb_completion`. Registration order is stable
    /// (the backing `SpMap` is append-only, never renumbered), so a column's meaning is fixed
    /// for the run.
    ///
    /// Allocates and scans every op, so it is for per-round callers (the pool builder); a
    /// single op's column comes from [`completion_column`](Self::completion_column), which
    /// does neither.
    pub fn completion_ops(&self) -> Vec<O> {
        #[cfg(test)]
        COMPLETION_OPS_SCANS.with(|n| n.set(n.get() + 1));
        let mut v: Vec<O> = self.mset_ops().collect();
        v.extend(self.set_ops());
        v
    }

    /// Number of completion ops (`nb_completion` = MSet + Set), the `min_monomial` pool row
    /// width.
    pub fn completion_op_count(&self) -> usize {
        let (msets, sets) = self.completion_counts();
        msets + sets
    }

    /// The pool column index of a completion op, or `None` if `id` is not an MSet/Set op.
    ///
    /// One indexed read of the per-op completion table plus, for a Set op, the MSet
    /// total: no allocation and no scan of the op map, because
    /// `EGraph::register_if_fresh` calls this once per node the engine creates.
    /// The former implementation scanned the registry; current constant-factor
    /// comparisons belong in the Criterion registration/completion workload.
    pub fn completion_column(&self, id: O) -> Option<usize> {
        let slot = self.completion.as_slice().get(id.to_usize())?;
        match slot.kind {
            CompletionKind::NotCompletion => None,
            // Registration order within a segment is the column order, and `msets`/`sets`
            // count this op too, so its rank in its segment is the count minus one.
            CompletionKind::MSet => Some(slot.msets - 1),
            CompletionKind::Set => Some(self.completion_counts().0 + slot.sets - 1),
        }
    }

    pub fn id_by_name(&self, name: &str) -> Option<O> {
        self.map
            .id_of(&name.to_owned())
            .map(|id| id_at::<O>(id.as_usize()))
    }

    pub fn lit_op_for_sort(&self, sort: S) -> Option<O> {
        self.map
            .iter()
            .enumerate()
            .find(|(_, (_, info))| matches!(info.kind, OpKind::Lit) && info.return_sort == sort)
            .map(|(i, _)| id_at::<O>(i))
    }

    /// Find a unary op that takes `from` and returns `to` (e.g. ILit: IBig → IExpr).
    pub fn find_lift_op(&self, from: S, to: S) -> Option<O> {
        self.map
            .iter()
            .enumerate()
            .find(|(_, (_, info))| {
                info.return_sort == to
                    && matches!(&info.kind, OpKind::Normal { arg_sorts } if arg_sorts.len() == 1 && arg_sorts[0] == from)
            })
            .map(|(i, _)| id_at::<O>(i))
    }

    fn insert(&mut self, name: &str, return_sort: S, kind: OpKind<S>, meta: OpMeta) -> O {
        assert!(
            !self.map.contains_key(&name.to_owned()),
            "operator '{name}' already registered"
        );
        if self.builtin_count > 0 && return_sort.to_usize() < self.concrete_sort_count {
            panic!(
                "operator '{name}' cannot return concrete sort (index {})",
                return_sort.to_usize()
            );
        }
        let completion_kind = match kind {
            OpKind::MSet { .. } => CompletionKind::MSet,
            OpKind::Set { .. } => CompletionKind::Set,
            _ => CompletionKind::NotCompletion,
        };
        let id = self
            .map
            .try_insert(
                name.to_owned(),
                OpInfo {
                    name: name.to_owned(),
                    return_sort,
                    kind,
                    is_constructor: meta.is_constructor,
                    cost: meta.cost,
                    unextractable: meta.unextractable,
                },
            )
            .expect("registry id space exhausted for its index word");
        let (msets, sets) = self.completion_counts();
        let slot = CompletionSlot {
            kind: completion_kind,
            msets: msets + usize::from(completion_kind == CompletionKind::MSet),
            sets: sets + usize::from(completion_kind == CompletionKind::Set),
        };
        let slot_id = self
            .completion
            .try_push(slot)
            .expect("completion table shares the op log's index word");
        debug_assert_eq!(
            slot_id.as_usize(),
            id.as_usize(),
            "one completion slot per op, pushed in op-id order"
        );
        id_at::<O>(id.as_usize())
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> OpRegistryToken {
        OpRegistryToken {
            map: self
                .map
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
            completion: self
                .completion
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
        }
    }

    pub fn restore(&mut self, token: OpRegistryToken) {
        self.map
            .try_restore(token.map)
            .expect("restore: token minted by this container's own mark");
        self.completion
            .try_restore(token.completion)
            .expect("restore: token minted by this container's own mark");
        debug_assert_eq!(
            self.completion.len().as_usize(),
            self.map.log_len().as_usize(),
            "the completion table is truncated with the op log"
        );
    }
}

// ---------------------------------------------------------------------------
// Rule registry
// ---------------------------------------------------------------------------

/// Opaque token for [`RuleRegistry::mark`] / [`RuleRegistry::restore`].
#[derive(Clone, Copy, Debug)]
pub struct RuleRegistryToken(MapToken);

/// Metadata for a registered rewrite rule.
#[derive(Clone, Debug)]
pub struct RuleInfo {
    pub name: String,
    pub lhs: String,
    pub rhs: String,
}

/// Append-only rule registry backed by `SpMap`.
pub struct RuleRegistry<const TRACK: bool> {
    /// Positions in this log ARE rule ids, so the log's index word is `RuleId`'s — a
    /// `u16`, since `RuleId` is 15-bit.
    map: SpMap<String, RuleInfo, <crate::id::RuleId as DenseId>::Index, TRACK>,
}

impl<const TRACK: bool> Default for RuleRegistry<TRACK> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const TRACK: bool> RuleRegistry<TRACK> {
    pub fn new() -> Self {
        Self { map: SpMap::new() }
    }

    pub fn register(&mut self, name: &str, lhs: &str, rhs: &str) -> crate::id::RuleId {
        let id = self
            .map
            .try_insert(
                name.to_owned(),
                RuleInfo {
                    name: name.to_owned(),
                    lhs: lhs.to_owned(),
                    rhs: rhs.to_owned(),
                },
            )
            .expect("registry id space exhausted for its index word");
        id_at::<crate::id::RuleId>(id.as_usize())
    }

    pub fn info(&self, id: crate::id::RuleId) -> &RuleInfo {
        self.map.get_val(id.to_index())
    }

    pub fn name(&self, id: crate::id::RuleId) -> &str {
        self.map.key(id.to_index())
    }

    pub fn len(&self) -> usize {
        self.map.log_len().as_usize()
    }

    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    pub fn id_by_name(&self, name: &str) -> Option<crate::id::RuleId> {
        self.map
            .id_of(&name.to_owned())
            .map(|id| id_at::<crate::id::RuleId>(id.as_usize()))
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> RuleRegistryToken {
        RuleRegistryToken(
            self.map
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
        )
    }

    pub fn restore(&mut self, token: RuleRegistryToken) {
        self.map
            .try_restore(token.0)
            .expect("restore: token minted by this container's own mark");
    }
}

// ---------------------------------------------------------------------------
// Axiom registry
// ---------------------------------------------------------------------------

/// Opaque token for [`AxiomRegistry::mark`] / [`AxiomRegistry::restore`].
#[derive(Clone, Copy, Debug)]
pub struct AxiomRegistryToken(MapToken);

/// Metadata for a registered axiom (user-asserted equality).
#[derive(Clone, Debug)]
pub struct AxiomInfo<G: Copy> {
    pub name: String,
    pub lhs: G,
    pub rhs: G,
}

/// Append-only axiom registry backed by `SpMap`.
pub struct AxiomRegistry<G: Copy + DenseId, const TRACK: bool> {
    /// Positions in this log ARE axiom ids, so the log's index word is `AxiomId`'s — a
    /// `u16`, since `AxiomId` is 15-bit. Note this is NOT `G::Index`: `G` is the id type
    /// of the *terms* an axiom relates, not of the axiom.
    map: SpMap<String, AxiomInfo<G>, <crate::id::AxiomId as DenseId>::Index, TRACK>,
}

impl<G: Copy + DenseId, const TRACK: bool> Default for AxiomRegistry<G, TRACK> {
    fn default() -> Self {
        Self::new()
    }
}

impl<G: Copy + DenseId, const TRACK: bool> AxiomRegistry<G, TRACK> {
    pub fn new() -> Self {
        Self { map: SpMap::new() }
    }

    pub fn register(&mut self, name: &str, lhs: G, rhs: G) -> crate::id::AxiomId {
        let id = self
            .map
            .try_insert(
                name.to_owned(),
                AxiomInfo {
                    name: name.to_owned(),
                    lhs,
                    rhs,
                },
            )
            .expect("registry id space exhausted for its index word");
        id_at::<crate::id::AxiomId>(id.as_usize())
    }

    pub fn info(&self, id: crate::id::AxiomId) -> &AxiomInfo<G> {
        self.map.get_val(id.to_index())
    }

    pub fn name(&self, id: crate::id::AxiomId) -> &str {
        self.map.key(id.to_index())
    }

    pub fn len(&self) -> usize {
        self.map.log_len().as_usize()
    }

    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    pub fn mark(&mut self, shrink: ShrinkPolicy) -> AxiomRegistryToken {
        AxiomRegistryToken(
            self.map
                .try_mark(shrink)
                .expect("mark: frame depth is bounded by the saturation driver"),
        )
    }

    pub fn restore(&mut self, token: AxiomRegistryToken) {
        self.map
            .try_restore(token.0)
            .expect("restore: token minted by this container's own mark");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::id::{OpId, RuleId, SortId};

    type SR = SortRegistry<SortId, false>;
    type OR = OpRegistry<OpId, SortId, false>;

    // -- Id-space exhaustion --
    //
    // `RuleId` is 15-bit while its log's index word is `u16`, so the log can hold a
    // position (up to 65534) that no `RuleId` can name. That gap is why the mint has
    // to be checked before mutation: position 32768 must be rejected without adding
    // an unnameable registry entry.

    /// `RuleId`'s id bound, asserted rather than assumed: `id_bound()` is a spec
    /// function, so exec code reads the bound off `try_new`'s boundary.
    fn rule_id_bound() -> usize {
        let bound = 1usize << 15; // define_id15!
        assert!(RuleId::try_new(bound - 1).is_some(), "bound is too high");
        assert!(RuleId::try_new(bound).is_none(), "bound is too low");
        bound
    }

    /// Every position below the id bound mints its own distinct id.
    #[test]
    fn rule_registry_fills_its_id_space_without_aliasing() {
        let bound = rule_id_bound();
        let mut r: RuleRegistry<false> = RuleRegistry::new();
        for i in 0..bound {
            assert_eq!(r.register(&format!("r{i}"), "l", "r").to_usize(), i);
        }
        assert_eq!(r.len(), bound);
        // The last id round-trips, so no earlier entry was overwritten.
        assert_eq!(
            r.name(id_at::<RuleId>(bound - 1)),
            format!("r{}", bound - 1)
        );
        assert_eq!(r.id_by_name("r0").unwrap().to_usize(), 0);
    }

    /// One past the bound panics rather than aliasing rule 0.
    #[test]
    #[should_panic(expected = "the id space is exhausted")]
    fn rule_registry_past_its_id_space_panics() {
        let bound = rule_id_bound();
        let mut r: RuleRegistry<false> = RuleRegistry::new();
        for i in 0..=bound {
            r.register(&format!("r{i}"), "l", "r");
        }
    }

    #[test]
    fn builtin_sorts() {
        let mut r = SR::new();
        r.register_builtins(&["Bool", "Int", "Real"]);
        assert_eq!(r.name(SortId::new(0)), "Bool");
        assert_eq!(r.name(SortId::new(1)), "Int");
        assert_eq!(r.name(SortId::new(2)), "Real");
        assert!(r.is_builtin(SortId::new(0)));
        assert!(r.is_builtin(SortId::new(2)));
        let user = r.intern("BitVec");
        assert!(!r.is_builtin(user));
    }

    #[test]
    fn sort_intern_dedup() {
        let mut r = SR::new();
        let a = r.intern("BitVec");
        let b = r.intern("BitVec");
        assert_eq!(a, b);
    }

    #[test]
    fn canon_class_all_kinds() {
        let mut sorts = SR::new();
        let bool_sort = sorts.intern("Bool");
        let int_sort = sorts.intern("Int");

        let mut ops = OR::new();
        let lit = ops.register_lit("BLit", bool_sort);
        let not = ops.register("Not", &[bool_sort], bool_sort);
        let ite = ops.register("ITE", &[bool_sort, int_sort, int_sort], int_sort);
        let eq = ops.register_c("Eq", [int_sort, int_sort], bool_sort);
        let sub = ops.register_a("Sub", int_sort, int_sort, AssocDir::Left);
        let add = ops.register_mset("Add", int_sort, int_sort);
        let and = ops.register_set("And", bool_sort, bool_sort);

        assert_eq!(ops.info(lit).canon_class(), ENodeKind::Lit);
        assert_eq!(ops.info(not).canon_class(), ENodeKind::Plain1);
        assert_eq!(ops.info(ite).canon_class(), ENodeKind::Plain3);
        assert_eq!(ops.info(eq).canon_class(), ENodeKind::SPair);
        assert_eq!(ops.info(sub).canon_class(), ENodeKind::Seq);
        assert_eq!(ops.info(add).canon_class(), ENodeKind::MSet);
        assert_eq!(ops.info(and).canon_class(), ENodeKind::Set);
    }

    #[test]
    fn plain0_for_constants() {
        let int_sort = SortId::new(1);
        let mut ops = OR::new();
        let zero = ops.register("Zero", &[], int_sort);
        assert_eq!(ops.info(zero).canon_class(), ENodeKind::Plain0);
    }

    #[test]
    fn plainn_for_high_arity() {
        let int_sort = SortId::new(1);
        let mut ops = OR::new();
        let f = ops.register("F4", &[int_sort; 4], int_sort);
        assert_eq!(ops.info(f).canon_class(), ENodeKind::PlainN);
    }

    #[test]
    fn id_by_name() {
        let int_sort = SortId::new(1);
        let mut ops = OR::new();
        let add = ops.register_mset("Add", int_sort, int_sort);
        assert_eq!(ops.id_by_name("Add"), Some(add));
        assert_eq!(ops.id_by_name("nonexistent"), None);
    }

    #[test]
    #[should_panic(expected = "already registered")]
    fn duplicate_name_panics() {
        let int_sort = SortId::new(1);
        let mut ops = OR::new();
        ops.register_mset("Add", int_sort, int_sort);
        ops.register_mset("Add", int_sort, int_sort);
    }

    #[test]
    fn mset_ops_lists_only_mset() {
        let mut sorts = SR::new();
        let bool_sort = sorts.intern("Bool");
        let int_sort = sorts.intern("Int");

        let mut ops = OR::new();
        ops.register("Not", &[bool_sort], bool_sort); // Normal
        ops.register_c("Eq", [int_sort, int_sort], bool_sort); // Commutative
        ops.register_a("Sub", int_sort, int_sort, AssocDir::Left); // A
        let add = ops.register_mset("Add", int_sort, int_sort); // AC
        let mul = ops.register_mset("Mul", int_sort, int_sort); // AC
        ops.register_set("And", bool_sort, bool_sort); // ACI — must be excluded

        // mset_ops yields exactly the two MSet ids, and is_mset agrees per-op.
        let mut mset_ids: Vec<OpId> = ops.mset_ops().collect();
        mset_ids.sort();
        assert_eq!(mset_ids, vec![add, mul]);

        assert!(ops.is_mset(add));
        assert!(ops.is_mset(mul));
        // ACI is a distinct kind — not AC.
        assert!(!ops.is_mset(ops.id_by_name("And").unwrap()));
        assert!(!ops.is_mset(ops.id_by_name("Sub").unwrap()));
        assert!(!ops.is_mset(ops.id_by_name("Not").unwrap()));
    }

    #[test]
    fn mset_ops_empty_when_none_registered() {
        let int_sort = SortId::new(1);
        let mut ops = OR::new();
        ops.register("F", &[int_sort], int_sort);
        assert_eq!(ops.mset_ops().count(), 0);
    }

    #[test]
    fn completion_ops_mset_then_set_in_registration_order() {
        let mut sorts = SR::new();
        let bool_sort = sorts.intern("Bool");
        let int_sort = sorts.intern("Int");

        let mut ops = OR::new();
        let add = ops.register_mset("Add", int_sort, int_sort);
        let and = ops.register_set("And", bool_sort, bool_sort);
        let mul = ops.register_mset("Mul", int_sort, int_sort);
        let or = ops.register_set("Or", bool_sort, bool_sort);
        ops.register("Not", &[bool_sort], bool_sort); // non-completion op, excluded

        // completion_ops = all MSet (registration order) then all Set (registration order).
        assert_eq!(ops.completion_ops(), vec![add, mul, and, or]);
        assert_eq!(ops.completion_op_count(), 4);
        assert_eq!(ops.set_op_count(), 2);
        assert_eq!(ops.mset_op_count(), 2);

        // column() is the position in that array; non-completion ops have none.
        assert_eq!(ops.completion_column(add), Some(0));
        assert_eq!(ops.completion_column(mul), Some(1));
        assert_eq!(ops.completion_column(and), Some(2));
        assert_eq!(ops.completion_column(or), Some(3));
        assert_eq!(ops.completion_column(ops.id_by_name("Not").unwrap()), None);

        // is_set agrees.
        assert!(ops.is_set(and) && ops.is_set(or));
        assert!(!ops.is_set(add));
    }

    /// The column of a registered op is a table read: no call to `completion_ops`, hence no
    /// allocation and no rescan of the op map, however many times it is asked. This is the
    /// property `EGraph::register_if_fresh` depends on — it asks once per node created.
    #[test]
    fn completion_column_does_not_rebuild_the_column_array() {
        let mut sorts = SR::new();
        let bool_sort = sorts.intern("Bool");
        let int_sort = sorts.intern("Int");

        let mut ops = OR::new();
        let add = ops.register_mset("Add", int_sort, int_sort);
        let and = ops.register_set("And", bool_sort, bool_sort);
        let not = ops.register("Not", &[bool_sort], bool_sort);

        let scans = || COMPLETION_OPS_SCANS.with(|n| n.get());
        let before = scans();
        for _ in 0..1000 {
            assert_eq!(ops.completion_column(add), Some(0));
            assert_eq!(ops.completion_column(and), Some(1));
            assert_eq!(ops.completion_column(not), None);
            assert_eq!(ops.completion_op_count(), 2);
        }
        assert_eq!(
            scans(),
            before,
            "completion_column rebuilt the column array"
        );

        // The counter does fire for the array itself, so the assertion above is not vacuous.
        let _ = ops.completion_ops();
        assert_eq!(scans(), before + 1);
    }

    /// Restore truncates the completion table with the op log: columns and counts after a
    /// restore are the ones the surviving ops alone would produce, and ids registered next
    /// reuse the freed columns. Registering an MSet op after a Set op is the case that moves
    /// existing Set columns, so the table cannot cache columns directly.
    #[test]
    fn completion_columns_restore_with_the_op_log() {
        type TrackedOR = OpRegistry<OpId, SortId, true>;
        let mut sorts = SR::new();
        let bool_sort = sorts.intern("Bool");
        let int_sort = sorts.intern("Int");

        let mut ops = TrackedOR::new();
        let add = ops.register_mset("Add", int_sort, int_sort);
        let and = ops.register_set("And", bool_sort, bool_sort);
        assert_eq!(
            (ops.completion_column(add), ops.completion_column(and)),
            (Some(0), Some(1))
        );

        let token = ops.mark(ShrinkPolicy::Never);
        let mul = ops.register_mset("Mul", int_sort, int_sort);
        let or = ops.register_set("Or", bool_sort, bool_sort);
        // The new MSet op takes column 1, pushing every Set op up one.
        assert_eq!(ops.completion_ops(), vec![add, mul, and, or]);
        assert_eq!(ops.completion_column(mul), Some(1));
        assert_eq!(ops.completion_column(and), Some(2));
        assert_eq!(ops.completion_column(or), Some(3));
        assert_eq!(ops.completion_op_count(), 4);

        ops.restore(token);
        assert_eq!(ops.completion_ops(), vec![add, and]);
        assert_eq!(ops.completion_column(add), Some(0));
        assert_eq!(ops.completion_column(and), Some(1));
        assert_eq!(ops.mset_op_count(), 1);
        assert_eq!(ops.set_op_count(), 1);
        assert_eq!(ops.completion_op_count(), 2);
        // The restored ids are unregistered, so their columns are gone with them.
        assert_eq!(ops.completion_column(mul), None);
        assert_eq!(ops.completion_column(or), None);

        // Registering again after the restore mints the same ids and columns as before.
        let mul2 = ops.register_mset("Mul", int_sort, int_sort);
        assert_eq!(mul2, mul);
        assert_eq!(ops.completion_column(mul2), Some(1));
        assert_eq!(ops.completion_column(and), Some(2));
    }

    #[test]
    fn completion_ops_empty_when_none() {
        let int_sort = SortId::new(1);
        let mut ops = OR::new();
        ops.register("F", &[int_sort], int_sort);
        assert_eq!(ops.completion_ops(), Vec::<OpId>::new());
        assert_eq!(ops.completion_op_count(), 0);
    }
}