Skip to main content

logicaffeine_compile/codegen_sva/
rtl_extract.rs

1//! Verilog Declaration Parser
2//!
3//! Extracts module structure from Verilog/SystemVerilog source:
4//! module name, ports (direction, width), internal signals, parameters,
5//! and clock detection from `always @(posedge/negedge)` blocks.
6//!
7//! This is NOT a full Verilog parser — it handles declaration-level
8//! extraction for hardware verification KG construction.
9
10/// Port direction.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum PortDirection {
13    Input,
14    Output,
15    Inout,
16}
17
18/// Signal type.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum SignalType {
21    Wire,
22    Reg,
23    Logic,
24}
25
26/// A port in the module declaration.
27#[derive(Debug, Clone)]
28pub struct RtlPort {
29    pub name: String,
30    pub direction: PortDirection,
31    pub width: u32,
32}
33
34/// An internal signal declaration.
35#[derive(Debug, Clone)]
36pub struct RtlSignal {
37    pub name: String,
38    pub signal_type: SignalType,
39    pub width: u32,
40}
41
42/// A parameter declaration.
43#[derive(Debug, Clone)]
44pub struct RtlParam {
45    pub name: String,
46    pub value: String,
47}
48
49/// Extracted module structure.
50#[derive(Debug, Clone)]
51pub struct RtlModule {
52    pub name: String,
53    pub ports: Vec<RtlPort>,
54    pub signals: Vec<RtlSignal>,
55    pub params: Vec<RtlParam>,
56    pub clocks: Vec<String>,
57}
58
59/// Parse error.
60#[derive(Debug)]
61pub struct RtlParseError {
62    pub message: String,
63}
64
65impl std::fmt::Display for RtlParseError {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        write!(f, "RTL parse error: {}", self.message)
68    }
69}
70
71/// Parse a Verilog module declaration and extract its structure.
72pub fn parse_verilog_module(src: &str) -> Result<RtlModule, RtlParseError> {
73    // Strip comments
74    let cleaned = strip_comments(src);
75
76    // Find module declaration (must be at word boundary — not inside another word)
77    let module_start = find_keyword(&cleaned, "module").ok_or_else(|| RtlParseError {
78        message: "no 'module' keyword found".into(),
79    })?;
80
81    // Check for endmodule
82    if !cleaned.contains("endmodule") {
83        return Err(RtlParseError {
84            message: "no 'endmodule' found".into(),
85        });
86    }
87
88    // Extract module name
89    let after_module = &cleaned[module_start + 7..];
90    let name_end = after_module
91        .find(|c: char| c == '(' || c == ';' || c.is_whitespace())
92        .unwrap_or(after_module.len());
93    let module_name = after_module[..name_end].trim().to_string();
94
95    let mut module = RtlModule {
96        name: module_name,
97        ports: Vec::new(),
98        signals: Vec::new(),
99        params: Vec::new(),
100        clocks: Vec::new(),
101    };
102
103    // Parse ANSI-style port list: module name ( ... );
104    if let Some(paren_start) = after_module.find('(') {
105        if let Some(paren_end) = find_balanced_paren(&after_module[paren_start..]) {
106            let port_list = &after_module[paren_start + 1..paren_start + paren_end];
107            parse_port_list(port_list, &mut module.ports);
108        }
109    }
110
111    // Parse body: signals, parameters, always blocks
112    let body_start = cleaned.find(';').unwrap_or(0) + 1;
113    let body_end = cleaned.rfind("endmodule").unwrap_or(cleaned.len());
114    let body = &cleaned[body_start..body_end];
115
116    for line in body.lines() {
117        let trimmed = line.trim();
118        parse_body_line(trimmed, &mut module);
119    }
120
121    Ok(module)
122}
123
124/// Find a keyword at a word boundary (not inside another identifier).
125fn find_keyword(input: &str, keyword: &str) -> Option<usize> {
126    let klen = keyword.len();
127    for i in 0..input.len() {
128        if i + klen > input.len() {
129            break;
130        }
131        if &input[i..i + klen] == keyword {
132            let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
133            let before_ok = i == 0 || !is_ident(input.as_bytes()[i - 1]);
134            let after_ok = i + klen >= input.len() || !is_ident(input.as_bytes()[i + klen]);
135            if before_ok && after_ok {
136                return Some(i);
137            }
138        }
139    }
140    None
141}
142
143/// Strip single-line (//) and multi-line (/* */) comments.
144fn strip_comments(src: &str) -> String {
145    let mut result = String::with_capacity(src.len());
146    let bytes = src.as_bytes();
147    let mut i = 0;
148    while i < bytes.len() {
149        if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'/' {
150            // Single-line comment: skip to end of line
151            while i < bytes.len() && bytes[i] != b'\n' {
152                i += 1;
153            }
154        } else if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' {
155            // Multi-line comment: skip to */
156            i += 2;
157            while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
158                i += 1;
159            }
160            i += 2; // skip */
161        } else {
162            result.push(bytes[i] as char);
163            i += 1;
164        }
165    }
166    result
167}
168
169/// Find the closing paren that balances the opening paren at position 0.
170fn find_balanced_paren(input: &str) -> Option<usize> {
171    let mut depth = 0i32;
172    for (i, c) in input.chars().enumerate() {
173        match c {
174            '(' => depth += 1,
175            ')' => {
176                depth -= 1;
177                if depth == 0 {
178                    return Some(i);
179                }
180            }
181            _ => {}
182        }
183    }
184    None
185}
186
187/// Parse a comma-separated port list.
188fn parse_port_list(port_list: &str, ports: &mut Vec<RtlPort>) {
189    for port_decl in port_list.split(',') {
190        let trimmed = port_decl.trim();
191        if trimmed.is_empty() {
192            continue;
193        }
194        if let Some(port) = parse_port_decl(trimmed) {
195            ports.push(port);
196        }
197    }
198}
199
200/// Parse a single port declaration like "input [7:0] data".
201fn parse_port_decl(decl: &str) -> Option<RtlPort> {
202    let tokens: Vec<&str> = decl.split_whitespace().collect();
203    if tokens.is_empty() {
204        return None;
205    }
206
207    let mut idx = 0;
208    let direction = match tokens.get(idx)?.to_lowercase().as_str() {
209        "input" => {
210            idx += 1;
211            PortDirection::Input
212        }
213        "output" => {
214            idx += 1;
215            PortDirection::Output
216        }
217        "inout" => {
218            idx += 1;
219            PortDirection::Inout
220        }
221        _ => return None,
222    };
223
224    // Skip optional wire/reg/logic keyword
225    if let Some(tok) = tokens.get(idx) {
226        if matches!(tok.to_lowercase().as_str(), "wire" | "reg" | "logic") {
227            idx += 1;
228        }
229    }
230
231    // Check for width: [N:M]
232    let width = if let Some(tok) = tokens.get(idx) {
233        if tok.starts_with('[') {
234            idx += 1;
235            parse_width_spec(tok)
236        } else {
237            1
238        }
239    } else {
240        1
241    };
242
243    // Port name
244    let name = tokens
245        .get(idx)?
246        .trim_end_matches(|c: char| c == ',' || c == ')' || c == ';');
247    if name.is_empty() {
248        return None;
249    }
250
251    Some(RtlPort {
252        name: name.to_string(),
253        direction,
254        width,
255    })
256}
257
258/// Parse [N:M] width specification, returning the width (N - M + 1).
259fn parse_width_spec(spec: &str) -> u32 {
260    let inner = spec.trim_start_matches('[').trim_end_matches(']');
261    if let Some(colon) = inner.find(':') {
262        let high: i32 = inner[..colon].trim().parse().unwrap_or(0);
263        let low: i32 = inner[colon + 1..].trim().parse().unwrap_or(0);
264        ((high - low).abs() + 1) as u32
265    } else {
266        1
267    }
268}
269
270/// Parse a line from the module body.
271fn parse_body_line(line: &str, module: &mut RtlModule) {
272    let tokens: Vec<&str> = line.split_whitespace().collect();
273    if tokens.is_empty() {
274        return;
275    }
276
277    match tokens[0] {
278        "wire" | "reg" | "logic" => {
279            let sig_type = match tokens[0] {
280                "wire" => SignalType::Wire,
281                "reg" => SignalType::Reg,
282                "logic" => SignalType::Logic,
283                _ => return,
284            };
285            let mut idx = 1;
286            let width = if tokens.get(idx).map(|t| t.starts_with('[')).unwrap_or(false) {
287                let w = parse_width_spec(tokens[idx]);
288                idx += 1;
289                w
290            } else {
291                1
292            };
293            if let Some(name) = tokens.get(idx) {
294                let name = name.trim_end_matches(';');
295                if !name.is_empty() {
296                    module.signals.push(RtlSignal {
297                        name: name.to_string(),
298                        signal_type: sig_type,
299                        width,
300                    });
301                }
302            }
303        }
304        "parameter" | "localparam" => {
305            if tokens.len() >= 3 {
306                let name = tokens[1].to_string();
307                // Skip '=' and get value
308                let value = if tokens.len() >= 4 && tokens[2] == "=" {
309                    tokens[3].trim_end_matches(';').to_string()
310                } else if tokens.len() >= 3 {
311                    tokens[2]
312                        .trim_start_matches('=')
313                        .trim_end_matches(';')
314                        .to_string()
315                } else {
316                    String::new()
317                };
318                module.params.push(RtlParam { name, value });
319            }
320        }
321        "always" => {
322            // Detect clock from always @(posedge/negedge clk)
323            let joined = line.to_string();
324            if let Some(edge_start) = joined.find("posedge").or_else(|| joined.find("negedge")) {
325                let after_edge = &joined[edge_start..];
326                let clock_start = after_edge.find(char::is_whitespace).unwrap_or(0) + 1;
327                let after_space = after_edge[clock_start..].trim();
328                let clock_end = after_space
329                    .find(|c: char| c == ')' || c == ',' || c.is_whitespace())
330                    .unwrap_or(after_space.len());
331                let clock_name = &after_space[..clock_end];
332                if !clock_name.is_empty() {
333                    if !module.clocks.contains(&clock_name.to_string()) {
334                        module.clocks.push(clock_name.to_string());
335                    }
336                }
337            }
338        }
339        _ => {}
340    }
341}