Skip to main content

logicaffeine_compile/codegen_sva/
synthesis_refine.rs

1//! CEGAR Refinement for SVA Synthesis
2//!
3//! When synthesized SVA doesn't match the spec, classify the divergence
4//! as too-strong or too-weak, apply transformations, and re-check.
5
6#[cfg(feature = "verification")]
7use super::hw_pipeline::check_z3_equivalence;
8
9/// Classification of synthesis divergence.
10#[derive(Debug, Clone, PartialEq)]
11pub enum Divergence {
12    /// SVA is stricter than the spec — it rejects valid behaviors.
13    TooStrong,
14    /// SVA is more permissive than the spec — it allows invalid behaviors.
15    TooWeak,
16    /// Cannot classify.
17    Unknown,
18}
19
20/// Refinement result.
21#[derive(Debug)]
22pub struct RefinementResult {
23    pub converged: bool,
24    pub iterations: u32,
25    pub final_sva: String,
26    pub divergence: Option<Divergence>,
27}
28
29/// Classify whether an SVA is too strong or too weak relative to the spec.
30///
31/// Too strong: spec allows a behavior that SVA rejects.
32/// Too weak: SVA allows a behavior that spec rejects.
33pub fn classify_divergence(spec_allows_ce: bool, sva_allows_ce: bool) -> Divergence {
34    match (spec_allows_ce, sva_allows_ce) {
35        (true, false) => Divergence::TooStrong,
36        (false, true) => Divergence::TooWeak,
37        _ => Divergence::Unknown,
38    }
39}
40
41/// Apply a weakening transformation to an SVA body.
42/// Converts overlapping implication to non-overlapping (adds delay).
43pub fn weaken_implication(sva: &str) -> String {
44    sva.replace("|->", "|=>")
45}
46
47/// Apply a strengthening transformation to an SVA body.
48/// Converts non-overlapping to overlapping (removes delay).
49pub fn strengthen_implication(sva: &str) -> String {
50    sva.replace("|=>", "|->")
51}
52
53/// Apply an eventual-response transformation.
54/// Converts immediate response to eventual.
55pub fn weaken_to_eventual(sva: &str) -> String {
56    if sva.contains("|-> ") && !sva.contains("s_eventually") {
57        sva.replace("|-> ", "|-> s_eventually(") + ")"
58    } else {
59        sva.to_string()
60    }
61}
62
63/// Run a CEGAR refinement loop: check equivalence, classify divergence,
64/// apply transformation, re-check. Bounded to max_iterations.
65#[cfg(feature = "verification")]
66pub fn refine_sva(spec: &str, initial_sva: &str, clock: &str, bound: u32) -> RefinementResult {
67    use logicaffeine_verify::equivalence::EquivalenceResult;
68
69    let max_iterations: u32 = 5;
70    let mut current_sva = initial_sva.to_string();
71    let transformations: Vec<fn(&str) -> String> = vec![
72        weaken_implication,
73        strengthen_implication,
74        weaken_to_eventual,
75    ];
76
77    for i in 0..max_iterations {
78        let result = check_z3_equivalence(spec, &current_sva, bound);
79        match result {
80            Ok(EquivalenceResult::Equivalent) => {
81                return RefinementResult {
82                    converged: true,
83                    iterations: i + 1,
84                    final_sva: current_sva,
85                    divergence: None,
86                };
87            }
88            Ok(EquivalenceResult::NotEquivalent { .. }) => {
89                // Try next transformation
90                let transform_idx = i as usize % transformations.len();
91                let new_sva = transformations[transform_idx](&current_sva);
92                if new_sva == current_sva {
93                    // Transformation had no effect — try next one
94                    if transform_idx + 1 < transformations.len() {
95                        let alt_sva = transformations[transform_idx + 1](&current_sva);
96                        if alt_sva != current_sva {
97                            current_sva = alt_sva;
98                            continue;
99                        }
100                    }
101                    // No transformation helped
102                    return RefinementResult {
103                        converged: false,
104                        iterations: i + 1,
105                        final_sva: current_sva,
106                        divergence: Some(Divergence::Unknown),
107                    };
108                }
109                current_sva = new_sva;
110            }
111            Ok(EquivalenceResult::Unknown) | Err(_) => {
112                return RefinementResult {
113                    converged: false,
114                    iterations: i + 1,
115                    final_sva: current_sva,
116                    divergence: Some(Divergence::Unknown),
117                };
118            }
119        }
120    }
121
122    RefinementResult {
123        converged: false,
124        iterations: max_iterations,
125        final_sva: current_sva,
126        divergence: Some(Divergence::Unknown),
127    }
128}