1use logicaffeine_kernel::{normalize, ring, Literal as KLiteral, Term};
31
32use super::{CompilerEGraph, CompilerENode, NodeId};
33use crate::optimize::ScalarKind;
34
35pub struct Rewrite {
36 pub name: &'static str,
37 pub apply: fn(&mut CompilerEGraph, NodeId) -> Option<NodeId>,
38 pub certificate: Certificate,
39}
40
41#[derive(Debug, Clone)]
48pub enum RingExpr {
49 Var(u8),
50 Const(i64),
51 Add(Box<RingExpr>, Box<RingExpr>),
52 Sub(Box<RingExpr>, Box<RingExpr>),
53 Mul(Box<RingExpr>, Box<RingExpr>),
54}
55
56#[derive(Debug, Clone)]
59pub enum BoolExpr {
60 Var(u8),
61 Const(bool),
62 And(Box<BoolExpr>, Box<BoolExpr>),
63 Or(Box<BoolExpr>, Box<BoolExpr>),
64 Not(Box<BoolExpr>),
65}
66
67pub enum Certificate {
68 Ring { lhs: RingExpr, rhs: RingExpr },
70 BoolCases {
73 vars: u8,
74 lhs: BoolExpr,
75 rhs: BoolExpr,
76 },
77 Bitvector { check: fn() -> Result<(), String> },
80 LogosProperty {
85 program: &'static str,
86 expected: &'static str,
87 },
88}
89
90fn s_lit(n: i64) -> Term {
93 Term::App(
94 Box::new(Term::Global("SLit".to_string())),
95 Box::new(Term::Lit(KLiteral::Int(n))),
96 )
97}
98
99fn s_var(i: i64) -> Term {
100 Term::App(
101 Box::new(Term::Global("SVar".to_string())),
102 Box::new(Term::Lit(KLiteral::Int(i))),
103 )
104}
105
106fn s_name(name: &str) -> Term {
107 Term::App(
108 Box::new(Term::Global("SName".to_string())),
109 Box::new(Term::Lit(KLiteral::Text(name.to_string()))),
110 )
111}
112
113fn s_app(f: Term, x: Term) -> Term {
114 Term::App(
115 Box::new(Term::App(
116 Box::new(Term::Global("SApp".to_string())),
117 Box::new(f),
118 )),
119 Box::new(x),
120 )
121}
122
123fn s_binop(op: &str, a: Term, b: Term) -> Term {
124 s_app(s_app(s_name(op), a), b)
125}
126
127fn ring_to_syntax(e: &RingExpr) -> Term {
128 match e {
129 RingExpr::Var(i) => s_var(*i as i64),
130 RingExpr::Const(k) => s_lit(*k),
131 RingExpr::Add(a, b) => s_binop("add", ring_to_syntax(a), ring_to_syntax(b)),
132 RingExpr::Sub(a, b) => s_binop("sub", ring_to_syntax(a), ring_to_syntax(b)),
133 RingExpr::Mul(a, b) => s_binop("mul", ring_to_syntax(a), ring_to_syntax(b)),
134 }
135}
136
137fn check_ring(lhs: &RingExpr, rhs: &RingExpr) -> Result<(), String> {
138 let mut vars = logicaffeine_kernel::VarInterner::new();
139 let pl = ring::reify(&ring_to_syntax(lhs), &mut vars)
140 .map_err(|e| format!("ring reify (lhs): {e:?}"))?;
141 let pr = ring::reify(&ring_to_syntax(rhs), &mut vars)
142 .map_err(|e| format!("ring reify (rhs): {e:?}"))?;
143 if pl.canonical_eq(&pr) {
144 Ok(())
145 } else {
146 Err("polynomials differ".to_string())
147 }
148}
149
150fn k_bool(b: bool) -> Term {
153 Term::Global(if b { "true" } else { "false" }.to_string())
154}
155
156fn match_bool(disc: Term, on_true: Term, on_false: Term) -> Term {
157 Term::Match {
158 discriminant: Box::new(disc),
159 motive: Box::new(Term::Lambda {
160 param: "_b".to_string(),
161 param_type: Box::new(Term::Global("Bool".to_string())),
162 body: Box::new(Term::Global("Bool".to_string())),
163 }),
164 cases: vec![on_true, on_false],
165 }
166}
167
168fn bool_to_term(e: &BoolExpr, valuation: &[bool]) -> Term {
173 match e {
174 BoolExpr::Var(i) => k_bool(valuation[*i as usize]),
175 BoolExpr::Const(b) => k_bool(*b),
176 BoolExpr::And(a, b) => match_bool(
177 bool_to_term(a, valuation),
178 bool_to_term(b, valuation),
179 k_bool(false),
180 ),
181 BoolExpr::Or(a, b) => match_bool(
182 bool_to_term(a, valuation),
183 k_bool(true),
184 bool_to_term(b, valuation),
185 ),
186 BoolExpr::Not(a) => match_bool(bool_to_term(a, valuation), k_bool(false), k_bool(true)),
187 }
188}
189
190fn check_bool_cases(vars: u8, lhs: &BoolExpr, rhs: &BoolExpr) -> Result<(), String> {
191 let ctx = logicaffeine_kernel::prelude::StandardLibrary::context();
192 for bits in 0..(1u32 << vars) {
193 let valuation: Vec<bool> = (0..vars).map(|i| bits & (1 << i) != 0).collect();
194 let nl = normalize(ctx, &bool_to_term(lhs, &valuation));
195 let nr = normalize(ctx, &bool_to_term(rhs, &valuation));
196 if nl != nr {
197 return Err(format!("valuation {valuation:?}: {nl:?} ≠ {nr:?}"));
198 }
199 }
200 Ok(())
201}
202
203const GRID: &[i64] = &[
208 i64::MIN,
209 i64::MIN + 1,
210 i64::MIN / 2,
211 -4_294_967_296,
212 -65_537,
213 -255,
214 -65,
215 -64,
216 -63,
217 -9,
218 -8,
219 -7,
220 -3,
221 -2,
222 -1,
223 0,
224 1,
225 2,
226 3,
227 7,
228 8,
229 9,
230 63,
231 64,
232 65,
233 255,
234 65_537,
235 4_294_967_296,
236 i64::MAX / 2,
237 i64::MAX - 1,
238 i64::MAX,
239];
240
241const POWERS: &[u32] = &[0, 1, 2, 3, 5, 16, 31, 32, 62];
242
243fn bv_mul_pow2_is_shl() -> Result<(), String> {
244 for &x in GRID {
245 for &n in POWERS {
246 let p = 1i64.wrapping_shl(n);
247 let mul = x.wrapping_mul(p);
248 let shl = x.wrapping_shl(n);
249 if mul != shl {
250 return Err(format!("{x} * 2^{n}: mul {mul} ≠ shl {shl}"));
251 }
252 }
253 }
254 Ok(())
255}
256
257fn bv_div_pow2_is_shr_nonneg() -> Result<(), String> {
258 for &x in GRID.iter().filter(|&&x| x >= 0) {
259 for &n in POWERS {
260 let p = 1i64.wrapping_shl(n);
261 if p <= 0 {
262 continue;
263 }
264 let div = x.wrapping_div(p);
265 let shr = x.wrapping_shr(n);
266 if div != shr {
267 return Err(format!("{x} / 2^{n}: div {div} ≠ shr {shr}"));
268 }
269 }
270 }
271 if (-7i64).wrapping_div(4) == (-7i64).wrapping_shr(2) {
273 return Err("guard witness failed: -7/4 should differ from -7>>2".to_string());
274 }
275 Ok(())
276}
277
278fn bv_mod_pow2_is_and_nonneg() -> Result<(), String> {
279 for &x in GRID.iter().filter(|&&x| x >= 0) {
280 for &n in POWERS {
281 let p = 1i64.wrapping_shl(n);
282 if p <= 0 {
283 continue;
284 }
285 let md = x.wrapping_rem(p);
286 let masked = x & (p - 1);
287 if md != masked {
288 return Err(format!("{x} % 2^{n}: rem {md} ≠ mask {masked}"));
289 }
290 }
291 }
292 if (-7i64).wrapping_rem(4) == (-7i64 & 3) {
293 return Err("guard witness failed: -7%4 should differ from -7&3".to_string());
294 }
295 Ok(())
296}
297
298fn bv_div_one_is_identity() -> Result<(), String> {
299 for &x in GRID {
300 if x.wrapping_div(1) != x {
301 return Err(format!("{x} / 1 ≠ {x}"));
302 }
303 }
304 Ok(())
305}
306
307fn bv_fold_evaluator_matches_kernel() -> Result<(), String> {
312 for &a in GRID {
313 for &b in GRID {
314 let cases: &[(&str, Option<i64>, Option<i64>)] = &[
318 ("add", fold_binop(FoldOp::Add, a, b), a.checked_add(b)),
319 ("sub", fold_binop(FoldOp::Sub, a, b), a.checked_sub(b)),
320 ("mul", fold_binop(FoldOp::Mul, a, b), a.checked_mul(b)),
321 (
322 "div",
323 fold_binop(FoldOp::Div, a, b),
324 if b == 0 { None } else { a.checked_div(b) },
325 ),
326 (
327 "mod",
328 fold_binop(FoldOp::Mod, a, b),
329 if b == 0 { None } else { a.checked_rem(b) },
330 ),
331 (
332 "shl",
333 fold_binop(FoldOp::Shl, a, b),
334 Some(a.wrapping_shl(b as u32)),
335 ),
336 (
337 "shr",
338 fold_binop(FoldOp::Shr, a, b),
339 Some(a.wrapping_shr(b as u32)),
340 ),
341 ("xor", fold_binop(FoldOp::Xor, a, b), Some(a ^ b)),
342 ("and", fold_binop(FoldOp::And, a, b), Some(a & b)),
343 ("or", fold_binop(FoldOp::Or, a, b), Some(a | b)),
344 ];
345 for (name, got, want) in cases {
346 if got != want {
347 return Err(format!("fold {name}({a}, {b}): {got:?} ≠ {want:?}"));
348 }
349 }
350 }
351 }
352 Ok(())
353}
354
355#[derive(Clone, Copy)]
360pub(crate) enum FoldOp {
361 Add,
362 Sub,
363 Mul,
364 Div,
365 Mod,
366 Shl,
367 Shr,
368 Xor,
369 And,
370 Or,
371}
372
373pub(crate) fn fold_binop(op: FoldOp, a: i64, b: i64) -> Option<i64> {
379 match op {
380 FoldOp::Add => a.checked_add(b),
381 FoldOp::Sub => a.checked_sub(b),
382 FoldOp::Mul => a.checked_mul(b),
383 FoldOp::Div => {
384 if b == 0 {
385 return None;
386 }
387 a.checked_div(b)
388 }
389 FoldOp::Mod => {
390 if b == 0 {
391 return None;
392 }
393 a.checked_rem(b)
394 }
395 FoldOp::Shl => Some(a.wrapping_shl(b as u32)),
396 FoldOp::Shr => Some(a.wrapping_shr(b as u32)),
397 FoldOp::Xor => Some(a ^ b),
398 FoldOp::And => Some(a & b),
399 FoldOp::Or => Some(a | b),
400 }
401}
402
403fn is_int(eg: &mut CompilerEGraph, id: NodeId) -> bool {
408 eg.scalar_of(id) == Some(ScalarKind::Int)
409}
410
411fn is_bool(eg: &mut CompilerEGraph, id: NodeId) -> bool {
412 eg.scalar_of(id) == Some(ScalarKind::Bool)
413}
414
415fn removable(eg: &mut CompilerEGraph, id: NodeId) -> bool {
417 eg.provably_total(id)
418}
419
420fn proven(eg: &mut CompilerEGraph, id: NodeId, k: i64) -> bool {
423 eg.int_value(id) == Some(k)
424}
425
426fn r_add_zero(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
431 if let CompilerENode::Add(l, r) = eg.canonical_node(id) {
432 if proven(eg, r, 0) && is_int(eg, l) && removable(eg, r) {
433 return Some(l);
434 }
435 if proven(eg, l, 0) && is_int(eg, r) && removable(eg, l) {
436 return Some(r);
437 }
438 }
439 None
440}
441
442fn r_mul_one(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
443 if let CompilerENode::Mul(l, r) = eg.canonical_node(id) {
444 if proven(eg, r, 1) && is_int(eg, l) && removable(eg, r) {
445 return Some(l);
446 }
447 if proven(eg, l, 1) && is_int(eg, r) && removable(eg, l) {
448 return Some(r);
449 }
450 }
451 None
452}
453
454fn r_mul_zero(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
455 if let CompilerENode::Mul(l, r) = eg.canonical_node(id) {
456 let zero_side = if proven(eg, r, 0) {
457 Some((r, l))
458 } else if proven(eg, l, 0) {
459 Some((l, r))
460 } else {
461 None
462 };
463 if let Some((zero, other)) = zero_side {
464 if is_int(eg, other) && removable(eg, other) && removable(eg, zero) {
466 let z = eg.add(CompilerENode::Int(0));
467 return Some(z);
468 }
469 }
470 }
471 None
472}
473
474fn r_sub_zero(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
475 if let CompilerENode::Sub(l, r) = eg.canonical_node(id) {
476 if proven(eg, r, 0) && is_int(eg, l) && removable(eg, r) {
477 return Some(l);
478 }
479 }
480 None
481}
482
483fn r_sub_self(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
484 if let CompilerENode::Sub(l, r) = eg.canonical_node(id) {
485 if eg.find(l) == eg.find(r) && is_int(eg, l) && removable(eg, l) {
486 let z = eg.add(CompilerENode::Int(0));
487 return Some(z);
488 }
489 }
490 None
491}
492
493fn r_div_one(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
494 if let CompilerENode::Div(l, r) = eg.canonical_node(id) {
495 if proven(eg, r, 1) && is_int(eg, l) && removable(eg, r) {
496 return Some(l);
497 }
498 }
499 None
500}
501
502fn r_not_not_bool(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
503 if let CompilerENode::Not(inner) = eg.canonical_node(id) {
504 for m in eg.class_members(inner) {
505 if let CompilerENode::Not(x) = eg.canonical_node(m) {
506 if is_bool(eg, x) {
507 return Some(x);
508 }
509 }
510 }
511 }
512 None
513}
514
515fn r_true_and(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
526 if let CompilerENode::And(l, r) = eg.canonical_node(id) {
527 if eg.class_has_bool(l, true) && is_bool(eg, r) && removable(eg, l) {
528 return Some(r);
529 }
530 }
531 None
532}
533
534fn r_false_and(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
535 if let CompilerENode::And(l, r) = eg.canonical_node(id) {
536 if eg.class_has_bool(l, false) && is_bool(eg, r) && removable(eg, l) {
539 let f = eg.add(CompilerENode::Bool(false));
540 return Some(f);
541 }
542 }
543 None
544}
545
546fn r_true_or(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
547 if let CompilerENode::Or(l, r) = eg.canonical_node(id) {
548 if eg.class_has_bool(l, true) && is_bool(eg, r) && removable(eg, l) {
549 let t = eg.add(CompilerENode::Bool(true));
550 return Some(t);
551 }
552 }
553 None
554}
555
556fn r_false_or(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
557 if let CompilerENode::Or(l, r) = eg.canonical_node(id) {
558 if eg.class_has_bool(l, false) && is_bool(eg, r) && removable(eg, l) {
559 return Some(r);
560 }
561 }
562 None
563}
564
565fn r_and_self(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
566 if let CompilerENode::And(l, r) = eg.canonical_node(id) {
567 if eg.find(l) == eg.find(r) && is_bool(eg, l) {
570 return Some(l);
571 }
572 }
573 None
574}
575
576fn r_or_self(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
577 if let CompilerENode::Or(l, r) = eg.canonical_node(id) {
578 if eg.find(l) == eg.find(r) && is_bool(eg, l) {
579 return Some(l);
580 }
581 }
582 None
583}
584
585fn class_negates(eg: &mut CompilerEGraph, maybe_not: NodeId, base: NodeId) -> bool {
587 let broot = eg.find(base);
588 for m in eg.class_members(maybe_not) {
589 if let CompilerENode::Not(x) = eg.canonical_node(m) {
590 if eg.find(x) == broot {
591 return true;
592 }
593 }
594 }
595 false
596}
597
598fn r_and_not_self(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
599 if let CompilerENode::And(l, r) = eg.canonical_node(id) {
600 if is_bool(eg, l)
601 && (class_negates(eg, r, l) || class_negates(eg, l, r))
602 && removable(eg, l)
603 && removable(eg, r)
604 {
605 let f = eg.add(CompilerENode::Bool(false));
606 return Some(f);
607 }
608 }
609 None
610}
611
612fn r_or_not_self(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
613 if let CompilerENode::Or(l, r) = eg.canonical_node(id) {
614 if is_bool(eg, l)
615 && (class_negates(eg, r, l) || class_negates(eg, l, r))
616 && removable(eg, l)
617 && removable(eg, r)
618 {
619 let t = eg.add(CompilerENode::Bool(true));
620 return Some(t);
621 }
622 }
623 None
624}
625
626fn pow2_log(k: i64) -> Option<u32> {
631 if k > 0 && (k as u64).is_power_of_two() {
632 Some(k.trailing_zeros())
633 } else {
634 None
635 }
636}
637
638fn r_mul_two_add(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
639 if let CompilerENode::Mul(l, r) = eg.canonical_node(id) {
640 let x = if proven(eg, r, 2) && removable(eg, r) {
641 Some(l)
642 } else if proven(eg, l, 2) && removable(eg, l) {
643 Some(r)
644 } else {
645 None
646 };
647 if let Some(x) = x {
648 if is_int(eg, x) {
649 let sum = eg.add(CompilerENode::Add(x, x));
650 return Some(sum);
651 }
652 }
653 }
654 None
655}
656
657fn mul_pow2_fits_i64(range: Option<(i64, i64)>, n: u32) -> bool {
663 let Some((lo, hi)) = range else { return false };
664 if n >= 63 {
665 return false;
666 }
667 let m = 1i64 << n;
668 lo.checked_mul(m).is_some() && hi.checked_mul(m).is_some()
669}
670
671fn r_mul_pow2_shl(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
672 if let CompilerENode::Mul(l, r) = eg.canonical_node(id) {
673 let hit = if let Some(n) = eg.int_value(r).and_then(pow2_log) {
674 if removable(eg, r) {
675 Some((l, n))
676 } else {
677 None
678 }
679 } else if let Some(n) = eg.int_value(l).and_then(pow2_log) {
680 if removable(eg, l) {
681 Some((r, n))
682 } else {
683 None
684 }
685 } else {
686 None
687 };
688 if let Some((x, n)) = hit {
689 if is_int(eg, x) && mul_pow2_fits_i64(eg.int_range(x), n) {
695 let shift = eg.add(CompilerENode::Int(n as i64));
696 let shl = eg.add(CompilerENode::Shl(x, shift));
697 return Some(shl);
698 }
699 }
700 }
701 None
702}
703
704fn r_div_pow2_shr(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
705 if let CompilerENode::Div(l, r) = eg.canonical_node(id) {
706 if let Some(n) = eg.int_value(r).and_then(pow2_log) {
707 if is_int(eg, l) && eg.proven_nonneg(l) && removable(eg, r) {
710 let shift = eg.add(CompilerENode::Int(n as i64));
711 let shr = eg.add(CompilerENode::Shr(l, shift));
712 return Some(shr);
713 }
714 }
715 }
716 None
717}
718
719fn r_mod_pow2_and(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
720 if let CompilerENode::Mod(l, r) = eg.canonical_node(id) {
721 if let Some(k) = eg.int_value(r) {
722 if pow2_log(k).is_some() && is_int(eg, l) && eg.proven_nonneg(l) && removable(eg, r) {
723 let mask = eg.add(CompilerENode::Int(k - 1));
724 let masked = eg.add(CompilerENode::BitAnd(l, mask));
725 return Some(masked);
726 }
727 }
728 }
729 None
730}
731
732fn member_matching(
740 eg: &mut CompilerEGraph,
741 class: NodeId,
742 pred: fn(&CompilerENode) -> bool,
743) -> Option<CompilerENode> {
744 let members = eg.class_members(class);
745 members.into_iter().map(|m| eg.canonical_node(m)).find(pred)
746}
747
748fn r_len_copy(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
751 if let CompilerENode::Len(c) = eg.canonical_node(id) {
752 if let Some(CompilerENode::Copy(inner)) =
753 member_matching(eg, c, |n| matches!(n, CompilerENode::Copy(_)))
754 {
755 if eg.proven_collection(inner) {
756 return Some(eg.add(CompilerENode::Len(inner)));
757 }
758 }
759 }
760 None
761}
762
763fn r_index_copy(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
766 if let CompilerENode::Index(c, i) = eg.canonical_node(id) {
767 if let Some(CompilerENode::Copy(inner)) =
768 member_matching(eg, c, |n| matches!(n, CompilerENode::Copy(_)))
769 {
770 if eg.proven_collection(inner) {
771 return Some(eg.add(CompilerENode::Index(inner, i)));
772 }
773 }
774 }
775 None
776}
777
778fn r_copy_copy(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
782 if let CompilerENode::Copy(c) = eg.canonical_node(id) {
783 if member_matching(eg, c, |n| matches!(n, CompilerENode::Copy(_))).is_some() {
784 return Some(eg.find(c));
785 }
786 }
787 None
788}
789
790fn r_slice_full_copy(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
794 if let CompilerENode::Slice(xs, a, b) = eg.canonical_node(id) {
795 if eg.int_value(a) == Some(1) && eg.proven_list(xs) {
796 let len_match = member_matching(eg, b, |n| matches!(n, CompilerENode::Len(_)));
797 if let Some(CompilerENode::Len(c2)) = len_match {
798 if eg.find(c2) == eg.find(xs) {
799 return Some(eg.add(CompilerENode::Copy(xs)));
800 }
801 }
802 }
803 }
804 None
805}
806
807fn r_len_slice_bounds(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
812 if let CompilerENode::Len(s) = eg.canonical_node(id) {
813 let slice = member_matching(eg, s, |n| matches!(n, CompilerENode::Slice(..)));
814 if let Some(CompilerENode::Slice(xs, a, b)) = slice {
815 let (Some(av), Some(bv)) = (eg.int_value(a), eg.int_value(b)) else {
816 return None;
817 };
818 if av < 1 || av > bv.saturating_add(1) || !eg.proven_list(xs) {
819 return None;
820 }
821 let len_class = eg.add(CompilerENode::Len(xs));
822 let Some((len_lo, _)) = eg.int_range(len_class) else {
823 return None;
824 };
825 if bv <= len_lo && removable(eg, xs) {
826 return Some(eg.add(CompilerENode::Int(bv - av + 1)));
827 }
828 }
829 }
830 None
831}
832
833fn r_add_comm(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
840 if let CompilerENode::Add(l, r) = eg.canonical_node(id) {
841 if is_int(eg, l) && is_int(eg, r) && removable(eg, l) && removable(eg, r) {
844 let flipped = eg.add(CompilerENode::Add(r, l));
845 return Some(flipped);
846 }
847 }
848 None
849}
850
851fn r_mul_comm(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
852 if let CompilerENode::Mul(l, r) = eg.canonical_node(id) {
853 if is_int(eg, l) && is_int(eg, r) && removable(eg, l) && removable(eg, r) {
854 let flipped = eg.add(CompilerENode::Mul(r, l));
855 return Some(flipped);
856 }
857 }
858 None
859}
860
861fn r_add_assoc(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
862 if let CompilerENode::Add(l, c) = eg.canonical_node(id) {
863 if !is_int(eg, c) {
864 return None;
865 }
866 for m in eg.class_members(l) {
867 if let CompilerENode::Add(a, b) = eg.canonical_node(m) {
868 if is_int(eg, a) && is_int(eg, b) {
869 let bc = eg.add(CompilerENode::Add(b, c));
870 let abc = eg.add(CompilerENode::Add(a, bc));
871 return Some(abc);
872 }
873 }
874 }
875 }
876 None
877}
878
879fn r_mul_assoc(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
880 if let CompilerENode::Mul(l, c) = eg.canonical_node(id) {
881 if !is_int(eg, c) {
882 return None;
883 }
884 for m in eg.class_members(l) {
885 if let CompilerENode::Mul(a, b) = eg.canonical_node(m) {
886 if is_int(eg, a) && is_int(eg, b) {
887 let bc = eg.add(CompilerENode::Mul(b, c));
888 let abc = eg.add(CompilerENode::Mul(a, bc));
889 return Some(abc);
890 }
891 }
892 }
893 }
894 None
895}
896
897fn r_gauss_butterfly(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
906 if let CompilerENode::Add(l, r) = eg.canonical_node(id) {
907 for lm in eg.class_members(l) {
908 if let CompilerENode::Mul(la, lb) = eg.canonical_node(lm) {
909 for rm in eg.class_members(r) {
910 if let CompilerENode::Mul(ra, rb) = eg.canonical_node(rm) {
911 if [la, lb, ra, rb]
912 .iter()
913 .all(|&x| is_int(eg, x) && removable(eg, x))
914 {
915 let sum_a = eg.add(CompilerENode::Add(la, ra));
916 let sum_b = eg.add(CompilerENode::Add(lb, rb));
917 let prod = eg.add(CompilerENode::Mul(sum_a, sum_b));
918 let cross1 = eg.add(CompilerENode::Mul(la, rb));
919 let cross2 = eg.add(CompilerENode::Mul(ra, lb));
920 let s1 = eg.add(CompilerENode::Sub(prod, cross1));
921 let res = eg.add(CompilerENode::Sub(s1, cross2));
922 return Some(res);
923 }
924 }
925 }
926 }
927 }
928 }
929 None
930}
931
932fn r_const_fold(eg: &mut CompilerEGraph, id: NodeId) -> Option<NodeId> {
938 let node = eg.canonical_node(id);
939 let op = match node {
940 CompilerENode::Add(..) => FoldOp::Add,
941 CompilerENode::Sub(..) => FoldOp::Sub,
942 CompilerENode::Mul(..) => FoldOp::Mul,
943 CompilerENode::Div(..) => FoldOp::Div,
944 CompilerENode::Mod(..) => FoldOp::Mod,
945 CompilerENode::Shl(..) => FoldOp::Shl,
946 CompilerENode::Shr(..) => FoldOp::Shr,
947 CompilerENode::BitXor(..) => FoldOp::Xor,
948 CompilerENode::BitAnd(..) => FoldOp::And,
949 CompilerENode::BitOr(..) => FoldOp::Or,
950 _ => return None,
951 };
952 let (l, r) = match node {
953 CompilerENode::Add(l, r)
954 | CompilerENode::Sub(l, r)
955 | CompilerENode::Mul(l, r)
956 | CompilerENode::Div(l, r)
957 | CompilerENode::Mod(l, r)
958 | CompilerENode::Shl(l, r)
959 | CompilerENode::Shr(l, r)
960 | CompilerENode::BitXor(l, r)
961 | CompilerENode::BitAnd(l, r)
962 | CompilerENode::BitOr(l, r) => (l, r),
963 _ => unreachable!(),
964 };
965 if eg.find(id) == eg.find(l) || eg.find(id) == eg.find(r) {
966 return None;
969 }
970 let a = eg.int_value(l)?;
971 let b = eg.int_value(r)?;
972 if !(removable(eg, l) && removable(eg, r)) {
973 return None;
974 }
975 let v = fold_binop(op, a, b)?;
976 let lit = eg.add(CompilerENode::Int(v));
977 Some(lit)
978}
979
980fn rx(e: RingExpr) -> Box<RingExpr> {
985 Box::new(e)
986}
987
988fn bx(e: BoolExpr) -> Box<BoolExpr> {
989 Box::new(e)
990}
991
992pub fn all() -> Vec<Rewrite> {
993 use BoolExpr as B;
994 use RingExpr as R;
995 vec![
996 Rewrite {
997 name: "add-zero",
998 apply: r_add_zero,
999 certificate: Certificate::Ring {
1000 lhs: R::Add(rx(R::Var(0)), rx(R::Const(0))),
1001 rhs: R::Var(0),
1002 },
1003 },
1004 Rewrite {
1005 name: "mul-one",
1006 apply: r_mul_one,
1007 certificate: Certificate::Ring {
1008 lhs: R::Mul(rx(R::Var(0)), rx(R::Const(1))),
1009 rhs: R::Var(0),
1010 },
1011 },
1012 Rewrite {
1013 name: "mul-zero",
1014 apply: r_mul_zero,
1015 certificate: Certificate::Ring {
1016 lhs: R::Mul(rx(R::Var(0)), rx(R::Const(0))),
1017 rhs: R::Const(0),
1018 },
1019 },
1020 Rewrite {
1021 name: "sub-zero",
1022 apply: r_sub_zero,
1023 certificate: Certificate::Ring {
1024 lhs: R::Sub(rx(R::Var(0)), rx(R::Const(0))),
1025 rhs: R::Var(0),
1026 },
1027 },
1028 Rewrite {
1029 name: "sub-self",
1030 apply: r_sub_self,
1031 certificate: Certificate::Ring {
1032 lhs: R::Sub(rx(R::Var(0)), rx(R::Var(0))),
1033 rhs: R::Const(0),
1034 },
1035 },
1036 Rewrite {
1037 name: "gauss-butterfly",
1038 apply: r_gauss_butterfly,
1039 certificate: Certificate::Ring {
1040 lhs: R::Add(
1042 rx(R::Mul(rx(R::Var(0)), rx(R::Var(1)))),
1043 rx(R::Mul(rx(R::Var(2)), rx(R::Var(3)))),
1044 ),
1045 rhs: R::Sub(
1046 rx(R::Sub(
1047 rx(R::Mul(
1048 rx(R::Add(rx(R::Var(0)), rx(R::Var(2)))),
1049 rx(R::Add(rx(R::Var(1)), rx(R::Var(3)))),
1050 )),
1051 rx(R::Mul(rx(R::Var(0)), rx(R::Var(3)))),
1052 )),
1053 rx(R::Mul(rx(R::Var(2)), rx(R::Var(1)))),
1054 ),
1055 },
1056 },
1057 Rewrite {
1058 name: "div-one",
1059 apply: r_div_one,
1060 certificate: Certificate::Bitvector {
1061 check: bv_div_one_is_identity,
1062 },
1063 },
1064 Rewrite {
1065 name: "not-not-bool",
1066 apply: r_not_not_bool,
1067 certificate: Certificate::BoolCases {
1068 vars: 1,
1069 lhs: B::Not(bx(B::Not(bx(B::Var(0))))),
1070 rhs: B::Var(0),
1071 },
1072 },
1073 Rewrite {
1074 name: "true-and",
1075 apply: r_true_and,
1076 certificate: Certificate::BoolCases {
1077 vars: 1,
1078 lhs: B::And(bx(B::Const(true)), bx(B::Var(0))),
1079 rhs: B::Var(0),
1080 },
1081 },
1082 Rewrite {
1083 name: "false-and",
1084 apply: r_false_and,
1085 certificate: Certificate::BoolCases {
1086 vars: 1,
1087 lhs: B::And(bx(B::Const(false)), bx(B::Var(0))),
1088 rhs: B::Const(false),
1089 },
1090 },
1091 Rewrite {
1092 name: "true-or",
1093 apply: r_true_or,
1094 certificate: Certificate::BoolCases {
1095 vars: 1,
1096 lhs: B::Or(bx(B::Const(true)), bx(B::Var(0))),
1097 rhs: B::Const(true),
1098 },
1099 },
1100 Rewrite {
1101 name: "false-or",
1102 apply: r_false_or,
1103 certificate: Certificate::BoolCases {
1104 vars: 1,
1105 lhs: B::Or(bx(B::Const(false)), bx(B::Var(0))),
1106 rhs: B::Var(0),
1107 },
1108 },
1109 Rewrite {
1110 name: "and-self",
1111 apply: r_and_self,
1112 certificate: Certificate::BoolCases {
1113 vars: 1,
1114 lhs: B::And(bx(B::Var(0)), bx(B::Var(0))),
1115 rhs: B::Var(0),
1116 },
1117 },
1118 Rewrite {
1119 name: "or-self",
1120 apply: r_or_self,
1121 certificate: Certificate::BoolCases {
1122 vars: 1,
1123 lhs: B::Or(bx(B::Var(0)), bx(B::Var(0))),
1124 rhs: B::Var(0),
1125 },
1126 },
1127 Rewrite {
1128 name: "and-not-self",
1129 apply: r_and_not_self,
1130 certificate: Certificate::BoolCases {
1131 vars: 1,
1132 lhs: B::And(bx(B::Var(0)), bx(B::Not(bx(B::Var(0))))),
1133 rhs: B::Const(false),
1134 },
1135 },
1136 Rewrite {
1137 name: "or-not-self",
1138 apply: r_or_not_self,
1139 certificate: Certificate::BoolCases {
1140 vars: 1,
1141 lhs: B::Or(bx(B::Var(0)), bx(B::Not(bx(B::Var(0))))),
1142 rhs: B::Const(true),
1143 },
1144 },
1145 Rewrite {
1146 name: "mul-two-add",
1147 apply: r_mul_two_add,
1148 certificate: Certificate::Ring {
1149 lhs: R::Mul(rx(R::Var(0)), rx(R::Const(2))),
1150 rhs: R::Add(rx(R::Var(0)), rx(R::Var(0))),
1151 },
1152 },
1153 Rewrite {
1154 name: "mul-pow2-shl",
1155 apply: r_mul_pow2_shl,
1156 certificate: Certificate::Bitvector {
1157 check: bv_mul_pow2_is_shl,
1158 },
1159 },
1160 Rewrite {
1161 name: "div-pow2-shr",
1162 apply: r_div_pow2_shr,
1163 certificate: Certificate::Bitvector {
1164 check: bv_div_pow2_is_shr_nonneg,
1165 },
1166 },
1167 Rewrite {
1168 name: "mod-pow2-and",
1169 apply: r_mod_pow2_and,
1170 certificate: Certificate::Bitvector {
1171 check: bv_mod_pow2_is_and_nonneg,
1172 },
1173 },
1174 Rewrite {
1175 name: "add-comm",
1176 apply: r_add_comm,
1177 certificate: Certificate::Ring {
1178 lhs: R::Add(rx(R::Var(0)), rx(R::Var(1))),
1179 rhs: R::Add(rx(R::Var(1)), rx(R::Var(0))),
1180 },
1181 },
1182 Rewrite {
1183 name: "add-assoc",
1184 apply: r_add_assoc,
1185 certificate: Certificate::Ring {
1186 lhs: R::Add(rx(R::Add(rx(R::Var(0)), rx(R::Var(1)))), rx(R::Var(2))),
1187 rhs: R::Add(rx(R::Var(0)), rx(R::Add(rx(R::Var(1)), rx(R::Var(2))))),
1188 },
1189 },
1190 Rewrite {
1191 name: "mul-comm",
1192 apply: r_mul_comm,
1193 certificate: Certificate::Ring {
1194 lhs: R::Mul(rx(R::Var(0)), rx(R::Var(1))),
1195 rhs: R::Mul(rx(R::Var(1)), rx(R::Var(0))),
1196 },
1197 },
1198 Rewrite {
1199 name: "mul-assoc",
1200 apply: r_mul_assoc,
1201 certificate: Certificate::Ring {
1202 lhs: R::Mul(rx(R::Mul(rx(R::Var(0)), rx(R::Var(1)))), rx(R::Var(2))),
1203 rhs: R::Mul(rx(R::Var(0)), rx(R::Mul(rx(R::Var(1)), rx(R::Var(2))))),
1204 },
1205 },
1206 Rewrite {
1207 name: "const-fold",
1208 apply: r_const_fold,
1209 certificate: Certificate::Bitvector {
1210 check: bv_fold_evaluator_matches_kernel,
1211 },
1212 },
1213 Rewrite {
1214 name: "len-copy",
1215 apply: r_len_copy,
1216 certificate: Certificate::LogosProperty {
1217 program: PROP_LEN_COPY,
1218 expected: "0",
1219 },
1220 },
1221 Rewrite {
1222 name: "index-copy",
1223 apply: r_index_copy,
1224 certificate: Certificate::LogosProperty {
1225 program: PROP_INDEX_COPY,
1226 expected: "0",
1227 },
1228 },
1229 Rewrite {
1230 name: "copy-copy",
1231 apply: r_copy_copy,
1232 certificate: Certificate::LogosProperty {
1233 program: PROP_COPY_COPY,
1234 expected: "0",
1235 },
1236 },
1237 Rewrite {
1238 name: "slice-full-copy",
1239 apply: r_slice_full_copy,
1240 certificate: Certificate::LogosProperty {
1241 program: PROP_SLICE_FULL_COPY,
1242 expected: "0",
1243 },
1244 },
1245 Rewrite {
1246 name: "len-slice-bounds",
1247 apply: r_len_slice_bounds,
1248 certificate: Certificate::LogosProperty {
1249 program: PROP_LEN_SLICE_BOUNDS,
1250 expected: "0",
1251 },
1252 },
1253 ]
1254}
1255
1256const PROP_LEN_COPY: &str = "## Main\n\
1263Let mutable seed be 42.\n\
1264Let mutable failures be 0.\n\
1265Let mutable t be 0.\n\
1266While t is less than 40:\n\
1267\x20 Let mutable xs be a new Seq of Int.\n\
1268\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1269\x20 Let n be seed % 13.\n\
1270\x20 Let mutable i be 0.\n\
1271\x20 While i is less than n:\n\
1272\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1273\x20 Push seed % 100 to xs.\n\
1274\x20 Set i to i + 1.\n\
1275\x20 If length of (copy of xs) is not length of xs:\n\
1276\x20 Set failures to failures + 1.\n\
1277\x20 Set t to t + 1.\n\
1278Show failures.\n";
1279
1280const PROP_INDEX_COPY: &str = "## Main\n\
1281Let mutable seed be 99.\n\
1282Let mutable failures be 0.\n\
1283Let mutable t be 0.\n\
1284While t is less than 40:\n\
1285\x20 Let mutable xs be a new Seq of Int.\n\
1286\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1287\x20 Let n be seed % 13.\n\
1288\x20 Let mutable i be 0.\n\
1289\x20 While i is less than n:\n\
1290\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1291\x20 Push seed % 100 to xs.\n\
1292\x20 Set i to i + 1.\n\
1293\x20 If n is at least 1:\n\
1294\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1295\x20 Let k be seed % n + 1.\n\
1296\x20 If item k of (copy of xs) is not item k of xs:\n\
1297\x20 Set failures to failures + 1.\n\
1298\x20 Set t to t + 1.\n\
1299Show failures.\n";
1300
1301const PROP_COPY_COPY: &str = "## Main\n\
1302Let mutable seed be 7.\n\
1303Let mutable failures be 0.\n\
1304Let mutable t be 0.\n\
1305While t is less than 40:\n\
1306\x20 Let mutable xs be a new Seq of Int.\n\
1307\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1308\x20 Let n be seed % 13.\n\
1309\x20 Let mutable i be 0.\n\
1310\x20 While i is less than n:\n\
1311\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1312\x20 Push seed % 100 to xs.\n\
1313\x20 Set i to i + 1.\n\
1314\x20 Let a be copy of (copy of xs).\n\
1315\x20 Let b be copy of xs.\n\
1316\x20 If length of a is not length of b:\n\
1317\x20 Set failures to failures + 1.\n\
1318\x20 Let mutable j be 1.\n\
1319\x20 While j is at most length of a:\n\
1320\x20 If item j of a is not item j of b:\n\
1321\x20 Set failures to failures + 1.\n\
1322\x20 Set j to j + 1.\n\
1323\x20 Set t to t + 1.\n\
1324Show failures.\n";
1325
1326const PROP_SLICE_FULL_COPY: &str = "## Main\n\
1327Let mutable seed be 1234.\n\
1328Let mutable failures be 0.\n\
1329Let mutable t be 0.\n\
1330While t is less than 40:\n\
1331\x20 Let mutable xs be a new Seq of Int.\n\
1332\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1333\x20 Let n be seed % 13.\n\
1334\x20 Let mutable i be 0.\n\
1335\x20 While i is less than n:\n\
1336\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1337\x20 Push seed % 100 to xs.\n\
1338\x20 Set i to i + 1.\n\
1339\x20 Let s be items 1 through length of xs of xs.\n\
1340\x20 Let c be copy of xs.\n\
1341\x20 If length of s is not length of c:\n\
1342\x20 Set failures to failures + 1.\n\
1343\x20 Let mutable j be 1.\n\
1344\x20 While j is at most length of s:\n\
1345\x20 If item j of s is not item j of c:\n\
1346\x20 Set failures to failures + 1.\n\
1347\x20 Set j to j + 1.\n\
1348\x20 Set t to t + 1.\n\
1349Show failures.\n";
1350
1351const PROP_LEN_SLICE_BOUNDS: &str = "## Main\n\
1352Let mutable seed be 5150.\n\
1353Let mutable failures be 0.\n\
1354Let mutable t be 0.\n\
1355While t is less than 60:\n\
1356\x20 Let mutable xs be a new Seq of Int.\n\
1357\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1358\x20 Let n be seed % 12 + 1.\n\
1359\x20 Let mutable i be 0.\n\
1360\x20 While i is less than n:\n\
1361\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1362\x20 Push seed % 100 to xs.\n\
1363\x20 Set i to i + 1.\n\
1364\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1365\x20 Let lo be seed % n + 1.\n\
1366\x20 Set seed to (seed * 1103515245 + 12345) % 2147483648.\n\
1367\x20 Let hi be lo - 1 + (seed % (n - lo + 2)).\n\
1368\x20 Let s be items (lo) through (hi) of xs.\n\
1369\x20 If length of s is not hi - lo + 1:\n\
1370\x20 Set failures to failures + 1.\n\
1371\x20 Set t to t + 1.\n\
1372Show failures.\n";
1373
1374pub fn verify_all_with_kernel() -> Result<usize, String> {
1377 let rules = all();
1378 for rule in &rules {
1379 let outcome = match &rule.certificate {
1380 Certificate::Ring { lhs, rhs } => check_ring(lhs, rhs),
1381 Certificate::BoolCases { vars, lhs, rhs } => check_bool_cases(*vars, lhs, rhs),
1382 Certificate::Bitvector { check } => check(),
1383 Certificate::LogosProperty { program, expected } => {
1384 match crate::compile::interpret_program(program) {
1385 Ok(out) if out.trim() == *expected => Ok(()),
1386 Ok(out) => Err(format!(
1387 "property program printed {:?}, expected {:?}",
1388 out.trim(),
1389 expected
1390 )),
1391 Err(e) => Err(format!(
1392 "property program failed: {}",
1393 crate::compile::describe_parse_error(&e)
1394 )),
1395 }
1396 }
1397 };
1398 outcome.map_err(|e| format!("rule '{}': {e}", rule.name))?;
1399 }
1400 Ok(rules.len())
1401}
1402
1403#[cfg(test)]
1404#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/optimize/egraph/rules/tests.rs"]
1405mod tests;