Skip to main content

logicaffeine_compile/codegen_sva/
sufficiency.rs

1//! Property Sufficiency Analysis
2//!
3//! Before running verification, check if your properties are sufficient
4//! to cover the spec.
5
6use logicaffeine_language::semantics::knowledge_graph::HwKnowledgeGraph;
7use serde::{Deserialize, Serialize};
8
9/// Sufficiency analysis report.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct SufficiencyReport {
12    pub lonely_signals: Vec<String>,
13    pub unconstrained_outputs: Vec<String>,
14    pub missing_handshakes: Vec<(String, String)>,
15    pub coverage_ratio: f64,
16    pub recommendations: Vec<String>,
17}
18
19/// Known handshake pairing patterns: (trigger_pattern, response_patterns)
20const HANDSHAKE_PAIRS: &[(&str, &[&str])] = &[
21    ("req", &["ack", "gnt", "grant"]),
22    (
23        "request",
24        &["acknowledge", "acknowledgment", "response", "grant"],
25    ),
26    ("valid", &["ready", "rdy"]),
27    ("cmd", &["resp", "response"]),
28    ("start", &["done", "complete"]),
29];
30
31/// Analyze property sufficiency from a KG.
32pub fn analyze_sufficiency(kg: &HwKnowledgeGraph) -> SufficiencyReport {
33    use logicaffeine_language::semantics::knowledge_graph::SignalRole;
34
35    let signal_names: std::collections::HashSet<String> =
36        kg.signals.iter().map(|s| s.name.clone()).collect();
37    let edge_signals: std::collections::HashSet<String> = kg
38        .edges
39        .iter()
40        .flat_map(|e| vec![e.from.clone(), e.to.clone()])
41        .collect();
42
43    // Lonely signals: not mentioned in any edge
44    let lonely_signals: Vec<String> = signal_names
45        .iter()
46        .filter(|s| !edge_signals.contains(*s))
47        .cloned()
48        .collect();
49
50    // Unconstrained outputs: output signals with no driving edge
51    let unconstrained_outputs: Vec<String> = kg
52        .signals
53        .iter()
54        .filter(|s| s.role == SignalRole::Output)
55        .filter(|s| !kg.edges.iter().any(|e| e.to == s.name))
56        .map(|s| s.name.clone())
57        .collect();
58
59    // Missing handshake pairs: detect common naming patterns without edges
60    let mut missing_handshakes: Vec<(String, String)> = Vec::new();
61    for (trigger_pattern, response_patterns) in HANDSHAKE_PAIRS {
62        let trigger_match = kg
63            .signals
64            .iter()
65            .find(|s| s.name.to_lowercase().contains(trigger_pattern));
66        if let Some(trigger_sig) = trigger_match {
67            for resp_pattern in *response_patterns {
68                let resp_match = kg.signals.iter().find(|s| {
69                    let lower = s.name.to_lowercase();
70                    lower.contains(resp_pattern) && s.name != trigger_sig.name
71                });
72                if let Some(resp_sig) = resp_match {
73                    // Check if there's already a direct edge between them
74                    let has_edge = kg.edges.iter().any(|e| {
75                        (e.from == trigger_sig.name && e.to == resp_sig.name)
76                            || (e.from == resp_sig.name && e.to == trigger_sig.name)
77                    });
78                    if !has_edge {
79                        missing_handshakes.push((trigger_sig.name.clone(), resp_sig.name.clone()));
80                    }
81                    break; // Only match first response pattern
82                }
83            }
84        }
85    }
86
87    // Coverage ratio
88    let total = signal_names.len() + kg.edges.len();
89    let covered = edge_signals.len();
90    let coverage_ratio = if total > 0 {
91        covered as f64 / total as f64
92    } else {
93        0.0
94    };
95
96    // Recommendations
97    let mut recommendations = Vec::new();
98    for sig in &lonely_signals {
99        recommendations.push(format!(
100            "Signal '{}' is not constrained by any property",
101            sig
102        ));
103    }
104    for sig in &unconstrained_outputs {
105        recommendations.push(format!("Output '{}' has no driving property", sig));
106    }
107    for (trigger, response) in &missing_handshakes {
108        recommendations.push(format!(
109            "Missing handshake: '{}' has no edge to '{}'",
110            trigger, response
111        ));
112    }
113
114    SufficiencyReport {
115        lonely_signals,
116        unconstrained_outputs,
117        missing_handshakes,
118        coverage_ratio,
119        recommendations,
120    }
121}