diff --git a/.github/workflows/publish-aplite.yml b/.github/workflows/publish-aplite.yml index bd20e7ea3ee..7a63ac31eef 100644 --- a/.github/workflows/publish-aplite.yml +++ b/.github/workflows/publish-aplite.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/checkout@v7 with: ref: ${{ github.sha }} - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: node-version: '24' - name: Check release identity @@ -46,7 +46,7 @@ jobs: - uses: actions/checkout@v7 with: ref: ${{ github.sha }} - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: node-version: '24' - uses: ./.github/actions/setup-rust diff --git a/crates/aplite/README.md b/crates/aplite/README.md index 9e08d3aa567..0a9b136e90e 100644 --- a/crates/aplite/README.md +++ b/crates/aplite/README.md @@ -57,3 +57,32 @@ let result = solve_seeded(&boolv(true), &context, Limits::default(), 42); assert_eq!(result.verdict, Verdict::Sat); assert!(result.original_formula_validated); ``` + +## Reusable constraints and temporary assumptions + +`PreparedQuery` validates and bit-blasts a fixed scalar formula, context and list +of Boolean predicates once. Each solve can assert either polarity of any of those +predicates. Their definitions are compiled, but unused predicates do not constrain +the answer. Successful searches reuse their SAT database and learned clauses. +UNSAT or interrupted searches discard mutable search state and retain the compiled +encoding, so failed assumptions cannot contaminate the next call. + +```rust +use aplite::{Assumption, Env, Limits, PreparedQuery, Sort, Verdict, boolv, bv, eq, var}; +let x = var("x".into(), Sort::Bv(32)); +let context = Env::from([("x".into(), x.clone())]); +let predicates = [eq(x, bv(32, 7))]; +let mut query = PreparedQuery::new(&boolv(true), &context, &predicates, Limits::default()).unwrap(); +for value in [true, false] { + let result = query.solve(&[Assumption { predicate: 0, value }], Limits::default(), 42); + assert_eq!(result.verdict, Verdict::Sat); + assert!(result.original_formula_validated); +} +``` + +Preparation and each solve have separate budgets; `preparation_work()` reports +the setup work and each outcome reports its solve work. Reproducibility includes +the query history because learning and search activity are retained. Unknown +includes invalid predicate indexes and exhausted budgets, and is not Unsat. +This API supplies reusable solving for future distribution policies; it does not +implement uniform sampling, variable ordering, or SystemVerilog `randomize()`. diff --git a/crates/aplite/src/finite.rs b/crates/aplite/src/finite.rs index dd9dab46e8e..a3136f146ee 100644 --- a/crates/aplite/src/finite.rs +++ b/crates/aplite/src/finite.rs @@ -14,7 +14,9 @@ use std::{ mod control; mod lookup; +mod prepared; mod readonly; +pub use prepared::{Assumption, PreparedQuery}; pub use readonly::ArrayModel; type Lit = i32; @@ -1394,6 +1396,18 @@ impl Sat { conflicts: 0, } } + fn seed_phases(&mut self, mut state: u64, budget: &mut Budget) -> Res<()> { + // SplitMix64 is local and deterministic, including seed zero. + for phase in self.phase.iter_mut().skip(1) { + budget.tick(1)?; + state = state.wrapping_add(0x9e3779b97f4a7c15); + let mut value = state; + value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb); + *phase = (value ^ (value >> 31)) >> 63 != 0; + } + Ok(()) + } fn enqueue(&mut self, p: Lit, reason: Option) -> bool { let v = p.unsigned_abs() as usize; if self.values[v] != 0 { @@ -1552,6 +1566,14 @@ impl Sat { Ok((learned, backtrack)) } fn run_slice(&mut self, b: &mut Budget, quantum: u64) -> Res { + self.run_slice_assuming(b, quantum, &[]) + } + fn run_slice_assuming( + &mut self, + b: &mut Budget, + quantum: u64, + assumptions: &[Lit], + ) -> Res { let stop_work = b.work.saturating_add(quantum.max(1)); if !self.initialized { for id in 0..self.clauses.len() { @@ -1598,6 +1620,22 @@ impl Sat { return Err("finite SAT asserting clause invariant violated".into()); } } else { + // Reapply assumptions after every backjump. Each has its own + // level, including already-implied ones, so the level indexes + // remain stable. An assumption falsified by propagation proves + // only this query UNSAT, not the permanent clause database. + if self.starts.len() < assumptions.len() { + b.tick(1)?; + let p = assumptions[self.starts.len()]; + if truth(&self.values, p) < 0 { + return Ok(Search::Complete(Verdict::Unsat)); + } + self.starts.push(self.trail.len()); + if truth(&self.values, p) == 0 { + self.enqueue(p, None); + } + continue; + } let v = loop { let Some(v) = self.order.pop(&self.activity, b)? else { #[cfg(test)] @@ -1774,6 +1812,100 @@ fn solve_plain(formula: &Term, context: &Env, limits: Limits, search_hint: Searc solve_plain_with_seed(formula, context, limits, search_hint, None) } +fn replay_model( + formula: &Term, + context: &Env, + blast: &Blast, + sat: &Sat, + budget: &mut Budget, +) -> Res<(BTreeMap, BTreeMap)> { + // Validate every original CNF clause as well as the source-level witness. + for clause in &sat.clauses { + budget.tick(clause.len() as u64)?; + if !clause.iter().any(|&p| truth(&sat.values, p) > 0) { + return Err("finite SAT assignment failed CNF validation".into()); + } + } + let mut assignments = BTreeMap::new(); + for (n, bits) in &blast.inputs { + let value = match bits.sort { + Sort::Bool => Scalar::Bool(truth(&sat.values, bits.bits[0]) > 0), + Sort::Bv(width) => Scalar::Bv { + width, + value: bits.bits.iter().enumerate().fold(0u64, |v, (i, &p)| { + v | ((truth(&sat.values, p) > 0) as u64) << i + }), + }, + _ => unreachable!(), + }; + assignments.insert(n.clone(), value); + } + let mut memo = HashMap::new(); + if evaluate(formula, &assignments, &mut memo, budget, 0)? != Scalar::Bool(true) { + return Err("finite SAT assignment failed original-formula validation".into()); + } + let mut values = BTreeMap::new(); + for (label, term) in context { + values.insert( + label.clone(), + evaluate(term, &assignments, &mut memo, budget, 0)?, + ); + } + budget.check_time()?; + Ok((assignments, values)) +} + +fn compile_scalar( + blast: &mut Blast, + formula: &Term, + context: &Env, + budget: &mut Budget, + scalar_only: bool, +) -> Res<()> { + budget.tick(1)?; + if scalar_only && (formula.contains_memory() || context.values().any(Term::contains_memory)) { + return Err("scalar search supports scalar formulas and contexts only".into()); + } + if budget.limits.max_variables < 1 || budget.limits.max_clauses < 1 { + return Err("finite solver initial CNF budget exhausted".into()); + } + if formula.0.sort != Sort::Bool { + return Err("finite formula must have Bool sort".into()); + } + // Rewriting can bypass source nodes. Validate every original formula + // and context signature first, including dead branches and Sat hints. + blast.lookup.source_nodes = lookup::validate_source(formula, context, budget)?; + blast.aliases.collect(formula, budget)?; + let root = blast.term(formula, budget, 0)?; + for term in context.values() { + blast.term(term, budget, 0)?; + } + // Exact normalization may erase the last occurrence of a variable. + // Materialize missing ORIGINAL inputs after normal blasting, preserving + // the existing search order while keeping original SAT replay complete. + let mut source = vec![formula]; + source.extend(context.values()); + let mut seen = HashSet::new(); + let mut variables = BTreeMap::new(); + while let Some(term) = source.pop() { + budget.tick(1)?; + if !seen.insert(term.clone()) { + continue; + } + if let Some(name) = term.0.op.strip_prefix('@') { + if !blast.inputs.contains_key(name) { + variables.insert(name.to_string(), term.clone()); + } + } + source.extend(&term.0.args); + } + for term in variables.values() { + blast.term(term, budget, 0)?; + } + blast.clause(vec![root.bits[0]], budget)?; + Ok(()) +} + fn solve_plain_with_seed( formula: &Term, context: &Env, @@ -1800,52 +1932,7 @@ fn solve_plain_with_seed( time_check_in: 0, }; let mut blast = Blast::new(); - let compile = (|| -> Res<()> { - budget.tick(1)?; - if seed.is_some() - && (formula.contains_memory() || context.values().any(Term::contains_memory)) - { - return Err("seeded search supports scalar formulas and contexts only".into()); - } - if budget.limits.max_variables < 1 || budget.limits.max_clauses < 1 { - return Err("finite solver initial CNF budget exhausted".into()); - } - if formula.0.sort != Sort::Bool { - return Err("finite formula must have Bool sort".into()); - } - // Rewriting can bypass source nodes. Validate every original formula - // and context signature first, including dead branches and Sat hints. - blast.lookup.source_nodes = lookup::validate_source(formula, context, &mut budget)?; - blast.aliases.collect(formula, &mut budget)?; - let root = blast.term(formula, &mut budget, 0)?; - for term in context.values() { - blast.term(term, &mut budget, 0)?; - } - // Exact normalization may erase the last occurrence of a variable. - // Materialize missing ORIGINAL inputs after normal blasting, preserving - // the existing search order while keeping original SAT replay complete. - let mut source = vec![formula]; - source.extend(context.values()); - let mut seen = HashSet::new(); - let mut variables = BTreeMap::new(); - while let Some(term) = source.pop() { - budget.tick(1)?; - if !seen.insert(term.clone()) { - continue; - } - if let Some(name) = term.0.op.strip_prefix('@') { - if !blast.inputs.contains_key(name) { - variables.insert(name.to_string(), term.clone()); - } - } - source.extend(&term.0.args); - } - for term in variables.values() { - blast.term(term, &mut budget, 0)?; - } - blast.clause(vec![root.bits[0]], &mut budget)?; - Ok(()) - })(); + let compile = compile_scalar(&mut blast, formula, context, &mut budget, seed.is_some()); outcome.stats.asserted_definitions = blast.aliases.definitions.len(); outcome.stats.guarded_equalities = blast.aliases.guarded.len(); outcome.stats.guarded_rewrites = blast.guarded_rewrites; @@ -1891,18 +1978,8 @@ fn solve_plain_with_seed( SearchStrategy::CounterexampleProbeFair }; let result = (|| -> Res { - if let Some(mut state) = seed { - // SplitMix64 gives a local, fully specified stream (including seed - // zero). No process RNG, global state or platform-dependent hashing. - for phase in sat.phase.iter_mut().skip(1) { - budget.tick(1)?; - state = state.wrapping_add(0x9e3779b97f4a7c15); - let mut value = state; - value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb); - value ^= value >> 31; - *phase = value >> 63 != 0; - } + if let Some(seed) = seed { + sat.seed_phases(seed, &mut budget)?; } let mut probe_verdict = None; if !choices.is_empty() && search_hint == SearchHint::Sat { @@ -2100,39 +2177,7 @@ fn solve_plain_with_seed( if verdict != Verdict::Sat { return Ok(verdict); } - // Validate every original CNF clause as well as the source-level witness. - for clause in &sat.clauses { - budget.tick(clause.len() as u64)?; - if !clause.iter().any(|&p| truth(&sat.values, p) > 0) { - return Err("finite SAT assignment failed CNF validation".into()); - } - } - let mut assignments = BTreeMap::new(); - for (n, bits) in &blast.inputs { - let value = match bits.sort { - Sort::Bool => Scalar::Bool(truth(&sat.values, bits.bits[0]) > 0), - Sort::Bv(width) => Scalar::Bv { - width, - value: bits.bits.iter().enumerate().fold(0u64, |v, (i, &p)| { - v | ((truth(&sat.values, p) > 0) as u64) << i - }), - }, - _ => unreachable!(), - }; - assignments.insert(n.clone(), value); - } - let mut memo = HashMap::new(); - if evaluate(formula, &assignments, &mut memo, &mut budget, 0)? != Scalar::Bool(true) { - return Err("finite SAT assignment failed original-formula validation".into()); - } - let mut values = BTreeMap::new(); - for (label, term) in context { - values.insert( - label.clone(), - evaluate(term, &assignments, &mut memo, &mut budget, 0)?, - ); - } - budget.check_time()?; + let (assignments, values) = replay_model(formula, context, &blast, &sat, &mut budget)?; outcome.assignments = assignments; outcome.context_values = values; outcome.original_formula_validated = true; diff --git a/crates/aplite/src/finite/prepared.rs b/crates/aplite/src/finite/prepared.rs new file mode 100644 index 00000000000..3016ce5691c --- /dev/null +++ b/crates/aplite/src/finite/prepared.rs @@ -0,0 +1,489 @@ +//! Reusable scalar encoding with temporary Boolean assumptions. +use super::*; + +/// Select the polarity of a predicate supplied when preparing the query. +#[derive(Clone, Copy, Debug)] +pub struct Assumption { + pub predicate: usize, + pub value: bool, +} + +/// A compiled scalar query. Predicate definitions are permanent, but asserting +/// their truth values is local to each call. A successful search retains its +/// learned clauses and heuristic state; UNSAT and interrupted searches discard +/// search state while preserving the compiled encoding. +/// +/// This provides reusable solving, not uniform sampling. Seed reproducibility +/// requires the same query history and solver version. Preparation and each +/// solve have separate explicit budgets; callers must account for an aggregate +/// operation budget themselves. +pub struct PreparedQuery { + formula: Term, + context: Env, + predicates: Vec, + literals: Vec, + blast: Blast, + sat: Option, + preparation_work: u64, +} + +impl PreparedQuery { + pub fn new(formula: &Term, context: &Env, predicates: &[Term], limits: Limits) -> Res { + let mut budget = Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + budget.tick(1)?; + // Add predicates to the compile context so source validation sees dead + // branches, sort conflicts and variables erased by normalization too. + let mut compile_context = context.clone(); + for (index, term) in predicates.iter().enumerate() { + budget.tick(1)?; + if term.0.sort != Sort::Bool { + return Err("prepared predicates must have Bool sort".into()); + } + let mut key = format!("__aplite_predicate_{index}"); + while compile_context.contains_key(&key) { + budget.tick(1)?; + key.push('_'); + } + compile_context.insert(key, term.clone()); + } + let mut blast = Blast::new(); + compile_scalar(&mut blast, formula, &compile_context, &mut budget, true)?; + let mut literals = Vec::with_capacity(predicates.len()); + for term in predicates { + literals.push(blast.term(term, &mut budget, 0)?.bits[0]); + } + budget.check_time()?; + Ok(Self { + formula: formula.clone(), + context: context.clone(), + predicates: predicates.to_vec(), + literals, + blast, + sat: None, + preparation_work: budget.work, + }) + } + + /// Work charged for the one-time source validation and bit blasting. + pub fn preparation_work(&self) -> u64 { + self.preparation_work + } + + /// Solve with temporary assumptions. Invalid indexes and exhausted budgets + /// yield Unknown. SAT models are replayed against the original formula, + /// context and each asserted predicate before becoming visible. + pub fn solve(&mut self, assumptions: &[Assumption], limits: Limits, seed: u64) -> Outcome { + let mut outcome = Outcome { + search_hint: SearchHint::Sat, + search_strategy: SearchStrategy::SingleSearch, + verdict: Verdict::Unknown, + reason: None, + assignments: BTreeMap::new(), + context_values: BTreeMap::new(), + array_assignments: BTreeMap::new(), + array_context_values: BTreeMap::new(), + original_formula_validated: false, + stats: Stats::default(), + }; + let mut budget = Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + // Take ownership so any error drops possibly interrupted mutations. + let mut sat = self.sat.take(); + let result = (|| -> Res { + budget.tick(1)?; + if self.blast.vars > budget.limits.max_variables + || self.blast.memo.len() > budget.limits.max_terms + { + return Err("prepared query exceeds solve size limits".into()); + } + let mut literals = Vec::with_capacity(assumptions.len()); + for assumption in assumptions { + budget.tick(1)?; + let p = *self + .literals + .get(assumption.predicate) + .ok_or("invalid prepared predicate index")?; + literals.push(if assumption.value { p } else { -p }); + } + if self.blast.clauses.len() > budget.limits.max_clauses { + return Err("prepared query exceeds solve clause limit".into()); + } + if sat.is_none() { + let mut clauses = Vec::with_capacity(self.blast.clauses.len()); + for clause in &self.blast.clauses { + budget.tick(1 + clause.len() as u64)?; + clauses.push(clause.clone()); + } + sat = Some(Sat::new(self.blast.vars, clauses)); + } + let solver = sat.as_mut().unwrap(); + if solver.clauses.len() > budget.limits.max_clauses { + return Err("prepared query exceeds solve clause limit".into()); + } + solver.backtrack(0, &mut budget)?; + solver.seed_phases(seed, &mut budget)?; + let decisions = solver.decisions; + let conflicts = solver.conflicts; + let result = solver.run_slice_assuming(&mut budget, u64::MAX, &literals); + outcome.stats.decisions = solver.decisions - decisions; + outcome.stats.conflicts = solver.conflicts - conflicts; + outcome.stats.search_slices = 1; + let verdict = match result? { + Search::Complete(verdict) => verdict, + Search::Pending => return Err("prepared search did not complete".into()), + }; + if verdict != Verdict::Sat { + budget.check_time()?; + return Ok(verdict); + } + let (assignments, values) = replay_model( + &self.formula, + &self.context, + &self.blast, + solver, + &mut budget, + )?; + let mut memo = HashMap::new(); + for assumption in assumptions { + if evaluate( + &self.predicates[assumption.predicate], + &assignments, + &mut memo, + &mut budget, + 0, + )? != Scalar::Bool(assumption.value) + { + return Err("prepared model failed assumption replay".into()); + } + } + budget.check_time()?; + outcome.assignments = assignments; + outcome.context_values = values; + outcome.original_formula_validated = true; + Ok(Verdict::Sat) + })(); + outcome.stats.work = budget.work; + outcome.stats.base_cnf_reused = true; + outcome.stats.terms = self.blast.memo.len(); + outcome.stats.variables = self.blast.vars; + outcome.stats.base_clauses = self.blast.clauses.len(); + outcome.stats.clauses = sat + .as_ref() + .map_or(self.blast.clauses.len(), |sat| sat.clauses.len()); + outcome.stats.peak_live_clauses = outcome.stats.clauses; + match result { + Ok(verdict) => outcome.verdict = verdict, + Err(reason) => outcome.reason = Some(reason), + } + if outcome.verdict == Verdict::Sat { + self.sat = sat; + } + outcome + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{and, boolv, bv, eq, node, not, var}; + + fn assumption(predicate: usize, value: bool) -> Assumption { + Assumption { predicate, value } + } + + #[test] + fn assumptions_do_not_escape_calls_or_become_alias_definitions() { + let x = var("x".into(), Sort::Bv(8)); + let y = var("y".into(), Sort::Bv(8)); + let predicates = [eq(x.clone(), y.clone()), eq(x.clone(), bv(8, 37))]; + let context = Env::from([("x".into(), x), ("y".into(), y)]); + let mut prepared = + PreparedQuery::new(&boolv(true), &context, &predicates, Limits::default()).unwrap(); + assert!(prepared.preparation_work() > 0); + for value in [true, false, true, false] { + let outcome = prepared.solve( + &[assumption(0, value), assumption(1, true)], + Limits::default(), + 42, + ); + assert_eq!(outcome.verdict, Verdict::Sat); + assert!(outcome.original_formula_validated); + assert_eq!( + outcome.assignments["x"], + Scalar::Bv { + width: 8, + value: 37 + } + ); + assert_eq!(outcome.assignments["x"] == outcome.assignments["y"], value); + assert!(prepared.sat.is_some()); + } + let bad = prepared.solve( + &[assumption(0, true), assumption(0, false)], + Limits::default(), + 0, + ); + assert_eq!(bad.verdict, Verdict::Unsat); + assert!(bad.assignments.is_empty()); + assert_eq!( + prepared.solve(&[], Limits::default(), 0).verdict, + Verdict::Sat + ); + } + + #[test] + fn constant_aliased_and_duplicate_assumptions_are_sound() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let formula = and(x.clone(), eq(x.clone(), y.clone())); + let predicates = [boolv(true), boolv(false), x, y]; + let mut query = + PreparedQuery::new(&formula, &Env::new(), &predicates, Limits::default()).unwrap(); + for (index, required) in [(0, true), (1, false), (2, true), (3, true)] { + let sat = query.solve( + &[assumption(index, required), assumption(index, required)], + Limits::default(), + 0, + ); + assert_eq!(sat.verdict, Verdict::Sat); + assert_eq!( + query + .solve(&[assumption(index, !required)], Limits::default(), 0) + .verdict, + Verdict::Unsat + ); + } + } + + #[test] + fn exhaustive_three_boolean_queries_match_truth_tables_across_reuse() { + let vars = [ + var("x".into(), Sort::Bool), + var("y".into(), Sort::Bool), + var("z".into(), Sort::Bool), + ]; + let context = Env::from([ + ("x".into(), vars[0].clone()), + ("y".into(), vars[1].clone()), + ("z".into(), vars[2].clone()), + ]); + for mask in 0..256u16 { + let mut formula = boolv(false); + for row in 0..8 { + if mask & (1 << row) != 0 { + let mut cube = boolv(true); + for (index, variable) in vars.iter().enumerate() { + cube = and( + cube, + if row & (1 << index) != 0 { + variable.clone() + } else { + not(variable.clone()) + }, + ); + } + formula = node(Sort::Bool, "or", vec![formula, cube]); + } + } + let predicates = [ + vars[0].clone(), + vars[1].clone(), + vars[2].clone(), + node(Sort::Bool, "xor", vec![vars[0].clone(), vars[1].clone()]), + ]; + let mut query = + PreparedQuery::new(&formula, &context, &predicates, Limits::default()).unwrap(); + for choice in 0..16 { + // Alternate partial assumptions and XOR predicates to leave + // search decisions/conflicts beyond the assumption prefix. + let conditions = [ + assumption(choice % 3, choice & 1 != 0), + assumption(3, choice & 2 != 0), + ]; + let legal: Vec<_> = (0..8) + .filter(|row| { + mask & (1 << row) != 0 + && ((*row >> (choice % 3)) & 1 != 0) == (choice & 1 != 0) + && (((*row & 1) != 0) ^ ((*row & 2) != 0)) == (choice & 2 != 0) + }) + .collect(); + let outcome = query.solve(&conditions, Limits::default(), choice as u64); + assert_eq!( + outcome.verdict, + if legal.is_empty() { + Verdict::Unsat + } else { + Verdict::Sat + }, + "mask={mask}, choice={choice}" + ); + if outcome.verdict == Verdict::Sat { + let mut row = 0; + for (index, name) in ["x", "y", "z"].iter().enumerate() { + if outcome.assignments[*name] == Scalar::Bool(true) { + row |= 1 << index; + } + } + assert!(legal.contains(&row)); + assert!(outcome.original_formula_validated); + } + } + } + } + + #[test] + fn interruptions_and_invalid_indexes_leave_the_encoding_reusable() { + let x = var("x".into(), Sort::Bv(8)); + let context = Env::from([("x".into(), x.clone())]); + let predicate = eq(x, bv(8, 127)); + let mut query = + PreparedQuery::new(&boolv(true), &context, &[predicate], Limits::default()).unwrap(); + for work in 0..100 { + let result = query.solve( + &[assumption(0, true)], + Limits { + max_work: work, + ..Limits::default() + }, + 0, + ); + if result.verdict == Verdict::Unknown { + assert!(query.sat.is_none()); + assert!(result.assignments.is_empty()); + } + let next = query.solve(&[assumption(0, false)], Limits::default(), 0); + assert_eq!(next.verdict, Verdict::Sat); + assert_ne!( + next.assignments["x"], + Scalar::Bv { + width: 8, + value: 127 + } + ); + } + for conditions in [ + vec![assumption(usize::MAX, true)], + vec![assumption(1, false)], + ] { + assert_eq!( + query.solve(&conditions, Limits::default(), 0).verdict, + Verdict::Unknown + ); + assert_eq!(query.solve(&[], Limits::default(), 0).verdict, Verdict::Sat); + } + for limits in [ + Limits { + max_variables: 0, + ..Limits::default() + }, + Limits { + max_clauses: 0, + ..Limits::default() + }, + Limits { + timeout_ms: 0, + ..Limits::default() + }, + ] { + assert_eq!(query.solve(&[], limits, 0).verdict, Verdict::Unknown); + assert_eq!(query.solve(&[], Limits::default(), 0).verdict, Verdict::Sat); + } + } + + #[test] + fn learned_clauses_survive_success_but_do_not_turn_assumptions_into_facts() { + // Resolution proves x, but there is no x unit in the source. Exercise + // a conflict and retained learning before changing the assumptions. + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let formula = and( + node(Sort::Bool, "or", vec![x.clone(), y.clone()]), + node(Sort::Bool, "or", vec![x.clone(), not(y.clone())]), + ); + let mut exercised_learning = false; + for seed in 0..64 { + let mut query = PreparedQuery::new( + &formula, + &Env::new(), + &[x.clone(), y.clone()], + Limits::default(), + ) + .unwrap(); + let first = query.solve(&[], Limits::default(), seed); + assert_eq!(first.verdict, Verdict::Sat); + if first.stats.conflicts == 0 { + continue; + } + exercised_learning = true; + assert!(query.sat.as_ref().unwrap().clauses.len() > query.blast.clauses.len()); + for value in [false, true, false] { + let result = query.solve(&[assumption(1, value)], Limits::default(), seed); + assert_eq!(result.verdict, Verdict::Sat); + assert_eq!(result.assignments["x"], Scalar::Bool(true)); + assert_eq!(result.assignments["y"], Scalar::Bool(value)); + } + assert_eq!( + query + .solve(&[assumption(0, false)], Limits::default(), seed) + .verdict, + Verdict::Unsat + ); + assert_eq!( + query + .solve(&[assumption(0, true)], Limits::default(), seed) + .verdict, + Verdict::Sat + ); + break; + } + assert!(exercised_learning); + } + + #[test] + fn preparation_checks_predicates_even_when_unasserted() { + for predicate in [ + bv(8, 1), + node(Sort::Bool, "unknown", vec![]), + eq( + var("m".into(), Sort::Mem(4, 8)), + var("m".into(), Sort::Mem(4, 8)), + ), + ] { + assert!( + PreparedQuery::new(&boolv(true), &Env::new(), &[predicate], Limits::default()) + .is_err() + ); + } + let context = Env::from([("x".into(), var("x".into(), Sort::Bv(8)))]); + assert!( + PreparedQuery::new( + &boolv(true), + &context, + &[var("x".into(), Sort::Bool)], + Limits::default() + ) + .is_err() + ); + assert!( + PreparedQuery::new( + &boolv(true), + &Env::new(), + &[], + Limits { + max_work: 0, + ..Limits::default() + } + ) + .is_err() + ); + } +} diff --git a/crates/aplite/src/lib.rs b/crates/aplite/src/lib.rs index 79a6868d102..7a721daf55f 100644 --- a/crates/aplite/src/lib.rs +++ b/crates/aplite/src/lib.rs @@ -4,14 +4,18 @@ //! The solver runs in process, without an external SMT executable. Unsupported //! expressions and exhausted resource budgets return [`Verdict::Unknown`]. //! SAT models are replayed against the original formula; UNSAT trusts the solver. -//! This crate does not provide random sampling of satisfying assignments. +//! This crate does not provide uniform sampling of satisfying assignments. pub mod term; pub use term::*; pub type Env = std::collections::BTreeMap; pub mod finite; pub use finite::{ - Limits, Outcome, Scalar, SearchHint, Verdict, solve, solve_seeded, solve_with_hint, + Assumption, Limits, Outcome, PreparedQuery, Scalar, SearchHint, Verdict, solve, solve_seeded, + solve_with_hint, }; #[cfg(test)] mod seeded_tests; + +#[cfg(test)] +mod sampling_oracle; diff --git a/crates/aplite/src/sampling_oracle.rs b/crates/aplite/src/sampling_oracle.rs new file mode 100644 index 00000000000..da695f26d68 --- /dev/null +++ b/crates/aplite/src/sampling_oracle.rs @@ -0,0 +1,369 @@ +//! Test-only bounded enumeration oracle for projected scalar solution sets. +//! Never use whole-space enumeration on the runtime randomization path. +use crate::{ + Env, Limits, Outcome, Scalar, SearchHint, Sort, Term, Verdict, and, boolv, bv, eq, not, + solve_with_hint, +}; +use std::{collections::BTreeSet, time::Instant}; + +/// One budget for the complete enumeration, not a fresh budget per model. +#[derive(Clone, Debug)] +pub struct SamplingLimits { + pub solver: Limits, + /// Maximum number of distinct projected models. One final UNSAT query is + /// permitted to establish that this limit exactly covers the solution set. + pub max_models: u64, +} + +impl Default for SamplingLimits { + fn default() -> Self { + Self { + solver: Limits::default(), + max_models: 256, + } + } +} + +#[derive(Debug)] +pub struct Sample { + pub verdict: Verdict, + /// Present only after complete enumeration of a nonempty solution set. + pub model: Option, + /// Distinct projected assignments processed within the model-count limit. + pub models: u64, + pub work: u64, + pub reason: Option, +} + +/// Uniform reservoir sampling over distinct assignments to `projection`. +/// +/// Projection values must be distinct Boolean or 1..=64-bit variable terms; +/// labels are arbitrary. Variables outside the projection are existentially +/// quantified: the number of their witnesses does not weight a projected value. +/// An empty projection has exactly one assignment if the formula is satisfiable. +/// +/// This enumerates all projected models and is intended for small domains. +/// It returns no sample on exhaustion or unsupported input. The PRNG is local +/// SplitMix64 and bounded draws use rejection to avoid modulo bias. As with any +/// seeded PRNG, this is not a cryptographic entropy source. Reproducibility is +/// within a solver version, for identical inputs and sufficient budgets. +/// Arrays, weighting, and variable-order distribution policies are unsupported. +pub fn sample_uniform( + formula: &Term, + projection: &Env, + limits: SamplingLimits, + seed: u64, +) -> Sample { + let start = Instant::now(); + let mut result = Sample { + verdict: Verdict::Unknown, + model: None, + models: 0, + work: 0, + reason: None, + }; + let mut selected = None; + let mut rng = seed; + let run = (|| -> Result { + if formula.contains_memory() { + return Err("sampling supports scalar formulas only".into()); + } + let mut names = BTreeSet::new(); + for term in projection.values() { + charge(&mut result.work, 1, limits.solver.max_work)?; + let Some(name) = term.0.op.strip_prefix('@') else { + return Err("sampling projection must contain variables".into()); + }; + if !term.0.args.is_empty() || !matches!(term.0.sort, Sort::Bool | Sort::Bv(1..=64)) { + return Err( + "sampling projection requires scalar variables of supported width".into(), + ); + } + if !names.insert(name) { + return Err("sampling projection contains a duplicate variable".into()); + } + } + let mut clauses = vec![formula.clone()]; + loop { + // Rebuild a balanced conjunction so enumeration does not consume + // the depth limit just by accumulating blocking clauses. + charge( + &mut result.work, + clauses.len() as u64, + limits.solver.max_work, + )?; + let query = conjunction(&clauses); + let remaining_ms = limits + .solver + .timeout_ms + .checked_sub(u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)) + .filter(|ms| *ms > 0) + .ok_or("sampling timeout exhausted")?; + let mut solver_limits = limits.solver.clone(); + solver_limits.max_work = limits.solver.max_work - result.work; + solver_limits.timeout_ms = remaining_ms; + let model = solve_with_hint(&query, projection, solver_limits, SearchHint::Sat); + charge(&mut result.work, model.stats.work, limits.solver.max_work)?; + match model.verdict { + Verdict::Unknown => { + return Err(model + .reason + .unwrap_or_else(|| "sampling solver returned Unknown".into())); + } + Verdict::Unsat => { + return Ok(if result.models == 0 { + Verdict::Unsat + } else { + Verdict::Sat + }); + } + Verdict::Sat => {} + } + if result.models == limits.max_models { + return Err("sampling model limit exhausted".into()); + } + result.models += 1; + let mut equalities = Vec::with_capacity(projection.len()); + for (label, term) in projection { + charge(&mut result.work, 1, limits.solver.max_work)?; + let value = match &model.context_values[label] { + Scalar::Bool(value) => boolv(*value), + Scalar::Bv { width, value } => bv(*width, *value), + }; + equalities.push(eq(term.clone(), value)); + } + clauses.push(not(conjunction(&equalities))); + // Reservoir step: after k models each one is retained with 1/k + // probability, regardless of the SAT solver's enumeration order. + if draw_below( + &mut rng, + result.models, + &mut result.work, + limits.solver.max_work, + )? == 0 + { + selected = Some(model); + } + } + })(); + match run { + Ok(verdict) if start.elapsed().as_millis() < u128::from(limits.solver.timeout_ms) => { + result.verdict = verdict; + if verdict == Verdict::Sat { + result.model = selected; + } + } + Ok(_) => result.reason = Some("sampling timeout exhausted".into()), + Err(reason) => result.reason = Some(reason), + } + result +} + +fn charge(work: &mut u64, amount: u64, limit: u64) -> Result<(), String> { + *work = work.checked_add(amount).ok_or("sampling work overflow")?; + if *work > limit { + return Err("sampling work limit exhausted".into()); + } + Ok(()) +} + +fn conjunction(terms: &[Term]) -> Term { + match terms.len() { + 0 => boolv(true), + 1 => terms[0].clone(), + n => and(conjunction(&terms[..n / 2]), conjunction(&terms[n / 2..])), + } +} + +fn draw_below(state: &mut u64, bound: u64, work: &mut u64, limit: u64) -> Result { + let threshold = bound.wrapping_neg() % bound; + loop { + charge(work, 1, limit)?; + *state = state.wrapping_add(0x9e3779b97f4a7c15); + let mut value = *state; + value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb); + value ^= value >> 31; + if value >= threshold { + return Ok(value % bound); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{node, var}; + + #[test] + fn projected_models_are_not_weighted_by_hidden_witnesses() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + // x=false has two y witnesses, x=true has one. Projecting x must + // enumerate two models, while projecting both must enumerate three. + let formula = node(Sort::Bool, "or", vec![not(x.clone()), y.clone()]); + let projection = Env::from([("chosen".into(), x.clone())]); + let both = Env::from([("x".into(), x), ("y".into(), y)]); + let mut counts = [0; 2]; + for seed in 0..512 { + let sample = sample_uniform(&formula, &projection, SamplingLimits::default(), seed); + assert_eq!(sample.verdict, Verdict::Sat); + assert_eq!(sample.models, 2); + let model = sample.model.unwrap(); + assert!(model.original_formula_validated); + let Scalar::Bool(x) = model.context_values["chosen"] else { + panic!() + }; + counts[usize::from(x)] += 1; + } + // Fixed seeds, broad regression threshold: distinguish 1/2 from the + // 1/3 weighting caused by accidentally enumerating hidden witnesses. + assert!( + counts.iter().all(|count| (210..302).contains(count)), + "{counts:?}" + ); + assert_eq!( + sample_uniform(&formula, &both, SamplingLimits::default(), 0).models, + 3 + ); + } + + #[test] + fn exact_model_limit_allows_final_unsat_check_but_never_partial_samples() { + let x = var("x".into(), Sort::Bv(2)); + let projection = Env::from([("x".into(), x)]); + for limit in 0..=4 { + let result = sample_uniform( + &boolv(true), + &projection, + SamplingLimits { + max_models: limit, + ..SamplingLimits::default() + }, + 42, + ); + assert_eq!(result.models, limit); + if limit < 4 { + assert_eq!(result.verdict, Verdict::Unknown); + assert!(result.model.is_none()); + assert!(result.reason.unwrap().contains("model limit")); + } else { + assert_eq!(result.verdict, Verdict::Sat); + assert!(result.model.is_some()); + } + } + } + + #[test] + fn empty_projection_and_unsat_have_exact_cardinality() { + for (formula, verdict, count) in [ + (boolv(true), Verdict::Sat, 1), + (boolv(false), Verdict::Unsat, 0), + ] { + let sample = sample_uniform(&formula, &Env::new(), SamplingLimits::default(), 0); + assert_eq!(sample.verdict, verdict); + assert_eq!(sample.models, count); + assert_eq!(sample.model.is_some(), verdict == Verdict::Sat); + } + } + + #[test] + fn work_budget_is_global_and_seed_is_reproducible() { + let projection = Env::from([("x".into(), var("x".into(), Sort::Bv(3)))]); + let a = sample_uniform(&boolv(true), &projection, SamplingLimits::default(), 13); + let b = sample_uniform(&boolv(true), &projection, SamplingLimits::default(), 13); + assert_eq!(a.verdict, Verdict::Sat); + assert_eq!(a.models, 8); + assert_eq!(a.work, b.work); + assert_eq!(a.model.unwrap().assignments, b.model.unwrap().assignments); + for budget in [0, a.work - 1] { + let limited = sample_uniform( + &boolv(true), + &projection, + SamplingLimits { + solver: Limits { + max_work: budget, + ..Limits::default() + }, + ..SamplingLimits::default() + }, + 13, + ); + assert_eq!(limited.verdict, Verdict::Unknown); + assert!(limited.model.is_none()); + } + let timed_out = sample_uniform( + &boolv(true), + &projection, + SamplingLimits { + solver: Limits { + timeout_ms: 0, + ..Limits::default() + }, + ..SamplingLimits::default() + }, + 13, + ); + assert_eq!(timed_out.verdict, Verdict::Unknown); + assert!(timed_out.model.is_none()); + } + + #[test] + fn malformed_projection_and_unsupported_formula_fail_closed() { + let x = var("x".into(), Sort::Bool); + for projection in [ + Env::from([("literal".into(), boolv(true))]), + Env::from([("x".into(), x.clone()), ("alias".into(), x)]), + Env::from([("wide".into(), var("wide".into(), Sort::Bv(65)))]), + Env::from([("m".into(), var("m".into(), Sort::Mem(4, 8)))]), + ] { + let result = sample_uniform(&boolv(true), &projection, SamplingLimits::default(), 0); + assert_eq!(result.verdict, Verdict::Unknown); + assert!(result.model.is_none()); + } + let formula = node(Sort::Bool, "unsupported", vec![]); + let result = sample_uniform(&formula, &Env::new(), SamplingLimits::default(), 0); + assert_eq!(result.verdict, Verdict::Unknown); + assert!(result.model.is_none()); + } + + #[test] + fn all_two_boolean_truth_tables_match_exhaustive_counts() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let projection = Env::from([("x".into(), x.clone()), ("y".into(), y.clone())]); + for mask in 0..16u8 { + let mut formula = boolv(false); + for row in 0..4u8 { + if mask & (1 << row) != 0 { + let case = and( + eq(x.clone(), boolv(row & 1 != 0)), + eq(y.clone(), boolv(row & 2 != 0)), + ); + formula = node(Sort::Bool, "or", vec![formula, case]); + } + } + for seed in 0..8 { + let result = sample_uniform(&formula, &projection, SamplingLimits::default(), seed); + assert_eq!(result.models, u64::from(mask.count_ones())); + assert_eq!( + result.verdict, + if mask == 0 { + Verdict::Unsat + } else { + Verdict::Sat + } + ); + if let Some(model) = result.model { + let Scalar::Bool(x) = model.context_values["x"] else { + panic!() + }; + let Scalar::Bool(y) = model.context_values["y"] else { + panic!() + }; + assert_ne!(mask & (1 << (u8::from(x) | u8::from(y) << 1)), 0); + } + } + } + } +} diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index a5a2a7f987d..22f1c650f7c 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -8840,6 +8840,12 @@ fn runtime_select_width( if constant(msb).is_some() && constant(lsb).is_some() { return None; } + // A bit select has width one regardless of its runtime position. Sampling + // both bounds evaluates the same (potentially inlined) expression twice, + // and the zero sample need not even be a valid index computation. + if msb == lsb { + return Some(1); + } // The width is the same for every value of the runtime operands. let mut sample = constants.clone(); for name in name_to_id.keys() { @@ -10523,6 +10529,37 @@ fn inferred_clock( mod tests { use super::*; + #[test] + fn bit_select_width_does_not_evaluate_a_runtime_zero_sample() { + let index = sv::ir::ConstExpr::Ident("index".into()); + let bound = sv::ir::ConstExpr::Binary { + left: Box::new(sv::ir::ConstExpr::Literal("255".into())), + op: sv::ir::BinaryOp::Div, + right: Box::new(index.clone()), + }; + let names = HashMap::from_iter([("index".into(), SourceVarId(0))]); + let constants = HashMap::default(); + let types = HashMap::default(); + assert_eq!( + runtime_select_width(&bound, &bound, &names, &constants, &types), + Some(1) + ); + let high = sv::ir::ConstExpr::Binary { + left: Box::new(index.clone()), + op: sv::ir::BinaryOp::Add, + right: Box::new(sv::ir::ConstExpr::Literal("7".into())), + }; + assert_eq!( + runtime_select_width(&high, &index, &names, &constants, &types), + Some(8) + ); + let constant = sv::ir::ConstExpr::Literal("3".into()); + assert_eq!( + runtime_select_width(&constant, &constant, &names, &constants, &types), + None + ); + } + /// The per-name driver scan [`ModuleDrivers`] replaced, which walks every /// process for each name. mod per_name_scan { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 353055ff483..83c870dbb80 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -21,21 +21,46 @@ fn query_context(context: &PackedDimensions) -> PackedDimensions { query } +/// These operands carry all type information in their literal leaves. Walking +/// declaration scopes cannot change their shape or signedness. Keep calls, +/// casts and names on the discovery path, including names in unevaluated arms. +fn literal_operand(root: ExprId, native: &celox_sv_syntax::Declarations) -> bool { + let root = expression_binding::ungroup(root, native); + if matches!(native.expression(root).kind, ExprKind::Literal(_)) { + return true; + } + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + match &native.expression(id).kind { + ExprKind::Literal(_) => {} + ExprKind::Group(inner) + | ExprKind::Unary { + expression: inner, .. + } => { + pending.push(*inner); + } + ExprKind::Binary { left, right, .. } => pending.extend([*left, *right]), + ExprKind::Conditional { + condition, + then_expression, + else_expression, + } => { + pending.extend([*condition, *then_expression, *else_expression]); + } + _ => return false, + } + } + true +} + pub(in crate::ast) fn query_context_for_operand( root: ExprId, tree: &AnalysisContext<'_>, context: &PackedDimensions, ) -> Converted { - // Literals carry their type in their spelling and cannot reference lexical - // declarations. Pattern elements otherwise rediscover the whole scope for - // each literal while the surrounding declaration is still being bound. - let operand = expression_binding::ungroup(root, tree.declarations()); - if context.scope_types_complete - || matches!( - tree.declarations().expression(operand).kind, - ExprKind::Literal(_) - ) - { + // Aggregate port defaults commonly repeat literal arithmetic. Rediscovering + // all declarations for each item repeatedly snapshots the growing prefix. + if context.scope_types_complete || literal_operand(root, tree.declarations()) { return Ok(query_context(context)); } Ok(query_context(&query_operand_dimensions_id( diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index f29dadcf3e5..eeeac9bcae6 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -45,6 +45,74 @@ fn query_number( .and_then(|value| usize::try_from(value).ok()) } +#[test] +fn repeated_literal_port_defaults_do_not_rediscover_declarations() { + for count in [8, 32, 128] { + let ports = (0..count) + .map(|i| format!("input logic [7:0] p{i}[2] = '{{2{{8'd60-1}}}}")) + .collect::>() + .join(","); + let code = format!("module Top({ports}, output wire [7:0] y); assign y=p0[0]; endmodule"); + let tree = + crate::source_tree::parse_scope_fixture(&code, Path::new("literal-port-defaults.sv")) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + let source = Source::from_syntax(&tree).unwrap(); + assert_eq!(source.modules()[0].ports().len(), count + 1); + assert_eq!( + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()), + 0, + "{count} ports" + ); + } +} + +#[test] +fn literal_arithmetic_queries_keep_widths_and_skip_scope_discovery() { + let code = "module Top; assign y=$bits(8'd60-1)+$bits(-8'sd1+16'sd2)+$bits(1'b0 ? 8'hff : 16'hffff)+$bits(~8'hff)+$bits(32'd1<<64'd40); endmodule"; + let tree = + crate::source_tree::parse_scope_fixture(code, Path::new("literal-query-types.sv")).unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + let input = PackedDimensions::default(); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + let values = native_calls(&tree) + .into_iter() + .map(|root| { + query_number( + root, + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&input), + ) + }) + .collect::>(); + assert_eq!(values, [Some(32), Some(16), Some(16), Some(8), Some(32)]); + assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()), 0); +} + +#[test] +fn queries_still_discover_names_in_unselected_conditional_arms() { + let code = "module Top; logic [15:0] data; assign y=$bits(1'b0 ? data : 8'hff); endmodule"; + let tree = + crate::source_tree::parse_scope_fixture(code, Path::new("conditional-query-types.sv")) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + assert_eq!( + query_number( + native_calls(&tree)[0], + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&PackedDimensions::default()) + ), + Some(16) + ); + assert!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()) > 0); +} + #[test] fn function_result_queries_preserve_expression_bodies() { let tree = crate::source_tree::parse_scope_fixture( diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 460881888e5..f795cfb1994 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -345,6 +345,11 @@ pub fn eval_const_expr_with_types( constants: &HashMap, types: &HashMap, ) -> Option { + // Runtime select bounds often contain large inlined expressions. Reject a + // required runtime value before attempting literal folding at every node. + if requires_unbound_value(expr, constants) { + return None; + } // Substitution only replaces the identifiers of typed constants. if !has_typed_constant(expr, constants, types) { return eval_const_expr(expr, constants); @@ -353,6 +358,38 @@ pub fn eval_const_expr_with_types( eval_const_expr(&expr, constants) } +fn requires_unbound_value(expr: &ConstExpr, constants: &HashMap) -> bool { + match expr { + ConstExpr::Literal(_) | ConstExpr::Function { .. } => return false, + ConstExpr::Ident(name) => return !constants.contains_key(name), + _ => {} + } + let mut pending = vec![expr]; + while let Some(expr) = pending.pop() { + match expr { + ConstExpr::Ident(name) if !constants.contains_key(name) => return true, + ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => pending.push(expr), + ConstExpr::Select { expr, bit } => pending.extend([bit.as_ref(), expr.as_ref()]), + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + pending.extend([lsb.as_ref(), msb.as_ref(), expr.as_ref()]); + } + ConstExpr::Binary { left, op, right } => { + // A right logical operand can be skipped. The left operand is + // required; preserve the evaluator's short-circuiting policy. + if !matches!(op, BinaryOp::LogicAnd | BinaryOp::LogicOr) { + pending.push(right); + } + pending.push(left); + } + ConstExpr::Mux { condition, .. } => pending.push(condition), + // Argument evaluation belongs to the callee (including checked + // accesses). Do not infer whether a call needs its actuals here. + ConstExpr::Function { .. } | ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} + } + } + false +} + /// Whether `expr` names a constant that has a type, which /// [`substitute_typed_constants`] replaces with a sized literal. fn has_typed_constant( @@ -714,6 +751,15 @@ fn context_binary_operands( right: &ConstExpr, ) -> Option<(IntegralLiteral, IntegralLiteral, bool)> { let (left_type, right_type) = integral_binary_operands(left, right)?; + context_binary_values(left, right, left_type, right_type) +} + +fn context_binary_values( + left: &ConstExpr, + right: &ConstExpr, + left_type: IntegralLiteral, + right_type: IntegralLiteral, +) -> Option<(IntegralLiteral, IntegralLiteral, bool)> { let width = left_type.width.max(right_type.width); let signed = left_type.signed && right_type.signed; // These values were already evaluated in their own expression contexts. @@ -783,7 +829,7 @@ fn eval_literal_binary( ); return eval_four_state_binary(&left, op, &right, signed); } - let (left, right, signed) = context_binary_operands(left_expr, right_expr)?; + let (left, right, signed) = context_binary_values(left_expr, right_expr, left, right)?; eval_four_state_binary(&left, op, &right, signed) } @@ -1089,7 +1135,14 @@ fn self_determined_integral_literal(expr: &ConstExpr) -> Option } } +#[cfg(test)] +thread_local! { + static LITERAL_EVALUATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + fn integral_literal_from_const_expr(expr: &ConstExpr) -> Option { + #[cfg(test)] + LITERAL_EVALUATIONS.with(|count| count.set(count.get() + 1)); match expr { ConstExpr::Literal(literal) => parse_integral_literal(literal), ConstExpr::Resize { @@ -2015,6 +2068,115 @@ fn extension_for_leading_digit(ch: char) -> (bool, bool) { mod literal_tests { use super::*; + #[test] + fn numeric_binary_operands_are_evaluated_once_before_type_context() { + let expr = ConstExpr::Binary { + left: Box::new(ConstExpr::Literal("2".into())), + op: BinaryOp::Add, + right: Box::new(ConstExpr::Literal("3".into())), + }; + LITERAL_EVALUATIONS.with(|count| count.set(0)); + assert_eq!( + eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()), + Some(5) + ); + assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 2); + } + + #[test] + fn runtime_bounds_skip_literal_evaluation_before_substitution() { + let mut bound = ConstExpr::Ident("runtime_index".into()); + for _ in 0..64 { + bound = ConstExpr::Resize { + expr: Box::new(ConstExpr::Binary { + left: Box::new(bound), + op: BinaryOp::Add, + right: Box::new(ConstExpr::Ident("P".into())), + }), + width: 32, + signed: false, + }; + } + LITERAL_EVALUATIONS.with(|count| count.set(0)); + assert_eq!( + eval_const_expr_with_types( + &bound, + &HashMap::from_iter([("P".into(), 7)]), + &HashMap::from_iter([("P".into(), (32, false))]) + ), + None + ); + assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 0); + } + + #[test] + fn runtime_bound_probe_preserves_short_circuiting_and_sampled_values() { + let literal = |text: &str| ConstExpr::Literal(text.into()); + let missing = || ConstExpr::Ident("runtime_index".into()); + let expressions = [ + ( + ConstExpr::Binary { + left: Box::new(literal("0")), + op: BinaryOp::LogicAnd, + right: Box::new(missing()), + }, + Some(0), + ), + ( + ConstExpr::Binary { + left: Box::new(literal("1")), + op: BinaryOp::LogicOr, + right: Box::new(missing()), + }, + Some(1), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("1")), + then_expr: Box::new(literal("13")), + else_expr: Box::new(missing()), + }, + Some(13), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("0")), + then_expr: Box::new(missing()), + else_expr: Box::new(literal("19")), + }, + Some(19), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("1'bx")), + then_expr: Box::new(literal("17")), + else_expr: Box::new(literal("17")), + }, + Some(17), + ), + ]; + for (expr, expected) in expressions { + assert_eq!( + eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()), + expected, + "{expr:?}" + ); + } + let sample = ConstExpr::Binary { + left: Box::new(missing()), + op: BinaryOp::Mul, + right: Box::new(ConstExpr::Ident("P".into())), + }; + assert_eq!( + eval_const_expr_with_types( + &sample, + &HashMap::from_iter([("runtime_index".into(), 3), ("P".into(), 7)]), + &HashMap::from_iter([("P".into(), (32, false))]) + ), + Some(21) + ); + } + /// Expressions without typed constants evaluate as their substituted /// copies do, and typed constants still take their declared type. #[test]