//! 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_refactor::{ add_port, instantiation_plan, module_definition, port_actions, prepare_rename, rename, Layout, ModuleRef, }; use vlog_semantic::WorkspaceIndex; fn corpus() -> Option> { 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) { 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 = 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 ` 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 { 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 }