1mod build;
10pub(crate) use build::count_mod;
11pub use build::traps;
12mod eval;
13mod fp;
14mod node;
15mod symbols;
16#[cfg(test)]
17mod tests;
18
19use core::cmp::Ordering;
20use core::fmt;
21use core::num::NonZeroU32;
22use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
23
24use hashbrown::HashTable;
25
26use crate::error::Error;
27use crate::hash::{IdMap, combine};
28use crate::ops::{BinOp, CmpOp, UnOp};
29use crate::value::wide::nlimbs;
30use crate::{BitVec, Width};
31
32pub use eval::{Env, FnEnv, Substitution};
33pub(crate) use node::{AUX_POOLED, Node, OpCode};
34pub(crate) use symbols::{SymEntry, SymbolTable};
35pub use symbols::{SymbolId, SymbolKey};
36
37#[derive(Copy, Clone, Debug, PartialEq, Eq)]
39pub struct Checkpoint {
40 tag: NonZeroU32,
41 nodes: u32,
42 wide: usize,
43 symbols: u32,
44}
45
46impl Checkpoint {
47 pub fn nodes(&self) -> u32 {
50 self.nodes
51 }
52}
53
54#[derive(Copy, Clone, PartialEq, Eq, Hash)]
60pub struct Expr {
61 index: u32,
62 tag: NonZeroU32,
63}
64
65impl Expr {
66 #[inline]
69 pub fn index(self) -> u32 {
70 self.index
71 }
72
73 #[inline]
76 pub fn to_bits(self) -> u64 {
77 u64::from(self.tag.get()) << 32 | u64::from(self.index)
78 }
79
80 #[inline]
84 pub fn from_bits(bits: u64) -> Option<Expr> {
85 Some(Expr {
86 index: bits as u32,
87 tag: NonZeroU32::new((bits >> 32) as u32)?,
88 })
89 }
90}
91
92impl fmt::Debug for Expr {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 write!(f, "e{}", self.index)
95 }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq)]
100#[non_exhaustive]
101pub struct ContextConfig {
102 pub max_nodes: u32,
104 pub hash_seed: u64,
106 pub fact_work: u32,
108}
109
110impl Default for ContextConfig {
111 fn default() -> Self {
112 ContextConfig {
113 max_nodes: 1 << 24,
114 hash_seed: 0,
115 fact_work: 1 << 20,
116 }
117 }
118}
119
120impl ContextConfig {
121 pub fn with_max_nodes(mut self, n: u32) -> Self {
123 self.max_nodes = n;
124 self
125 }
126
127 pub fn with_fact_work(mut self, n: u32) -> Self {
129 self.fact_work = n;
130 self
131 }
132
133 pub fn with_hash_seed(mut self, seed: u64) -> Self {
135 self.hash_seed = seed;
136 self
137 }
138}
139
140#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
143#[non_exhaustive]
144pub struct ArenaCounters {
145 pub caller_nodes: u64,
147 pub engine_nodes: u64,
149}
150
151#[derive(Copy, Clone, Debug, PartialEq, Eq)]
153pub struct Mark {
154 tag: NonZeroU32,
155 caller_nodes: u64,
156}
157
158#[derive(Copy, Clone, Debug, PartialEq, Eq)]
160#[non_exhaustive]
161pub enum Bounded {
162 Exact(u32),
164 AtLeast(u32),
166}
167
168#[derive(Copy, Clone, PartialEq, Eq, Debug)]
170#[non_exhaustive]
171pub enum View {
172 Const(BitVec),
174 Sym(SymbolId),
176 Un(UnOp, Expr),
178 Bin(BinOp, Expr, Expr),
180 Cmp(CmpOp, Expr, Expr),
182 Zext(Expr),
184 Sext(Expr),
186 Extract {
188 lo: u16,
190 src: Expr,
192 },
193 Concat {
195 hi: Expr,
197 lo: Expr,
199 },
200 Select {
202 cond: Expr,
204 then: Expr,
206 els: Expr,
208 },
209 Fp {
211 op: crate::fp::FpOp,
213 format: crate::fp::FpFormat,
216 args: crate::fp::FpArgs,
218 },
219 Ext {
221 op: crate::ext::ExtId,
223 output: u8,
225 args: crate::ext::ExtArgs,
227 },
228}
229
230#[derive(Copy, Clone, Debug)]
231pub(crate) struct Meta {
232 pub(crate) shash: u64,
233 pub(crate) height: u32,
234 pub(crate) tree: u32,
235}
236
237#[derive(Clone, Debug, Default)]
239pub(crate) struct Marks {
240 stamp: Vec<u32>,
241 cur: u32,
242}
243
244impl Marks {
245 pub(crate) fn begin(&mut self, len: usize) {
246 if self.stamp.len() < len {
247 self.stamp.resize(len, 0);
248 }
249 self.cur = self.cur.wrapping_add(1);
250 if self.cur == 0 {
251 self.stamp.fill(0);
252 self.cur = 1;
253 }
254 }
255
256 #[inline]
258 pub(crate) fn test_and_set(&mut self, i: u32) -> bool {
259 let s = &mut self.stamp[i as usize];
260 let was = *s == self.cur;
261 *s = self.cur;
262 was
263 }
264}
265
266static TAGS: AtomicU32 = AtomicU32::new(0);
270
271fn fresh_tag() -> NonZeroU32 {
272 loop {
273 let t = TAGS.fetch_add(1, AtomicOrdering::Relaxed).wrapping_add(1);
274 if let Some(nz) = NonZeroU32::new(t) {
275 return nz;
276 }
277 }
278}
279
280const RETIRED: usize = 8;
283
284pub struct Context {
306 pub(crate) nodes: Vec<Node>,
307 pub(crate) meta: Vec<Meta>,
308 interner: HashTable<u32>,
309 pub(crate) wide_consts: Vec<u64>,
310 pub(crate) symbols: SymbolTable,
311 config: ContextConfig,
312 generation: u32,
313 pub(crate) declaration_revision: u64,
314 tag: NonZeroU32,
315 retired: [u32; RETIRED],
316 counters: ArenaCounters,
317 engine_mode: bool,
318 engine_allowance: Option<u64>,
321 engine_refused: bool,
323 pub(crate) marks: Marks,
324 dag_cache: IdMap<u32, u32>,
325 eval_plan: Option<Box<eval::Plan>>,
327 pub(crate) facts: crate::facts::FactCache,
328 pub(crate) memo: crate::engine::Memo,
329 pub(crate) sweep: crate::engine::SweepNotes,
332 #[cfg(feature = "eqsat")]
333 pub(crate) eqsat_memo: crate::eqsat::Memo,
334 pub(crate) registry: Option<std::sync::Arc<crate::ext::Registry>>,
336}
337
338impl fmt::Debug for Context {
339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340 f.debug_struct("Context")
341 .field("nodes", &self.nodes.len())
342 .field("symbols", &self.symbols.entries.len())
343 .field("generation", &self.generation)
344 .finish_non_exhaustive()
345 }
346}
347
348impl Default for Context {
349 fn default() -> Self {
350 Self::new()
351 }
352}
353
354impl Context {
355 pub fn fork(&self) -> Self {
363 Context {
364 nodes: self.nodes.clone(),
365 meta: self.meta.clone(),
366 interner: self.interner.clone(),
367 wide_consts: self.wide_consts.clone(),
368 symbols: self.symbols.clone(),
369 config: self.config.clone(),
370 generation: self.generation,
371 declaration_revision: self.declaration_revision,
372 tag: self.tag,
373 retired: self.retired,
374 counters: self.counters,
375 engine_mode: self.engine_mode,
376 engine_allowance: self.engine_allowance,
377 engine_refused: self.engine_refused,
378 marks: self.marks.clone(),
379 dag_cache: self.dag_cache.clone(),
380 eval_plan: None,
381 facts: self.facts.clone(),
382 memo: self.memo.clone(),
383 sweep: Default::default(),
384 #[cfg(feature = "eqsat")]
385 eqsat_memo: self.eqsat_memo.clone(),
386 registry: self.registry.clone(),
387 }
388 }
389
390 pub fn new() -> Self {
392 Self::with_config(ContextConfig::default())
393 }
394
395 pub fn with_config(config: ContextConfig) -> Self {
397 Context {
398 nodes: Vec::new(),
399 meta: Vec::new(),
400 interner: HashTable::new(),
401 wide_consts: Vec::new(),
402 symbols: SymbolTable::default(),
403 config,
404 generation: 0,
405 declaration_revision: 0,
406 tag: fresh_tag(),
407 retired: [0; RETIRED],
408 counters: ArenaCounters::default(),
409 engine_mode: false,
410 engine_allowance: None,
411 engine_refused: false,
412 marks: Marks::default(),
413 dag_cache: IdMap::default(),
414 eval_plan: None,
415 facts: crate::facts::FactCache::default(),
416 memo: crate::engine::Memo::default(),
417 sweep: Default::default(),
418 #[cfg(feature = "eqsat")]
419 eqsat_memo: crate::eqsat::Memo::default(),
420 registry: None,
421 }
422 }
423
424 pub fn with_registry(
426 config: ContextConfig,
427 registry: std::sync::Arc<crate::ext::Registry>,
428 ) -> Self {
429 let mut cx = Self::with_config(config);
430 cx.registry = Some(registry);
431 cx
432 }
433
434 pub fn registry(&self) -> Option<&crate::ext::Registry> {
436 self.registry.as_deref()
437 }
438
439 pub fn extend_registry(
443 &mut self,
444 registry: std::sync::Arc<crate::ext::Registry>,
445 ) -> Result<(), Error> {
446 if let Some(old) = self.registry.as_deref() {
447 let kept = old.ids().all(|id| {
450 registry.op(id).is_some_and(|o| {
451 old.op(id).is_some_and(|p| {
452 p.name() == o.name()
453 && p.revision() == o.revision()
454 && p.traits() == o.traits()
455 })
456 })
457 });
458 if !kept {
459 return Err(Error::Unsupported(
460 "the new registry does not extend the current one".into(),
461 ));
462 }
463 }
464 self.registry = Some(registry);
465 Ok(())
466 }
467
468 pub fn config(&self) -> &ContextConfig {
470 &self.config
471 }
472
473 pub fn set_max_nodes(&mut self, n: u32) {
477 self.config.max_nodes = n;
478 }
479
480 pub fn len(&self) -> usize {
482 self.nodes.len()
483 }
484
485 pub fn is_empty(&self) -> bool {
487 self.nodes.is_empty()
488 }
489
490 pub fn clear(&mut self) {
493 self.nodes.clear();
494 self.meta.clear();
495 self.interner.clear();
496 self.wide_consts.clear();
497 self.symbols.clear();
498 self.declaration_revision = 0;
499 self.dag_cache.clear();
500 if let Some(plan) = &mut self.eval_plan {
501 plan.clear();
502 }
503 self.facts.clear();
504 self.memo.clear();
505 #[cfg(feature = "eqsat")]
506 self.eqsat_memo.clear();
507 self.counters = ArenaCounters::default();
508 self.generation = self.generation.wrapping_add(1);
509 self.retired.rotate_right(1);
510 self.retired[0] = self.tag.get();
511 self.tag = fresh_tag();
512 }
513
514 pub fn checkpoint(&self) -> Checkpoint {
517 Checkpoint {
518 tag: self.tag,
519 nodes: self.nodes.len() as u32,
520 wide: self.wide_consts.len(),
521 symbols: self.symbols.entries.len() as u32,
522 }
523 }
524
525 pub fn rollback(&mut self, at: Checkpoint) -> Result<(), Error> {
542 let (nodes, symbols) = (at.nodes as usize, at.symbols as usize);
543 if at.tag != self.tag
544 || nodes > self.nodes.len()
545 || at.wide > self.wide_consts.len()
546 || symbols > self.symbols.entries.len()
547 {
548 return Err(Error::Contract(
549 "a checkpoint of another context or of a state already rolled back past".into(),
550 ));
551 }
552 if nodes == self.nodes.len() && symbols == self.symbols.entries.len() {
553 return Ok(());
554 }
555 let seed = self.config.hash_seed;
556 for i in nodes..self.nodes.len() {
557 let hash = combine(seed, self.meta[i].shash);
558 if let Ok(entry) = self.interner.find_entry(hash, |&j| j as usize == i) {
559 entry.remove();
560 }
561 }
562 self.nodes.truncate(nodes);
563 self.meta.truncate(nodes);
564 self.wide_consts.truncate(at.wide);
565 for e in self.symbols.entries.drain(symbols..) {
566 self.symbols.index.remove(&e.key);
567 }
568 self.dag_cache.clear();
569 if let Some(plan) = &mut self.eval_plan {
570 plan.clear();
571 }
572 let widths = &self.nodes;
573 (self.facts).truncate(nodes, |i| {
574 Width::new(widths[i as usize].width).unwrap_or(Width::W1)
575 });
576 self.memo.clear();
577 #[cfg(feature = "eqsat")]
578 self.eqsat_memo.clear();
579 Ok(())
580 }
581
582 pub fn forget_results(&mut self) {
601 self.memo.clear();
602 #[cfg(feature = "eqsat")]
603 self.eqsat_memo.clear();
604 }
605
606 pub fn reserve(&mut self, additional: usize) {
610 self.nodes.reserve(additional);
611 self.meta.reserve(additional);
612 let seed = self.config.hash_seed;
613 let meta = &self.meta;
614 self.interner
615 .reserve(additional, |&i| combine(seed, meta[i as usize].shash));
616 }
617
618 pub fn counters(&self) -> ArenaCounters {
620 self.counters
621 }
622
623 pub fn mark(&self) -> Mark {
625 Mark {
626 tag: self.tag,
627 caller_nodes: self.counters.caller_nodes,
628 }
629 }
630
631 pub fn caller_growth_since(&self, mark: Mark) -> u64 {
634 if mark.tag != self.tag {
635 return self.counters.caller_nodes;
636 }
637 self.counters.caller_nodes.saturating_sub(mark.caller_nodes)
638 }
639
640 #[inline]
644 pub(crate) fn id(&self, e: Expr) -> Result<u32, Error> {
645 if e.tag == self.tag && (e.index as usize) < self.nodes.len() {
646 return Ok(e.index);
647 }
648 if self.retired.contains(&e.tag.get()) {
649 Err(Error::StaleExpr)
650 } else {
651 Err(Error::ForeignExpr)
652 }
653 }
654
655 #[inline]
656 pub(crate) fn handle(&self, index: u32) -> Expr {
657 Expr {
658 index,
659 tag: self.tag,
660 }
661 }
662
663 pub(crate) fn ids(&self, es: &[Expr]) -> Result<Vec<u32>, Error> {
664 es.iter().map(|&e| self.id(e)).collect()
665 }
666
667 #[inline]
670 pub(crate) fn node(&self, i: u32) -> Node {
671 self.nodes[i as usize]
672 }
673
674 #[inline]
675 pub(crate) fn wid(&self, i: u32) -> u16 {
676 self.nodes[i as usize].width
677 }
678
679 #[inline]
680 pub(crate) fn width_of(&self, i: u32) -> Width {
681 Width::new(self.nodes[i as usize].width).unwrap_or(Width::W1)
683 }
684
685 #[inline]
687 pub(crate) fn is_const(&self, i: u32) -> bool {
688 self.nodes[i as usize].op == OpCode::Const
689 }
690
691 pub(crate) fn const_val(&self, i: u32) -> Option<BitVec> {
693 let n = self.nodes[i as usize];
694 if n.op != OpCode::Const {
695 return None;
696 }
697 let width = Width::new(n.width).ok()?;
698 if n.aux & AUX_POOLED != 0 {
699 let len = nlimbs(n.width);
700 let off = n.a as usize;
701 Some(BitVec::wrapping_from_limbs(
702 width,
703 &self.wide_consts[off..off + len],
704 ))
705 } else {
706 Some(BitVec::wrapping_from_u64(
707 width,
708 u64::from(n.a) | (u64::from(n.b) << 32),
709 ))
710 }
711 }
712
713 fn table_hash(&self, shash: u64) -> u64 {
716 combine(self.config.hash_seed, shash)
717 }
718
719 fn node_hash(&self, n: &Node) -> u64 {
721 let mut h = combine(u64::from(n.op as u8), u64::from(n.width));
722 if n.op.as_ext().is_some() {
723 let op = self.registry.as_deref().map_or(0, |r| r.hash_at(n.aux));
725 h = combine(h, op);
726 }
727 if n.op.is_fp() {
728 h = combine(h, u64::from(n.aux));
730 if n.op == OpCode::FConvert {
731 h = combine(h, u64::from(n.b));
732 }
733 }
734 match n.op {
735 OpCode::Extract => {
736 h = combine(h, u64::from(n.b));
737 h = combine(h, self.meta[n.a as usize].shash);
738 }
739 _ => {
740 for c in n.children() {
741 h = combine(h, self.meta[c as usize].shash);
742 }
743 }
744 }
745 h
746 }
747
748 fn const_hash(v: &BitVec) -> u64 {
749 let mut h = combine(u64::from(OpCode::Const as u8), u64::from(v.width().bits()));
750 for &l in v.limbs() {
751 h = combine(h, l);
752 }
753 h
754 }
755
756 fn push(&mut self, n: Node, shash: u64) -> Result<u32, Error> {
758 self.room()?;
759 let idx = self.nodes.len() as u32;
760 let (mut height, mut tree) = (0u32, 1u32);
761 for c in n.children() {
762 let m = self.meta[c as usize];
763 height = height.max(m.height);
764 tree = tree.saturating_add(m.tree);
765 }
766 let height = if n.op.arity() == 0 {
767 0
768 } else {
769 height.saturating_add(1)
770 };
771 self.nodes.push(n);
772 self.meta.push(Meta {
773 shash,
774 height,
775 tree,
776 });
777 let seed = self.config.hash_seed;
778 let meta = &self.meta;
779 self.interner
780 .insert_unique(combine(seed, shash), idx, |&i| {
781 combine(seed, meta[i as usize].shash)
782 });
783 if self.engine_mode {
784 self.counters.engine_nodes += 1;
785 if let Some(a) = &mut self.engine_allowance {
786 *a -= 1;
787 }
788 } else {
789 self.counters.caller_nodes += 1;
790 }
791 Ok(idx)
792 }
793
794 pub(crate) fn mk(&mut self, n: Node) -> Result<u32, Error> {
796 let shash = self.node_hash(&n);
797 let nodes = &self.nodes;
798 if let Some(&i) = self
799 .interner
800 .find(self.table_hash(shash), |&i| nodes[i as usize] == n)
801 {
802 return Ok(i);
803 }
804 self.push(n, shash)
805 }
806
807 pub(crate) fn find(&self, n: &Node) -> Option<u32> {
809 let nodes = &self.nodes;
810 self.interner
811 .find(self.table_hash(self.node_hash(n)), |&i| {
812 nodes[i as usize] == *n
813 })
814 .copied()
815 }
816
817 pub(crate) fn mk_const_u64(&mut self, w: u16, v: u64) -> Result<u32, Error> {
820 debug_assert!(
821 w <= 64 && (w == 64 || v >> w == 0),
822 "a canonical small constant"
823 );
824 let shash = combine(combine(u64::from(OpCode::Const as u8), u64::from(w)), v);
826 let nodes = &self.nodes;
827 let found = self.interner.find(self.table_hash(shash), |&i| {
828 let n = &nodes[i as usize];
829 n.op == OpCode::Const && n.width == w && u64::from(n.a) | (u64::from(n.b) << 32) == v
830 });
831 if let Some(&i) = found {
832 return Ok(i);
833 }
834 self.room()?;
835 self.push(
836 Node::new(OpCode::Const, w, v as u32, (v >> 32) as u32, 0),
837 shash,
838 )
839 }
840
841 pub(crate) fn mk_const(&mut self, v: &BitVec) -> Result<u32, Error> {
843 let w = v.width().bits();
844 if w <= 64 {
845 return self.mk_const_u64(w, v.limbs()[0]);
846 }
847 let shash = Self::const_hash(v);
848 let (nodes, wide) = (&self.nodes, &self.wide_consts);
849 let limbs = v.limbs();
850 let inline = w <= 64;
851 let lo = limbs[0];
852 let found = self.interner.find(self.table_hash(shash), |&i| {
853 let n = &nodes[i as usize];
854 n.op == OpCode::Const
855 && n.width == w
856 && if inline {
857 u64::from(n.a) | (u64::from(n.b) << 32) == lo
858 } else {
859 let off = n.a as usize;
860 wide[off..off + limbs.len()] == *limbs
861 }
862 });
863 if let Some(&i) = found {
864 return Ok(i);
865 }
866 self.room()?;
867 let node = if inline {
868 Node::new(OpCode::Const, w, lo as u32, (lo >> 32) as u32, 0)
869 } else {
870 let off = self.wide_consts.len() as u32;
871 self.wide_consts.extend_from_slice(limbs);
872 let mut n = Node::new(OpCode::Const, w, off, 0, 0);
873 n.aux = AUX_POOLED;
874 n
875 };
876 self.push(node, shash)
877 }
878
879 fn room(&mut self) -> Result<(), Error> {
882 let limit = self.config.max_nodes;
883 if self.nodes.len() >= limit as usize {
884 return Err(Error::ArenaFull { limit });
885 }
886 if self.engine_mode && self.engine_allowance == Some(0) {
887 self.engine_refused = true;
888 return Err(Error::ArenaFull { limit });
889 }
890 Ok(())
891 }
892
893 pub(crate) fn as_engine_limited<T>(
896 &mut self,
897 allowance: u64,
898 f: impl FnOnce(&mut Self) -> T,
899 ) -> (T, bool) {
900 let prev = (
901 self.engine_allowance.replace(allowance),
902 core::mem::replace(&mut self.engine_refused, false),
903 );
904 let r = self.as_engine(f);
905 let refused = self.engine_refused;
906 (self.engine_allowance, self.engine_refused) = prev;
907 (r, refused)
908 }
909
910 pub(crate) fn as_engine<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
912 let prev = core::mem::replace(&mut self.engine_mode, true);
913 let r = f(self);
914 self.engine_mode = prev;
915 r
916 }
917
918 pub(crate) fn order(&self, x: u32, y: u32) -> Ordering {
924 if x == y {
925 return Ordering::Equal;
926 }
927 let (nx, ny) = (self.node(x), self.node(y));
928 let class = |op: OpCode| match op {
929 OpCode::Const => 2u8,
930 OpCode::Sym => 1,
931 _ => 0,
932 };
933 class(nx.op)
934 .cmp(&class(ny.op))
935 .then_with(|| match (nx.op, ny.op) {
936 (OpCode::Const, OpCode::Const) => {
937 let (a, b) = (self.const_val(x), self.const_val(y));
938 match (a, b) {
939 (Some(a), Some(b)) => {
940 let (la, lb) = (a.limbs(), b.limbs());
941 la.len()
942 .cmp(&lb.len())
943 .then_with(|| la.iter().rev().cmp(lb.iter().rev()))
944 }
945 _ => Ordering::Equal,
946 }
947 }
948 (OpCode::Sym, OpCode::Sym) => {
949 let ka = &self.symbols.entries[nx.a as usize].key;
950 let kb = &self.symbols.entries[ny.a as usize].key;
951 ka.cmp(kb)
952 }
953 _ => (nx.op as u8).cmp(&(ny.op as u8)).then(
954 self.meta[x as usize]
955 .shash
956 .cmp(&self.meta[y as usize].shash),
957 ),
958 })
959 .then(nx.width.cmp(&ny.width))
960 .then(x.cmp(&y))
961 }
962
963 pub fn width(&self, e: Expr) -> Result<Width, Error> {
967 Ok(self.width_of(self.id(e)?))
968 }
969
970 pub fn structural_hash(&self, e: Expr) -> Result<u64, Error> {
976 Ok(self.meta[self.id(e)? as usize].shash)
977 }
978
979 pub fn shape_hashes(&mut self, roots: &[Expr]) -> Result<Vec<u64>, Error> {
987 let ids = self.ids(roots)?;
988 let mut shape: crate::hash::IdMap<u32, u64> = Default::default();
989 Ok(ids
990 .iter()
991 .map(|&i| self.shape_into(i, &mut shape))
992 .collect())
993 }
994
995 pub(crate) fn shape_into(&self, n: u32, memo: &mut crate::hash::IdMap<u32, u64>) -> u64 {
999 let mut stack = vec![(n, false)];
1000 while let Some((i, ready)) = stack.pop() {
1001 if memo.contains_key(&i) {
1002 continue;
1003 }
1004 let node = self.node(i);
1005 if !ready {
1006 stack.push((i, true));
1007 stack.extend(node.children().map(|c| (c, false)));
1008 continue;
1009 }
1010 let mut h = combine(
1012 0x7368_6170_6521,
1013 combine(u64::from(node.op as u8), u64::from(node.width)),
1014 );
1015 match node.op {
1016 OpCode::Const | OpCode::Sym => {}
1017 OpCode::Extract => {
1018 h = combine(h, u64::from(node.b));
1019 h = combine(h, memo[&node.a]);
1020 }
1021 _ => {
1022 if node.op.as_ext().is_some() {
1023 let op = self.registry.as_deref().map_or(0, |r| r.hash_at(node.aux));
1024 h = combine(h, op);
1025 }
1026 if node.op.is_fp() {
1027 h = combine(h, u64::from(node.aux));
1028 if node.op == OpCode::FConvert {
1029 h = combine(h, u64::from(node.b));
1030 }
1031 }
1032 let commutative = node.op.as_bin().is_some_and(BinOp::is_commutative)
1033 || matches!(node.op, OpCode::Eq | OpCode::Ne);
1034 if commutative {
1035 let (a, b) = (memo[&node.a], memo[&node.b]);
1036 h = combine(combine(h, a.min(b)), a.max(b));
1037 } else {
1038 for c in node.children() {
1039 h = combine(h, memo[&c]);
1040 }
1041 }
1042 }
1043 }
1044 memo.insert(i, h);
1045 }
1046 memo[&n]
1047 }
1048
1049 pub fn view(&self, e: Expr) -> Result<View, Error> {
1051 let i = self.id(e)?;
1052 Ok(self.view_of(i))
1053 }
1054
1055 pub(crate) fn view_of(&self, i: u32) -> View {
1056 let n = self.node(i);
1057 let h = |j: u32| self.handle(j);
1058 match n.op {
1059 OpCode::Const => View::Const(self.const_val(i).unwrap_or(BitVec::zero(Width::W1))),
1060 OpCode::Sym => View::Sym(SymbolId(n.a)),
1061 OpCode::Zext => View::Zext(h(n.a)),
1062 OpCode::Sext => View::Sext(h(n.a)),
1063 OpCode::Extract => View::Extract {
1064 lo: n.b as u16,
1065 src: h(n.a),
1066 },
1067 OpCode::Concat => View::Concat {
1068 hi: h(n.a),
1069 lo: h(n.b),
1070 },
1071 OpCode::Select => View::Select {
1072 cond: h(n.a),
1073 then: h(n.b),
1074 els: h(n.c),
1075 },
1076 op if op.as_ext().is_some() => {
1077 let (arity, k) = op.as_ext().unwrap_or((1, 0));
1078 View::Ext {
1079 op: self
1080 .registry
1081 .as_deref()
1082 .and_then(|r| r.id_at(n.aux))
1083 .unwrap_or_else(crate::ext::ExtId::dangling),
1084 output: k as u8,
1085 args: crate::ext::ExtArgs::new(&[h(n.a), h(n.b), h(n.c)][..arity]),
1086 }
1087 }
1088 op => {
1089 if let Some(u) = op.as_un() {
1090 View::Un(u, h(n.a))
1091 } else if let Some(b) = op.as_bin() {
1092 View::Bin(b, h(n.a), h(n.b))
1093 } else if let Some(c) = op.as_cmp() {
1094 View::Cmp(c, h(n.a), h(n.b))
1095 } else if let Some(d) = self.fp_desc(i) {
1096 let arity = d.kind().arity();
1097 View::Fp {
1098 op: d.op,
1099 format: d.format,
1100 args: crate::fp::FpArgs::new(&[h(n.a), h(n.b), h(n.c)][..arity]),
1101 }
1102 } else {
1103 unreachable!("every opcode is covered")
1104 }
1105 }
1106 }
1107 }
1108
1109 pub(crate) fn fp_desc(&self, i: u32) -> Option<crate::fp::node::Desc> {
1111 let n = self.node(i);
1112 crate::fp::node::Kind::of(n.op)?;
1113 crate::fp::node::Desc::decode(&n, self.wid(n.a))
1114 }
1115
1116 pub fn children(&self, e: Expr) -> Result<impl Iterator<Item = Expr> + '_, Error> {
1118 let i = self.id(e)?;
1119 Ok(self.node(i).children().map(|c| self.handle(c)))
1120 }
1121
1122 pub fn as_const(&self, e: Expr) -> Result<Option<BitVec>, Error> {
1124 Ok(self.const_val(self.id(e)?))
1125 }
1126
1127 pub fn is_leaf(&self, e: Expr) -> Result<bool, Error> {
1129 Ok(self.node(self.id(e)?).op.arity() == 0)
1130 }
1131
1132 pub fn height(&self, e: Expr) -> Result<u32, Error> {
1134 Ok(self.meta[self.id(e)? as usize].height)
1135 }
1136
1137 pub fn tree_size(&self, e: Expr) -> Result<u32, Error> {
1139 Ok(self.meta[self.id(e)? as usize].tree)
1140 }
1141
1142 pub fn symbol(&mut self, key: impl Into<SymbolKey>, width: Width) -> Result<Expr, Error> {
1147 let key = key.into();
1148 if let Some(&id) = self.symbols.index.get(&key) {
1149 let e = &self.symbols.entries[id as usize];
1150 if e.width != width {
1151 return Err(Error::SymbolWidthConflict {
1152 key,
1153 have: e.width,
1154 want: width,
1155 });
1156 }
1157 return Ok(self.handle(e.node));
1158 }
1159 self.new_symbol(key, width).map(|i| self.handle(i))
1160 }
1161
1162 fn new_symbol(&mut self, key: SymbolKey, width: Width) -> Result<u32, Error> {
1163 let id = self.symbols.entries.len() as u32;
1164 let shash = combine(
1165 combine(u64::from(OpCode::Sym as u8), u64::from(width.bits())),
1166 key.structural_hash(),
1167 );
1168 let node = self.push(Node::new(OpCode::Sym, width.bits(), id, 0, 0), shash)?;
1169 self.symbols.index.insert(key.clone(), id);
1170 self.symbols.entries.push(SymEntry {
1171 key,
1172 width,
1173 node,
1174 known: None,
1175 });
1176 Ok(node)
1177 }
1178
1179 pub fn fresh_symbol(&mut self, width: Width) -> Result<Expr, Error> {
1181 loop {
1182 let key = SymbolKey::Fresh(self.symbols.next_fresh);
1183 self.symbols.next_fresh += 1;
1184 if !self.symbols.index.contains_key(&key) {
1185 return self.new_symbol(key, width).map(|i| self.handle(i));
1186 }
1187 }
1188 }
1189
1190 pub fn find_symbol(&self, key: &SymbolKey) -> Option<Expr> {
1192 let id = *self.symbols.index.get(key)?;
1193 Some(self.handle(self.symbols.entries[id as usize].node))
1194 }
1195
1196 pub fn symbol_id(&self, e: Expr) -> Result<Option<SymbolId>, Error> {
1198 let n = self.node(self.id(e)?);
1199 Ok((n.op == OpCode::Sym).then_some(SymbolId(n.a)))
1200 }
1201
1202 pub fn symbol_key(&self, id: SymbolId) -> Option<&SymbolKey> {
1204 self.symbols.entries.get(id.0 as usize).map(|e| &e.key)
1205 }
1206
1207 pub fn symbol_width(&self, id: SymbolId) -> Option<Width> {
1209 self.symbols.entries.get(id.0 as usize).map(|e| e.width)
1210 }
1211
1212 pub fn symbol_count(&self) -> usize {
1214 self.symbols.entries.len()
1215 }
1216
1217 pub fn declare_known(&mut self, s: Expr, known: crate::KnownBits) -> Result<(), Error> {
1243 let i = self.id(s)?;
1244 let n = self.node(i);
1245 if n.op != OpCode::Sym {
1246 return Err(Error::Unsupported(
1247 "known bits are declared for symbols only".into(),
1248 ));
1249 }
1250 if known.width().bits() != n.width {
1251 return Err(crate::error::WidthError::Mismatch {
1252 left: n.width,
1253 right: known.width().bits(),
1254 }
1255 .into());
1256 }
1257 let known = (!known.known().is_zero()).then_some(known);
1258 let entry = &mut self.symbols.entries[n.a as usize];
1259 if entry.known == known {
1260 return Ok(());
1261 }
1262 entry.known = known;
1263 self.declaration_revision = self.declaration_revision.wrapping_add(1);
1264 self.facts.clear();
1266 self.memo.clear();
1267 #[cfg(feature = "eqsat")]
1268 self.eqsat_memo.clear();
1269 Ok(())
1270 }
1271
1272 pub fn declared_known(&self, s: Expr) -> Result<Option<crate::KnownBits>, Error> {
1274 let i = self.id(s)?;
1275 Ok(self.declared_at(i))
1276 }
1277
1278 #[cfg_attr(not(feature = "prove"), allow(dead_code))]
1280 pub(crate) fn any_declared(&self) -> bool {
1281 self.declaration_revision != 0 && self.symbols.entries.iter().any(|e| e.known.is_some())
1282 }
1283
1284 pub(crate) fn declared_at(&self, i: u32) -> Option<crate::KnownBits> {
1286 let n = self.node(i);
1287 (n.op == OpCode::Sym)
1288 .then(|| self.symbols.entries[n.a as usize].known)
1289 .flatten()
1290 }
1291
1292 pub fn post_order(&mut self, roots: &[Expr]) -> Result<Vec<Expr>, Error> {
1296 let ids = self.ids(roots)?;
1297 let order = self.post_order_ids(&ids);
1298 Ok(order.into_iter().map(|i| self.handle(i)).collect())
1299 }
1300
1301 pub(crate) fn post_order_ids(&mut self, roots: &[u32]) -> Vec<u32> {
1302 self.post_order_ids_pruned(roots, |_| false)
1303 }
1304
1305 pub(crate) fn post_order_ids_pruned(
1308 &mut self,
1309 roots: &[u32],
1310 skip: impl Fn(Expr) -> bool,
1311 ) -> Vec<u32> {
1312 let mut out = Vec::new();
1313 let mut stack: Vec<(u32, u8)> = Vec::new();
1314 let mut begun = false;
1315 for &r in roots {
1316 if skip(self.handle(r)) {
1317 continue;
1318 }
1319 if !begun {
1320 self.marks.begin(self.nodes.len());
1321 begun = true;
1322 }
1323 if self.marks.test_and_set(r) {
1324 continue;
1325 }
1326 stack.push((r, 0));
1327 while let Some(top) = stack.last_mut() {
1328 let (i, k) = *top;
1329 let n = self.nodes[i as usize];
1330 if (k as usize) < n.op.arity() {
1331 top.1 += 1;
1332 let c = [n.a, n.b, n.c][k as usize];
1333 if !self.marks.test_and_set(c) && !skip(self.handle(c)) {
1334 stack.push((c, 0));
1335 }
1336 } else {
1337 stack.pop();
1338 out.push(i);
1339 }
1340 }
1341 }
1342 out
1343 }
1344
1345 pub fn symbols_in(&mut self, roots: &[Expr]) -> Result<Vec<SymbolId>, Error> {
1347 let ids = self.ids(roots)?;
1348 let mut syms: Vec<SymbolId> = self
1349 .post_order_ids(&ids)
1350 .into_iter()
1351 .filter_map(|i| {
1352 let n = self.node(i);
1353 (n.op == OpCode::Sym).then_some(SymbolId(n.a))
1354 })
1355 .collect();
1356 syms.sort_by(|a, b| {
1357 self.symbols.entries[a.0 as usize]
1358 .key
1359 .cmp(&self.symbols.entries[b.0 as usize].key)
1360 });
1361 Ok(syms)
1362 }
1363
1364 pub fn dag_size(&mut self, roots: &[Expr], cap: u32) -> Result<Bounded, Error> {
1367 let ids = self.ids(roots)?;
1368 if let [r] = ids[..]
1369 && let Some(&n) = self.dag_cache.get(&r)
1370 {
1371 return Ok(if n <= cap {
1372 Bounded::Exact(n)
1373 } else {
1374 Bounded::AtLeast(cap.saturating_add(1))
1375 });
1376 }
1377 self.marks.begin(self.nodes.len());
1378 let mut count: u32 = 0;
1379 let mut stack: Vec<u32> = Vec::new();
1380 for &r in &ids {
1381 if !self.marks.test_and_set(r) {
1382 stack.push(r);
1383 }
1384 }
1385 while let Some(i) = stack.pop() {
1386 count += 1;
1387 if count > cap {
1388 return Ok(Bounded::AtLeast(cap.saturating_add(1)));
1389 }
1390 for c in self.nodes[i as usize].children() {
1391 if !self.marks.test_and_set(c) {
1392 stack.push(c);
1393 }
1394 }
1395 }
1396 if let [r] = ids[..] {
1397 self.dag_cache.insert(r, count);
1398 }
1399 Ok(Bounded::Exact(count))
1400 }
1401}
1402
1403#[derive(Clone, Debug)]
1405pub struct ExprMap<T> {
1406 data: Vec<Option<T>>,
1407}
1408
1409impl<T> Default for ExprMap<T> {
1410 fn default() -> Self {
1411 ExprMap { data: Vec::new() }
1412 }
1413}
1414
1415impl<T> ExprMap<T> {
1416 pub fn new() -> Self {
1418 Self::default()
1419 }
1420
1421 pub fn insert(&mut self, e: Expr, v: T) -> Option<T> {
1423 let i = e.index() as usize;
1424 if self.data.len() <= i {
1425 self.data.resize_with(i + 1, || None);
1426 }
1427 self.data[i].replace(v)
1428 }
1429
1430 pub fn get(&self, e: Expr) -> Option<&T> {
1432 self.data.get(e.index() as usize)?.as_ref()
1433 }
1434
1435 pub fn remove(&mut self, e: Expr) -> Option<T> {
1437 self.data.get_mut(e.index() as usize)?.take()
1438 }
1439
1440 pub fn contains(&self, e: Expr) -> bool {
1442 self.get(e).is_some()
1443 }
1444
1445 pub fn clear(&mut self) {
1447 self.data.clear();
1448 }
1449}
1450
1451#[derive(Clone, Debug, Default)]
1453pub struct ExprSet {
1454 bits: Vec<u64>,
1455}
1456
1457impl ExprSet {
1458 pub fn new() -> Self {
1460 Self::default()
1461 }
1462
1463 pub fn insert(&mut self, e: Expr) -> bool {
1465 let i = e.index() as usize;
1466 if self.bits.len() <= i / 64 {
1467 self.bits.resize(i / 64 + 1, 0);
1468 }
1469 let m = 1u64 << (i % 64);
1470 let fresh = self.bits[i / 64] & m == 0;
1471 self.bits[i / 64] |= m;
1472 fresh
1473 }
1474
1475 pub fn contains(&self, e: Expr) -> bool {
1477 let i = e.index() as usize;
1478 self.bits
1479 .get(i / 64)
1480 .is_some_and(|w| w & (1 << (i % 64)) != 0)
1481 }
1482
1483 pub fn clear(&mut self) {
1485 self.bits.clear();
1486 }
1487}