Skip to main content

logicaffeine_compile/codegen_sva/
hw_pipeline.rs

1//! Hardware Verification Pipeline
2//!
3//! Public API for the LOGOS hardware verification pipeline:
4//! English spec → Kripke FOL → Knowledge Graph → SVA → Z3 Equivalence.
5
6use super::fol_to_verify::FolTranslator;
7use super::sva_model::{parse_sva, sva_exprs_structurally_equivalent, SvaExpr};
8use super::sva_to_verify::{BoundedExpr, SvaTranslator, TranslateResult};
9use super::{emit_sva_property, sanitize_property_name, SvaAssertionKind, SvaProperty};
10use logicaffeine_language::semantics::knowledge_graph::{HwKnowledgeGraph, SignalRole};
11use std::collections::HashMap;
12
13// ═══════════════════════════════════════════════════════════════════════════
14// SIGNAL MAP
15// ═══════════════════════════════════════════════════════════════════════════
16
17/// Maps FOL argument names (from English proper nouns) to SVA signal names.
18///
19/// When the English spec says "Req is valid", LOGOS produces `Valid(Req, w)`.
20/// The signal map translates `Req` → `req` so the bounded variable becomes
21/// `req@t` instead of `Valid_Req_@t`, matching the SVA side.
22#[derive(Debug, Clone)]
23pub struct SignalMap {
24    map: HashMap<String, String>,
25}
26
27impl SignalMap {
28    pub fn new() -> Self {
29        Self {
30            map: HashMap::new(),
31        }
32    }
33
34    /// Add a mapping from FOL argument name to SVA signal name.
35    pub fn add(&mut self, fol_arg: &str, sva_signal: &str) {
36        self.map.insert(fol_arg.to_string(), sva_signal.to_string());
37    }
38
39    /// Resolve a FOL argument name to its SVA signal name.
40    pub fn resolve(&self, fol_arg: &str) -> Option<&str> {
41        self.map.get(fol_arg).map(|s| s.as_str())
42    }
43
44    /// Build a signal map from hardware signal declarations.
45    pub fn from_decls(decls: &[HwSignalDecl]) -> Self {
46        let mut map = Self::new();
47        for decl in decls {
48            map.add(&decl.english_name, &decl.sva_name);
49        }
50        map
51    }
52}
53
54// ═══════════════════════════════════════════════════════════════════════════
55// HARDWARE SIGNAL DECLARATION
56// ═══════════════════════════════════════════════════════════════════════════
57
58/// Declares a hardware signal with its English name and SVA name.
59///
60/// The `english_name` should be a capitalized proper noun used in the English spec
61/// (e.g., "Req", "Ack", "Awvalid"). The `sva_name` is the corresponding SVA signal
62/// (e.g., "req", "ack", "AWVALID").
63#[derive(Debug, Clone)]
64pub struct HwSignalDecl {
65    pub english_name: String,
66    pub sva_name: String,
67    pub width: u32,
68    pub role: SignalRole,
69}
70
71impl HwSignalDecl {
72    pub fn new(english_name: &str, sva_name: &str, width: u32, role: SignalRole) -> Self {
73        Self {
74            english_name: english_name.to_string(),
75            sva_name: sva_name.to_string(),
76            width,
77            role,
78        }
79    }
80}
81
82// ═══════════════════════════════════════════════════════════════════════════
83// PIPELINE TYPES
84// ═══════════════════════════════════════════════════════════════════════════
85
86/// Result of checking semantic equivalence between FOL and SVA.
87#[derive(Debug)]
88pub struct EquivalenceResult {
89    /// Whether the properties are equivalent at the given bound.
90    pub equivalent: bool,
91    /// If not equivalent, counterexample signal assignments (name@timestep → value).
92    pub counterexample: Option<Vec<(String, String)>>,
93    /// The BMC bound used for checking.
94    pub bound: u32,
95}
96
97/// A compiled hardware specification.
98#[derive(Debug)]
99pub struct HwSpec {
100    /// Kripke-lowered FOL as formatted text.
101    pub fol_text: String,
102    /// Knowledge graph extracted from the spec.
103    pub kg: HwKnowledgeGraph,
104}
105
106/// Full pipeline result.
107#[derive(Debug)]
108pub struct PipelineResult {
109    /// Property name.
110    pub property_name: String,
111    /// Equivalence result.
112    pub result: EquivalenceResult,
113    /// Generated SVA text.
114    pub sva_text: String,
115    /// FOL text from the spec.
116    pub fol_text: String,
117}
118
119/// Error type for hardware verification pipeline.
120#[derive(Debug)]
121pub enum HwError {
122    ParseError(String),
123    SvaParseError(String),
124    VerificationError(String),
125}
126
127impl std::fmt::Display for HwError {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        match self {
130            HwError::ParseError(msg) => write!(f, "Parse error: {}", msg),
131            HwError::SvaParseError(msg) => write!(f, "SVA parse error: {}", msg),
132            HwError::VerificationError(msg) => write!(f, "Verification error: {}", msg),
133        }
134    }
135}
136
137// ═══════════════════════════════════════════════════════════════════════════
138// PIPELINE FUNCTIONS
139// ═══════════════════════════════════════════════════════════════════════════
140
141/// Check structural equivalence between two SVA expressions.
142pub fn check_structural_equivalence(sva_a: &str, sva_b: &str) -> Result<bool, HwError> {
143    let expr_a = parse_sva(sva_a).map_err(|e| HwError::SvaParseError(e.message))?;
144    let expr_b = parse_sva(sva_b).map_err(|e| HwError::SvaParseError(e.message))?;
145    Ok(sva_exprs_structurally_equivalent(&expr_a, &expr_b))
146}
147
148/// Check bounded equivalence between two BoundedExpr trees.
149pub fn check_bounded_equivalence(
150    fol_bounded: &BoundedExpr,
151    sva_bounded: &BoundedExpr,
152    bound: u32,
153) -> EquivalenceResult {
154    let equivalent = bounded_exprs_equal(fol_bounded, sva_bounded);
155    EquivalenceResult {
156        equivalent,
157        counterexample: None,
158        bound,
159    }
160}
161
162/// Translate an SVA string to bounded verification IR.
163///
164/// Uses translate_property (G-wrapping) to model `assert property` semantics.
165pub fn translate_sva_to_bounded(sva_text: &str, bound: u32) -> Result<TranslateResult, HwError> {
166    let sva_expr = parse_sva(sva_text).map_err(|e| HwError::SvaParseError(e.message))?;
167    let mut translator = SvaTranslator::new(bound);
168    let result = translator.translate_property(&sva_expr);
169    Ok(result)
170}
171
172/// Translate SVA with smart G-wrapping for equivalence checking.
173/// If the outermost SVA node is already temporal (s_eventually, nexttime),
174/// translates at t=0 without G-wrapping. Otherwise uses translate_property.
175fn translate_sva_for_equiv(sva_text: &str, bound: u32) -> Result<TranslateResult, HwError> {
176    let sva_expr = parse_sva(sva_text).map_err(|e| HwError::SvaParseError(e.message))?;
177    let mut translator = SvaTranslator::new(bound);
178    if sva_has_outermost_temporal(&sva_expr) {
179        let expr = translator.translate(&sva_expr, 0);
180        let declarations: Vec<String> = translator.declarations.iter().cloned().collect();
181        Ok(TranslateResult { expr, declarations })
182    } else {
183        Ok(translator.translate_property(&sva_expr))
184    }
185}
186
187/// Check if the outermost SVA node is a temporal operator that already encodes
188/// the temporal unrolling (s_eventually, nexttime). These should NOT be wrapped
189/// in an additional G (conjunction over all timesteps).
190fn sva_has_outermost_temporal(expr: &SvaExpr) -> bool {
191    matches!(
192        expr,
193        SvaExpr::SEventually(_) | SvaExpr::Nexttime(_, _) | SvaExpr::SAlways(_)
194    )
195}
196
197/// Translate a LOGOS spec to bounded verification IR using compile_kripke_with.
198pub fn translate_spec_to_bounded(spec: &str, bound: u32) -> Result<TranslateResult, HwError> {
199    logicaffeine_language::compile_kripke_with(spec, |ast, interner| {
200        let mut translator = FolTranslator::new(interner, bound);
201        translator.translate_property(ast)
202    })
203    .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
204}
205
206/// Compile an English hardware property with signal declarations.
207///
208/// Takes an English specification and a list of signal declarations that map
209/// English proper nouns to SVA signal names. Produces a BoundedExpr with
210/// correctly-mapped signal variables.
211pub fn compile_hw_property(
212    spec: &str,
213    decls: &[HwSignalDecl],
214    bound: u32,
215) -> Result<TranslateResult, HwError> {
216    let signal_map = SignalMap::from_decls(decls);
217    logicaffeine_language::compile_kripke_with(spec, |ast, interner| {
218        let mut translator = FolTranslator::new(interner, bound);
219        translator.set_signal_map(&signal_map);
220        translator.translate_property(ast)
221    })
222    .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
223}
224
225/// Compile an English hardware spec to FOL text.
226pub fn compile_hw_spec(source: &str) -> Result<String, HwError> {
227    logicaffeine_language::compile_kripke(source)
228        .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
229}
230
231/// Emit SVA from a property specification.
232pub fn emit_hw_sva(name: &str, clock: &str, body: &str, kind: SvaAssertionKind) -> String {
233    let prop = SvaProperty {
234        name: sanitize_property_name(name),
235        clock: clock.to_string(),
236        body: body.to_string(),
237        kind,
238    };
239    emit_sva_property(&prop)
240}
241
242/// Extract a Knowledge Graph from an English hardware spec (one call).
243pub fn extract_kg(spec: &str) -> Result<HwKnowledgeGraph, HwError> {
244    logicaffeine_language::compile_kripke_with(spec, |ast, interner| {
245        logicaffeine_language::semantics::knowledge_graph::extract_from_kripke_ast(ast, interner)
246    })
247    .map_err(|e| HwError::ParseError(crate::compile::describe_parse_error(&e)))
248}
249
250/// Check Z3 semantic equivalence between an English spec and an SVA string.
251///
252/// This is the core contribution — nobody else does this.
253#[cfg(feature = "verification")]
254pub fn check_z3_equivalence(
255    spec_source: &str,
256    sva_text: &str,
257    bound: u32,
258) -> Result<logicaffeine_verify::equivalence::EquivalenceResult, HwError> {
259    use super::sva_to_verify::{bounded_to_verify, extract_signal_names};
260
261    let spec_bounded = translate_spec_to_bounded(spec_source, bound)?;
262    let spec_verify = bounded_to_verify(&spec_bounded.expr);
263
264    let sva_bounded = translate_sva_for_equiv(sva_text, bound)?;
265    let sva_verify = bounded_to_verify(&sva_bounded.expr);
266
267    let mut all_signals = extract_signal_names(&spec_bounded);
268    let sva_signals = extract_signal_names(&sva_bounded);
269    for sig in sva_signals {
270        if !all_signals.contains(&sig) {
271            all_signals.push(sig);
272        }
273    }
274
275    Ok(logicaffeine_verify::equivalence::check_equivalence(
276        &spec_verify,
277        &sva_verify,
278        &all_signals,
279        bound as usize,
280    ))
281}
282
283/// Check Z3 semantic equivalence with hardware signal declarations.
284///
285/// This is the signal-bridge version that maps English proper nouns to SVA signal
286/// names via HwSignalDecl. Both sides translate to the same variable namespace.
287#[cfg(feature = "verification")]
288pub fn check_z3_hw_equivalence(
289    spec: &str,
290    sva_text: &str,
291    decls: &[HwSignalDecl],
292    bound: u32,
293) -> Result<logicaffeine_verify::equivalence::EquivalenceResult, HwError> {
294    use super::sva_to_verify::{bounded_to_verify, extract_signal_names};
295
296    // 1. Compile English with signal map
297    let spec_bounded = compile_hw_property(spec, decls, bound)?;
298    let spec_verify = bounded_to_verify(&spec_bounded.expr);
299
300    // 2. Translate SVA with G-wrapping to match FOL temporal structure
301    let sva_bounded = translate_sva_for_equiv(sva_text, bound)?;
302    let sva_verify = bounded_to_verify(&sva_bounded.expr);
303
304    // 3. Signal list from declarations + any extra signals from either side
305    let mut all_signals: Vec<String> = decls.iter().map(|d| d.sva_name.clone()).collect();
306    let spec_signals = extract_signal_names(&spec_bounded);
307    let sva_signals = extract_signal_names(&sva_bounded);
308    for sig in spec_signals.into_iter().chain(sva_signals.into_iter()) {
309        if !all_signals.contains(&sig) {
310            all_signals.push(sig);
311        }
312    }
313
314    // 4. Z3 equivalence check
315    Ok(logicaffeine_verify::equivalence::check_equivalence(
316        &spec_verify,
317        &sva_verify,
318        &all_signals,
319        bound as usize,
320    ))
321}
322
323/// Check FOL ↔ SVA **semantic** equivalence at a bound with our pure-Rust, certified prover
324/// (no Z3) — the in-browser counterpart of `check_z3_equivalence`. Lowers both bounded
325/// obligations to `ProofExpr` and discharges `F ↔ S` through the CDCL → RUP tiers: an
326/// `equivalent` verdict is RUP-certified, a non-equivalent one carries a counterexample
327/// trace (`name@t` → `"1"`/`"0"`). Errors (fail-closed, never a false "equivalent") if
328/// either obligation leaves the Boolean fragment — data-path needs bit-blasting, not wired
329/// yet.
330pub fn prove_bounded_equivalence(
331    fol_bounded: &BoundedExpr,
332    sva_bounded: &BoundedExpr,
333    bound: u32,
334) -> Result<EquivalenceResult, HwError> {
335    use super::sva_to_proof::bounded_to_proof;
336    use logicaffeine_proof::sat::{prove_equivalence, EquivOutcome};
337
338    let fol = bounded_to_proof(fol_bounded).ok_or_else(|| {
339        HwError::VerificationError(
340            "FOL obligation is outside the Boolean fragment (bit-blasting not yet wired)".into(),
341        )
342    })?;
343    let sva = bounded_to_proof(sva_bounded).ok_or_else(|| {
344        HwError::VerificationError(
345            "SVA obligation is outside the Boolean fragment (bit-blasting not yet wired)".into(),
346        )
347    })?;
348
349    match prove_equivalence(&fol, &sva) {
350        EquivOutcome::Equivalent => Ok(EquivalenceResult {
351            equivalent: true,
352            counterexample: None,
353            bound,
354        }),
355        EquivOutcome::Differ(model) => Ok(EquivalenceResult {
356            equivalent: false,
357            counterexample: Some(
358                model
359                    .into_iter()
360                    .map(|(name, v)| (name, if v { "1" } else { "0" }.to_string()))
361                    .collect(),
362            ),
363            bound,
364        }),
365        EquivOutcome::Unsupported => Err(HwError::VerificationError(
366            "obligation not purely propositional — escalate to bit-blasting".into(),
367        )),
368    }
369}
370
371/// End-to-end: an English spec and a candidate SVA string → certified semantic equivalence
372/// with our prover. The Z3-free counterpart of `check_z3_equivalence`: the same
373/// translators, our CDCL → RUP tiers instead of Z3.
374pub fn prove_spec_sva_equivalence(
375    spec_source: &str,
376    sva_text: &str,
377    bound: u32,
378) -> Result<EquivalenceResult, HwError> {
379    let spec_bounded = translate_spec_to_bounded(spec_source, bound)?;
380    let sva_bounded = translate_sva_for_equiv(sva_text, bound)?;
381    prove_bounded_equivalence(&spec_bounded.expr, &sva_bounded.expr, bound)
382}
383
384/// A node in the renderable knowledge-graph view: a signal with its role and width.
385#[derive(Debug, Clone, PartialEq, Eq)]
386pub struct KgNode {
387    pub name: String,
388    pub role: String,
389    pub width: u32,
390}
391
392/// A directed relation between two nodes (indices into [`KgSummary::nodes`]).
393#[derive(Debug, Clone, PartialEq, Eq)]
394pub struct KgLink {
395    pub from: usize,
396    pub to: usize,
397    pub relation: String,
398}
399
400/// A compact, render-ready view of the hardware knowledge graph extracted from an English
401/// spec — signals as nodes, relations (drives / triggers / handshakes / …) as directed links.
402#[derive(Debug, Clone, PartialEq, Eq, Default)]
403pub struct KgSummary {
404    pub nodes: Vec<KgNode>,
405    pub links: Vec<KgLink>,
406}
407
408/// Extract a render-ready knowledge graph from an English hardware spec. Pure Rust (no Z3),
409/// so it runs in the browser. Merges the legacy and typed (ontology) edge sets.
410pub fn kg_summary(spec: &str) -> Result<KgSummary, HwError> {
411    use logicaffeine_language::semantics::knowledge_graph::{KgRelation, SignalRole};
412    use std::collections::HashMap;
413
414    let kg = extract_kg(spec)?;
415    let mut nodes = Vec::new();
416    let mut index: HashMap<String, usize> = HashMap::new();
417    for s in &kg.signals {
418        let role = match s.role {
419            SignalRole::Input => "input",
420            SignalRole::Output => "output",
421            SignalRole::Internal => "internal",
422            SignalRole::Clock => "clock",
423        }
424        .to_string();
425        index.insert(s.name.clone(), nodes.len());
426        nodes.push(KgNode {
427            name: s.name.clone(),
428            role,
429            width: s.width,
430        });
431    }
432
433    let mut links = Vec::new();
434    let mut seen = std::collections::HashSet::new();
435    let mut add = |from: &str, to: &str, rel: String, links: &mut Vec<KgLink>| {
436        if let (Some(&f), Some(&t)) = (index.get(from), index.get(to)) {
437            if f != t && seen.insert((f, t, rel.clone())) {
438                links.push(KgLink {
439                    from: f,
440                    to: t,
441                    relation: rel,
442                });
443            }
444        }
445    };
446    for e in &kg.edges {
447        let rel = match e.relation {
448            KgRelation::Temporal => "temporal",
449            KgRelation::Triggers => "triggers",
450            KgRelation::Constrains => "constrains",
451            KgRelation::TypeOf => "type",
452        }
453        .to_string();
454        add(&e.from, &e.to, rel, &mut links);
455    }
456    for (from, to, rel) in &kg.typed_edges {
457        add(from, to, typed_relation_label(rel), &mut links);
458    }
459
460    Ok(KgSummary { nodes, links })
461}
462
463fn typed_relation_label(
464    rel: &logicaffeine_language::semantics::knowledge_graph::HwRelation,
465) -> String {
466    use logicaffeine_language::semantics::knowledge_graph::HwRelation as R;
467    match rel {
468        R::Drives | R::DrivesRegistered { .. } => "drives",
469        R::DataFlow => "data",
470        R::Reads => "reads",
471        R::Writes => "writes",
472        R::Controls => "controls",
473        R::Selects => "selects",
474        R::Enables => "enables",
475        R::Resets => "resets",
476        R::Triggers { .. } => "triggers",
477        R::Constrains => "constrains",
478        R::Follows { .. } => "follows",
479        R::Precedes => "precedes",
480        R::Preserves => "preserves",
481        R::Contains => "contains",
482        R::Instantiates => "instantiates",
483        R::ConnectsTo => "connects",
484        R::BelongsToDomain { .. } => "domain",
485        R::HandshakesWith => "handshake",
486        R::Acknowledges => "acks",
487        R::Pipelines { .. } => "pipeline",
488        R::MutuallyExcludes => "mutex",
489        R::EventuallyFollows => "eventually",
490        R::AssumedBy => "assumed",
491    }
492    .to_string()
493}
494
495/// One signal's value over time in a counterexample waveform. `width` is the bit width
496/// (1 = a boolean control bit); each `values[t]` is the (reconstructed) register value at
497/// timestep `t`, or `None` if unconstrained there.
498#[derive(Debug, Clone, PartialEq, Eq)]
499pub struct WaveSignal {
500    pub name: String,
501    pub width: u32,
502    pub values: Vec<Option<u64>>,
503}
504
505/// A counterexample rendered as a waveform: signals (rows) over discrete timesteps (columns).
506#[derive(Debug, Clone, PartialEq, Eq, Default)]
507pub struct Waveform {
508    pub timesteps: u32,
509    pub signals: Vec<WaveSignal>,
510}
511
512/// Turn a counterexample's bindings into a waveform. Handles both 1-bit signals (`name@t`)
513/// and bit-blasted multi-bit registers (`name@t#i`), reconstructing each register's integer
514/// value per timestep from its bits. Signals are sorted by name; each row spans
515/// `0..timesteps`. Malformed keys (no `@t`) are skipped.
516pub fn counterexample_waveform(counterexample: &[(String, String)]) -> Waveform {
517    use std::collections::BTreeMap;
518    // name → (width, timestep → (bit-index → value))
519    struct Acc {
520        width: u32,
521        per_t: BTreeMap<u32, BTreeMap<u32, bool>>,
522    }
523    let mut sigs: BTreeMap<String, Acc> = BTreeMap::new();
524    let mut max_t = 0u32;
525    let mut any = false;
526    for (key, val) in counterexample {
527        let bit_val = match val.as_str() {
528            "1" | "true" => true,
529            "0" | "false" => false,
530            _ => continue,
531        };
532        // Optional `#<bit>` suffix marks a bit of a bit-blasted register.
533        let (base, bit, multibit) = match key.rsplit_once('#') {
534            Some((b, idx)) => match idx.parse::<u32>() {
535                Ok(i) => (b, i, true),
536                Err(_) => continue,
537            },
538            None => (key.as_str(), 0u32, false),
539        };
540        let Some((name, t_str)) = base.rsplit_once('@') else {
541            continue;
542        };
543        let Ok(t) = t_str.parse::<u32>() else {
544            continue;
545        };
546        let acc = sigs.entry(name.to_string()).or_insert(Acc {
547            width: 1,
548            per_t: BTreeMap::new(),
549        });
550        if multibit {
551            acc.width = acc.width.max(bit + 1);
552        }
553        acc.per_t.entry(t).or_default().insert(bit, bit_val);
554        max_t = max_t.max(t);
555        any = true;
556    }
557    let timesteps = if any { max_t + 1 } else { 0 };
558    let signals = sigs
559        .into_iter()
560        .map(|(name, acc)| {
561            let values = (0..timesteps)
562                .map(|t| {
563                    acc.per_t.get(&t).map(|bits| {
564                        bits.iter()
565                            .fold(0u64, |v, (&i, &b)| if b { v | (1u64 << i) } else { v })
566                    })
567                })
568                .collect();
569            WaveSignal {
570                name,
571                width: acc.width,
572                values,
573            }
574        })
575        .collect();
576    Waveform { timesteps, signals }
577}
578
579/// A vacuity verdict for a synthesized property.
580#[derive(Debug, Clone, PartialEq, Eq)]
581pub enum VacuityReport {
582    /// The trigger (implication antecedent) is reachable — the property is non-vacuous.
583    NonVacuous,
584    /// The trigger can never fire — the property holds vacuously (a dead trigger / likely bug).
585    Vacuous,
586    /// The property has no antecedent (e.g. a pure safety assertion) — vacuity does not apply.
587    NoTrigger,
588    /// The antecedent left the Boolean fragment — escalate (bit-blasting).
589    Unsupported,
590}
591
592/// The first implication antecedent reachable through the Boolean structure of a bounded
593/// property — the SVA "trigger". `None` for a property with no implication (pure safety).
594fn first_antecedent(e: &BoundedExpr) -> Option<&BoundedExpr> {
595    match e {
596        BoundedExpr::Implies(a, _) => Some(a),
597        BoundedExpr::And(l, r) | BoundedExpr::Or(l, r) => {
598            first_antecedent(l).or_else(|| first_antecedent(r))
599        }
600        BoundedExpr::Not(x) => first_antecedent(x),
601        _ => None,
602    }
603}
604
605/// Vacuity check (Z3-free, certified): does the property's trigger ever fire? An
606/// unsatisfiable antecedent means the property passes vacuously — a dead trigger that usually
607/// signals a malformed spec. Reuses [`logicaffeine_proof::bmc::check_vacuity`].
608pub fn check_spec_vacuity(spec_source: &str, bound: u32) -> Result<VacuityReport, HwError> {
609    use super::sva_to_proof::bounded_to_proof;
610    use logicaffeine_proof::bmc::{check_vacuity, VacuityOutcome};
611
612    let fol = translate_spec_to_bounded(spec_source, bound)?;
613    let antecedent = match first_antecedent(&fol.expr) {
614        Some(a) => a,
615        None => return Ok(VacuityReport::NoTrigger),
616    };
617    let proof = match bounded_to_proof(antecedent) {
618        Some(p) => p,
619        None => return Ok(VacuityReport::Unsupported),
620    };
621    Ok(match check_vacuity(&proof) {
622        VacuityOutcome::Vacuous => VacuityReport::Vacuous,
623        VacuityOutcome::Reachable(_) => VacuityReport::NonVacuous,
624        VacuityOutcome::Unsupported => VacuityReport::Unsupported,
625    })
626}
627
628#[cfg(test)]
629#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen_sva/hw_pipeline/native_prove_tests.rs"]
630mod native_prove_tests;
631
632/// Check if two BoundedExpr trees are structurally equal.
633fn bounded_exprs_equal(a: &BoundedExpr, b: &BoundedExpr) -> bool {
634    match (a, b) {
635        (BoundedExpr::Var(va), BoundedExpr::Var(vb)) => va == vb,
636        (BoundedExpr::Bool(va), BoundedExpr::Bool(vb)) => va == vb,
637        (BoundedExpr::Int(va), BoundedExpr::Int(vb)) => va == vb,
638        (BoundedExpr::And(la, ra), BoundedExpr::And(lb, rb)) => {
639            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
640        }
641        (BoundedExpr::Or(la, ra), BoundedExpr::Or(lb, rb)) => {
642            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
643        }
644        (BoundedExpr::Not(ia), BoundedExpr::Not(ib)) => bounded_exprs_equal(ia, ib),
645        (BoundedExpr::Implies(la, ra), BoundedExpr::Implies(lb, rb)) => {
646            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
647        }
648        (BoundedExpr::Eq(la, ra), BoundedExpr::Eq(lb, rb)) => {
649            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
650        }
651        (BoundedExpr::Lt(la, ra), BoundedExpr::Lt(lb, rb)) => {
652            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
653        }
654        (BoundedExpr::Gt(la, ra), BoundedExpr::Gt(lb, rb)) => {
655            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
656        }
657        (BoundedExpr::Lte(la, ra), BoundedExpr::Lte(lb, rb)) => {
658            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
659        }
660        (BoundedExpr::Gte(la, ra), BoundedExpr::Gte(lb, rb)) => {
661            bounded_exprs_equal(la, lb) && bounded_exprs_equal(ra, rb)
662        }
663        _ => false,
664    }
665}