1use std::hash::Hash;
6
7use crate::caches::*;
8use crate::canon::{CCanon, MSetCanon, OrderedCanon, PlainCanon, SetCanon, VarCanon};
9use crate::containers::DenseId;
10use crate::containers::ShrinkPolicy;
11use crate::containers::Tagged;
12use crate::multiplicity::Multiplicity;
13use crate::registry::{Clamp, OpKind, OpRegistry};
14use crate::typed_routing::{NodeIds, NodeRef, RoutingToken, TypedRouting};
15
16fn mset_clamp_of<O: DenseId, S: DenseId, const TRACK: bool>(
21 ops: &OpRegistry<O, S, TRACK>,
22 op: O,
23) -> crate::canon::MSetClamp {
24 match ops.info(op).kind {
25 OpKind::MSet {
26 clamp: Clamp::Nilpotent { order },
27 ..
28 } => crate::canon::MSetClamp::Nilpotent { order },
29 _ => crate::canon::MSetClamp::None,
30 }
31}
32
33pub type MSetChild<G, M = Multiplicity> = crate::containers::Pair<G, M>;
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum Added<G> {
45 Existing(G),
46 Fresh(G),
47}
48
49impl<G: Copy> Added<G> {
50 pub fn id(&self) -> G {
51 match *self {
52 Added::Existing(id) | Added::Fresh(id) => id,
53 }
54 }
55 pub fn is_fresh(&self) -> bool {
56 matches!(self, Added::Fresh(_))
57 }
58}
59
60pub struct NodeStore<
61 G: DenseId<Index = I::Index>,
65 O: DenseId,
66 V: DenseId,
67 C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
68 I: NodeIds,
69 const TRACK: bool = true,
70 const PROOFS: bool = false,
71> {
72 routing: TypedRouting<G, I, TRACK>,
73 pub plain0: FixedArityCache<G, O, I::L0, 0, TRACK, PROOFS>,
74 pub plain1: FixedArityCache<G, O, I::L1, 1, TRACK, PROOFS>,
75 pub plain2: FixedArityCache<G, O, I::L2, 2, TRACK, PROOFS>,
76 pub plain3: FixedArityCache<G, O, I::L3, 3, TRACK, PROOFS>,
77 pub spair: FixedArityCache<G, O, I::LSPair, 2, TRACK, PROOFS>,
78 pub plain_n: VariableArityCache<G, O, G, I::LN, TRACK, PROOFS>,
79 pub seq: VariableArityCache<G, O, G, I::LSeq, TRACK, PROOFS>,
80 pub mset: VariableArityCache<G, O, C, I::LMSet, TRACK, PROOFS>,
81 pub set: VariableArityCache<G, O, G, I::LSet, TRACK, PROOFS>,
82 pub lit: LitCache<G, O, V, I::LLit, TRACK>,
83}
84
85impl<G, O, V, C, I, const TRACK: bool, const PROOFS: bool> Default
86 for NodeStore<G, O, V, C, I, TRACK, PROOFS>
87where
88 G: DenseId<Index = I::Index> + Hash,
89 O: DenseId + Hash,
90 V: DenseId + Hash,
91 C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
92 I: NodeIds,
93{
94 fn default() -> Self {
95 Self::new()
96 }
97}
98
99impl<G, O, V, C, I, const TRACK: bool, const PROOFS: bool> NodeStore<G, O, V, C, I, TRACK, PROOFS>
100where
101 G: DenseId<Index = I::Index> + Hash,
102 O: DenseId + Hash,
103 V: DenseId + Hash,
104 C: Tagged + Clone + Copy + Hash + Eq + core::fmt::Debug,
105 I: NodeIds,
106{
107 pub fn new() -> Self {
108 Self {
109 routing: TypedRouting::new(),
110 plain0: FixedArityCache::new(),
111 plain1: FixedArityCache::new(),
112 plain2: FixedArityCache::new(),
113 plain3: FixedArityCache::new(),
114 spair: FixedArityCache::new(),
115 plain_n: VariableArityCache::new(),
116 seq: VariableArityCache::new(),
117 mset: VariableArityCache::new(),
118 set: VariableArityCache::new(),
119 lit: LitCache::new(),
120 }
121 }
122
123 pub fn len(&self) -> usize {
124 self.routing.len()
125 }
126 pub fn is_empty(&self) -> bool {
127 self.routing.is_empty()
128 }
129 pub fn routing(&self) -> &TypedRouting<G, I, TRACK> {
130 &self.routing
131 }
132
133 pub fn add<S: crate::DenseId>(
138 &mut self,
139 op: O,
140 children: &[G],
141 ops: &OpRegistry<O, S, TRACK>,
142 flags: u8,
143 ) -> Added<G> {
144 match ops.info(op).kind {
145 OpKind::Normal { .. } => match children.len() {
146 0 => self.add_plain0(op, flags),
147 1 => self.add_plain1(op, children[0], flags),
148 2 => self.add_plain2(op, [children[0], children[1]], flags),
149 3 => self.add_plain3(op, [children[0], children[1], children[2]], flags),
150 _ => self.add_plain_n(op, children, flags),
151 },
152 OpKind::Commutative { .. } => {
153 assert_eq!(children.len(), 2);
154 let pair = if children[0].to_usize() <= children[1].to_usize() {
155 [children[0], children[1]]
156 } else {
157 [children[1], children[0]]
158 };
159 self.add_c(op, pair, flags)
160 }
161 OpKind::A { .. } => self.add_a(op, children, flags),
162 OpKind::MSet { .. } => panic!("use add_mset with pre-canonicalized children"),
163 OpKind::Set { .. } => panic!("use add_set with pre-canonicalized children"),
164 OpKind::Lit => panic!("use add_lit for literal operators"),
165 }
166 }
167
168 pub fn add_plain0(&mut self, op: O, flags: u8) -> Added<G> {
173 let fresh = self.routing.reserve();
174 match self.plain0.probe_or_insert(fresh, op, []) {
175 InsertResult::Hit { global_id } => {
176 self.routing.unreserve();
177 Added::Existing(global_id)
178 }
179 InsertResult::Inserted { local_id } => {
180 if flags != 0 {
181 let mut n = self.plain0.get(local_id);
182 n.flags |= flags;
183 self.plain0.set(local_id, n);
184 }
185 self.routing.finalize(fresh, NodeRef::Plain0(local_id));
186 Added::Fresh(fresh)
187 }
188 }
189 }
190
191 pub fn add_plain1(&mut self, op: O, child: G, flags: u8) -> Added<G> {
192 let fresh = self.routing.reserve();
193 match self.plain1.probe_or_insert(fresh, op, [child]) {
194 InsertResult::Hit { global_id } => {
195 self.routing.unreserve();
196 Added::Existing(global_id)
197 }
198 InsertResult::Inserted { local_id } => {
199 if flags != 0 {
200 let mut n = self.plain1.get(local_id);
201 n.flags |= flags;
202 self.plain1.set(local_id, n);
203 }
204 self.routing.finalize(fresh, NodeRef::Plain1(local_id));
205 Added::Fresh(fresh)
206 }
207 }
208 }
209
210 pub fn add_plain2(&mut self, op: O, children: [G; 2], flags: u8) -> Added<G> {
211 let fresh = self.routing.reserve();
212 match self.plain2.probe_or_insert(fresh, op, children) {
213 InsertResult::Hit { global_id } => {
214 self.routing.unreserve();
215 Added::Existing(global_id)
216 }
217 InsertResult::Inserted { local_id } => {
218 if flags != 0 {
219 let mut n = self.plain2.get(local_id);
220 n.flags |= flags;
221 self.plain2.set(local_id, n);
222 }
223 self.routing.finalize(fresh, NodeRef::Plain2(local_id));
224 Added::Fresh(fresh)
225 }
226 }
227 }
228
229 pub fn add_plain3(&mut self, op: O, children: [G; 3], flags: u8) -> Added<G> {
230 let fresh = self.routing.reserve();
231 match self.plain3.probe_or_insert(fresh, op, children) {
232 InsertResult::Hit { global_id } => {
233 self.routing.unreserve();
234 Added::Existing(global_id)
235 }
236 InsertResult::Inserted { local_id } => {
237 if flags != 0 {
238 let mut n = self.plain3.get(local_id);
239 n.flags |= flags;
240 self.plain3.set(local_id, n);
241 }
242 self.routing.finalize(fresh, NodeRef::Plain3(local_id));
243 Added::Fresh(fresh)
244 }
245 }
246 }
247
248 pub fn add_c(&mut self, op: O, children: [G; 2], flags: u8) -> Added<G> {
249 let fresh = self.routing.reserve();
250 match self.spair.probe_or_insert(fresh, op, children) {
251 InsertResult::Hit { global_id } => {
252 self.routing.unreserve();
253 Added::Existing(global_id)
254 }
255 InsertResult::Inserted { local_id } => {
256 if flags != 0 {
257 let mut n = self.spair.get(local_id);
258 n.flags |= flags;
259 self.spair.set(local_id, n);
260 }
261 self.routing.finalize(fresh, NodeRef::SPair(local_id));
262 Added::Fresh(fresh)
263 }
264 }
265 }
266
267 pub fn add_plain_n(&mut self, op: O, children: &[G], flags: u8) -> Added<G> {
268 let fresh = self.routing.reserve();
269 match self.plain_n.probe_or_insert(fresh, op, children) {
270 InsertResult::Hit { global_id } => {
271 self.routing.unreserve();
272 Added::Existing(global_id)
273 }
274 InsertResult::Inserted { local_id } => {
275 if flags != 0 {
276 let mut n = self.plain_n.get(local_id);
277 n.flags |= flags;
278 self.plain_n.set(local_id, n);
279 }
280 self.routing.finalize(fresh, NodeRef::PlainN(local_id));
281 Added::Fresh(fresh)
282 }
283 }
284 }
285
286 pub fn add_a(&mut self, op: O, children: &[G], flags: u8) -> Added<G> {
287 let fresh = self.routing.reserve();
288 match self.seq.probe_or_insert(fresh, op, children) {
289 InsertResult::Hit { global_id } => {
290 self.routing.unreserve();
291 Added::Existing(global_id)
292 }
293 InsertResult::Inserted { local_id } => {
294 if flags != 0 {
295 let mut n = self.seq.get(local_id);
296 n.flags |= flags;
297 self.seq.set(local_id, n);
298 }
299 self.routing.finalize(fresh, NodeRef::Seq(local_id));
300 Added::Fresh(fresh)
301 }
302 }
303 }
304
305 pub fn add_mset(&mut self, op: O, children: &[C], flags: u8) -> Added<G> {
306 let fresh = self.routing.reserve();
307 match self.mset.probe_or_insert(fresh, op, children) {
308 InsertResult::Hit { global_id } => {
309 self.routing.unreserve();
310 Added::Existing(global_id)
311 }
312 InsertResult::Inserted { local_id } => {
313 if flags != 0 {
314 let mut n = self.mset.get(local_id);
315 n.flags |= flags;
316 self.mset.set(local_id, n);
317 }
318 self.routing.finalize(fresh, NodeRef::MSet(local_id));
319 Added::Fresh(fresh)
320 }
321 }
322 }
323
324 pub fn add_set(&mut self, op: O, children: &[G], flags: u8) -> Added<G> {
325 let fresh = self.routing.reserve();
326 match self.set.probe_or_insert(fresh, op, children) {
327 InsertResult::Hit { global_id } => {
328 self.routing.unreserve();
329 Added::Existing(global_id)
330 }
331 InsertResult::Inserted { local_id } => {
332 if flags != 0 {
333 let mut n = self.set.get(local_id);
334 n.flags |= flags;
335 self.set.set(local_id, n);
336 }
337 self.routing.finalize(fresh, NodeRef::Set(local_id));
338 Added::Fresh(fresh)
339 }
340 }
341 }
342
343 pub fn add_lit(&mut self, op: O, lit: V, flags: u8) -> Added<G> {
344 let fresh = self.routing.reserve();
345 match self.lit.probe_or_insert(fresh, op, lit) {
346 InsertResult::Hit { global_id } => {
347 self.routing.unreserve();
348 Added::Existing(global_id)
349 }
350 InsertResult::Inserted { local_id } => {
351 if flags != 0 {
352 let mut n = self.lit.get(local_id);
353 n.flags |= flags;
354 self.lit.set(local_id, n);
355 }
356 self.routing.finalize(fresh, NodeRef::Lit(local_id));
357 Added::Fresh(fresh)
358 }
359 }
360 }
361
362 pub fn recanonize_node<S: crate::DenseId>(
377 &mut self,
378 id: G,
379 find: impl Fn(G) -> G,
380 unit_of: impl Fn(O) -> Option<G>,
381 g_buf: &mut Vec<G>,
382 mset_buf: &mut Vec<C>,
383 collisions: &mut Vec<(G, G)>,
384 touched: &mut Vec<G>,
385 ops: &OpRegistry<O, S, TRACK>,
386 ) where
387 MSetCanon: VarCanon<G, C>,
388 {
389 use crate::canon::CanonMode;
390 match self.routing.get(id) {
391 NodeRef::Plain0(_) => {}
392 NodeRef::Plain1(l) => self
393 .plain1
394 .recanonize_node::<PlainCanon>(l, &find, collisions, touched),
395 NodeRef::Plain2(l) => self
396 .plain2
397 .recanonize_node::<PlainCanon>(l, &find, collisions, touched),
398 NodeRef::Plain3(l) => self
399 .plain3
400 .recanonize_node::<PlainCanon>(l, &find, collisions, touched),
401 NodeRef::SPair(l) => self
402 .spair
403 .recanonize_node::<CCanon>(l, &find, collisions, touched),
404 NodeRef::PlainN(l) => self.plain_n.recanonize_node::<OrderedCanon>(
405 l,
406 &find,
407 g_buf,
408 collisions,
409 touched,
410 CanonMode::PLAIN,
411 ),
412 NodeRef::Seq(l) => self.seq.recanonize_node::<OrderedCanon>(
413 l,
414 &find,
415 g_buf,
416 collisions,
417 touched,
418 CanonMode::PLAIN,
419 ),
420 NodeRef::MSet(l) => {
421 let op = self.mset.get(l).op();
426 let mode = CanonMode {
427 clamp: mset_clamp_of(ops, op),
428 unit: unit_of(op),
429 };
430 self.mset
431 .recanonize_node::<MSetCanon>(l, &find, mset_buf, collisions, touched, mode)
432 }
433 NodeRef::Set(l) => {
434 let op = self.set.get(l).op();
435 let mode = CanonMode {
436 clamp: crate::canon::MSetClamp::None,
437 unit: unit_of(op),
438 };
439 self.set
440 .recanonize_node::<SetCanon>(l, &find, g_buf, collisions, touched, mode)
441 }
442 NodeRef::Lit(_) => {}
443 }
444 }
445
446 pub fn original_children(&self, id: G, g_out: &mut Vec<G>, mset_out: &mut Vec<C>) -> bool
454 where
455 MSetCanon: VarCanon<G, C>,
456 {
457 match self.routing.get(id) {
458 NodeRef::Plain0(_) | NodeRef::Lit(_) => false,
459 NodeRef::Plain1(_) => {
460 if let Some(c) = self.plain1.original_children(id) {
461 g_out.extend_from_slice(&c);
462 true
463 } else {
464 false
465 }
466 }
467 NodeRef::Plain2(_) => {
468 if let Some(c) = self.plain2.original_children(id) {
469 g_out.extend_from_slice(&c);
470 true
471 } else {
472 false
473 }
474 }
475 NodeRef::Plain3(_) => {
476 if let Some(c) = self.plain3.original_children(id) {
477 g_out.extend_from_slice(&c);
478 true
479 } else {
480 false
481 }
482 }
483 NodeRef::SPair(_) => {
484 if let Some(c) = self.spair.original_children(id) {
485 g_out.extend_from_slice(&c);
486 true
487 } else {
488 false
489 }
490 }
491 NodeRef::PlainN(_) => self.plain_n.original_children(id, g_out),
492 NodeRef::Seq(_) => self.seq.original_children(id, g_out),
493 NodeRef::MSet(_) => self.mset.original_children(id, mset_out),
494 NodeRef::Set(_) => self.set.original_children(id, g_out),
495 }
496 }
497
498 pub fn mark(&mut self, shrink: ShrinkPolicy) -> NodeStoreToken {
503 NodeStoreToken {
504 routing: self.routing.mark(shrink),
505 plain0: self.plain0.mark(shrink),
506 plain1: self.plain1.mark(shrink),
507 plain2: self.plain2.mark(shrink),
508 plain3: self.plain3.mark(shrink),
509 spair: self.spair.mark(shrink),
510 plain_n: self.plain_n.mark(shrink),
511 seq: self.seq.mark(shrink),
512 mset: self.mset.mark(shrink),
513 set: self.set.mark(shrink),
514 lit: self.lit.mark(shrink),
515 }
516 }
517
518 pub fn restore(&mut self, token: NodeStoreToken) {
519 self.routing.restore(token.routing);
520 self.plain0.restore(token.plain0);
521 self.plain1.restore(token.plain1);
522 self.plain2.restore(token.plain2);
523 self.plain3.restore(token.plain3);
524 self.spair.restore(token.spair);
525 self.plain_n.restore(token.plain_n);
526 self.seq.restore(token.seq);
527 self.mset.restore(token.mset);
528 self.set.restore(token.set);
529 self.lit.restore(token.lit);
530 }
531}
532
533#[derive(Clone, Copy, Debug)]
534pub struct NodeStoreToken {
535 routing: RoutingToken,
536 plain0: CacheToken,
537 plain1: CacheToken,
538 plain2: CacheToken,
539 plain3: CacheToken,
540 spair: CacheToken,
541 plain_n: PoolCacheToken,
542 seq: PoolCacheToken,
543 mset: PoolCacheToken,
544 set: PoolCacheToken,
545 lit: CacheToken,
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551 use crate::id::{ENodeId, OpId, SortId};
552 use crate::nodes::*;
553 use crate::registry::SortRegistry;
554
555 struct TestIds;
556 impl NodeIds for TestIds {
557 type Index = u32;
558 type L0 = Plain0Id;
559 type L1 = Plain1Id;
560 type L2 = Plain2Id;
561 type L3 = Plain3Id;
562 type LSPair = SPairNodeId;
563 type LN = PlainNId;
564 type LSeq = SeqNodeId;
565 type LMSet = MSetNodeId;
566 type LSet = SetNodeId;
567 type LLit = LitNodeId;
568 }
569
570 type NS = NodeStore<ENodeId, OpId, LitValId, MSetChild<ENodeId>, TestIds, false>;
571
572 fn setup() -> (NS, OpRegistry<OpId, SortId, false>) {
573 let mut sorts: SortRegistry<SortId, false> = SortRegistry::new();
574 let int = sorts.intern("Int");
575 let bool_ = sorts.intern("Bool");
576
577 let mut ops: OpRegistry<OpId, SortId, false> = OpRegistry::new();
578 ops.register("Zero", &[], int);
579 ops.register("Neg", &[int], int);
580 ops.register("Div", &[int, int], int);
581 ops.register("ITE", &[bool_, int, int], int);
582 ops.register_c("Eq", [int, int], bool_);
583 ops.register_a("Sub", int, int, crate::registry::AssocDir::Left);
584 ops.register_mset("Add", int, int);
585 ops.register_set("And", bool_, bool_);
586 ops.register_lit("ILit", int);
587
588 (NS::new(), ops)
589 }
590
591 #[test]
592 fn add_and_dedup() {
593 let (mut ns, ops) = setup();
594 let zero = ops.id_by_name("Zero").unwrap();
595
596 let a = ns.add(zero, &[], &ops, 0);
597 assert!(a.is_fresh());
598 let b = ns.add(zero, &[], &ops, 0);
599 assert!(!b.is_fresh());
600 assert_eq!(a.id(), b.id());
601 assert_eq!(ns.len(), 1);
602 }
603
604 #[test]
605 fn commutative_dedup() {
606 let (mut ns, ops) = setup();
607 let eq = ops.id_by_name("Eq").unwrap();
608 let ilit = ops.id_by_name("ILit").unwrap();
609
610 let a = ns.add_lit(ilit, LitValId::new(0), 0);
611 let b = ns.add_lit(ilit, LitValId::new(1), 0);
612
613 let e1 = ns.add(eq, &[a.id(), b.id()], &ops, 0);
614 let e2 = ns.add(eq, &[b.id(), a.id()], &ops, 0);
615 assert!(e1.is_fresh());
616 assert!(!e2.is_fresh());
617 assert_eq!(e1.id(), e2.id());
618 }
619
620 #[test]
621 fn routing_roundtrip() {
622 let (mut ns, ops) = setup();
623 let neg = ops.id_by_name("Neg").unwrap();
624 let ilit = ops.id_by_name("ILit").unwrap();
625
626 let lit = ns.add_lit(ilit, LitValId::new(42), 0);
627 let n = ns.add(neg, &[lit.id()], &ops, 0);
628 let r = ns.routing().get(n.id());
629 assert!(matches!(r, NodeRef::Plain1(_)));
630 }
631
632 #[test]
633 fn recanonize_plain_collision() {
634 let (mut ns, ops) = setup();
635 let neg = ops.id_by_name("Neg").unwrap();
636 let ilit = ops.id_by_name("ILit").unwrap();
637
638 let a = ns.add_lit(ilit, LitValId::new(0), 0).id(); let b = ns.add_lit(ilit, LitValId::new(1), 0).id(); let na = ns.add(neg, &[a], &ops, 0).id(); let nb = ns.add(neg, &[b], &ops, 0).id(); let mut g_buf = Vec::new();
645 let mut mset_buf = Vec::new();
646 let mut collisions = Vec::new();
647 ns.recanonize_node(
648 nb,
649 |g| if g == b { a } else { g },
650 |_op| None,
651 &mut g_buf,
652 &mut mset_buf,
653 &mut collisions,
654 &mut Vec::new(),
655 &ops,
656 );
657 assert_eq!(collisions, vec![(nb, na)]);
659 }
660
661 #[test]
662 fn recanonize_no_change() {
663 let (mut ns, ops) = setup();
664 let neg = ops.id_by_name("Neg").unwrap();
665 let ilit = ops.id_by_name("ILit").unwrap();
666
667 let a = ns.add_lit(ilit, LitValId::new(0), 0).id();
668 let _na = ns.add(neg, &[a], &ops, 0).id();
669
670 let mut g_buf = Vec::new();
671 let mut mset_buf = Vec::new();
672 let mut collisions = Vec::new();
673 ns.recanonize_node(
674 _na,
675 |g| g,
676 |_op| None,
677 &mut g_buf,
678 &mut mset_buf,
679 &mut collisions,
680 &mut Vec::new(),
681 &ops,
682 );
683 assert!(collisions.is_empty());
684 }
685}