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/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index aeb7df2da7b..86a357142ff 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -145,6 +145,17 @@ contains 3,300 case/mode verdicts at the pinned revision. These are its only changed rows, with no passing case regressing: 1,201 cases pass in 2state and 1,212 in 4state. Only these reviewed expectations are updated. +Integral array reductions (7.12.3) support `sum`, `product`, `and`, `or` and +`xor`, with or without empty parentheses. The five unmodified +`chapter-7/arrays/unpacked/reduction-methods` simulation cases pass the +official runner in both state modes at the pinned revision. Only those ten +reviewed expectations change from `fail` to `pass`; this is a focused run, +not a new full-corpus measurement. Shared regressions also exercise fixed +arrays, queues, integral- and string-indexed associative arrays, element-width +overflow, signed results, packed type queries and four-state propagation. +Empty containers reduce to zero. `with` expressions, iterator arguments and +multidimensional unpacked receivers remain unsupported. + ## Running locally Use the locked development shell and install the pinned [`requirements.txt`](requirements.txt) in a Python environment. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index b9bae1143b3..0a14efc833b 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1383,16 +1383,16 @@ chapter-7/arrays/unpacked/ordering-methods/shuffle.sv 2state fail chapter-7/arrays/unpacked/ordering-methods/shuffle.sv 4state fail chapter-7/arrays/unpacked/ordering-methods/sort.sv 2state fail chapter-7/arrays/unpacked/ordering-methods/sort.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/and.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/and.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/or.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/or.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/product.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/product.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/sum.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/sum.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/xor.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/xor.sv 4state fail +chapter-7/arrays/unpacked/reduction-methods/and.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/and.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/or.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/or.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/product.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/product.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/sum.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/sum.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/xor.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/xor.sv 4state pass chapter-7/arrays/unpacked/slice-equality.sv 2state pass chapter-7/arrays/unpacked/slice-equality.sv 4state pass chapter-7/arrays/unpacked/slice.sv 2state pass diff --git a/crates/aplite/README.md b/crates/aplite/README.md index 0a9b136e90e..077f0fec470 100644 --- a/crates/aplite/README.md +++ b/crates/aplite/README.md @@ -86,3 +86,34 @@ 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()`. + +## Bounded hash cells + +`HashCells` prepares seed-selected affine XOR predicates over chosen scalar +variables. A query chooses a prefix of those predicates and their target bits; +shorter prefixes leave larger cells. The original formula and all predicates are +compiled once. The cell query uses one temporary SAT database and retains local +learning while it blocks already-seen projected assignments. It does not recompile +the formula for each model or retain blockers between cells. + +```rust +use aplite::{CellStatus, Env, HashCells, Limits, Sort, boolv, var}; +let projection = Env::from([("value".into(), var("x".into(), Sort::Bv(3)))]); +let cells = HashCells::new(&boolv(true), &projection, 2, 42, Limits::default()).unwrap(); +let cell = cells.cell(&[true, false], 8, Limits::default()); +assert_eq!(cell.status, CellStatus::Complete); +assert!(cell.models.iter().all(|model| model.contains_key("x"))); +``` + +`Complete` certifies all models in that cell, including an empty cell. `TooLarge` +means the cell has more models than the caller's bound, and `Unknown` covers +invalid input or exhausted budgets. Neither exposes a truncated model list. +All searches and replay in one cell share one work/time budget. Hidden variables +are existential: multiple witnesses cannot duplicate a projected assignment. +Call `PreparedQuery::enumerate_cell` directly for custom partition predicates. + +These operations are building blocks, **not a uniform sampler**. Uniformly picking +a cell and then uniformly picking one of its models generally biases results +when cells have different sizes. A sampling policy must control cell sizing and +acceptance separately. The exhaustive reservoir sampler remains a test-only reference. +Rows may be dependent or constant; hash construction preserves those cases. diff --git a/crates/aplite/src/finite.rs b/crates/aplite/src/finite.rs index a3136f146ee..62443ec8663 100644 --- a/crates/aplite/src/finite.rs +++ b/crates/aplite/src/finite.rs @@ -16,7 +16,7 @@ mod control; mod lookup; mod prepared; mod readonly; -pub use prepared::{Assumption, PreparedQuery}; +pub use prepared::{Assumption, Cell, CellStatus, HashCells, PreparedQuery}; pub use readonly::ArrayModel; type Lit = i32; diff --git a/crates/aplite/src/finite/prepared.rs b/crates/aplite/src/finite/prepared.rs index 3016ce5691c..36f5d3916b9 100644 --- a/crates/aplite/src/finite/prepared.rs +++ b/crates/aplite/src/finite/prepared.rs @@ -1,6 +1,11 @@ //! Reusable scalar encoding with temporary Boolean assumptions. use super::*; +mod cell; +mod hashing; +pub use cell::{Cell, CellStatus}; +pub use hashing::HashCells; + /// Select the polarity of a predicate supplied when preparing the query. #[derive(Clone, Copy, Debug)] pub struct Assumption { diff --git a/crates/aplite/src/finite/prepared/cell.rs b/crates/aplite/src/finite/prepared/cell.rs new file mode 100644 index 00000000000..47da225784e --- /dev/null +++ b/crates/aplite/src/finite/prepared/cell.rs @@ -0,0 +1,442 @@ +//! Bounded projected model enumeration in a temporary SAT database. +use super::*; +use std::collections::BTreeSet; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CellStatus { + /// The entire selected cell was enumerated. It may be empty. + Complete, + /// At least max_models + 1 distinct projected models exist in the cell. + TooLarge, + /// Invalid input, unsupported query, or an exhausted resource budget. + Unknown, +} + +#[derive(Debug)] +pub struct Cell { + pub status: CellStatus, + /// Exposed only for Complete cells; never a biased truncated prefix. + /// Keys are original variable names, not context labels. + pub models: Vec>, + pub work: u64, + pub reason: Option, +} + +impl PreparedQuery { + /// Enumerate a bounded cell selected by temporary predicate assumptions. + /// + /// `projection` names distinct original scalar variables known at preparation. + /// Hidden witnesses do not multiply a projected assignment. One extra SAT + /// query distinguishes an exact-size cell from an oversized cell. The work + /// and time budgets cover all searches, blocking and replay in this call. + /// + /// This is a building block for hash-based sampling, not a sampling policy. + /// It never enumerates more than max_models + 1 witnesses. Blocking clauses + /// and learned clauses derived from them live only inside this call, so they + /// cannot change later cells or ordinary solves on the prepared query. + pub fn enumerate_cell( + &self, + assumptions: &[Assumption], + projection: &[String], + max_models: usize, + limits: Limits, + ) -> Cell { + let mut cell = Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: 0, + reason: None, + }; + let mut budget = Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + let run = (|| -> Res { + budget.tick(1)?; + if self.blast.vars > budget.limits.max_variables + || self.blast.memo.len() > budget.limits.max_terms + || self.blast.clauses.len() > budget.limits.max_clauses + { + return Err("prepared cell exceeds solve size limits".into()); + } + let mut seen = BTreeSet::new(); + let mut bits = Vec::new(); + for name in projection { + budget.tick(1)?; + if !seen.insert(name) { + return Err("duplicate cell projection variable".into()); + } + let input = self + .blast + .inputs + .get(name) + .ok_or("unknown cell projection variable")?; + budget.tick(input.bits.len() as u64)?; + bits.extend_from_slice(&input.bits); + } + let mut literals = Vec::new(); + for assumption in assumptions { + budget.tick(1)?; + let lit = *self + .literals + .get(assumption.predicate) + .ok_or("invalid prepared predicate index")?; + literals.push(if assumption.value { lit } else { -lit }); + } + let mut clauses = Vec::new(); + for clause in &self.blast.clauses { + budget.tick(1 + clause.len() as u64)?; + clauses.push(clause.clone()); + } + // One scoped CDCL instance for the whole cell. Reuse encoding, + // propagation and local learning between models, without copying + // or recompiling the base formula on each enumeration step. + let mut solver = Sat::new(self.blast.vars, clauses); + loop { + match solver.run_slice_assuming(&mut budget, u64::MAX, &literals)? { + Search::Complete(Verdict::Unsat) => { + budget.check_time()?; + return Ok(CellStatus::Complete); + } + Search::Complete(Verdict::Sat) => {} + _ => return Err("cell search did not complete".into()), + } + let (assignments, _) = 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("cell model failed assumption replay".into()); + } + } + if cell.models.len() == max_models { + budget.check_time()?; + return Ok(CellStatus::TooLarge); + } + let mut model = BTreeMap::new(); + for name in projection { + budget.tick(1)?; + model.insert(name.clone(), assignments[name].clone()); + } + let mut blocking = Vec::new(); + for &bit in &bits { + budget.tick(1)?; + blocking.push(if truth(&solver.values, bit) > 0 { + -bit + } else { + bit + }); + } + cell.models.push(model); + solver.backtrack(0, &mut budget)?; + if !add_blocking_clause(&mut solver, blocking, &mut budget)? { + budget.check_time()?; + return Ok(CellStatus::Complete); + } + } + })(); + cell.work = budget.work; + match run { + Ok(status) => cell.status = status, + Err(reason) => cell.reason = Some(reason), + } + if cell.status != CellStatus::Complete { + cell.models.clear(); + } + cell + } +} + +/// Insert a model blocker after backtracking to root. Root assignments are +/// permanent within this scoped database. Simplify by them before watching the +/// clause, so a newly inserted unit is propagated and an empty clause closes +/// the cell immediately. Assumption decisions have already been removed. +fn add_blocking_clause(solver: &mut Sat, clause: Vec, budget: &mut Budget) -> Res { + debug_assert!(solver.starts.is_empty()); + let mut remaining = BTreeSet::new(); + for lit in clause { + budget.tick(1)?; + match truth(&solver.values, lit) { + 1 => return Ok(true), + -1 => {} + _ => { + remaining.insert(lit); + } + } + } + if remaining.is_empty() { + return Ok(false); + } + if solver.clauses.len() >= budget.limits.max_clauses { + return Err("cell blocking-clause budget exhausted".into()); + } + let clause: Vec<_> = remaining.into_iter().collect(); + let unit = (clause.len() == 1).then_some(clause[0]); + let id = solver.clauses.len(); + solver.clauses.push(clause); + solver.attach(id); + if let Some(unit) = unit { + return Ok(solver.enqueue(unit, Some(id))); + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{and, boolv, bv, eq, node, not, var}; + + fn selected(predicate: usize, value: bool) -> Assumption { + Assumption { predicate, value } + } + + #[test] + fn projected_enumeration_ignores_hidden_witnesses_and_is_scoped() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let formula = node(Sort::Bool, "or", vec![not(x.clone()), y.clone()]); + let mut query = + PreparedQuery::new(&formula, &Env::new(), &[x, y], Limits::default()).unwrap(); + for _ in 0..3 { + let cell = query.enumerate_cell(&[], &["x".into()], 2, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models.len(), 2); + assert_ne!(cell.models[0], cell.models[1]); + let both = query.enumerate_cell(&[], &["x".into(), "y".into()], 3, Limits::default()); + assert_eq!(both.status, CellStatus::Complete); + assert_eq!(both.models.len(), 3); + assert_eq!( + query + .solve(&[selected(0, true)], Limits::default(), 1) + .verdict, + Verdict::Sat + ); + assert_eq!( + query + .solve(&[selected(0, false)], Limits::default(), 1) + .verdict, + Verdict::Sat + ); + } + } + + #[test] + fn exact_limit_overflow_empty_and_unsat_are_distinct() { + let x = var("x".into(), Sort::Bv(2)); + let query = PreparedQuery::new( + &boolv(true), + &Env::new(), + &[eq(x.clone(), bv(2, 0))], + Limits::default(), + ) + .unwrap(); + for bound in 0..=4 { + let cell = query.enumerate_cell(&[], &["x".into()], bound, Limits::default()); + assert_eq!( + cell.status, + if bound == 4 { + CellStatus::Complete + } else { + CellStatus::TooLarge + } + ); + assert_eq!(cell.models.len(), if bound == 4 { 4 } else { 0 }); + } + let empty = query.enumerate_cell( + &[selected(0, true), selected(0, false)], + &["x".into()], + 0, + Limits::default(), + ); + assert_eq!(empty.status, CellStatus::Complete); + assert!(empty.models.is_empty()); + let unit = query.enumerate_cell(&[], &[], 1, Limits::default()); + assert_eq!(unit.status, CellStatus::Complete); + assert_eq!(unit.models, vec![BTreeMap::new()]); + } + + #[test] + fn alias_and_constant_bits_do_not_duplicate_models() { + let x = var("x".into(), Sort::Bv(3)); + let y = var("y".into(), Sort::Bv(3)); + let z = var("z".into(), Sort::Bv(3)); + let formula = and(eq(x, y), eq(z, bv(3, 5))); + let query = PreparedQuery::new(&formula, &Env::new(), &[], Limits::default()).unwrap(); + let cell = query.enumerate_cell( + &[], + &["x".into(), "y".into(), "z".into()], + 8, + Limits::default(), + ); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models.len(), 8); + for model in cell.models { + assert_eq!(model["x"], model["y"]); + assert_eq!(model["z"], Scalar::Bv { width: 3, value: 5 }); + } + } + + #[test] + fn xor_cells_cover_small_truth_tables_without_overlap() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let z = var("z".into(), Sort::Bool); + let predicates = [ + node(Sort::Bool, "xor", vec![x.clone(), y.clone()]), + node(Sort::Bool, "xor", vec![y.clone(), z.clone()]), + ]; + for mask in 0..256u16 { + let mut formula = boolv(false); + for row in 0..8 { + if mask & (1 << row) != 0 { + let cube = and( + and( + eq(x.clone(), boolv(row & 1 != 0)), + eq(y.clone(), boolv(row & 2 != 0)), + ), + eq(z.clone(), boolv(row & 4 != 0)), + ); + formula = node(Sort::Bool, "or", vec![formula, cube]); + } + } + let query = + PreparedQuery::new(&formula, &Env::new(), &predicates, Limits::default()).unwrap(); + let mut found = BTreeSet::new(); + for target in 0..4 { + let cell = query.enumerate_cell( + &[selected(0, target & 1 != 0), selected(1, target & 2 != 0)], + &["x".into(), "y".into(), "z".into()], + 2, + Limits::default(), + ); + assert_eq!(cell.status, CellStatus::Complete); + for model in cell.models { + let row = usize::from(model["x"] == Scalar::Bool(true)) + | (usize::from(model["y"] == Scalar::Bool(true)) << 1) + | (usize::from(model["z"] == Scalar::Bool(true)) << 2); + assert_ne!(mask & (1 << row), 0); + assert!(found.insert(row)); + } + } + assert_eq!(found.len(), mask.count_ones() as usize); + } + } + + #[test] + fn wide_space_is_bounded_by_xor_cell_not_total_cardinality() { + let x = var("x".into(), Sort::Bv(32)); + let bit = |i| { + eq( + node(Sort::Bv(1), format!("(_ extract {i} {i})"), vec![x.clone()]), + bv(1, 1), + ) + }; + let predicates: Vec<_> = (4..32) + .map(|i| node(Sort::Bool, "xor", vec![bit(i), bit(i - 1)])) + .collect(); + let query = + PreparedQuery::new(&boolv(true), &Env::new(), &predicates, Limits::default()).unwrap(); + let assumptions: Vec<_> = (0..28).map(|i| selected(i, i % 3 == 0)).collect(); + let cell = query.enumerate_cell(&assumptions, &["x".into()], 16, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete, "{:?}", cell.reason); + assert_eq!(cell.models.len(), 16); + let mut lows = BTreeSet::new(); + for model in cell.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + lows.insert(value & 15); + for i in 4..32 { + assert_eq!( + ((value >> i) ^ (value >> (i - 1))) & 1 != 0, + (i - 4) % 3 == 0 + ); + } + } + assert_eq!(lows.len(), 16); + assert_eq!( + query + .enumerate_cell(&[], &["x".into()], 16, Limits::default()) + .status, + CellStatus::TooLarge + ); + } + + #[test] + fn failures_clear_partial_results_and_leave_prepared_state_untouched() { + let x = var("x".into(), Sort::Bv(3)); + let mut query = PreparedQuery::new( + &boolv(true), + &Env::from([("label".into(), x.clone())]), + &[eq(x, bv(3, 3))], + Limits::default(), + ) + .unwrap(); + query.solve(&[], Limits::default(), 0); + let original_clauses = query.sat.as_ref().unwrap().clauses.len(); + let full = query.enumerate_cell(&[], &["x".into()], 8, Limits::default()); + assert_eq!(full.status, CellStatus::Complete); + for work in [0, full.work / 2, full.work - 1] { + let cell = query.enumerate_cell( + &[], + &["x".into()], + 8, + Limits { + max_work: work, + ..Limits::default() + }, + ); + assert_eq!(cell.status, CellStatus::Unknown); + assert!(cell.models.is_empty()); + assert_eq!(query.sat.as_ref().unwrap().clauses.len(), original_clauses); + } + for projection in [vec!["label".into()], vec!["x".into(), "x".into()]] { + assert_eq!( + query + .enumerate_cell(&[], &projection, 8, Limits::default()) + .status, + CellStatus::Unknown + ); + } + assert_eq!( + query + .enumerate_cell(&[selected(1, true)], &[], 1, Limits::default()) + .status, + CellStatus::Unknown + ); + assert_eq!( + query + .enumerate_cell( + &[], + &[], + 1, + Limits { + timeout_ms: 0, + ..Limits::default() + } + ) + .status, + CellStatus::Unknown + ); + assert_eq!( + query + .solve(&[selected(0, true)], Limits::default(), 0) + .verdict, + Verdict::Sat + ); + } +} diff --git a/crates/aplite/src/finite/prepared/hashing.rs b/crates/aplite/src/finite/prepared/hashing.rs new file mode 100644 index 00000000000..02646a8c882 --- /dev/null +++ b/crates/aplite/src/finite/prepared/hashing.rs @@ -0,0 +1,410 @@ +//! Seeded affine XOR partitions, with bounded projected cell queries. +use super::*; +use crate::{boolv, bv, eq, node}; +use std::collections::BTreeSet; + +/// A prepared family of affine XOR rows over projected scalar bits. +/// +/// Each row includes each bit and a constant with seed-selected coefficients. +/// With ideal independent random coefficients this is the standard affine XOR +/// hash family. The implementation uses a deterministic SplitMix64 PRNG, not a +/// source of cryptographic entropy. Rows may be zero or dependent: preserving +/// those cases is essential to the family; we do not silently repair them. +/// Prefix-preserving Gaussian elimination simplifies rows and transforms target +/// bits together, preserving exactly the original random cells. +/// +/// `cell` selects a prefix of the rows and a target value for each selected row. +/// A caller can measure differently sized cells without recompiling the formula. +/// This is NOT a uniform sampler: choosing a cell and then a model arbitrarily +/// can bias results. A sampling policy must separately control cell acceptance, +/// target selection, and the distribution of models within accepted cells. +pub struct HashCells { + query: PreparedQuery, + projection: Vec, + rows: usize, + transforms: Vec>, + preparation_work: u64, +} + +impl HashCells { + /// Build at most `rows` XOR constraints. Projection values must be distinct + /// Bool or 1..=64-bit variable terms. Context labels do not affect model keys. + /// The single budget covers hash construction and query preparation. + pub fn new( + formula: &Term, + projection: &Env, + rows: usize, + seed: u64, + limits: Limits, + ) -> Res { + let mut budget = Budget { + limits: limits.clone(), + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + budget.tick(1)?; + let mut created = 0usize; + let mut names = BTreeSet::new(); + let mut bits = Vec::new(); + for variable in projection.values() { + budget.tick(1)?; + let name = variable + .0 + .op + .strip_prefix('@') + .ok_or("hash projection requires variables")?; + if !variable.0.args.is_empty() + || !valid_sort(&variable.0.sort) + || !names.insert(name.to_owned()) + { + return Err("hash projection requires distinct supported scalar variables".into()); + } + let width = match variable.0.sort { + Sort::Bool => 1, + Sort::Bv(width) => width, + _ => unreachable!(), + }; + if bits.len().saturating_add(width as usize) > limits.max_variables { + return Err("hash projection bit budget exhausted".into()); + } + for bit in 0..width { + budget.tick(1)?; + let term = if variable.0.sort == Sort::Bool { + variable.clone() + } else { + reserve_terms(&mut created, 3, &budget)?; + eq( + node( + Sort::Bv(1), + format!("(_ extract {bit} {bit})"), + vec![variable.clone()], + ), + bv(1, 1), + ) + }; + bits.push(term); + } + } + if rows > bits.len() || rows > limits.max_terms { + return Err("hash row limit exceeds projected width or term budget".into()); + } + let mut rng = seed; + let mut predicates = Vec::new(); + let mut echelon: Vec<(Vec, bool, Vec, Option)> = Vec::new(); + let mut transforms = Vec::new(); + for index in 0..rows { + budget.tick(1)?; + let mut constant = next(&mut rng) & 1 != 0; + let mut coefficients = Vec::new(); + for _ in &bits { + budget.tick(1)?; + coefficients.push(next(&mut rng) & 1 != 0); + } + budget.tick(rows as u64)?; + let mut transform = vec![false; rows]; + transform[index] = true; + // Only earlier rows participate: every prefix remains equivalent + // to the same prefix of the original random affine hash family. + for (previous, offset, mapping, pivot) in &echelon { + budget.tick(1)?; + if pivot.is_some_and(|pivot| coefficients[pivot]) { + for (bit, other) in coefficients.iter_mut().zip(previous) { + budget.tick(1)?; + *bit ^= other; + } + constant ^= offset; + for (bit, other) in transform.iter_mut().zip(mapping) { + budget.tick(1)?; + *bit ^= other; + } + } + } + let mut pivot = None; + let mut terms = Vec::new(); + reserve_terms(&mut created, 1, &budget)?; + terms.push(boolv(constant)); + for (position, (&include, bit)) in coefficients.iter().zip(&bits).enumerate() { + budget.tick(1)?; + if include { + pivot.get_or_insert(position); + terms.push(bit.clone()); + } + } + predicates.push(parity(&terms, &mut budget, &mut created)?); + transforms.push( + transform + .iter() + .enumerate() + .filter_map(|(i, &bit)| bit.then_some(i)) + .collect(), + ); + echelon.push((coefficients, constant, transform, pivot)); + } + budget.check_time()?; + let mut remaining = limits; + remaining.max_work -= budget.work; + remaining.timeout_ms = remaining + .timeout_ms + .checked_sub(u64::try_from(budget.start.elapsed().as_millis()).unwrap_or(u64::MAX)) + .filter(|&ms| ms > 0) + .ok_or("hash preparation time budget exhausted")?; + let query = PreparedQuery::new(formula, projection, &predicates, remaining)?; + budget.tick(query.preparation_work())?; + budget.check_time()?; + Ok(Self { + query, + projection: names.into_iter().collect(), + rows, + transforms, + preparation_work: budget.work, + }) + } + + pub fn preparation_work(&self) -> u64 { + self.preparation_work + } + + /// Targets select a prefix of the prepared XOR rows. Empty targets query + /// the unpartitioned space with the same bounded model limit. + pub fn cell(&self, targets: &[bool], max_models: usize, mut limits: Limits) -> Cell { + let start = Instant::now(); + if targets.len() > self.rows + || targets.len() as u64 >= limits.max_work + || limits.timeout_ms == 0 + { + return Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: 0, + reason: Some("hash targets exceed prepared rows or query budget".into()), + }; + } + let mut overhead = targets.len() as u64; + let mut assumptions = Vec::new(); + for (predicate, mapping) in self.transforms.iter().take(targets.len()).enumerate() { + overhead = overhead.saturating_add(mapping.len() as u64); + if overhead >= limits.max_work + || start.elapsed().as_millis() >= u128::from(limits.timeout_ms) + { + return Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: overhead, + reason: Some("hash target transformation budget exhausted".into()), + }; + } + let value = mapping + .iter() + .fold(false, |value, &index| value ^ targets[index]); + assumptions.push(Assumption { predicate, value }); + } + limits.max_work -= overhead; + let timeout = limits.timeout_ms; + let mut cell = + self.query + .enumerate_cell(&assumptions, &self.projection, max_models, limits); + cell.work = cell.work.saturating_add(overhead); + if start.elapsed().as_millis() >= u128::from(timeout) { + cell.status = CellStatus::Unknown; + cell.models.clear(); + cell.reason = Some("hash cell time budget exhausted".into()); + } + cell + } +} + +fn next(state: &mut u64) -> u64 { + *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) +} + +fn reserve_terms(created: &mut usize, amount: usize, budget: &Budget) -> Res<()> { + *created = created + .checked_add(amount) + .ok_or("hash construction term overflow")?; + if *created > budget.limits.max_terms { + return Err("hash construction term budget exhausted".into()); + } + Ok(()) +} + +fn parity(terms: &[Term], budget: &mut Budget, created: &mut usize) -> Res { + budget.tick(1)?; + if terms.len() == 1 { + return Ok(terms[0].clone()); + } + reserve_terms(created, 1, budget)?; + let mid = terms.len() / 2; + Ok(node( + Sort::Bool, + "xor", + vec![ + parity(&terms[..mid], budget, created)?, + parity(&terms[mid..], budget, created)?, + ], + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::var; + + #[test] + fn random_affine_cells_partition_and_reproduce_the_projected_domain() { + let x = var("x".into(), Sort::Bv(3)); + let context = Env::from([("label".into(), x)]); + let mut signatures = BTreeSet::new(); + for seed in 0..16 { + let cells = HashCells::new(&boolv(true), &context, 2, seed, Limits::default()).unwrap(); + let same = HashCells::new(&boolv(true), &context, 2, seed, Limits::default()).unwrap(); + let mut found = BTreeSet::new(); + let mut signature = Vec::new(); + for target in 0..4 { + let bits = [target & 1 != 0, target & 2 != 0]; + let cell = cells.cell(&bits, 8, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models, same.cell(&bits, 8, Limits::default()).models); + let mut values = Vec::new(); + for model in cell.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + assert!(found.insert(value)); + values.push(value); + } + values.sort(); + signature.push(values); + } + assert_eq!(found.len(), 8); + signatures.insert(signature); + assert_eq!( + cells.cell(&[], 4, Limits::default()).status, + CellStatus::TooLarge + ); + assert_eq!( + cells.cell(&[false; 3], 8, Limits::default()).status, + CellStatus::Unknown + ); + } + assert!(signatures.len() > 1); + } + + #[test] + fn elimination_preserves_every_original_affine_prefix_and_target() { + let context = Env::from([("x".into(), var("x".into(), Sort::Bv(3)))]); + for seed in 0..32 { + let cells = HashCells::new(&boolv(true), &context, 3, seed, Limits::default()).unwrap(); + let mut rng = seed; + let original: Vec<_> = (0..3) + .map(|_| { + let constant = next(&mut rng) & 1 != 0; + let mask: Vec<_> = (0..3).map(|_| next(&mut rng) & 1 != 0).collect(); + (constant, mask) + }) + .collect(); + for prefix in 0..=3 { + for target in 0..(1 << prefix) { + let targets: Vec<_> = (0..prefix).map(|i| target & (1 << i) != 0).collect(); + let cell = cells.cell(&targets, 8, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + let actual: BTreeSet<_> = cell + .models + .iter() + .map(|model| { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + value + }) + .collect(); + let expected: BTreeSet<_> = (0..8u64) + .filter(|value| { + original + .iter() + .zip(&targets) + .all(|((constant, mask), target)| { + mask.iter().enumerate().fold( + *constant, + |parity, (i, &include)| { + parity ^ (include && value & (1 << i) != 0) + }, + ) == *target + }) + }) + .collect(); + assert_eq!( + actual, expected, + "seed={seed}, prefix={prefix}, target={target}" + ); + } + } + } + } + + #[test] + fn construction_and_cell_budgets_fail_closed() { + let context = Env::from([("x".into(), var("x".into(), Sort::Bv(8)))]); + assert!(HashCells::new(&boolv(true), &context, 9, 0, Limits::default()).is_err()); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + max_work: 1, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + timeout_ms: 0, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + max_terms: 2, + ..Limits::default() + } + ) + .is_err() + ); + let hash = HashCells::new(&boolv(true), &context, 3, 0, Limits::default()).unwrap(); + assert!(hash.preparation_work() > 0); + let failed = hash.cell( + &[true], + 8, + Limits { + max_work: 2, + ..Limits::default() + }, + ); + assert_eq!(failed.status, CellStatus::Unknown); + assert!(failed.models.is_empty()); + let duplicates = Env::from([ + ("x".into(), var("x".into(), Sort::Bool)), + ("alias".into(), var("x".into(), Sort::Bool)), + ]); + assert!(HashCells::new(&boolv(true), &duplicates, 1, 0, Limits::default()).is_err()); + } +} diff --git a/crates/aplite/src/lib.rs b/crates/aplite/src/lib.rs index 7a721daf55f..c9cad434b1a 100644 --- a/crates/aplite/src/lib.rs +++ b/crates/aplite/src/lib.rs @@ -10,8 +10,8 @@ pub use term::*; pub type Env = std::collections::BTreeMap; pub mod finite; pub use finite::{ - Assumption, Limits, Outcome, PreparedQuery, Scalar, SearchHint, Verdict, solve, solve_seeded, - solve_with_hint, + Assumption, Cell, CellStatus, HashCells, Limits, Outcome, PreparedQuery, Scalar, SearchHint, + Verdict, solve, solve_seeded, solve_with_hint, }; #[cfg(test)] diff --git a/crates/celox-frontend-sv/src/lowering/ff/containers.rs b/crates/celox-frontend-sv/src/lowering/ff/containers.rs index b4cb6765076..291702ad329 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/containers.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/containers.rs @@ -37,6 +37,9 @@ impl Ff<'_, '_> { string_key, ); let code = |opcode| encode(opcode, parameter); + if op.reduction().is_some() { + return self.container_reduction(op, layout, &args[0], parameter); + } let zero = self.constant64(0); let (width, signed) = op.result_type(layout); let element_result = matches!(op, Get | PopFront | PopBack); @@ -298,6 +301,110 @@ impl Ff<'_, '_> { Ok(sv::ir::Expr::Ident(name)) } + fn container_reduction( + &mut self, + op: ContainerOp, + layout: ContainerLayout, + receiver: &sv::ir::Expr, + parameter: u64, + ) -> Result { + let width = layout.width as usize; + let four_state = !layout.two_state && self.m.four_state; + let alloc = |b: &mut SIRBuilder| { + if four_state { + b.alloc_logic(width) + } else { + b.alloc_bit(width, layout.signed) + } + }; + let code = |opcode| encode(opcode, parameter); + // Keep one immutable snapshot of the receiver throughout the traversal. + let handle = self.handle(receiver)?; + let zero = self.constant64(0); + let one = self.constant64(1); + let length = self.heap_call(code(heap::LEN), &[handle]); + let associative = matches!(layout.kind, ContainerKind::Associative { .. }); + let first = if associative { + self.heap_call(code(heap::FIRST), &[handle, zero]) + } else { + zero + }; + let seed = alloc(&mut self.b); + let identity = match op { + ContainerOp::ReduceProduct => BigUint::from(1u8), + ContainerOp::ReduceAnd => (BigUint::from(1u8) << width) - BigUint::from(1u8), + _ => BigUint::zero(), + }; + self.b + .emit(SIRInstruction::Imm(seed, SIRValue::new(identity))); + let remaining = self.b.alloc_bit(64, false); + let key = self.b.alloc_bit(64, false); + let accumulator = alloc(&mut self.b); + let header = self.b.new_block_with(vec![remaining, key, accumulator]); + let body = self.b.new_block(); + let result = alloc(&mut self.b); + let exit = self.b.new_block_with(vec![result]); + self.b + .seal_block(SIRTerminator::Jump(header, vec![length, first, seed])); + self.b.switch_to_block(header); + let more = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(more, remaining, BinaryOp::Ne, zero)); + self.b.seal_block(SIRTerminator::Branch { + cond: more, + true_block: (body, Vec::new()), + false_block: (exit, vec![accumulator]), + }); + self.b.switch_to_block(body); + let raw = self.heap_call(code(heap::GET), &[handle, key, zero]); + let mask = self.heap_call(code(heap::GET_MASK), &[handle, key, zero]); + let element = self.container_join(raw, mask, width, four_state); + let combined = alloc(&mut self.b); + let binary = match op { + ContainerOp::ReduceSum => BinaryOp::Add, + ContainerOp::ReduceProduct => BinaryOp::Mul, + ContainerOp::ReduceAnd => BinaryOp::And, + ContainerOp::ReduceOr => BinaryOp::Or, + ContainerOp::ReduceXor => BinaryOp::Xor, + _ => unreachable!("reduction method"), + }; + self.b.emit(SIRInstruction::Binary( + combined, + accumulator, + binary, + element, + )); + let next = if associative { + self.heap_call(code(heap::NEXT), &[handle, key]) + } else { + let next = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Binary(next, key, BinaryOp::Add, one)); + next + }; + let fewer = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Binary(fewer, remaining, BinaryOp::Sub, one)); + self.b + .seal_block(SIRTerminator::Jump(header, vec![fewer, next, combined])); + self.b.switch_to_block(exit); + // Empty reductions return zero, including product and bitwise AND. + let empty = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(empty, length, BinaryOp::Eq, zero)); + let value = alloc(&mut self.b); + let empty_value = alloc(&mut self.b); + self.b + .emit(SIRInstruction::Imm(empty_value, SIRValue::new(0u8))); + self.b + .emit(SIRInstruction::Mux(value, empty, empty_value, result)); + let (temp, name) = self + .m + .temp("array_reduction", width, layout.signed, four_state); + self.store(temp, SIROffset::Static(0), width, value); + Ok(sv::ir::Expr::Ident(name)) + } + fn container_element( &mut self, expr: &sv::ir::Expr, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 1a54e524fcd..9f87f573325 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -163,6 +163,7 @@ mod port_owners; mod timing; mod type_binding; pub(crate) use parameters::unbounded_parameter_marker; +mod array_reductions; mod containers; mod patterns; mod procedural; diff --git a/crates/celox-sv-analyzer/src/ast/array_reductions.rs b/crates/celox-sv-analyzer/src/ast/array_reductions.rs new file mode 100644 index 00000000000..c530864303f --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/array_reductions.rs @@ -0,0 +1,133 @@ +//! Integral unpacked array reductions (IEEE 1800-2023 7.12.3). +use super::*; +use celox_sv_syntax::{Declarations, ExprId, ExprKind}; +use system_functions::ContainerOp; + +pub(super) fn bind( + id: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted> { + let callee = match &native.expression(id).kind { + ExprKind::Call { expression, .. } => *expression, + _ => id, + }; + let ExprKind::Member { + expression: base, + separator, + name, + } = &native.expression(callee).kind + else { + return Ok(None); + }; + if separator != "." { + return Ok(None); + } + let op = match name.spelling.as_str() { + "sum" => ContainerOp::ReduceSum, + "product" => ContainerOp::ReduceProduct, + "and" => ContainerOp::ReduceAnd, + "or" => ContainerOp::ReduceOr, + "xor" => ContainerOp::ReduceXor, + _ => return Ok(None), + }; + let ExprKind::Name(receiver) = &native + .expression(expression_binding::ungroup(*base, native)) + .kind + else { + return Ok(None); + }; + let receiver = instances::normalize_identifier(&receiver.spelling); + let Some(shape) = dims.get(&receiver) else { + return Ok(None); + }; + if shape.container.is_none() && shape.unpacked.is_empty() { + return Ok(None); + } + if let ExprKind::Call { arguments, .. } = &native.expression(id).kind + && !arguments.is_empty() + { + return Err(unsupported( + "array reduction arguments require a with expression", + )); + } + if let Some(container) = shape.container.as_deref() { + if container.layout.handle.is_some() { + return Err(unsupported("array reduction requires integral elements")); + } + return Ok(Some(( + containers::call(op, container.layout, vec![Expr::Ident(receiver)]), + procedural::dimensions_from_type(&container.element), + ))); + } + if shape.unpacked.len() != 1 || shape.real || shape.string || shape.class.is_some() { + return Err(unsupported( + "array reduction requires one-dimensional integral elements", + )); + } + let width = shape + .packed + .iter() + .try_fold(1usize, |width, dim| { + width.checked_mul( + usize::try_from(eval_ast_const_expr( + &tree.state, + &dim.width, + &dims.const_env, + )?) + .ok()?, + ) + }) + .ok_or_else(|| unsupported("array reduction element width"))?; + let count = usize::try_from( + eval_ast_const_expr(&tree.state, &shape.unpacked[0].width, &dims.const_env) + .ok_or_else(|| unsupported("array reduction length"))?, + ) + .map_err(|_| unsupported("array reduction length"))?; + let elements = (0..count).map(|index| Expr::Select { + expr: Box::new(Expr::Ident(receiver.clone())), + msb: ConstExpr::Literal(((index + 1) * width - 1).to_string()), + lsb: ConstExpr::Literal((index * width).to_string()), + signed: shape.signed, + }); + let identity = match op { + ContainerOp::ReduceProduct => format!("{width}'d1"), + ContainerOp::ReduceAnd => format!("{width}'b{}", "1".repeat(width)), + _ => format!("{width}'d0"), + }; + let mut level = std::iter::once(Expr::Literal(identity)) + .chain(elements) + .collect::>(); + // A balanced tree keeps large fixed arrays from making expression depth + // proportional to the number of elements. + while level.len() > 1 { + let mut next = Vec::with_capacity(level.len().div_ceil(2)); + let mut values = level.into_iter(); + while let Some(left) = values.next() { + next.push(if let Some(right) = values.next() { + Expr::Binary { + left: Box::new(left), + op: op.reduction().expect("reduction method").into(), + right: Box::new(right), + } + } else { + left + }); + } + level = next; + } + let result = level.pop().expect("reduction identity"); + // A method result is self-determined: assignment context must not widen + // intermediate additions or products past the element type. + let mut result_shape = shape.clone(); + result_shape.unpacked.clear(); + Ok(Some(( + Expr::Resize { + expr: Box::new(result), + width, + signed: shape.signed, + }, + result_shape, + ))) +} diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index de0eb38e4c8..28701f62ad3 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -73,7 +73,7 @@ pub(super) fn expr_is_two_state( callee: Callee::Object(op), .. } => { - !matches!(**op, ObjectOp::Container { op: ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal, layout } if !layout.two_state) + !matches!(**op, ObjectOp::Container { op, layout } if !layout.two_state && (op.reduction().is_some() || matches!(op, ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal))) } Expr::Call { callee: Callee::Subroutine(name), 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 83c870dbb80..84a8ae00ed3 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -715,6 +715,10 @@ pub(in crate::ast) fn shape( while let Some(job) = jobs.pop() { match job { Job::Enter(id) => { + if let Some((_, shape)) = array_reductions::bind(id, native, tree, context)? { + values.push(shape); + continue; + } if let Some((name, dimensions)) = type_binding::argument_alias(id, native) && dimensions.is_empty() { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index c7416bb7102..6c92fb05059 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -296,6 +296,10 @@ pub(in crate::ast) fn bind_value( )); } } + if let Some((value, _)) = array_reductions::bind(id, native, tree, dimensions)? { + values.push(value); + continue; + } if let Some(value) = containers::value(id, native, tree, dimensions, false)? { values.push(value); continue; diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 594ed4bed04..f2136049a4b 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1199,6 +1199,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); + if let Some((mut value, _)) = array_reductions::bind(root, native, self.tree, &self.dims)? { + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } if let Some(mut value) = containers::value(root, native, self.tree, &self.dims, true)? { self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); @@ -1236,6 +1240,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { let query_root = expression_binding::call_statement_root(root, discarded, self.tree.declarations())?; + if discarded + && let Some((mut value, _)) = + array_reductions::bind(query_root, native, self.tree, &self.dims)? + { + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } if let Some(call) = self.method_call_statement(query_root)? { return Ok(vec![call]); } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 0ee78a1655e..832f06e33ff 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -844,6 +844,11 @@ pub enum ContainerKind { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ContainerOp { + ReduceSum, + ReduceProduct, + ReduceAnd, + ReduceOr, + ReduceXor, Equal, CaseEqual, New, @@ -866,6 +871,17 @@ pub enum ContainerOp { Prev, } impl ContainerOp { + pub fn reduction(self) -> Option { + use crate::ir::BinaryOp; + match self { + Self::ReduceSum => Some(BinaryOp::Add), + Self::ReduceProduct => Some(BinaryOp::Mul), + Self::ReduceAnd => Some(BinaryOp::BitAnd), + Self::ReduceOr => Some(BinaryOp::BitOr), + Self::ReduceXor => Some(BinaryOp::BitXor), + _ => None, + } + } pub fn mutates(self) -> bool { matches!( self, @@ -882,7 +898,14 @@ impl ContainerOp { pub fn result_type(self, layout: ContainerLayout) -> (usize, bool) { match self { Self::Equal | Self::CaseEqual => (1, false), - Self::Get | Self::PopFront | Self::PopBack => (layout.width as usize, layout.signed), + Self::Get + | Self::PopFront + | Self::PopBack + | Self::ReduceSum + | Self::ReduceProduct + | Self::ReduceAnd + | Self::ReduceOr + | Self::ReduceXor => (layout.width as usize, layout.signed), Self::Size | Self::Exists | Self::First | Self::Last | Self::Next | Self::Prev => { (32, true) } diff --git a/crates/celox-test-suite/src/sv/cases/containers.vtest b/crates/celox-test-suite/src/sv/cases/containers.vtest index ef81766ee8d..f210cf374ab 100644 --- a/crates/celox-test-suite/src/sv/cases/containers.vtest +++ b/crates/celox-test-suite/src/sv/cases/containers.vtest @@ -386,3 +386,108 @@ module Top(output bit [2:0] flags); endmodule "#) (top Top) (run_until 0) (assert_eq flags 7)) + +(case array_reduction_fixed + (source "array_reductions.sv" #" +module Top(output bit [7:0] flags); + byte ascending[-2:1], descending[5:2]; + bit [128:0] wide[2]; + bit [3:0] nibbles[3]; + int result; + initial begin + ascending = '{1, 2, 3, 4}; descending = '{1, 3, 5, 7}; + flags[0] = ascending.sum == 10 && ascending.product() == 24; + flags[1] = ascending.or() == 7 && ascending.xor == 4; + flags[2] = descending.and == 1 && descending.sum() == 16; + ascending = '{100, 100, 100, 100}; + result = ascending.sum(); + flags[3] = result == -112 && $bits(ascending.sum()) == 8; + ascending = '{-2, 3, 1, 1}; + flags[4] = ascending.product == -6 && ascending.sum == 3; + wide = '{129'h100000000000000000000000000000001, 129'h100000000000000000000000000000002}; + flags[5] = wide.sum() == 129'h200000000000000000000000000000003; + flags[6] = wide.xor() == 3 && wide.and() == 129'h100000000000000000000000000000000; + nibbles = '{15, 2, 3}; + flags[7] = nibbles.sum() == 4 && nibbles.product() == 10 && $bits(nibbles.sum) == 4; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case array_reduction_dynamic_queue + (source "array_reductions.sv" #" +module Top(output bit [7:0] flags); + byte values[], q[$]; + int result; + initial begin + values = '{1, 2, 3, 4}; q = {1, 3, 5, 7}; + flags[0] = values.sum == 10 && values.product() == 24; + flags[1] = values.and() == 0 && values.or == 7 && values.xor == 4; + flags[2] = q.sum() == 16 && q.product == 105 && q.and() == 1; + flags[3] = q.or == 7 && q.xor() == 0 && q.size() == 4 && q[0] == 1; + values = '{100, 100, 100, 100}; result = values.sum(); + flags[4] = result == -112 && $bits(values.sum) == 8; + q = {-2, 3}; + flags[5] = q.product == -6 && q.sum() == 1; + values.delete(); q.delete(); + flags[6] = values.sum == 0 && values.product == 0 && values.and == 0; + flags[7] = q.or() == 0 && q.xor() == 0 && q.size() == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case array_reduction_associative + (source "array_reductions.sv" #" +module Top(output bit [3:0] flags); + int numbers[int], words[string]; + initial begin + numbers[-10] = 1; numbers[0] = 3; numbers[1000] = 5; + flags[0] = numbers.sum == 9 && numbers.product() == 15 && numbers.and == 1; + flags[1] = numbers.or() == 7 && numbers.xor == 7 && numbers.num() == 3; + words["beta"] = 2; words["alpha"] = 4; words[""] = 6; + flags[2] = words.sum() == 12 && words.product == 48 && words.and() == 0; + flags[3] = words.or == 6 && words.xor() == 0 && words["beta"] == 2; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case array_reduction_four_state + (source "array_reductions.sv" #" +module Top(output bit [5:0] flags); + logic [3:0] fixed_values[2], dynamic_values[], q[$], assoc[int]; + initial begin + fixed_values = '{4'b0x1z, 4'b1010}; + dynamic_values = '{4'b0x1z, 4'b1010}; + q = {4'b0x1z, 4'b1010}; assoc[-1] = 4'b0x1z; assoc[5] = 4'b1010; + flags[0] = fixed_values.and() === 4'b0010 && dynamic_values.and === 4'b0010; + flags[1] = fixed_values.or === 4'b1x1x && q.or() === 4'b1x1x; + flags[2] = fixed_values.xor() === 4'b1x0x && assoc.xor === 4'b1x0x; + flags[3] = fixed_values.sum === 4'bxxxx && dynamic_values.sum() === 4'bxxxx; + flags[4] = q.product === 4'bxxxx && assoc.product() === 4'bxxxx; + fixed_values = '{4'bzzzz, 4'b0000}; dynamic_values = '{4'bzzzz, 4'b1111}; + flags[5] = fixed_values.and === 4'b0000 && dynamic_values.or === 4'b1111; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq flags 63)) + +(case array_reduction_type_queries + (source "array_reductions.sv" #" +module Top(output bit [3:0] flags); + bit [1:0][3:0] fixed_values[2], dynamic_values[]; + bit [7:0] single[1]; + initial begin + fixed_values = '{8'h12, 8'h23}; dynamic_values = '{8'h12, 8'h23}; single = '{8'h35}; + fixed_values.sum(); dynamic_values.product; + void'(fixed_values.xor); void'(dynamic_values.and()); + flags[0] = $bits(fixed_values.sum) == 8 && $bits(dynamic_values.sum()) == 8; + flags[1] = $dimensions(fixed_values.sum()) == 2 && $dimensions(dynamic_values.sum) == 2; + flags[2] = $size(fixed_values.sum) == 2 && $size(dynamic_values.sum(), 2) == 4; + flags[3] = fixed_values.sum() == single.sum && single.product() == 8'h35 && single.and == 8'h35; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) diff --git a/crates/celox/tests/frontends/systemverilog/containers.rs b/crates/celox/tests/frontends/systemverilog/containers.rs index 693181a3894..1d928b86b57 100644 --- a/crates/celox/tests/frontends/systemverilog/containers.rs +++ b/crates/celox/tests/frontends/systemverilog/containers.rs @@ -1,6 +1,11 @@ use super::*; sv_backends! { + fn array_reduction_type_queries(sim) { @case "containers::array_reduction_type_queries"; } + fn array_reduction_fixed(sim) { @case "containers::array_reduction_fixed"; } + fn array_reduction_dynamic_queue(sim) { @case "containers::array_reduction_dynamic_queue"; } + fn array_reduction_associative(sim) { @case "containers::array_reduction_associative"; } + fn array_reduction_four_state(sim) { @case "containers::array_reduction_four_state"; } fn queue_argument_side_effects(sim) { @case "containers::queue_argument_side_effects"; } fn queue_argument_four_state(sim) { @case "containers::queue_argument_four_state"; } fn string_associative_foreach(sim) { @case "containers::string_associative_foreach"; } diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ea7c9387bfb..b2992e7e534 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -377,8 +377,16 @@ portable state files require a checkpoint instead. Strings and class objects held in elements remain reachable during heap collection. Array assignment copies elements while class handles retain their usual reference semantics. +Integral fixed arrays, dynamic arrays, queues and associative arrays support +`sum`, `product`, `and`, `or` and `xor`, with or without empty parentheses +(IEEE 1800-2023 7.12.3). The result retains the element width and signedness, +including overflow at that width, and propagates four-state unknowns. +Empty containers reduce to zero. Fixed arrays may have elements wider than +64 bits. These methods currently require a one-dimensional array variable; +`with` expressions and iterator arguments remain unsupported. + Multidimensional containers, elements wider than 64 bits, real elements, -wildcard or class keys, slices, array manipulation methods, keyed patterns, +wildcard or class keys, slices, array locator and ordering methods, keyed patterns, container operands within concatenations, compound or nonblocking element assignments, container ports / subroutine parameters / class properties and const containers remain unsupported. A `new[]` initializer currently requires