Skip to main content

logicaffeine_compile/codegen_sva/
rtl_kg.rs

1//! RTL KG + Spec-RTL Linking
2//!
3//! Converts RtlModule → HwKnowledgeGraph and links spec KG to RTL KG.
4
5use super::rtl_extract::{PortDirection, RtlModule};
6use logicaffeine_language::semantics::knowledge_graph::{HwKnowledgeGraph, SignalRole};
7
8/// Convert an RtlModule to a HwKnowledgeGraph.
9pub fn rtl_to_kg(module: &RtlModule) -> HwKnowledgeGraph {
10    let mut kg = HwKnowledgeGraph::new();
11
12    for port in &module.ports {
13        let role = match &port.direction {
14            PortDirection::Input => SignalRole::Input,
15            PortDirection::Output => SignalRole::Output,
16            PortDirection::Inout => SignalRole::Internal,
17        };
18        // Override for detected clocks
19        let role = if module.clocks.contains(&port.name) {
20            SignalRole::Clock
21        } else {
22            role
23        };
24        kg.add_signal(&port.name, port.width, role);
25    }
26
27    for sig in &module.signals {
28        kg.add_signal(&sig.name, sig.width, SignalRole::Internal);
29    }
30
31    kg
32}
33
34/// Link result reporting unmatched signals.
35#[derive(Debug)]
36pub struct LinkResult {
37    pub matched: Vec<(String, String)>,
38    pub unmatched_spec: Vec<String>,
39    pub unmatched_rtl: Vec<String>,
40}
41
42/// Link a spec KG to an RTL KG by signal name matching.
43/// Strategy: exact match → case-insensitive match.
44pub fn link_kg(spec_kg: &HwKnowledgeGraph, rtl_kg: &HwKnowledgeGraph) -> LinkResult {
45    let mut matched = Vec::new();
46    let mut used_rtl: std::collections::HashSet<String> = std::collections::HashSet::new();
47
48    let rtl_names: Vec<String> = rtl_kg.signals.iter().map(|s| s.name.clone()).collect();
49
50    for spec_sig in &spec_kg.signals {
51        // Exact match
52        if let Some(rtl_name) = rtl_names.iter().find(|n| **n == spec_sig.name) {
53            matched.push((spec_sig.name.clone(), rtl_name.clone()));
54            used_rtl.insert(rtl_name.clone());
55            continue;
56        }
57        // Case-insensitive match
58        if let Some(rtl_name) = rtl_names
59            .iter()
60            .find(|n| n.to_lowercase() == spec_sig.name.to_lowercase())
61        {
62            matched.push((spec_sig.name.clone(), rtl_name.clone()));
63            used_rtl.insert(rtl_name.clone());
64            continue;
65        }
66    }
67
68    let unmatched_spec: Vec<String> = spec_kg
69        .signals
70        .iter()
71        .filter(|s| !matched.iter().any(|(spec, _)| spec == &s.name))
72        .map(|s| s.name.clone())
73        .collect();
74
75    let unmatched_rtl: Vec<String> = rtl_kg
76        .signals
77        .iter()
78        .filter(|s| !used_rtl.contains(&s.name))
79        .map(|s| s.name.clone())
80        .collect();
81
82    LinkResult {
83        matched,
84        unmatched_spec,
85        unmatched_rtl,
86    }
87}