Skip to main content

bitwright/expr/
mod.rs

1//! The hash-consed expression arena.
2//!
3//! A [`Context`] owns every node it creates. Nodes are immutable and appended in creation
4//! order, and every child index is lower than its parent's, so ascending index order is a
5//! topological order. Structurally equal expressions are the same node ("equal handle implies
6//! equal value"; the converse does not hold). Every node is in canonical form (see
7//! `build.rs` and `docs/design.md` §4.3).
8
9mod 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/// A state of a context to come back to ([`Context::checkpoint`], [`Context::rollback`]).
38#[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    /// The number of nodes the context held: a handle with a lower
48    /// [`index`](Expr::index) is from before the checkpoint.
49    pub fn nodes(&self) -> u32 {
50        self.nodes
51    }
52}
53
54/// A handle to an expression node.
55///
56/// A handle is valid only in the context, and the context generation, that created it. Using it
57/// anywhere else is detected (best effort) and reported as [`Error::ForeignExpr`] or
58/// [`Error::StaleExpr`]; it never silently refers to another node.
59#[derive(Copy, Clone, PartialEq, Eq, Hash)]
60pub struct Expr {
61    index: u32,
62    tag: NonZeroU32,
63}
64
65impl Expr {
66    /// The node's index. Indices are dense from 0 in creation order, and children always have
67    /// lower indices than their parents. Useful as a key for caller-side dense tables.
68    #[inline]
69    pub fn index(self) -> u32 {
70        self.index
71    }
72
73    /// The handle as one integer, never 0, for hosts that keep handles outside Rust (the C and
74    /// Python bindings). [`Expr::from_bits`] reads it back.
75    #[inline]
76    pub fn to_bits(self) -> u64 {
77        u64::from(self.tag.get()) << 32 | u64::from(self.index)
78    }
79
80    /// The handle [`Expr::to_bits`] gave, or `None` for 0. Any other integer reads as a handle:
81    /// a context rejects one it did not create ([`Error::ForeignExpr`] or
82    /// [`Error::StaleExpr`]), like any other foreign handle.
83    #[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/// Configuration of a [`Context`].
99#[derive(Clone, Debug, PartialEq, Eq)]
100#[non_exhaustive]
101pub struct ContextConfig {
102    /// The maximum number of nodes. Building past it fails with [`Error::ArenaFull`].
103    pub max_nodes: u32,
104    /// Seed for the interning table's layout. It never changes any result.
105    pub hash_seed: u64,
106    /// The most transfer functions one fact query may run before answering `top`.
107    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    /// Sets [`max_nodes`](Self::max_nodes).
122    pub fn with_max_nodes(mut self, n: u32) -> Self {
123        self.max_nodes = n;
124        self
125    }
126
127    /// Sets [`fact_work`](Self::fact_work).
128    pub fn with_fact_work(mut self, n: u32) -> Self {
129        self.fact_work = n;
130        self
131    }
132
133    /// Sets [`hash_seed`](Self::hash_seed).
134    pub fn with_hash_seed(mut self, seed: u64) -> Self {
135        self.hash_seed = seed;
136        self
137    }
138}
139
140/// Nodes created by the caller's own builder calls versus nodes created by bitwright itself
141/// (simplification, search). Lets a host retry maintenance only after enough *input* growth.
142#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
143#[non_exhaustive]
144pub struct ArenaCounters {
145    /// New nodes created through the public builder.
146    pub caller_nodes: u64,
147    /// New nodes created by the library's own transformations.
148    pub engine_nodes: u64,
149}
150
151/// A position in the caller-growth counter; see [`Context::caller_growth_since`].
152#[derive(Copy, Clone, Debug, PartialEq, Eq)]
153pub struct Mark {
154    tag: NonZeroU32,
155    caller_nodes: u64,
156}
157
158/// A size that may have been cut off at a bound.
159#[derive(Copy, Clone, Debug, PartialEq, Eq)]
160#[non_exhaustive]
161pub enum Bounded {
162    /// The exact value.
163    Exact(u32),
164    /// The walk stopped at the bound; the value is at least this.
165    AtLeast(u32),
166}
167
168/// A read-only view of one node.
169#[derive(Copy, Clone, PartialEq, Eq, Debug)]
170#[non_exhaustive]
171pub enum View {
172    /// A constant.
173    Const(BitVec),
174    /// A symbol.
175    Sym(SymbolId),
176    /// A unary operator.
177    Un(UnOp, Expr),
178    /// A binary operator.
179    Bin(BinOp, Expr, Expr),
180    /// A comparison (1-bit result).
181    Cmp(CmpOp, Expr, Expr),
182    /// Zero extension to the node's width.
183    Zext(Expr),
184    /// Sign extension to the node's width.
185    Sext(Expr),
186    /// Bits `[lo, lo + W)` of `src`, where `W` is the node's width.
187    Extract {
188        /// First extracted bit.
189        lo: u16,
190        /// The operand.
191        src: Expr,
192    },
193    /// `hi` in the high bits and `lo` in the low bits.
194    Concat {
195        /// The high part.
196        hi: Expr,
197        /// The low part.
198        lo: Expr,
199    },
200    /// `cond ? then : els` with a 1-bit condition.
201    Select {
202        /// The condition.
203        cond: Expr,
204        /// The value when the condition is 1.
205        then: Expr,
206        /// The value when the condition is 0.
207        els: Expr,
208    },
209    /// A floating-point operation (see [`fp`](crate::fp)).
210    Fp {
211        /// The operation.
212        op: crate::fp::FpOp,
213        /// The format of its floating-point operands (for a conversion from an integer, of
214        /// its result).
215        format: crate::fp::FpFormat,
216        /// The operands.
217        args: crate::fp::FpArgs,
218    },
219    /// Output `output` of an extension call (see [`ext`](crate::ext)).
220    Ext {
221        /// The operation, in the context's registry.
222        op: crate::ext::ExtId,
223        /// Which output.
224        output: u8,
225        /// The arguments.
226        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/// Generation-stamped marks, reused across traversals without clearing.
238#[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    /// Marks `i`; returns whether it was already marked.
257    #[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
266/// The only process-wide state in bitwright: a counter that gives every context generation
267/// (each new context, and each `clear()`) a distinct handle tag. Tags repeat only after 2^32
268/// generations have been created in the process. It never influences any result or output.
269static 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
280/// How many earlier tags of a context are remembered to report `StaleExpr` (older ones are
281/// reported as `ForeignExpr`; both are rejected).
282const RETIRED: usize = 8;
283
284/// A hash-consed expression arena.
285///
286/// A context owns every node it creates. Nodes are immutable and appended in creation order,
287/// and every child index is lower than its parent's, so ascending index order is a topological
288/// order. Structurally equal expressions are the same node ("equal handle implies equal
289/// value"; the converse does not hold). Every node is in canonical form: constants are folded,
290/// commutative operands are ordered (constants last) independently of construction order, and
291/// a fixed set of O(1) identities and cast collapses is applied (see `docs/design.md` §4.3).
292///
293/// ```
294/// use bitwright::{Context, Width};
295/// let mut cx = Context::new();
296/// let x = cx.symbol("x", Width::W32)?;
297/// let one = cx.one(Width::W32)?;
298/// let a = cx.add(one, x)?;
299/// let b = cx.add(x, one)?;
300/// assert_eq!(a, b);
301/// let z = cx.xor(a, b)?;
302/// assert_eq!(cx.as_const(z)?.map(|v| v.is_zero()), Some(true));
303/// # Ok::<(), bitwright::Error>(())
304/// ```
305pub 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    /// Nodes the engine may still create in engine mode (its call's remaining `new_nodes`
319    /// budget), if limited; see [`Context::as_engine_limited`].
320    engine_allowance: Option<u64>,
321    /// Set when the engine allowance refused a node.
322    engine_refused: bool,
323    pub(crate) marks: Marks,
324    dag_cache: IdMap<u32, u32>,
325    /// The last evaluation's immutable schedule and reusable reachable-node registers.
326    eval_plan: Option<Box<eval::Plan>>,
327    pub(crate) facts: crate::facts::FactCache,
328    pub(crate) memo: crate::engine::Memo,
329    /// What a store of results tells the engine's run in progress, and what the run reports
330    /// back to it (see `engine::Remembered`).
331    pub(crate) sweep: crate::engine::SweepNotes,
332    #[cfg(feature = "eqsat")]
333    pub(crate) eqsat_memo: crate::eqsat::Memo,
334    /// The extension operations this context can build.
335    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    // fork a pre-lowered context for independent proofs.
356    /// An independent copy that accepts every expression already built in
357    /// this context.
358    ///
359    /// The immutable evaluation schedule is a cache and is rebuilt on
360    /// demand. Expressions built after the fork belong only to the context
361    /// that built them and must not cross between the two.
362    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    /// An empty context with the default configuration. Allocates nothing until the first node.
391    pub fn new() -> Self {
392        Self::with_config(ContextConfig::default())
393    }
394
395    /// An empty context.
396    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    /// An empty context that can build the extension operations of `registry`.
425    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    /// The extension operations this context can build.
435    pub fn registry(&self) -> Option<&crate::ext::Registry> {
436        self.registry.as_deref()
437    }
438
439    /// Replaces the registry by one that extends it: every operation of the current registry is
440    /// at the same position in `registry` (same name, revision and traits), so every existing
441    /// node keeps its meaning and canonical form. Otherwise an error, and nothing changes.
442    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            // Same operation (name, revision) with the same traits: the traits decide canonical
448            // forms (argument order) that existing nodes were built in.
449            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    /// The configuration.
469    pub fn config(&self) -> &ContextConfig {
470        &self.config
471    }
472
473    /// Changes the node limit ([`ContextConfig::max_nodes`]). Existing nodes stay; a limit
474    /// below the current size only stops new nodes from being created (lookups of existing
475    /// structure still succeed).
476    pub fn set_max_nodes(&mut self, n: u32) {
477        self.config.max_nodes = n;
478    }
479
480    /// The number of nodes.
481    pub fn len(&self) -> usize {
482        self.nodes.len()
483    }
484
485    /// Whether the context has no nodes.
486    pub fn is_empty(&self) -> bool {
487        self.nodes.is_empty()
488    }
489
490    /// Removes every node and symbol, keeping allocations. Handles created before the call
491    /// become stale and are rejected with [`Error::StaleExpr`].
492    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    /// The state to come back to with [`rollback`](Self::rollback): what the context holds
515    /// now.
516    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    /// Removes every node and symbol created since `at` and gives their memory back to the
526    /// context: the expressions of a query against a state that stays (a path condition and
527    /// what it is built from), without the context growing with each query.
528    ///
529    /// Handles created before the checkpoint stay valid and mean what they meant. **Handles
530    /// created after it must not be used again**: one is refused ([`Error::ForeignExpr`])
531    /// until the context has grown past its index, and names another node after that, which
532    /// no check can tell. Drop everything that holds such handles first (a
533    /// [`Solver`](crate::solve::Solver) does with
534    /// [`forget_since`](crate::solve::Solver::forget_since)).
535    ///
536    /// What the library remembers of the removed nodes goes with them; of the others, the
537    /// facts stay, and the simplifier's remembered results are dropped (they may name
538    /// removed nodes). An error, and nothing changes, when the checkpoint is of another
539    /// context, of before a [`clear`](Self::clear), or of a state this context has already
540    /// been rolled back past.
541    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    /// Forgets the results the engine keeps for the expressions of this context (what it made
583    /// of each node the last times it ran), and nothing else: the next run simplifies as in a
584    /// context that had only been built.
585    ///
586    /// A result is kept for a node, whatever the root it was found under, and the passes that
587    /// read a node's surroundings (how often it is used, which of its bits are read) may make
588    /// something else of it under another root. So in a context that lives long, what the
589    /// engine makes of an expression can depend on the expressions it was given before that
590    /// share parts with it: always an equal expression, not always the same one. A host that
591    /// wants results that depend less on what came before calls this between its questions,
592    /// and pays for the results it would have had.
593    ///
594    /// Less, not never. The passes count a node's uses over the nodes of the expression and
595    /// the nodes the run creates, and a node an earlier run left in the context is not created
596    /// again, so the count of what it uses can differ. For the same result as in a context of
597    /// its own, a question is asked between a [`checkpoint`](Self::checkpoint) and a
598    /// [`rollback`](Self::rollback), which removes what it built (the result is taken out
599    /// first, as text or by [`import`](Self::import) into another context).
600    pub fn forget_results(&mut self) {
601        self.memo.clear();
602        #[cfg(feature = "eqsat")]
603        self.eqsat_memo.clear();
604    }
605
606    /// Makes room for at least `additional` more nodes without reallocating (a host that knows
607    /// the size of the function it is about to build). Nodes are still created only on demand,
608    /// and [`ContextConfig::max_nodes`] still bounds them.
609    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    /// Node creation counters.
619    pub fn counters(&self) -> ArenaCounters {
620        self.counters
621    }
622
623    /// The current position of the caller-growth counter.
624    pub fn mark(&self) -> Mark {
625        Mark {
626            tag: self.tag,
627            caller_nodes: self.counters.caller_nodes,
628        }
629    }
630
631    /// New nodes created by the caller since `mark` (all of them, if the mark is from another
632    /// context or from before a `clear()`). Nodes created by the library itself are not counted.
633    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    // ----- handles --------------------------------------------------------------------------
641
642    /// Validates a handle and returns its node index.
643    #[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    // ----- raw node access ------------------------------------------------------------------
668
669    #[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        // Every stored width was validated at construction.
682        Width::new(self.nodes[i as usize].width).unwrap_or(Width::W1)
683    }
684
685    /// Whether node `i` is a constant (without reading its value).
686    #[inline]
687    pub(crate) fn is_const(&self, i: u32) -> bool {
688        self.nodes[i as usize].op == OpCode::Const
689    }
690
691    /// The value of a constant node.
692    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    // ----- interning ------------------------------------------------------------------------
714
715    fn table_hash(&self, shash: u64) -> u64 {
716        combine(self.config.hash_seed, shash)
717    }
718
719    /// The structural hash of a (non-constant, non-symbol) node from its children's hashes.
720    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            // The operation by name and revision, not by registry position.
724            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            // The rounding mode and format; a conversion's target exponent width too.
729            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    /// Appends a node that the caller has checked is not already interned.
757    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    /// Interns a canonical non-constant, non-symbol node.
795    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    /// The interned node `n` (canonical, neither a constant nor a symbol), without creating it.
808    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    /// Interns a constant of at most 64 bits, `v` with no bit set at or above `w`: the node and
818    /// structural hash [`mk_const`](Self::mk_const) gives the same value, without a `BitVec`.
819    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        // `const_hash` of a one-limb value.
825        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    /// Interns a constant.
842    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    /// Whether one more node may be created: the arena's `max_nodes`, and in engine mode the
880    /// engine's node allowance (refusing marks `engine_refused`).
881    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    /// Runs `f` in engine mode, creating at most `allowance` new nodes: a node past it is
894    /// refused (as a full arena) before it is created. Returns whether one was refused.
895    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    /// Runs `f` with new nodes counted as engine nodes.
911    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    // ----- canonical operand order ----------------------------------------------------------
919
920    /// The canonical order of two nodes: compound < symbol < constant; compounds by
921    /// (operator rank, structural hash); symbols by key; constants by value. Independent of the
922    /// context and of construction order (a hash collision falls back to the index).
923    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    // ----- inspection -----------------------------------------------------------------------
964
965    /// The width of an expression.
966    pub fn width(&self, e: Expr) -> Result<Width, Error> {
967        Ok(self.width_of(self.id(e)?))
968    }
969
970    /// The structural hash of an expression: a function of the expression alone (its
971    /// operators, widths, constants and symbol keys), the same in every context and
972    /// whatever was built before it, under one [`HASH_VERSION`](crate::HASH_VERSION). Equal
973    /// expressions hash alike; as with any hash, different ones may too. A fresh symbol
974    /// ([`fresh_symbol`](Self::fresh_symbol)) hashes by its number, which is of its context.
975    pub fn structural_hash(&self, e: Expr) -> Result<u64, Error> {
976        Ok(self.meta[self.id(e)? as usize].shash)
977    }
978
979    /// The hash of each root's shape: its operators and widths with every constant read as
980    /// "a constant of its width" and every symbol as "a symbol of its width", and the
981    /// operands of a commutative operator in no order. Expressions that differ only in
982    /// constants, in which symbols they read, or in the order construction gave such
983    /// operands (it depends on both) have one shape: the key under which what was learned
984    /// from one is looked up for the others. A function of the expression alone, under one
985    /// [`HASH_VERSION`](crate::HASH_VERSION).
986    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    /// The shape hash of node `n` ([`shape_hashes`](Self::shape_hashes)), with `memo` holding
996    /// the shapes of the nodes met: what a caller asks next of the same memo costs what is
997    /// new below it.
998    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            // A different stream from the structural hash: the two never mean the same.
1011            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    /// A read-only view of an expression's top node.
1050    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    /// The operation of a floating-point node.
1110    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    /// The expression's direct operands, in order.
1117    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    /// The value, if the expression is a constant node.
1123    pub fn as_const(&self, e: Expr) -> Result<Option<BitVec>, Error> {
1124        Ok(self.const_val(self.id(e)?))
1125    }
1126
1127    /// Whether the expression is a constant or a symbol.
1128    pub fn is_leaf(&self, e: Expr) -> Result<bool, Error> {
1129        Ok(self.node(self.id(e)?).op.arity() == 0)
1130    }
1131
1132    /// Structural depth (leaves are 0), saturating at `u32::MAX`. O(1).
1133    pub fn height(&self, e: Expr) -> Result<u32, Error> {
1134        Ok(self.meta[self.id(e)? as usize].height)
1135    }
1136
1137    /// The size of the expression unfolded as a tree, saturating at `u32::MAX`. O(1).
1138    pub fn tree_size(&self, e: Expr) -> Result<u32, Error> {
1139        Ok(self.meta[self.id(e)? as usize].tree)
1140    }
1141
1142    // ----- symbols --------------------------------------------------------------------------
1143
1144    /// The symbol for `key`, created at width `width` on first use. A key has exactly one
1145    /// width per context.
1146    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    /// A new symbol with a key that is not yet used in this context.
1180    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    /// The symbol for `key`, if it exists. Never creates.
1191    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    /// The symbol id, if the expression is a symbol node.
1197    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    /// A symbol's key.
1203    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    /// A symbol's width.
1208    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    /// The number of symbols.
1213    pub fn symbol_count(&self) -> usize {
1214        self.symbols.entries.len()
1215    }
1216
1217    /// Declares what the host knows of the value of symbol `s`: every bit `known` has as zero
1218    /// or one is that bit of every value the symbol stands for (a compiler's known bits of a
1219    /// parameter, a load or a call result). It replaces any earlier declaration;
1220    /// [`KnownBits::unknown`](crate::KnownBits::unknown) withdraws it.
1221    ///
1222    /// The declaration becomes part of the symbol's meaning. Facts, proofs and the simplifier
1223    /// use it, and a result is equal to its input for every value of the symbols that agrees
1224    /// with their declarations, not for others. Evaluating at a value that does not agree is
1225    /// the host's error. A declaration drops the context's facts and simplification memo
1226    /// (both may depend on it), so declare right after creating the symbol. Existing assumption
1227    /// sets are repropagated from their original constraints when subsequently queried;
1228    /// [`Assumptions::refresh`](crate::Assumptions::refresh) also updates their diagnostics.
1229    ///
1230    /// ```
1231    /// use bitwright::{BitVec, Context, KnownBits, ParseOptions, Query, Truth, Width};
1232    ///
1233    /// let mut cx = Context::new();
1234    /// let x = cx.symbol("x", Width::W8)?;
1235    /// // The top four bits of `x` are zero.
1236    /// let zero = BitVec::from_u64(Width::W8, 0xf0)?;
1237    /// cx.declare_known(x, KnownBits::new(zero, BitVec::zero(Width::W8)).unwrap())?;
1238    /// let high = cx.parse("x >>u 4", &ParseOptions::width(Width::W8))?;
1239    /// assert_eq!(cx.prove(Query::IsZero(high))?, Truth::True);
1240    /// # Ok::<(), Box<dyn std::error::Error>>(())
1241    /// ```
1242    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        // Every cached fact and result may rest on the old declaration.
1265        self.facts.clear();
1266        self.memo.clear();
1267        #[cfg(feature = "eqsat")]
1268        self.eqsat_memo.clear();
1269        Ok(())
1270    }
1271
1272    /// The known bits declared for symbol `s` ([`declare_known`](Self::declare_known)), if any.
1273    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    /// Whether some symbol has known bits declared (at once where none ever was).
1279    #[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    /// The known bits declared for node `i`, if it is a symbol with a declaration.
1285    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    // ----- traversal ------------------------------------------------------------------------
1293
1294    /// Every node reachable from `roots`, each once, children before parents. Iterative.
1295    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    /// A post-order walk that omits nodes `skip` answers and their descendants, unless a
1306    /// descendant is also reached through another, unskipped path.
1307    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    /// The symbols reachable from `roots`, sorted by key.
1346    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    /// The number of distinct nodes reachable from `roots`, walking at most `cap + 1` nodes.
1365    /// Exact single-root results are cached.
1366    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/// A dense side table keyed by expression index.
1404#[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    /// An empty map.
1417    pub fn new() -> Self {
1418        Self::default()
1419    }
1420
1421    /// Inserts a value, returning the previous one.
1422    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    /// The value for `e`.
1431    pub fn get(&self, e: Expr) -> Option<&T> {
1432        self.data.get(e.index() as usize)?.as_ref()
1433    }
1434
1435    /// Removes and returns the value for `e`.
1436    pub fn remove(&mut self, e: Expr) -> Option<T> {
1437        self.data.get_mut(e.index() as usize)?.take()
1438    }
1439
1440    /// Whether `e` has a value.
1441    pub fn contains(&self, e: Expr) -> bool {
1442        self.get(e).is_some()
1443    }
1444
1445    /// Removes every entry, keeping the allocation.
1446    pub fn clear(&mut self) {
1447        self.data.clear();
1448    }
1449}
1450
1451/// A dense set of expressions (a bitset keyed by index).
1452#[derive(Clone, Debug, Default)]
1453pub struct ExprSet {
1454    bits: Vec<u64>,
1455}
1456
1457impl ExprSet {
1458    /// An empty set.
1459    pub fn new() -> Self {
1460        Self::default()
1461    }
1462
1463    /// Inserts `e`; returns whether it was newly inserted.
1464    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    /// Whether `e` is in the set.
1476    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    /// Removes every element, keeping the allocation.
1484    pub fn clear(&mut self) {
1485        self.bits.clear();
1486    }
1487}