TODO §53.2 (docs/features/extract-inline-module), the fifth §8
refactoring; extract → inline round-trips byte-equal after formatting.
`vlog_refactor::inline_module` (inline/{mod,site,source,render}.rs):
every symbol bound in `S`'s module scope is classified once — a port
becomes the name or literal connected to it, anything else `S` declares
at module scope is prefixed `u_S_` only when `M`'s file already spells
one of them; parameters become `localparam`s with the override or
default; the body is copied verbatim except name spans, with `.name`
shorthand connections expanded when their signal is renamed. Refusals:
`.*`, positional lists, expression connections, an unconnected port, an
output into a literal, any hierarchical reference to `u_S` in the handed
files, `S` unknown/twice/in `M`'s own file, interface/`inout`/unpacked/
non-ANSI ports, `initial`/`final`, macros, directives, any `generate`, a
differing `timescale`, collisions prefixing cannot resolve. Server:
`refactor.inline` lazy action, `lucisv.inlineModule`.
Verifier: `Moving` gains `Origin::{Moved, Copied}` — a copied region's
pieces join the transit under rule 0, "a copied file appears in no
edit"; eight attack pairs through the production entry; QA's neutering
map shows every rule load-bearing. QA's MEDIUMs filed: topo §2.9-32
(same blind spot) and §2.9-33 (`module_sources` lacks a transitive-
instantiators rung).
Trials: corpus 5 inlined / 9 refused, opentitan 5 / 56, the lint census
0 → 0 on every pair. 0 of 854 corpus files differ from 0.48.x.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
1184 lines
48 KiB
Rust
1184 lines
48 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, extract_module, instantiation_plan,
|
|
module_definition, port_actions, prepare_rename, rename, Home, 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!(©, text, "the expansion changed nothing in {}", path.display());
|
|
let once = vlog_formatter::format_source(©, &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(©, &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(©, 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
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// TODO §52 — organize imports
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// The census the plan asks for: every scope in the corpus writing two or
|
|
/// more `import` items, organized in a copy, with the counts reported.
|
|
///
|
|
/// Four properties per organized scope, and none of them a percentage. The
|
|
/// result **parses** (no diagnostic the original did not have). It
|
|
/// **formats**, and formatting it twice does not move it. Nothing in the file
|
|
/// stops resolving — the count of references that resolve to *nothing at all*
|
|
/// may not grow, which is the census-sized shadow of the resolution identity
|
|
/// `verify_splice` already proved inside the engine. And organizing the result
|
|
/// again finds nothing to do, which is idempotency.
|
|
///
|
|
/// A refusal is not a failure: it is the answer for a scope lucisv cannot
|
|
/// judge, and the reasons are counted and printed so the ratio is visible.
|
|
#[test]
|
|
fn every_scope_with_two_imports_in_the_corpus_organizes_or_refuses() {
|
|
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 scopes = 0usize;
|
|
let mut organized = 0usize;
|
|
let mut removed_total = 0usize;
|
|
let mut sorted_total = 0usize;
|
|
let mut refusals: Vec<(&'static str, usize)> = Vec::new();
|
|
let started = Instant::now();
|
|
for (path, text) in &sources {
|
|
for offset in import_run_offsets(text) {
|
|
scopes += 1;
|
|
match vlog_refactor::organize_counts(&sources, path, offset) {
|
|
Err(said) => {
|
|
let reason = refusal_kind(&said);
|
|
match refusals.iter_mut().find(|(held, _)| *held == reason) {
|
|
Some((_, count)) => *count += 1,
|
|
None => refusals.push((reason, 1)),
|
|
}
|
|
}
|
|
Ok((edit, removed, sorted)) => {
|
|
organized += 1;
|
|
removed_total += removed;
|
|
sorted_total += sorted;
|
|
let copy = edited(text, edit.edits_for(path));
|
|
assert_ne!(
|
|
©,
|
|
text,
|
|
"an organize that changed nothing in {}",
|
|
path.display()
|
|
);
|
|
let before = vlog_parser::parse_source_tolerant(text).1.len();
|
|
let after = vlog_parser::parse_source_tolerant(©).1.len();
|
|
assert!(after <= before, "{} stopped parsing", path.display());
|
|
assert!(
|
|
unresolved(©) <= unresolved(text),
|
|
"{} lost a resolution",
|
|
path.display()
|
|
);
|
|
if let Ok(once) = vlog_formatter::format_source(text, &config) {
|
|
let _ = once;
|
|
let once =
|
|
vlog_formatter::format_source(©, &config).unwrap_or_else(|e| {
|
|
panic!(
|
|
"the formatter refuses the organize of {}: {e}",
|
|
path.display()
|
|
)
|
|
});
|
|
let twice = vlog_formatter::format_source(&once, &config)
|
|
.expect("formats a second time");
|
|
assert_eq!(
|
|
once,
|
|
twice,
|
|
"formatting {}'s organize diverges",
|
|
path.display()
|
|
);
|
|
}
|
|
// Idempotency: the same cursor, over the edited copy.
|
|
let mut again = sources.clone();
|
|
if let Some(entry) = again.iter_mut().find(|(p, _)| p == path) {
|
|
entry.1 = copy.clone();
|
|
}
|
|
let repeat = vlog_refactor::organize_imports(&again, path, offset);
|
|
assert!(repeat.is_err(), "{} organizes twice: {repeat:?}", path.display());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
refusals.sort_by_key(|(reason, _)| *reason);
|
|
println!(
|
|
"corpus organize-imports: {scopes} scopes with 2+ imports, {organized} organized \
|
|
({removed_total} imports removed, {sorted_total} sorted) in {:.2}s\n refused: {refusals:?}",
|
|
started.elapsed().as_secs_f64()
|
|
);
|
|
assert_eq!(
|
|
scopes,
|
|
organized + refusals.iter().map(|(_, n)| n).sum::<usize>(),
|
|
"every scope is either organized or refused"
|
|
);
|
|
}
|
|
|
|
/// How many of a file's references resolve to nothing at all.
|
|
fn unresolved(text: &str) -> usize {
|
|
let semantics = vlog_semantic::analyze(&vlog_parser::parse_source_tolerant(text).0, text);
|
|
semantics
|
|
.references()
|
|
.iter()
|
|
.filter(|r| matches!(r.resolution, vlog_semantic::Resolution::NotFound))
|
|
.count()
|
|
}
|
|
|
|
/// One offset per scope of the file that writes two or more `import` items:
|
|
/// the first import's package name.
|
|
fn import_run_offsets(text: &str) -> Vec<u32> {
|
|
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
|
if !diagnostics.is_empty() {
|
|
return Vec::new();
|
|
}
|
|
let semantics = vlog_semantic::analyze(&tree, text);
|
|
vlog_semantic::import_scopes(&tree, &semantics)
|
|
.into_iter()
|
|
.filter_map(|here| {
|
|
let scope = semantics.scope(here.scope)?;
|
|
(scope.imports.len() >= 2).then(|| scope.imports.first().map(|i| i.name_span.start))?
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Which refusal a sentence is, for the census's histogram.
|
|
fn refusal_kind(said: &str) -> &'static str {
|
|
const KINDS: [(&str, &str); 7] = [
|
|
("does not preprocess", "macro or directive"),
|
|
("nothing lucisv can see declares", "unknown package"),
|
|
("more than once", "package declared twice"),
|
|
("declared in another file", "base class elsewhere"),
|
|
("does not parse", "parse error"),
|
|
("one per line", "two imports on a line"),
|
|
("already sorted", "nothing to do"),
|
|
];
|
|
KINDS.iter().find(|(needle, _)| said.contains(needle)).map_or("other", |(_, kind)| *kind)
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// extracting a module out of real RTL (TODO §53.1)
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Where the extraction trial reads its design from. `corpus/` by default;
|
|
/// `LUCISV_EXTRACT_ROOT` points it at a **copy** of another tree — which is how
|
|
/// the opentitan trial is run without touching that checkout.
|
|
fn extract_root() -> Option<Vec<PathBuf>> {
|
|
let root = match std::env::var("LUCISV_EXTRACT_ROOT") {
|
|
Ok(path) => PathBuf::from(path),
|
|
Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"),
|
|
};
|
|
if !root.is_dir() {
|
|
eprintln!("{} not checked out — skipping", root.display());
|
|
return None;
|
|
}
|
|
let mut files = Vec::new();
|
|
collect(&root, &mut files);
|
|
files.sort();
|
|
Some(files)
|
|
}
|
|
|
|
/// The first `always` block or continuous assignment of each module, as a
|
|
/// selection an extraction could be asked about.
|
|
fn regions(text: &str) -> Vec<(String, u32, u32)> {
|
|
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
|
if !diagnostics.is_empty() {
|
|
return Vec::new();
|
|
}
|
|
let mut out = Vec::new();
|
|
for item in &tree.items {
|
|
let ItemKind::Module(module) = &item.kind else { continue };
|
|
let found = module.items.iter().find(|item| {
|
|
matches!(item.kind, ItemKind::Always { .. } | ItemKind::ContAssign(_))
|
|
&& item.meta.leading.is_empty()
|
|
});
|
|
if let Some(region) = found {
|
|
out.push((module.name.clone(), region.span.start, region.span.end));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// How many of a design's names fail to resolve. The census the trial holds
|
|
/// fixed: an extraction moves items and writes a header, so the number of
|
|
/// names nothing binds may not grow.
|
|
fn unresolved_over(sources: &[(PathBuf, String)]) -> usize {
|
|
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
|
let mut out = 0usize;
|
|
for (_, text) in sources {
|
|
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
|
let semantics = vlog_semantic::analyze(&tree, text);
|
|
let external = vlog_semantic::resolve_external(&semantics, &index);
|
|
for (n, reference) in semantics.references().iter().enumerate() {
|
|
if reference.resolved().is_some() {
|
|
continue;
|
|
}
|
|
let id = vlog_semantic::ReferenceId(n as u32);
|
|
if !matches!(external.get(id), Some(vlog_semantic::ExternalTarget::Resolved(_))) {
|
|
out += 1;
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
#[test]
|
|
fn five_regions_of_real_rtl_extract_into_modules_that_parse_format_and_converge() {
|
|
let Some(files) = extract_root() else { return };
|
|
let sources = read(&files);
|
|
assert!(!sources.is_empty(), "the tree exists but holds no Verilog");
|
|
let config = vlog_formatter::Config::default();
|
|
let before = unresolved_over(&sources);
|
|
|
|
let started = Instant::now();
|
|
let mut done: Vec<String> = Vec::new();
|
|
let mut refusals = 0usize;
|
|
'files: for (path, text) in &sources {
|
|
for (module, start, end) in regions(text) {
|
|
if done.len() == 5 {
|
|
break 'files;
|
|
}
|
|
let name = format!("{module}_lucisv_extracted");
|
|
let edit = match extract_module(&sources, path, start, end, &name, Home::NewFile) {
|
|
Ok(edit) => edit,
|
|
// Printed, not only counted: which regions the trial refuses
|
|
// and why is the other half of a reproducible run (2026-09-06
|
|
// rework — the opentitan numbers in the feature README are
|
|
// this list).
|
|
Err(said) => {
|
|
refusals += 1;
|
|
println!(" refused {} `{module}`: {said}", path.display());
|
|
continue;
|
|
}
|
|
};
|
|
|
|
// The two halves, as the editor would write them.
|
|
let mut after: Vec<(PathBuf, String)> = sources.clone();
|
|
for created in &edit.created {
|
|
after.push((created.clone(), String::new()));
|
|
}
|
|
for (file, edits) in &edit.edits {
|
|
let Some(slot) = after.iter_mut().find(|(held, _)| held == file) else {
|
|
panic!("{} edits {} which is not in scope", name, file.display())
|
|
};
|
|
let mut out = slot.1.clone();
|
|
for one in edits.iter().rev() {
|
|
out.replace_range(
|
|
one.range.start as usize..one.range.end as usize,
|
|
&one.new_text,
|
|
);
|
|
}
|
|
slot.1 = out;
|
|
}
|
|
|
|
// Both files parse, format, and formatting them again is a no-op.
|
|
for (file, edits) in &edit.edits {
|
|
let text = &after.iter().find(|(held, _)| held == file).expect("edited").1;
|
|
let (_, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
|
assert!(
|
|
diagnostics.is_empty(),
|
|
"{name}: {} no longer parses: {diagnostics:?}\n{text}",
|
|
file.display()
|
|
);
|
|
let once = vlog_formatter::format_source(text, &config).unwrap_or_else(|e| {
|
|
panic!("{name}: the formatter refuses {}: {e}", file.display())
|
|
});
|
|
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
|
assert_eq!(once, twice, "{name}: {} does not converge", file.display());
|
|
let _ = edits;
|
|
}
|
|
|
|
// The census over the whole design, the two files together.
|
|
let now = unresolved_over(&after);
|
|
assert!(now <= before, "{name}: {} names went unresolved, up from {before}", now);
|
|
// Printed, not only asserted: the trial's numbers are what the
|
|
// feature README records, and a census that merely *held* is the
|
|
// evidence the extraction was honest (2026-09-06 rework).
|
|
println!(" {name} in {}: census {before} -> {now}", path.display());
|
|
done.push(name);
|
|
}
|
|
}
|
|
println!(
|
|
"extract over {} files: {} regions extracted, {} refused, in {:.2}s",
|
|
sources.len(),
|
|
done.len(),
|
|
refusals,
|
|
started.elapsed().as_secs_f64()
|
|
);
|
|
assert_eq!(done.len(), 5, "five real regions must extract: {done:?}");
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// §53.2 inline module
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// The tree the inline trial runs over: `corpus/` by default, or whatever
|
|
/// `LUCISV_INLINE_ROOT` names — a scratch copy of opentitan, for the trial the
|
|
/// feature README records.
|
|
fn inline_root() -> Option<Vec<PathBuf>> {
|
|
let root = match std::env::var("LUCISV_INLINE_ROOT") {
|
|
Ok(path) => PathBuf::from(path),
|
|
Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"),
|
|
};
|
|
if !root.is_dir() {
|
|
eprintln!("{} not checked out — skipping", root.display());
|
|
return None;
|
|
}
|
|
let mut files = Vec::new();
|
|
collect(&root, &mut files);
|
|
files.sort();
|
|
Some(files)
|
|
}
|
|
|
|
/// Every instantiation written directly in a module's body, as an offset an
|
|
/// inline could be asked about.
|
|
fn instantiations(text: &str) -> Vec<(String, String, u32)> {
|
|
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
|
if !diagnostics.is_empty() {
|
|
return Vec::new();
|
|
}
|
|
let mut out = Vec::new();
|
|
for item in &tree.items {
|
|
let ItemKind::Module(module) = &item.kind else { continue };
|
|
for item in &module.items {
|
|
if let ItemKind::Instantiation(inst) = &item.kind {
|
|
out.push((module.name.clone(), inst.module.clone(), item.span.start));
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Five real instantiations, inlined in memory: each result parses, formats,
|
|
/// converges, and leaves the design's census of unbound names where it was.
|
|
///
|
|
/// With `LUCISV_INLINE_OUT` set, each case's two files are also written out
|
|
/// twice — `case_N/before/` and `case_N/after/` — which is what the
|
|
/// `lucisv check --select unused-signal,undriven-net` half of the trial reads.
|
|
#[test]
|
|
fn five_instantiations_of_real_rtl_inline_and_the_result_parses_formats_and_converges() {
|
|
let Some(files) = inline_root() else { return };
|
|
let sources = read(&files);
|
|
assert!(!sources.is_empty(), "the tree exists but holds no Verilog");
|
|
let config = vlog_formatter::Config::default();
|
|
let before = census(&sources);
|
|
let out_dir = std::env::var("LUCISV_INLINE_OUT").ok().map(PathBuf::from);
|
|
|
|
let started = Instant::now();
|
|
let mut done: Vec<String> = Vec::new();
|
|
let mut refusals = 0usize;
|
|
'files: for (path, text) in &sources {
|
|
for (host, target, at) in instantiations(text) {
|
|
if done.len() == 5 {
|
|
break 'files;
|
|
}
|
|
let edit = match vlog_refactor::inline_module(&sources, path, at) {
|
|
Ok(edit) => edit,
|
|
// Printed, not only counted: which instantiations the trial
|
|
// refuses and why is the other half of a reproducible run.
|
|
Err(said) => {
|
|
refusals += 1;
|
|
println!(" refused `{target}` in `{host}`: {said}");
|
|
continue;
|
|
}
|
|
};
|
|
let mut after: Vec<(PathBuf, String)> = sources.clone();
|
|
for (file, edits) in &edit.edits {
|
|
let Some(slot) = after.iter_mut().find(|(held, _)| held == file) else {
|
|
panic!("the inline edits {} which is not in scope", file.display())
|
|
};
|
|
let mut written = slot.1.clone();
|
|
for one in edits.iter().rev() {
|
|
written.replace_range(
|
|
one.range.start as usize..one.range.end as usize,
|
|
&one.new_text,
|
|
);
|
|
}
|
|
slot.1 = written;
|
|
}
|
|
|
|
let edited = &after.iter().find(|(held, _)| held == path).expect("edited").1;
|
|
let (_, diagnostics) = vlog_parser::parse_source_tolerant(edited);
|
|
assert!(
|
|
diagnostics.is_empty(),
|
|
"inlining `{target}` into `{host}` leaves {} unparseable: {diagnostics:?}\n{edited}",
|
|
path.display()
|
|
);
|
|
let once = vlog_formatter::format_source(edited, &config)
|
|
.unwrap_or_else(|e| panic!("the formatter refuses {}: {e}", path.display()));
|
|
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
|
assert_eq!(once, twice, "{} does not converge", path.display());
|
|
|
|
// Written before the census is asserted, so a run that fails
|
|
// leaves the pair on disk to look at.
|
|
if let Some(dir) = &out_dir {
|
|
write_case(dir, done.len(), path, &target, &sources, &after);
|
|
}
|
|
let now = census(&after);
|
|
let gained = borne(&before, &now, path);
|
|
println!(
|
|
" inlined `{target}` into `{host}` ({}): {} name(s) newly unbound, all of them `{target}`'s own",
|
|
path.display(),
|
|
gained.len()
|
|
);
|
|
done.push(format!("{target} in {host}"));
|
|
}
|
|
}
|
|
println!(
|
|
"inline over {} files: {} instantiations inlined, {} refused, in {:.2}s",
|
|
sources.len(),
|
|
done.len(),
|
|
refusals,
|
|
started.elapsed().as_secs_f64()
|
|
);
|
|
assert_eq!(done.len(), 5, "five real instantiations must inline: {done:?}");
|
|
}
|
|
|
|
/// One trial case on disk: the instantiating file and the inlined module's
|
|
/// own, before the inline and after it, so `lucisv check` can be run over
|
|
/// each pair.
|
|
fn write_case(
|
|
dir: &Path,
|
|
n: usize,
|
|
host: &Path,
|
|
target: &str,
|
|
before: &[(PathBuf, String)],
|
|
after: &[(PathBuf, String)],
|
|
) {
|
|
let declaring = before
|
|
.iter()
|
|
.find(|(path, text)| {
|
|
path != host && text.contains(&format!("module {target}")) && {
|
|
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
|
tree.items
|
|
.iter()
|
|
.any(|item| matches!(&item.kind, ItemKind::Module(m) if m.name == target))
|
|
}
|
|
})
|
|
.map(|(path, _)| path.clone());
|
|
for (label, sources) in [("before", before), ("after", after)] {
|
|
let out = dir.join(format!("case_{n}")).join(label);
|
|
if fs::create_dir_all(&out).is_err() {
|
|
return;
|
|
}
|
|
for path in [Some(host.to_path_buf()), declaring.clone()].into_iter().flatten() {
|
|
let Some((_, text)) = sources.iter().find(|(held, _)| *held == path) else { continue };
|
|
let Some(name) = path.file_name() else { continue };
|
|
let _ = fs::write(out.join(name), text);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Every name a design fails to bind, per file, with its duplicates — the
|
|
/// census an inline is held to.
|
|
///
|
|
/// An inline **copies**, so the whole-design count is the wrong number: a name
|
|
/// `S` already could not resolve is one `M` now cannot resolve either, and the
|
|
/// total legitimately grows by one per copy. What must hold instead is that
|
|
/// every name the edited file newly fails to bind is one the *copied* module's
|
|
/// own file already failed to bind — see [`borne`].
|
|
fn census(sources: &[(PathBuf, String)]) -> Vec<(PathBuf, Vec<String>)> {
|
|
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
|
let mut out = Vec::new();
|
|
for (path, text) in sources {
|
|
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
|
let semantics = vlog_semantic::analyze(&tree, text);
|
|
let external = vlog_semantic::resolve_external(&semantics, &index);
|
|
let mut names = Vec::new();
|
|
for (n, reference) in semantics.references().iter().enumerate() {
|
|
if reference.resolved().is_some() {
|
|
continue;
|
|
}
|
|
let id = vlog_semantic::ReferenceId(n as u32);
|
|
if !matches!(external.get(id), Some(vlog_semantic::ExternalTarget::Resolved(_))) {
|
|
names.push(reference.name.clone());
|
|
}
|
|
}
|
|
names.sort();
|
|
out.push((path.clone(), names));
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The names `edited` newly fails to bind, asserting on the way that no other
|
|
/// file's census moved at all and that every new name is one some *other*
|
|
/// file already could not bind — which for an inline is the file `S` was
|
|
/// copied out of.
|
|
fn borne(
|
|
before: &[(PathBuf, Vec<String>)],
|
|
after: &[(PathBuf, Vec<String>)],
|
|
edited: &Path,
|
|
) -> Vec<String> {
|
|
let mut elsewhere: Vec<String> = Vec::new();
|
|
let mut gained: Vec<String> = Vec::new();
|
|
for (path, now) in after {
|
|
let was = before
|
|
.iter()
|
|
.find(|(held, _)| held == path)
|
|
.map_or_else(Vec::new, |(_, names)| names.clone());
|
|
if path != edited {
|
|
assert_eq!(&was, now, "{} was not edited, and its census moved", path.display());
|
|
elsewhere.extend(now.iter().cloned());
|
|
continue;
|
|
}
|
|
let mut left = was.clone();
|
|
for name in now {
|
|
match left.iter().position(|held| held == name) {
|
|
Some(at) => {
|
|
left.remove(at);
|
|
}
|
|
None => gained.push(name.clone()),
|
|
}
|
|
}
|
|
}
|
|
for name in &gained {
|
|
assert!(
|
|
elsewhere.contains(name),
|
|
"`{name}` became unbound in {} and no other file leaves it unbound either",
|
|
edited.display()
|
|
);
|
|
}
|
|
gained
|
|
}
|