1use crate::canon::{MSetCanon, VarCanon};
13use crate::config::EGraphConfig;
14use crate::containers::{DenseId, MapToken, ShrinkPolicy, SpMap};
15use crate::egraph::EGraph;
16use crate::id::ENodeKind;
17use crate::literal::LitVal;
18use crate::multiplicity::{Multiplicity, MultiplicityLike};
19
20use super::AuIds31;
21use super::egraph_api::{AuSnapshot, ClassOf};
22use crate::config::AuIds;
23
24#[derive(Debug)]
26pub struct Action<O: DenseId, A: AuIds = AuIds31, M: MultiplicityLike = Multiplicity> {
27 pub op: O,
28 pub pairs: Vec<ActionPair<A, M>>,
29}
30
31impl<O: DenseId, A: AuIds, M: MultiplicityLike> Clone for Action<O, A, M> {
33 fn clone(&self) -> Self {
34 Action {
35 op: self.op,
36 pairs: self.pairs.clone(),
37 }
38 }
39}
40
41#[derive(Debug)]
58pub struct ActionPair<A: AuIds = AuIds31, M: MultiplicityLike = Multiplicity> {
59 pub left: A::Class,
60 pub right: A::Class,
61 pub count: M,
62}
63
64impl<A: AuIds, M: MultiplicityLike> Clone for ActionPair<A, M> {
65 fn clone(&self) -> Self {
66 *self
67 }
68}
69impl<A: AuIds, M: MultiplicityLike> Copy for ActionPair<A, M> {}
70impl<A: AuIds, M: MultiplicityLike> PartialEq for ActionPair<A, M> {
71 fn eq(&self, other: &Self) -> bool {
72 self.left == other.left && self.right == other.right && self.count == other.count
73 }
74}
75impl<A: AuIds, M: MultiplicityLike> Eq for ActionPair<A, M> {}
76
77pub const DEFAULT_A_MAX: usize = 32;
79
80pub struct ActionCache<O: DenseId, A: AuIds = AuIds31, M: MultiplicityLike = Multiplicity> {
87 index: SpMap<(A::Class, A::Class), A::Action, A::Index>,
92 values: Vec<Vec<Action<O, A, M>>>,
94 a_max: usize,
95 include_ac: bool,
96}
97
98#[derive(Clone, Copy, Debug)]
101pub struct ActionCacheToken {
102 index: MapToken,
103 values_len: usize,
104}
105
106impl<O: DenseId, A: AuIds, M: MultiplicityLike> ActionCache<O, A, M> {
107 pub fn new(a_max: usize) -> Self {
108 ActionCache {
109 index: SpMap::new(),
110 values: Vec::new(),
111 a_max,
112 include_ac: true,
113 }
114 }
115
116 pub fn without_ac_actions(a_max: usize) -> Self {
119 ActionCache {
120 index: SpMap::new(),
121 values: Vec::new(),
122 a_max,
123 include_ac: false,
124 }
125 }
126
127 pub fn include_ac(&self) -> bool {
128 self.include_ac
129 }
130
131 pub fn get(&self, l: A::Class, r: A::Class) -> Option<&[Action<O, A, M>]> {
132 let key = (l, r);
133 self.index.id_of(&key).map(|log_idx| {
134 let &idx = self.index.get_val(log_idx);
135 self.values[idx.to_usize()].as_slice()
136 })
137 }
138
139 pub fn insert(&mut self, l: A::Class, r: A::Class, actions: Vec<Action<O, A, M>>) {
140 let idx = crate::id::id_at::<A::Action>(self.values.len());
145 self.values.push(actions);
146 self.index
147 .try_insert((l, r), idx)
148 .expect("AU arena sized by its index word");
149 }
150
151 pub fn a_max(&self) -> usize {
152 self.a_max
153 }
154
155 pub fn mark(&mut self) -> ActionCacheToken {
156 ActionCacheToken {
157 index: self
158 .index
159 .try_mark(ShrinkPolicy::Never)
160 .expect("mark: depth bounded by the search driver"),
161 values_len: self.values.len(),
162 }
163 }
164
165 pub fn is_valid_token(&self, token: &ActionCacheToken) -> bool {
167 self.index.is_valid_token(&token.index)
168 }
169
170 pub fn restore(&mut self, token: ActionCacheToken) {
171 self.index
172 .try_restore(token.index)
173 .expect("restore: token minted by this container's own mark");
174 self.values.truncate(token.values_len);
175 }
176}
177
178impl<O: DenseId, A: AuIds, M: MultiplicityLike> Default for ActionCache<O, A, M> {
179 fn default() -> Self {
180 Self::new(DEFAULT_A_MAX)
181 }
182}
183
184pub fn generate_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
187 snap: &AuSnapshot<Cfg, L, T, P>,
188 cache: &mut ActionCache<Cfg::O, Cfg::Au, Cfg::M>,
189 l: ClassOf<Cfg>,
190 r: ClassOf<Cfg>,
191) where
192 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
193{
194 if cache.get(l, r).is_some() {
195 return;
196 }
197
198 let eg = snap.egraph();
199 let members_l = snap.members(l);
200 let members_r = snap.members(r);
201 let a_max = cache.a_max();
202 let include_ac = cache.include_ac();
203
204 let mut actions: Vec<Action<Cfg::O, Cfg::Au, Cfg::M>> = Vec::new();
205
206 let mut il = 0;
208 let mut ir = 0;
209
210 while il < members_l.len() && ir < members_r.len() {
211 let (op_l, _) = members_l[il];
212 let (op_r, _) = members_r[ir];
213
214 match op_l.to_usize().cmp(&op_r.to_usize()) {
215 std::cmp::Ordering::Less => {
216 while il < members_l.len() && members_l[il].0 == op_l {
218 il += 1;
219 }
220 }
221 std::cmp::Ordering::Greater => {
222 while ir < members_r.len() && members_r[ir].0 == op_r {
224 ir += 1;
225 }
226 }
227 std::cmp::Ordering::Equal => {
228 let il_start = il;
230 while il < members_l.len() && members_l[il].0 == op_l {
231 il += 1;
232 }
233 let ir_start = ir;
234 while ir < members_r.len() && members_r[ir].0 == op_r {
235 ir += 1;
236 }
237
238 let l_nodes = &members_l[il_start..il];
239 let r_nodes = &members_r[ir_start..ir];
240
241 let kind = eg.ops().info(op_l).canon_class();
242 match kind {
243 ENodeKind::Plain0 => {
244 actions.push(Action {
246 op: op_l,
247 pairs: Vec::new(),
248 });
249 }
250 ENodeKind::Plain1
251 | ENodeKind::Plain2
252 | ENodeKind::Plain3
253 | ENodeKind::PlainN => {
254 generate_ordered_actions(snap, eg, op_l, l_nodes, r_nodes, &mut actions);
255 }
256 ENodeKind::Seq => {
257 generate_seq_actions(snap, eg, op_l, l_nodes, r_nodes, &mut actions);
258 }
259 ENodeKind::SPair => {
260 generate_spair_actions(snap, eg, op_l, l_nodes, r_nodes, &mut actions);
261 }
262 ENodeKind::MSet => {
263 if include_ac {
264 generate_mset_actions(
265 snap,
266 eg,
267 op_l,
268 l_nodes,
269 r_nodes,
270 a_max,
271 &mut actions,
272 );
273 }
274 }
275 ENodeKind::Set => {
276 if include_ac {
277 generate_set_actions(
278 snap,
279 eg,
280 op_l,
281 l_nodes,
282 r_nodes,
283 a_max,
284 &mut actions,
285 );
286 }
287 }
288 ENodeKind::Lit => {
289 generate_lit_actions(eg, op_l, l_nodes, r_nodes, &mut actions);
290 }
291 }
292 }
293 }
294 }
295
296 if !include_ac {
301 dedup_and_insert(cache, l, r, actions);
304 return;
305 }
306 for &(op_id, _) in members_l.iter() {
307 let kind = eg.ops().info(op_id).canon_class();
308 if !matches!(kind, ENodeKind::MSet | ENodeKind::Set) {
309 continue;
310 }
311 let identity = snap.op_identity_class(op_id);
312 if identity.is_none() {
313 continue;
314 }
315 let r_has_op = members_r.iter().any(|&(o, _)| o == op_id);
317 if r_has_op {
318 continue;
319 }
320 let l_op_members: Vec<(Cfg::O, Cfg::G)> = members_l
322 .iter()
323 .filter(|&&(o, _)| o == op_id)
324 .copied()
325 .collect();
326 if kind == ENodeKind::Set {
327 let r_children = vec![(r, Cfg::M::ONE)];
329 for &(_, l_id) in &l_op_members {
330 let mut l_children: Vec<ClassOf<Cfg>> = Vec::new();
331 eg.for_each_child(l_id, |child, _| {
332 l_children.push(snap.class_of(child).unwrap());
333 });
334 let mut l_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
335 l_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
336 let id_class = identity.unwrap();
337 let (Some(r_total), Some(l_total)) =
341 (counts_total(&r_children), counts_total(&l_classes))
342 else {
343 continue;
344 };
345 let mut r_padded = r_children.clone();
346 if l_total > r_total {
347 r_padded.push((id_class, l_total.saturating_sub(r_total)));
348 } else if r_total > l_total
349 && pad_identity(&mut l_classes, id_class, r_total.saturating_sub(l_total))
350 .is_none()
351 {
352 continue;
353 }
354 enumerate_matrices(op_id, &l_classes, &r_padded, a_max, &mut actions);
355 }
356 } else {
357 let mut l_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
359 for &(_, l_id) in &l_op_members {
360 eg.mset_children(l_id, &mut l_mset_buf);
361 let Some((l_classes, l_total)) = mset_counts(snap, &l_mset_buf) else {
362 continue;
363 };
364 let id_class = identity.unwrap();
365 let mut r_classes = vec![(r, Cfg::M::ONE)];
366 if l_total > Cfg::M::ONE {
367 r_classes.push((id_class, l_total.saturating_sub(Cfg::M::ONE)));
368 }
369 enumerate_matrices(op_id, &l_classes, &r_classes, a_max, &mut actions);
370 }
371 }
372 }
373 for &(op_id, _) in members_r.iter() {
375 let kind = eg.ops().info(op_id).canon_class();
376 if !matches!(kind, ENodeKind::MSet | ENodeKind::Set) {
377 continue;
378 }
379 let identity = snap.op_identity_class(op_id);
380 if identity.is_none() {
381 continue;
382 }
383 let l_has_op = members_l.iter().any(|&(o, _)| o == op_id);
384 if l_has_op {
385 continue;
386 }
387 let r_op_members: Vec<(Cfg::O, Cfg::G)> = members_r
388 .iter()
389 .filter(|&&(o, _)| o == op_id)
390 .copied()
391 .collect();
392 if kind == ENodeKind::Set {
393 let l_children = vec![(l, Cfg::M::ONE)];
394 for &(_, r_id) in &r_op_members {
395 let mut r_children: Vec<ClassOf<Cfg>> = Vec::new();
396 eg.for_each_child(r_id, |child, _| {
397 r_children.push(snap.class_of(child).unwrap());
398 });
399 let mut r_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
400 r_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
401 let id_class = identity.unwrap();
402 let (Some(r_total), Some(l_total)) =
404 (counts_total(&r_classes), counts_total(&l_children))
405 else {
406 continue;
407 };
408 let mut l_padded = l_children.clone();
409 if r_total > l_total {
410 l_padded.push((id_class, r_total.saturating_sub(l_total)));
411 } else if l_total > r_total
412 && pad_identity(&mut r_classes, id_class, l_total.saturating_sub(r_total))
413 .is_none()
414 {
415 continue;
416 }
417 enumerate_matrices(op_id, &l_padded, &r_classes, a_max, &mut actions);
418 }
419 } else {
420 let mut r_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
421 for &(_, r_id) in &r_op_members {
422 eg.mset_children(r_id, &mut r_mset_buf);
423 let Some((r_classes, r_total)) = mset_counts(snap, &r_mset_buf) else {
424 continue;
425 };
426 let id_class = identity.unwrap();
427 let mut l_classes = vec![(l, Cfg::M::ONE)];
428 if r_total > Cfg::M::ONE {
429 l_classes.push((id_class, r_total.saturating_sub(Cfg::M::ONE)));
430 }
431 enumerate_matrices(op_id, &l_classes, &r_classes, a_max, &mut actions);
432 }
433 }
434 }
435
436 dedup_and_insert(cache, l, r, actions);
437}
438
439fn dedup_and_insert<O: DenseId, A: AuIds, M: MultiplicityLike>(
445 cache: &mut ActionCache<O, A, M>,
446 l: A::Class,
447 r: A::Class,
448 mut actions: Vec<Action<O, A, M>>,
449) {
450 let mut seen: hashbrown::HashSet<(O, Vec<(A::Class, A::Class, M)>)> = hashbrown::HashSet::new();
460 actions.retain(|action| {
461 let mut sig: Vec<(A::Class, A::Class, M)> = action
462 .pairs
463 .iter()
464 .map(|p| (p.left, p.right, p.count))
465 .collect();
466 sig.sort_unstable();
467 seen.insert((action.op, sig))
468 });
469 cache.insert(l, r, actions);
470}
471
472fn generate_ordered_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
474 snap: &AuSnapshot<Cfg, L, T, P>,
475 eg: &EGraph<Cfg, L, T, P>,
476 op: Cfg::O,
477 l_nodes: &[(Cfg::O, Cfg::G)],
478 r_nodes: &[(Cfg::O, Cfg::G)],
479 actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
480) where
481 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
482{
483 for &(_, l_id) in l_nodes {
484 let l_arity = eg.for_each_child(l_id, |_, _| {});
485 for &(_, r_id) in r_nodes {
486 let r_arity = eg.for_each_child(r_id, |_, _| {});
487 if l_arity != r_arity {
488 continue;
489 }
490 let mut pairs = Vec::with_capacity(l_arity);
492 let mut l_children = Vec::with_capacity(l_arity);
493 let mut r_children = Vec::with_capacity(r_arity);
494 eg.for_each_child(l_id, |child, _| l_children.push(child));
495 eg.for_each_child(r_id, |child, _| r_children.push(child));
496
497 for i in 0..l_arity {
498 let lc = snap.class_of(l_children[i]).unwrap();
499 let rc = snap.class_of(r_children[i]).unwrap();
500 pairs.push(ActionPair::<Cfg::Au, Cfg::M> {
501 left: lc,
502 right: rc,
503 count: Cfg::M::ONE,
504 });
505 }
506 actions.push(Action { op, pairs });
507 }
508 }
509}
510
511fn generate_seq_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
515 snap: &AuSnapshot<Cfg, L, T, P>,
516 eg: &EGraph<Cfg, L, T, P>,
517 op: Cfg::O,
518 l_nodes: &[(Cfg::O, Cfg::G)],
519 r_nodes: &[(Cfg::O, Cfg::G)],
520 actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
521) where
522 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
523{
524 generate_ordered_actions(snap, eg, op, l_nodes, r_nodes, actions);
526}
527
528fn generate_spair_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
531 snap: &AuSnapshot<Cfg, L, T, P>,
532 eg: &EGraph<Cfg, L, T, P>,
533 op: Cfg::O,
534 l_nodes: &[(Cfg::O, Cfg::G)],
535 r_nodes: &[(Cfg::O, Cfg::G)],
536 actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
537) where
538 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
539{
540 for &(_, l_id) in l_nodes {
541 let mut l_children = [<ClassOf<Cfg>>::default(); 2];
542 let mut li = 0;
543 eg.for_each_child(l_id, |child, _| {
544 if li < 2 {
545 l_children[li] = snap.class_of(child).unwrap();
546 li += 1;
547 }
548 });
549
550 for &(_, r_id) in r_nodes {
551 let mut r_children = [<ClassOf<Cfg>>::default(); 2];
552 let mut ri = 0;
553 eg.for_each_child(r_id, |child, _| {
554 if ri < 2 {
555 r_children[ri] = snap.class_of(child).unwrap();
556 ri += 1;
557 }
558 });
559
560 let pairs1 = vec![
562 ActionPair::<Cfg::Au, Cfg::M> {
563 left: l_children[0],
564 right: r_children[0],
565 count: Cfg::M::ONE,
566 },
567 ActionPair::<Cfg::Au, Cfg::M> {
568 left: l_children[1],
569 right: r_children[1],
570 count: Cfg::M::ONE,
571 },
572 ];
573 actions.push(Action { op, pairs: pairs1 });
574
575 if !(l_children[0] == l_children[1] || r_children[0] == r_children[1]) {
577 let pairs2 = vec![
578 ActionPair::<Cfg::Au, Cfg::M> {
579 left: l_children[0],
580 right: r_children[1],
581 count: Cfg::M::ONE,
582 },
583 ActionPair::<Cfg::Au, Cfg::M> {
584 left: l_children[1],
585 right: r_children[0],
586 count: Cfg::M::ONE,
587 },
588 ];
589 actions.push(Action { op, pairs: pairs2 });
590 }
591 }
592 }
593}
594
595fn generate_mset_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
602 snap: &AuSnapshot<Cfg, L, T, P>,
603 eg: &EGraph<Cfg, L, T, P>,
604 op: Cfg::O,
605 l_nodes: &[(Cfg::O, Cfg::G)],
606 r_nodes: &[(Cfg::O, Cfg::G)],
607 a_max: usize,
608 actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
609) where
610 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
611{
612 let identity_class = snap.op_identity_class(op);
613 let mut l_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
614 let mut r_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
615
616 for &(_, l_id) in l_nodes {
617 eg.mset_children(l_id, &mut l_mset_buf);
618 let Some((l_read, l_total)) = mset_counts(snap, &l_mset_buf) else {
620 continue;
621 };
622
623 for &(_, r_id) in r_nodes {
624 eg.mset_children(r_id, &mut r_mset_buf);
625 let Some((r_read, r_total)) = mset_counts(snap, &r_mset_buf) else {
626 continue;
627 };
628
629 let mut l_classes = l_read.clone();
630 let mut r_classes = r_read;
631
632 if l_total != r_total {
633 let Some(id_class) = identity_class else {
635 continue;
636 };
637 let padded = if l_total < r_total {
638 pad_identity(&mut l_classes, id_class, r_total.saturating_sub(l_total))
639 } else {
640 pad_identity(&mut r_classes, id_class, l_total.saturating_sub(r_total))
641 };
642 if padded.is_none() {
643 continue;
644 }
645 }
646
647 enumerate_matrices(op, &l_classes, &r_classes, a_max, actions);
648 }
649 }
650}
651
652fn generate_set_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
657 snap: &AuSnapshot<Cfg, L, T, P>,
658 eg: &EGraph<Cfg, L, T, P>,
659 op: Cfg::O,
660 l_nodes: &[(Cfg::O, Cfg::G)],
661 r_nodes: &[(Cfg::O, Cfg::G)],
662 a_max: usize,
663 actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
664) where
665 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
666{
667 let identity_class = snap.op_identity_class(op);
668
669 for &(_, l_id) in l_nodes {
670 let mut l_children: Vec<ClassOf<Cfg>> = Vec::new();
671 eg.for_each_child(l_id, |child, _| {
672 l_children.push(snap.class_of(child).unwrap());
673 });
674
675 for &(_, r_id) in r_nodes {
676 let mut r_children: Vec<ClassOf<Cfg>> = Vec::new();
677 eg.for_each_child(r_id, |child, _| {
678 r_children.push(snap.class_of(child).unwrap());
679 });
680
681 if l_children.len() != r_children.len() {
682 let Some(id_class) = identity_class else {
683 continue;
684 };
685 while l_children.len() < r_children.len() {
687 l_children.push(id_class);
688 }
689 while r_children.len() < l_children.len() {
690 r_children.push(id_class);
691 }
692 }
693
694 let l_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
695 l_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
696 let r_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
697 r_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
698
699 enumerate_matrices(op, &l_classes, &r_classes, a_max, actions);
700 }
701 }
702}
703
704fn generate_lit_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
706 eg: &EGraph<Cfg, L, T, P>,
707 op: Cfg::O,
708 l_nodes: &[(Cfg::O, Cfg::G)],
709 r_nodes: &[(Cfg::O, Cfg::G)],
710 actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
711) where
712 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
713{
714 for &(_, l_id) in l_nodes {
715 let l_val = eg.get_lit_val_id(l_id);
716 for &(_, r_id) in r_nodes {
717 let r_val = eg.get_lit_val_id(r_id);
718 if l_val == r_val {
719 actions.push(Action {
721 op,
722 pairs: Vec::new(),
723 });
724 }
725 }
726 }
727}
728
729fn mset_counts<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
743 snap: &AuSnapshot<Cfg, L, T, P>,
744 buf: &[(Cfg::G, Cfg::M)],
745) -> Option<(Vec<(ClassOf<Cfg>, Cfg::M)>, Cfg::M)>
746where
747 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
748{
749 let mut out: Vec<(ClassOf<Cfg>, Cfg::M)> = Vec::with_capacity(buf.len());
750 let mut total = Cfg::M::ZERO;
751 for (g, m) in buf {
752 out.push((snap.class_of(*g).unwrap(), *m));
753 total = total.checked_add(*m)?;
754 }
755 Some((out, total))
756}
757
758fn counts_total<C, M: MultiplicityLike>(v: &[(C, M)]) -> Option<M> {
760 v.iter()
761 .try_fold(M::ZERO, |acc, (_, k)| acc.checked_add(*k))
762}
763
764fn pad_identity<C: PartialEq, M: MultiplicityLike>(
767 v: &mut Vec<(C, M)>,
768 id_class: C,
769 deficit: M,
770) -> Option<()> {
771 match v.iter_mut().find(|(c, _)| *c == id_class) {
772 Some(entry) => entry.1 = entry.1.checked_add(deficit)?,
773 None => v.push((id_class, deficit)),
774 }
775 Some(())
776}
777
778fn enumerate_matrices<O: DenseId, A: AuIds, M: MultiplicityLike>(
793 op: O,
794 l_classes: &[(A::Class, M)],
795 r_classes: &[(A::Class, M)],
796 a_max: usize,
797 actions: &mut Vec<Action<O, A, M>>,
798) {
799 let rows = l_classes.len();
800 let cols = r_classes.len();
801
802 if rows == 0 || cols == 0 {
803 return;
804 }
805
806 let row_sums: Vec<M> = l_classes.iter().map(|(_, m)| *m).collect();
807 let col_residual: Vec<M> = r_classes.iter().map(|(_, m)| *m).collect();
808 let mut matrix: Vec<Vec<M>> = vec![vec![M::ZERO; cols]; rows];
809 let mut count = 0;
810
811 enumerate_row(
812 op,
813 l_classes,
814 r_classes,
815 &row_sums,
816 &mut matrix,
817 0,
818 &mut col_residual.clone(),
819 a_max,
820 &mut count,
821 actions,
822 );
823}
824
825#[allow(clippy::too_many_arguments)]
826fn enumerate_row<O: DenseId, A: AuIds, M: MultiplicityLike>(
827 op: O,
828 l_classes: &[(A::Class, M)],
829 r_classes: &[(A::Class, M)],
830 row_sums: &[M],
831 matrix: &mut [Vec<M>],
832 row: usize,
833 col_residual: &mut Vec<M>,
834 a_max: usize,
835 count: &mut usize,
836 actions: &mut Vec<Action<O, A, M>>,
837) {
838 if *count >= a_max {
839 return;
840 }
841
842 let rows = l_classes.len();
843 let cols = r_classes.len();
844
845 if row == rows {
846 let mut pairs: Vec<ActionPair<A, M>> = Vec::new();
847 for i in 0..rows {
848 for j in 0..cols {
849 if matrix[i][j] > M::ZERO {
850 pairs.push(ActionPair::<A, M> {
851 left: l_classes[i].0,
852 right: r_classes[j].0,
853 count: matrix[i][j],
854 });
855 }
856 }
857 }
858 actions.push(Action { op, pairs });
859 *count += 1;
860 return;
861 }
862
863 distribute_row(
864 op,
865 l_classes,
866 r_classes,
867 row_sums,
868 matrix,
869 row,
870 0,
871 row_sums[row],
872 col_residual,
873 a_max,
874 count,
875 actions,
876 );
877}
878
879#[allow(clippy::too_many_arguments)]
880fn distribute_row<O: DenseId, A: AuIds, M: MultiplicityLike>(
881 op: O,
882 l_classes: &[(A::Class, M)],
883 r_classes: &[(A::Class, M)],
884 row_sums: &[M],
885 matrix: &mut [Vec<M>],
886 row: usize,
887 col: usize,
888 remaining: M,
889 col_residual: &mut Vec<M>,
890 a_max: usize,
891 count: &mut usize,
892 actions: &mut Vec<Action<O, A, M>>,
893) {
894 if *count >= a_max {
895 return;
896 }
897
898 let cols = r_classes.len();
899
900 if col == cols - 1 {
901 if remaining <= col_residual[col] {
902 let saved = col_residual[col];
906 matrix[row][col] = remaining;
907 col_residual[col] = saved.saturating_sub(remaining);
908 enumerate_row(
909 op,
910 l_classes,
911 r_classes,
912 row_sums,
913 matrix,
914 row + 1,
915 col_residual,
916 a_max,
917 count,
918 actions,
919 );
920 col_residual[col] = saved;
921 matrix[row][col] = M::ZERO;
922 }
923 return;
924 }
925
926 let max_assign = remaining.min(col_residual[col]);
927 let saved = col_residual[col];
928
929 let greedy = l_classes[row].0 == r_classes[col].0;
932 if greedy {
933 for val in descending_upto(max_assign) {
935 matrix[row][col] = val;
936 col_residual[col] = saved.saturating_sub(val);
937 distribute_row(
938 op,
939 l_classes,
940 r_classes,
941 row_sums,
942 matrix,
943 row,
944 col + 1,
945 remaining.saturating_sub(val),
946 col_residual,
947 a_max,
948 count,
949 actions,
950 );
951 col_residual[col] = saved;
952 matrix[row][col] = M::ZERO;
953 if *count >= a_max {
954 return;
955 }
956 }
957 } else {
958 for val in descending_upto(max_assign) {
960 matrix[row][col] = val;
961 col_residual[col] = saved.saturating_sub(val);
962 distribute_row(
963 op,
964 l_classes,
965 r_classes,
966 row_sums,
967 matrix,
968 row,
969 col + 1,
970 remaining.saturating_sub(val),
971 col_residual,
972 a_max,
973 count,
974 actions,
975 );
976 col_residual[col] = saved;
977 matrix[row][col] = M::ZERO;
978 if *count >= a_max {
979 return;
980 }
981 }
982 }
983}
984
985fn descending_upto<M: MultiplicityLike>(max: M) -> impl Iterator<Item = M> {
993 (0..=max.to_u64()).rev().map(|v| {
994 M::try_from_u64(v).expect("a value at or below `max` fits the width `max` came from")
995 })
996}
997
998#[cfg(test)]
999mod tests {
1000 use super::*;
1001 use crate::egraph::EGraph31;
1002 use crate::literal::NiraLitVal;
1003
1004 #[test]
1006 fn appendix_b_six_actions() {
1007 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1008 let int = eg.intern_sort("Int");
1009 let a_op = eg.register_op0("a", int);
1010 let b_op = eg.register_op0("b", int);
1011 let c_op = eg.register_op0("c", int);
1012 let d_op = eg.register_op0("d", int);
1013 let and_op = eg.register_set("and", int, int);
1014
1015 let a = eg.add(a_op, &[]);
1016 let b = eg.add(b_op, &[]);
1017 let c = eg.add(c_op, &[]);
1018 let d = eg.add(d_op, &[]);
1019 let and_abc = eg.add(and_op, &[a, b, c]);
1020 let and_bcd = eg.add(and_op, &[b, c, d]);
1021 eg.rebuild();
1022
1023 let snap = AuSnapshot::new(&eg).unwrap();
1024 let l = snap.class_of(and_abc).unwrap();
1025 let r = snap.class_of(and_bcd).unwrap();
1026
1027 let mut cache = ActionCache::new(100);
1028 generate_actions(&snap, &mut cache, l, r);
1029
1030 let acts = cache.get(l, r).unwrap();
1031 assert_eq!(acts.len(), 6, "expected 6 actions, got {}", acts.len());
1033
1034 for action in acts {
1036 assert_eq!(action.pairs.len(), 3);
1037 for pair in &action.pairs {
1038 assert_eq!(pair.count, Multiplicity::ONE);
1039 }
1040 }
1041 }
1042
1043 #[test]
1045 fn ac_repeated_children() {
1046 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1047 let int = eg.intern_sort("Int");
1048 let a_op = eg.register_op0("a", int);
1049 let b_op = eg.register_op0("b", int);
1050 let plus_op = eg.register_mset("plus", int, int);
1051
1052 let a = eg.add(a_op, &[]);
1053 let b = eg.add(b_op, &[]);
1054 let plus_aa = eg.add(plus_op, &[a, a]);
1055 let plus_ab = eg.add(plus_op, &[a, b]);
1056 eg.rebuild();
1057
1058 let snap = AuSnapshot::new(&eg).unwrap();
1059 let l = snap.class_of(plus_aa).unwrap();
1060 let r = snap.class_of(plus_ab).unwrap();
1061
1062 let mut cache = ActionCache::new(100);
1063 generate_actions(&snap, &mut cache, l, r);
1064
1065 let acts = cache.get(l, r).unwrap();
1066 assert_eq!(acts.len(), 1, "expected 1 action, got {}", acts.len());
1069 assert_eq!(acts[0].pairs.len(), 2);
1070 }
1071
1072 #[test]
1074 fn ordered_positional_zip() {
1075 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1076 let int = eg.intern_sort("Int");
1077 let a_op = eg.register_op0("a", int);
1078 let b_op = eg.register_op0("b", int);
1079 let c_op = eg.register_op0("c", int);
1080 let d_op = eg.register_op0("d", int);
1081 let f_op = eg.register_op2("f", int, int, int);
1082
1083 let a = eg.add(a_op, &[]);
1084 let b = eg.add(b_op, &[]);
1085 let c = eg.add(c_op, &[]);
1086 let d = eg.add(d_op, &[]);
1087 let fab = eg.add(f_op, &[a, b]);
1088 let fcd = eg.add(f_op, &[c, d]);
1089 eg.rebuild();
1090
1091 let snap = AuSnapshot::new(&eg).unwrap();
1092 let l = snap.class_of(fab).unwrap();
1093 let r = snap.class_of(fcd).unwrap();
1094
1095 let mut cache = ActionCache::new(100);
1096 generate_actions(&snap, &mut cache, l, r);
1097
1098 let acts = cache.get(l, r).unwrap();
1099 assert_eq!(acts.len(), 1);
1100 assert_eq!(acts[0].pairs.len(), 2);
1101 assert_eq!(acts[0].pairs[0].count, Multiplicity::ONE);
1102 assert_eq!(acts[0].pairs[1].count, Multiplicity::ONE);
1103 }
1104
1105 #[test]
1107 fn seq_equal_length_zips_positionally() {
1108 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1109 let int = eg.intern_sort("Int");
1110 let a_op = eg.register_op0("a", int);
1111 let b_op = eg.register_op0("b", int);
1112 let c_op = eg.register_op0("c", int);
1113 let d_op = eg.register_op0("d", int);
1114 let seq_op = eg.register_a("seq", int, int, crate::registry::AssocDir::Both);
1115
1116 let a = eg.add(a_op, &[]);
1117 let b = eg.add(b_op, &[]);
1118 let c = eg.add(c_op, &[]);
1119 let d = eg.add(d_op, &[]);
1120 let left = eg.add(seq_op, &[a, b]);
1121 let right = eg.add(seq_op, &[c, d]);
1122 eg.rebuild();
1123
1124 let snap = AuSnapshot::new(&eg).unwrap();
1125 let left_class = snap.class_of(left).unwrap();
1126 let right_class = snap.class_of(right).unwrap();
1127 let mut cache = ActionCache::new(100);
1128 generate_actions(&snap, &mut cache, left_class, right_class);
1129
1130 let actions = cache.get(left_class, right_class).unwrap();
1131 assert_eq!(actions.len(), 1);
1132 assert_eq!(actions[0].pairs.len(), 2);
1133 assert_eq!(actions[0].pairs[0].left, snap.class_of(a).unwrap());
1134 assert_eq!(actions[0].pairs[0].right, snap.class_of(c).unwrap());
1135 assert_eq!(actions[0].pairs[1].left, snap.class_of(b).unwrap());
1136 assert_eq!(actions[0].pairs[1].right, snap.class_of(d).unwrap());
1137 }
1138
1139 #[test]
1141 fn seq_unequal_length_has_no_structural_action() {
1142 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1143 let int = eg.intern_sort("Int");
1144 let a_op = eg.register_op0("a", int);
1145 let b_op = eg.register_op0("b", int);
1146 let c_op = eg.register_op0("c", int);
1147 let d_op = eg.register_op0("d", int);
1148 let e_op = eg.register_op0("e", int);
1149 let seq_op = eg.register_a("seq", int, int, crate::registry::AssocDir::Both);
1150
1151 let a = eg.add(a_op, &[]);
1152 let b = eg.add(b_op, &[]);
1153 let c = eg.add(c_op, &[]);
1154 let d = eg.add(d_op, &[]);
1155 let e = eg.add(e_op, &[]);
1156 let left = eg.add(seq_op, &[a, b]);
1157 let right = eg.add(seq_op, &[c, d, e]);
1158 eg.rebuild();
1159
1160 let snap = AuSnapshot::new(&eg).unwrap();
1161 let left_class = snap.class_of(left).unwrap();
1162 let right_class = snap.class_of(right).unwrap();
1163 let mut cache = ActionCache::new(100);
1164 generate_actions(&snap, &mut cache, left_class, right_class);
1165
1166 assert!(cache.get(left_class, right_class).unwrap().is_empty());
1167 }
1168
1169 #[test]
1171 fn spair_two_orientations() {
1172 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1173 let int = eg.intern_sort("Int");
1174 let a_op = eg.register_op0("a", int);
1175 let b_op = eg.register_op0("b", int);
1176 let c_op = eg.register_op0("c", int);
1177 let d_op = eg.register_op0("d", int);
1178 let eq_op = eg.register_c("eq", [int, int], int);
1179
1180 let a = eg.add(a_op, &[]);
1181 let b = eg.add(b_op, &[]);
1182 let c = eg.add(c_op, &[]);
1183 let d = eg.add(d_op, &[]);
1184 let eq_ab = eg.add(eq_op, &[a, b]);
1185 let eq_cd = eg.add(eq_op, &[c, d]);
1186 eg.rebuild();
1187
1188 let snap = AuSnapshot::new(&eg).unwrap();
1189 let l = snap.class_of(eq_ab).unwrap();
1190 let r = snap.class_of(eq_cd).unwrap();
1191
1192 let mut cache = ActionCache::new(100);
1193 generate_actions(&snap, &mut cache, l, r);
1194
1195 let acts = cache.get(l, r).unwrap();
1196 assert_eq!(acts.len(), 2, "expected 2 orientations");
1197 }
1198
1199 #[test]
1201 fn spair_dedup_same_children() {
1202 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1203 let int = eg.intern_sort("Int");
1204 let a_op = eg.register_op0("a", int);
1205 let c_op = eg.register_op0("c", int);
1206 let d_op = eg.register_op0("d", int);
1207 let eq_op = eg.register_c("eq", [int, int], int);
1208
1209 let a = eg.add(a_op, &[]);
1210 let c = eg.add(c_op, &[]);
1211 let d = eg.add(d_op, &[]);
1212 let eq_aa = eg.add(eq_op, &[a, a]);
1213 let eq_cd = eg.add(eq_op, &[c, d]);
1214 eg.rebuild();
1215
1216 let snap = AuSnapshot::new(&eg).unwrap();
1217 let l = snap.class_of(eq_aa).unwrap();
1218 let r = snap.class_of(eq_cd).unwrap();
1219
1220 let mut cache = ActionCache::new(100);
1221 generate_actions(&snap, &mut cache, l, r);
1222
1223 let acts = cache.get(l, r).unwrap();
1224 assert_eq!(
1225 acts.len(),
1226 1,
1227 "dedup: only 1 orientation when l children are same"
1228 );
1229 }
1230
1231 #[test]
1235 fn identity_padding_unequal_cardinality() {
1236 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1237 let bool_s = eg.intern_sort("Bool");
1238 let a_op = eg.register_op0("a", bool_s);
1239 let b_op = eg.register_op0("b", bool_s);
1240 let c_op = eg.register_op0("c", bool_s);
1241 let tt_op = eg.register_op0("tt", bool_s);
1242 let conj_op = eg.register_set("conj", bool_s, bool_s);
1243
1244 let a = eg.add(a_op, &[]);
1245 let b = eg.add(b_op, &[]);
1246 let c = eg.add(c_op, &[]);
1247 let tt = eg.add(tt_op, &[]);
1248 eg.set_unit_node(conj_op, tt);
1249
1250 let left = eg.add(conj_op, &[a, b, c]); let right = eg.add(conj_op, &[b, c]); eg.rebuild();
1253
1254 let snap = AuSnapshot::new(&eg).unwrap();
1255 let lc = snap.class_of(left).unwrap();
1256 let rc = snap.class_of(right).unwrap();
1257
1258 let mut cache = ActionCache::new(100);
1259 generate_actions(&snap, &mut cache, lc, rc);
1260
1261 let acts = cache.get(lc, rc).unwrap();
1262 assert!(
1266 !acts.is_empty(),
1267 "identity padding should produce actions for unequal cardinality"
1268 );
1269 let has_identity_pair = acts.iter().any(|action| {
1271 action.pairs.len() == 3
1272 && action.pairs.iter().any(|p| {
1273 let tt_class = snap.class_of(tt).unwrap();
1274 (p.left == snap.class_of(a).unwrap() && p.right == tt_class)
1275 || (p.right == snap.class_of(a).unwrap() && p.left == tt_class)
1276 })
1277 });
1278 assert!(has_identity_pair, "one action should pair `a` with `tt`");
1279 }
1280
1281 #[test]
1287 fn ac_complete_enumeration_includes_all_matrices() {
1288 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1289 let int = eg.intern_sort("Int");
1290 let a_op = eg.register_op0("a", int);
1291 let b_op = eg.register_op0("b", int);
1292 let c_op = eg.register_op0("c", int);
1293 let d_op = eg.register_op0("d", int);
1294 let plus_op = eg.register_mset("plus", int, int);
1295
1296 let a = eg.add(a_op, &[]);
1297 let b = eg.add(b_op, &[]);
1298 let c = eg.add(c_op, &[]);
1299 let d = eg.add(d_op, &[]);
1300 let left = eg.add(plus_op, &[a, a, b, b]); let right = eg.add(plus_op, &[c, c, d, d]); eg.rebuild();
1303
1304 let snap = AuSnapshot::new(&eg).unwrap();
1305 let lc = snap.class_of(left).unwrap();
1306 let rc = snap.class_of(right).unwrap();
1307
1308 let mut cache = ActionCache::new(100);
1309 generate_actions(&snap, &mut cache, lc, rc);
1310
1311 let acts = cache.get(lc, rc).unwrap();
1312 assert_eq!(
1314 acts.len(),
1315 3,
1316 "expected 3 complete matrices, got {}",
1317 acts.len()
1318 );
1319 }
1320
1321 #[test]
1323 fn literal_same_value() {
1324 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1325 let int = eg.intern_sort("Int");
1326 let lit_op = eg.register_lit("intlit", int);
1327
1328 let val1 = eg.intern_lit(crate::literal::NiraLitVal::Int(42.into()));
1329 let val2 = eg.intern_lit(crate::literal::NiraLitVal::Int(99.into()));
1330
1331 let l = eg.add_lit(lit_op, val1);
1332 let r1 = eg.add_lit(lit_op, val1);
1333 let r2 = eg.add_lit(lit_op, val2);
1334 eg.rebuild();
1335
1336 let snap = AuSnapshot::new(&eg).unwrap();
1337 let lc = snap.class_of(l).unwrap();
1338 let r1c = snap.class_of(r1).unwrap();
1339 let r2c = snap.class_of(r2).unwrap();
1340
1341 let mut cache = ActionCache::new(100);
1343 generate_actions(&snap, &mut cache, lc, r1c);
1344 let acts = cache.get(lc, r1c).unwrap();
1345 assert_eq!(acts.len(), 1);
1346
1347 generate_actions(&snap, &mut cache, lc, r2c);
1349 let acts = cache.get(lc, r2c).unwrap();
1350 assert_eq!(acts.len(), 0);
1351 }
1352
1353 #[test]
1358 fn cross_operator_actions_survive_dedup() {
1359 let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1360 let int = eg.intern_sort("Int");
1361 let a_op = eg.register_op0("a", int);
1362 let b_op = eg.register_op0("b", int);
1363 let f_op = eg.register_op1("f", int, int);
1364 let g_op = eg.register_op1("g", int, int);
1365
1366 let a = eg.add(a_op, &[]);
1367 let b = eg.add(b_op, &[]);
1368 let fa = eg.add(f_op, &[a]);
1369 let ga = eg.add(g_op, &[a]);
1370 let fb = eg.add(f_op, &[b]);
1371 let gb = eg.add(g_op, &[b]);
1372 eg.merge(fa, ga);
1373 eg.merge(fb, gb);
1374 eg.rebuild();
1375
1376 let snap = AuSnapshot::new(&eg).unwrap();
1377 let l = snap.class_of(fa).unwrap();
1378 let r = snap.class_of(fb).unwrap();
1379
1380 let mut cache = ActionCache::new(100);
1381 generate_actions(&snap, &mut cache, l, r);
1382
1383 let acts = cache.get(l, r).unwrap();
1384 assert_eq!(
1385 acts.len(),
1386 2,
1387 "expected one action per operator, got {}",
1388 acts.len()
1389 );
1390 assert_ne!(
1391 acts[0].op, acts[1].op,
1392 "the two actions must differ in operator"
1393 );
1394 for action in acts {
1395 assert_eq!(action.pairs.len(), 1);
1396 assert_eq!(action.pairs[0].count, Multiplicity::ONE);
1397 }
1398 }
1399}