Files
lucisv/crates/vlog_refactor/tests/corpus.rs
T
lucioandClaude Fable 5.1 aa479cf701 Convert ports to ANSI: a Verilog-2001 header merged with its body declarations, and a verifier that never drops a comment or an attribute
TODO §51 (docs/features/ansi-conversion), the second §8 refactoring.

`vlog_refactor::convert_to_ansi` (ports/ansi.rs, ports/merge.rs): for a
`PortList::NonAnsi` module, each header name gains its direction, net or
variable type, signing and packed dims from the body declarations that
describe it, merged per IEEE 1800 §23.2.2.2 (`output b; reg [7:0] b;`
→ `output reg [7:0] b`), as insertions around the untouched name so no
reference anchor moves; the absorbed declarations are deleted with their
comments carried onto the ports. Twenty-three refusals, each a sentence
(port expressions, disagreeing ranges, initialisers, directives, a
comment that would have to move into a one-line list, an attributed
declaration). Code action `lucisv: convert ports to ANSI (N ports)` and
command `lucisv.convertToAnsi`.

Review rework (QA's two HIGHs, invariant 4): the verifier's comment rule
is now `never_dropped` over comments and attribute instances alike —
`has ≥ had`, `wrote ≤ gone` unless the text is the one generated
placeholder, `has == had − gone + wrote` — with masked-corruption attack
tests, re-attacked by QA (30-plus pairs, a neutering pass).

Neither the corpus nor opentitan holds a non-ANSI module; acceptance is
by round trip (ANSI → 2001 → ANSI, same ports/types in order) over five
corpus modules and 290 of 291 opentitan candidates (the one failure is
kmac_reduced_tb.sv's pre-existing trailing-comma parse error). 0 of 854
corpus files differ from 0.45.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00

656 lines
26 KiB
Rust

//! Real-RTL acceptance (`corpus/`, fetched by `tools/corpus_fetch.sh`).
//!
//! Two properties, neither of them a percentage: a refactoring over a real
//! workspace either does the whole job or refuses with a sentence — it never
//! panics and never produces an edit that does not cover what it claims — and
//! asking at offsets all over a real file answers without panicking.
//! Skipped when the corpus is not checked out.
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
use vlog_parser::ast::{Item, ItemKind, ListElem, PortList};
use vlog_refactor::{
add_port, convert_to_ansi, expand_wildcard, instantiation_plan, module_definition,
port_actions, prepare_rename, rename, Layout, ModuleRef,
};
use vlog_semantic::WorkspaceIndex;
fn corpus() -> Option<Vec<PathBuf>> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !root.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return None;
}
let mut files = Vec::new();
collect(&root, &mut files);
files.sort();
Some(files)
}
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect(&path, out);
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
out.push(path);
}
}
}
fn read(files: &[PathBuf]) -> Vec<(PathBuf, String)> {
files.iter().filter_map(|p| Some((p.clone(), fs::read_to_string(p).ok()?))).collect()
}
#[test]
fn a_rename_over_the_whole_corpus_answers_or_refuses() {
let Some(files) = corpus() else { return };
let sources = read(&files);
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
// One real cross-file target: a module every workspace instantiates.
let Some((path, text)) =
sources.iter().find(|(p, _)| p.file_name().is_some_and(|n| n == "prim_fifo_sync.sv"))
else {
eprintln!("prim_fifo_sync.sv not in this corpus — skipping the cross-file probe");
return;
};
let offset = text.find("module prim_fifo_sync").map(|i| i + 7).expect("the module's name");
let started = Instant::now();
let outcome = rename(&sources, path, offset as u32, "prim_fifo_sync_renamed");
let elapsed = started.elapsed();
println!(
"corpus rename over {} files: {:?} in {:.2}s",
sources.len(),
outcome.as_ref().map(|e| (e.file_count(), e.edit_count())).map_err(String::as_str),
elapsed.as_secs_f64()
);
match outcome {
Ok(edit) => {
// Every edit must cover exactly the old name in the file it names.
for (file, edits) in &edit.edits {
let text = sources
.iter()
.find(|(p, _)| p == file)
.map(|(_, t)| t.as_str())
.expect("an edited file is an in-scope file");
for e in edits {
assert_eq!(
text.get(e.range.as_range()),
Some("prim_fifo_sync"),
"{}: an edit that does not cover the name",
file.display()
);
}
}
assert!(edit.file_count() > 1, "this module is instantiated in other files");
}
// A refusal is a correct answer too — the corpus really does declare
// some names twice — but it must be a sentence, not a panic.
Err(message) => assert!(message.ends_with('.'), "a refusal must read as a sentence"),
}
assert!(elapsed.as_secs() < 30, "a rename must stay interactive: {elapsed:?}");
}
#[test]
fn asking_at_offsets_all_over_a_real_file_never_panics() {
let Some(files) = corpus() else { return };
// One small file, alone in its scope: the question is robustness at odd
// offsets, not cross-file resolution, and every probe rebuilds an index.
let Some((path, text)) = files
.iter()
.filter_map(|p| Some((p, fs::read_to_string(p).ok()?)))
.find(|(_, text)| (2_000..8_000).contains(&text.len()) && text.contains("endmodule"))
else {
eprintln!("no small file in this corpus — skipping");
return;
};
let sources = vec![(path.clone(), text.clone())];
// A few hundred offsets spread over the file: the point is to hit
// whitespace, punctuation, mid-token, mid-comment and mid-directive
// positions, not to be exhaustive.
let step = (text.len() / 300).max(1);
let mut probed = 0usize;
let mut renameable = 0usize;
for offset in (0..text.len() as u32).step_by(step) {
probed += 1;
if prepare_rename(&sources, path, offset).is_ok() {
renameable += 1;
}
}
println!(
"{}: {renameable} of {probed} probed offsets are renameable",
path.file_name().and_then(|n| n.to_str()).unwrap_or("?")
);
assert!(renameable > 0, "a real file must have something renameable in it");
}
#[test]
fn adding_a_port_to_a_real_module_answers_or_refuses() {
let Some(files) = corpus() else { return };
let sources = read(&files);
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
if !sources.iter().any(|(p, _)| p.file_name().is_some_and(|n| n == "prim_fifo_sync.sv")) {
eprintln!("prim_fifo_sync.sv not in this corpus — skipping the port probe");
return;
}
let started = Instant::now();
let outcome =
add_port(&sources, ModuleRef::Name("prim_fifo_sync"), "input logic lucisv_probe_i");
let elapsed = started.elapsed();
println!(
"corpus add_port over {} files: {:?} in {:.2}s",
sources.len(),
outcome.as_ref().map(|e| (e.file_count(), e.edit_count())).map_err(String::as_str),
elapsed.as_secs_f64()
);
match outcome {
Ok(edit) => {
// Every edit is an insertion of text that spells the new port.
for (_, edits) in &edit.edits {
for e in edits {
assert!(e.range.is_empty(), "adding a port only ever inserts");
assert!(!e.new_text.is_empty(), "an empty insertion is not an edit");
}
}
assert!(edit.file_count() >= 1);
}
// A refusal is a correct answer — real RTL instantiates modules
// positionally and with `.*` — as long as it reads as a sentence.
Err(message) => {
assert!(message.ends_with('.'), "a refusal must read as a sentence: {message}")
}
}
assert!(elapsed.as_secs() < 30, "a refactoring must stay interactive: {elapsed:?}");
}
#[test]
fn asking_for_port_actions_all_over_a_real_file_never_panics() {
let Some(files) = corpus() else { return };
let Some((path, text)) = files
.iter()
.filter_map(|p| Some((p, fs::read_to_string(p).ok()?)))
.find(|(_, text)| (2_000..8_000).contains(&text.len()) && text.contains("endmodule"))
else {
eprintln!("no small file in this corpus — skipping");
return;
};
let sources = vec![(path.clone(), text.clone())];
let step = (text.len() / 200).max(1);
let mut offered = 0usize;
for offset in (0..text.len() as u32).step_by(step) {
for action in port_actions(&sources, path, offset) {
offered += 1;
assert!(action.title.starts_with("lucisv: "), "{}", action.title);
assert!(action.edit.edit_count() > 0, "an action with no edit is not an action");
}
}
println!("port actions over {}: {offered} offered", path.display());
}
#[test]
fn every_module_in_the_corpus_yields_a_skeleton_that_parses() {
// The property that matters for module hinting: whatever a completion
// inserts must be valid Verilog with every default accepted, because that
// is what an editor writes into the buffer on the first Tab. Real RTL is
// where the interesting headers are — type parameters, `ifdef arms,
// non-ANSI legacy modules, package-qualified port types.
let Some(files) = corpus() else { return };
let sources = read(&files);
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
let index =
WorkspaceIndex::build(sources.iter().map(|(path, text)| (path.clone(), text.as_str())));
let started = Instant::now();
let mut planned = 0usize;
let mut refused = 0usize;
let mut unparseable: Vec<String> = Vec::new();
for (path, text) in &sources {
for name in module_names_in(text) {
let Ok(definition) = module_definition(&index, &name) else {
refused += 1;
continue;
};
// A module the index attributes to another file is that file's to
// plan; this one only probes its own.
if definition != path.as_path() {
continue;
}
let Ok(plan) = instantiation_plan(&name, text, None) else {
refused += 1;
continue;
};
planned += 1;
let skeleton = plan.render(&Layout::default());
let probe = format!("module lucisv_probe;\n{skeleton}\nendmodule\n");
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe);
if !diagnostics.is_empty() && unparseable.len() < 10 {
unparseable.push(format!("{}: {name}\n{skeleton}", path.display()));
}
}
}
println!(
"corpus skeletons: {planned} planned, {refused} refused, in {:.2}s",
started.elapsed().as_secs_f64()
);
assert!(planned > 100, "the corpus must hold plenty of modules, got {planned}");
assert!(unparseable.is_empty(), "skeletons that do not parse:\n{}", unparseable.join("\n\n"));
}
/// Every `module <name>` a file declares, read straight off the text — enough
/// for a probe that only wants names to feed the index with.
fn module_names_in(text: &str) -> Vec<String> {
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let mut out = Vec::new();
for item in &tree.items {
if let vlog_parser::ast::ItemKind::Module(module) = &item.kind {
if module.kw == "module" && !module.name.is_empty() {
out.push(module.name.clone());
}
}
}
out
}
#[test]
fn a_wildcard_expanded_in_the_corpus_is_something_the_formatter_accepts() {
// The `.*` sites in the corpus are real ones — testbenches and formal
// wrappers, where the wildcard is written most — and the property that
// matters is the same one the whole formatter lives by: what the
// refactoring writes must format, and formatting it twice must not move
// it. The edit is applied to a *copy* of the text; nothing is written back
// to `corpus/`.
let Some(files) = corpus() else { return };
let sources = read(&files);
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
let config = vlog_formatter::Config::default();
let mut expanded: Vec<String> = Vec::new();
let mut refused: Vec<String> = Vec::new();
for (path, text) in &sources {
if expanded.len() >= 3 {
break;
}
let Some(offset) = wildcard_offset(text) else { continue };
let started = Instant::now();
match expand_wildcard(&sources, path, offset) {
Err(said) => refused.push(format!("{}: {said}", path.display())),
Ok(edit) => {
let edits = edit.edits_for(path);
assert!(!edits.is_empty(), "{} was expanded with no edit", path.display());
let mut copy = text.clone();
for change in edits.iter().rev() {
copy.replace_range(
change.range.start as usize..change.range.end as usize,
&change.new_text,
);
}
assert_ne!(&copy, text, "the expansion changed nothing in {}", path.display());
let once = vlog_formatter::format_source(&copy, &config).unwrap_or_else(|e| {
panic!("the formatter refuses the expansion of {}: {e}\n{copy}", path.display())
});
let twice =
vlog_formatter::format_source(&once, &config).expect("formats a second time");
assert_eq!(once, twice, "formatting {}'s expansion diverges", path.display());
expanded.push(format!(
"{} in {:.2}s ({} edits)",
path.display(),
started.elapsed().as_secs_f64(),
edits.len()
));
}
}
}
println!("corpus `.*` expansions:\n {}", expanded.join("\n "));
if !refused.is_empty() {
println!("refused:\n {}", refused.join("\n "));
}
assert!(expanded.len() >= 3, "three real expansions, got {expanded:?}; refused: {refused:?}");
}
/// The offset of the first `.*` connection a file writes, found the way the
/// plan's census counts them: a `.*` followed by a `,` or a `)`.
fn wildcard_offset(text: &str) -> Option<u32> {
let mut at = 0usize;
while let Some(found) = text.get(at..)?.find(".*") {
let start = at + found;
let rest = text.get(start + 2..)?.trim_start();
if rest.starts_with(',') || rest.starts_with(')') {
return Some(start as u32);
}
at = start + 2;
}
None
}
// ----------------------------------------------------------------------
// TODO §51 — the non-ANSI → ANSI conversion
// ----------------------------------------------------------------------
/// The census the plan asks for: how many modules in the corpus write a
/// Verilog-2001 header, and does every one of them convert?
///
/// **The count is zero, and that is the finding.** common_cells, ibex,
/// opentitan and picorv32 are all written ANSI-style — even picorv32, the
/// oldest of them — so there is no non-ANSI header in 860 files to convert.
/// The assertion is therefore written as a census rather than as a number: it
/// converts *every* one it finds, and stays honest the day the corpus gains
/// one. The real-RTL exercise the conversion does get is
/// `an_ansi_header_written_the_2001_way_converts_back_to_itself` below, which
/// makes its material out of the corpus's own ANSI modules.
#[test]
fn every_non_ansi_module_in_the_corpus_converts() {
let Some(files) = corpus() else { return };
let sources = read(&files);
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
let config = vlog_formatter::Config::default();
let sites: Vec<(PathBuf, String, u32)> = sources
.iter()
.flat_map(|(path, text)| {
non_ansi_modules(text).into_iter().map(move |(name, at)| (path.clone(), name, at))
})
.collect();
println!("corpus non-ANSI module headers: {}", sites.len());
let mut refused: Vec<String> = Vec::new();
for (path, name, at) in &sites {
let Some((_, text)) = sources.iter().find(|(held, _)| held == path) else { continue };
match convert_to_ansi(&sources, path, *at) {
Err(said) => refused.push(format!("{} :: {name}: {said}", path.display())),
Ok(edit) => {
let copy = edited(text, edit.edits_for(path));
let once = vlog_formatter::format_source(&copy, &config).unwrap_or_else(|e| {
panic!("the formatter refuses {} :: {name}: {e}\n{copy}", path.display())
});
let twice =
vlog_formatter::format_source(&once, &config).expect("formats a second time");
assert_eq!(once, twice, "{} :: {name} does not converge", path.display());
assert_eq!(
port_names(&copy, name),
port_names(text, name),
"{} :: {name} changed its port list",
path.display()
);
}
}
}
println!("refused: {}\n {}", refused.len(), refused.join("\n "));
}
/// Real RTL, made non-ANSI and converted back.
///
/// The corpus writes no Verilog-2001 header, so this test manufactures them out
/// of real ones: a corpus module's ANSI port list is rewritten the 2001 way —
/// bare names in the header, each declaration moved into the body verbatim —
/// and `convert_to_ansi` is asked to undo it. Three properties, on real port
/// lists of up to a few dozen ports:
///
/// * the converted file **parses with no diagnostic** and formats, and
/// formatting it twice does not move it;
/// * its module declares the **same ports, in the same order, with the same
/// direction, net, type, signing and dimensions** as the module the corpus
/// ships — [`signature`], which is the whole of what the conversion promises;
/// * and the file's comment count is unchanged.
///
/// Not byte-identity after formatting: the formatter keeps the *author's*
/// column alignment in an ANSI port list, and a refactoring writes edited
/// source rather than formatted source, so the alignment the corpus wrote by
/// hand is not something the conversion undertakes to reproduce.
///
/// Nothing is written back to `corpus/`; every edit is applied to a copy.
#[test]
fn an_ansi_header_written_the_2001_way_converts_back_to_itself() {
let Some(files) = corpus() else { return };
let sources = read(&files);
let config = vlog_formatter::Config::default();
let mut done: Vec<String> = Vec::new();
for (path, text) in &sources {
if done.len() >= 5 {
break;
}
let Some((name, legacy)) = as_non_ansi(text) else { continue };
let mut scratch = sources.clone();
let Some(slot) = scratch.iter_mut().find(|(held, _)| held == path) else { continue };
slot.1 = legacy.clone();
let at = legacy.find(&format!("module {name}")).expect("the header") as u32;
let started = Instant::now();
let edit = match convert_to_ansi(&scratch, path, at) {
Ok(edit) => edit,
Err(said) => {
println!("skipped {} :: {name}: {said}", path.display());
continue;
}
};
let back = edited(&legacy, edit.edits_for(path));
assert!(
vlog_parser::parse_source_tolerant(&back).1.is_empty(),
"{} :: {name} does not parse after the conversion\n{back}",
path.display()
);
assert_eq!(
signature(&back, &name),
signature(text, &name),
"{} :: {name} did not come back to what the corpus ships",
path.display()
);
assert_eq!(
back.matches("//").count() + back.matches("/*").count(),
text.matches("//").count() + text.matches("/*").count(),
"{} :: {name} lost or gained a comment",
path.display()
);
let once = vlog_formatter::format_source(&back, &config).expect("the conversion formats");
let twice = vlog_formatter::format_source(&once, &config).expect("formats a second time");
assert_eq!(once, twice, "{} :: {name} does not converge", path.display());
done.push(format!(
"{} :: {name} in {:.2}s",
path.display(),
started.elapsed().as_secs_f64()
));
}
println!("round-tripped:\n {}", done.join("\n "));
assert!(done.len() >= 5, "five real round trips, got {done:?}");
}
/// Every module in a file whose header is a `PortList::NonAnsi`, with the
/// offset of its name.
fn non_ansi_modules(text: &str) -> Vec<(String, u32)> {
fn walk(items: &[Item], out: &mut Vec<(String, u32)>) {
for item in items {
match &item.kind {
ItemKind::Module(module) => {
if matches!(module.ports, PortList::NonAnsi(_)) {
out.push((module.name.clone(), module.name_span.start));
}
walk(&module.items, out);
}
ItemKind::Package { items, .. } => walk(items, out),
_ => {}
}
}
}
let mut out = Vec::new();
walk(&vlog_parser::parse_source_tolerant(text).0.items, &mut out);
out
}
/// What a module's ANSI port list says, port by port: direction, net type,
/// data type, signing, packed and unpacked dimensions, and the name.
///
/// The whole of what the conversion promises, and the one thing a
/// non-ANSI header and the ANSI header it becomes must agree about.
/// Whitespace is taken out, since a `[7 : 0]` and a `[7:0]` are one range.
fn signature(text: &str, module: &str) -> Vec<String> {
let (tree, _) = vlog_parser::parse_source_tolerant(text);
fn walk<'t>(items: &'t [Item], module: &str) -> Option<&'t vlog_parser::ast::Module> {
for item in items {
match &item.kind {
ItemKind::Module(found) if found.name == module => return Some(found),
ItemKind::Module(found) => {
if let Some(found) = walk(&found.items, module) {
return Some(found);
}
}
ItemKind::Package { items, .. } => {
if let Some(found) = walk(items, module) {
return Some(found);
}
}
_ => {}
}
}
None
}
let tight = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
let dims = |list: &[vlog_parser::ast::Dim]| -> String {
list.iter()
.map(|d| tight(text.get(d.span.start as usize..d.span.end as usize).unwrap_or("")))
.collect()
};
let Some(module) = walk(&tree.items, module) else { return Vec::new() };
let PortList::Ansi(ports) = &module.ports else { return Vec::new() };
ports
.iter()
.filter_map(ListElem::ok)
.map(|p| {
format!(
"{}|{}|{}|{}|{}|{}|{}",
p.dir.clone().unwrap_or_default(),
p.net.clone().unwrap_or_default(),
p.ty.name,
p.ty.signing.clone().unwrap_or_default(),
dims(&p.ty.packed),
dims(&p.unpacked),
p.name
)
})
.collect()
}
/// The port names a module declares, in order.
fn port_names(text: &str, module: &str) -> Vec<String> {
let (tree, _) = vlog_parser::parse_source_tolerant(text);
fn walk(items: &[Item], module: &str) -> Option<Vec<String>> {
for item in items {
match &item.kind {
ItemKind::Module(found) if found.name == module => {
return Some(match &found.ports {
PortList::Ansi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect()
}
PortList::NonAnsi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect()
}
PortList::Empty | PortList::None => Vec::new(),
})
}
ItemKind::Module(found) => {
if let Some(names) = walk(&found.items, module) {
return Some(names);
}
}
ItemKind::Package { items, .. } => {
if let Some(names) = walk(items, module) {
return Some(names);
}
}
_ => {}
}
}
None
}
walk(&tree.items, module).unwrap_or_default()
}
/// One file's first ANSI module rewritten the Verilog-2001 way: the header
/// keeps the names, each declaration moves into the body verbatim.
///
/// `None` for a file with no module the rewrite is faithful for — a port with
/// a default value, a comment inside the list, an interface port or a
/// direction-less continuation port all make the two spellings say different
/// things, and this is a test fixture rather than a second refactoring.
fn as_non_ansi(text: &str) -> Option<(String, String)> {
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
if !diagnostics.is_empty() {
return None;
}
let ItemKind::Module(module) = &tree
.items
.iter()
.find(|item| {
matches!(&item.kind, ItemKind::Module(m)
if m.kw == "module" && m.port_directives.is_empty())
})?
.kind
else {
return None;
};
let PortList::Ansi(ports) = &module.ports else { return None };
let ports: Vec<&vlog_parser::ast::AnsiPort> =
ports.iter().map(ListElem::ok).collect::<Option<Vec<_>>>()?;
let (first, last) = (ports.first()?, ports.last()?);
let list = text.get(first.span.start as usize..last.span.end as usize)?;
if list.contains("//") || list.contains("/*") {
return None;
}
for port in &ports {
let plain = port.dir.is_some()
&& port.default.is_none()
&& port.meta.leading.is_empty()
&& port.meta.trailing.is_none()
&& port.meta.before_sep.is_empty()
&& port.after_dir.is_empty()
&& port.before_name.is_empty()
&& port.ty.extra.is_none()
&& port.ty.virt.is_none();
if !plain {
return None;
}
}
// The header's `;`, which is where the body declarations go.
let semi = last.span.end as usize + text.get(last.span.end as usize..)?.find(';')? + 1;
// Each element is replaced by its own name, so the list keeps the layout
// the file wrote — the conversion is asked to put the declarations back,
// not to reflow anything.
let mut out = String::new();
let mut cursor = 0usize;
for port in &ports {
out.push_str(text.get(cursor..port.span.start as usize)?);
out.push_str(&port.name);
cursor = port.span.end as usize;
}
out.push_str(text.get(cursor..semi)?);
for port in &ports {
out.push_str("\n ");
out.push_str(text.get(port.span.start as usize..port.span.end as usize)?);
out.push(';');
}
out.push_str(text.get(semi..)?);
Some((module.name.clone(), out))
}
/// A copy of `text` with one file's edits applied.
fn edited(text: &str, edits: &[vlog_refactor::TextEdit]) -> String {
let mut copy = text.to_string();
for change in edits.iter().rev() {
copy.replace_range(
change.range.start as usize..change.range.end as usize,
&change.new_text,
);
}
copy
}