From 532a64546c5e59e6072a6901834adebabf09cf31 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 26 Nov 2026 17:18:59 -0800 Subject: [PATCH] Round 8: semantic and refactor edge cases (#12, #31, #32, L-5/L-6/L-10) DPI-export names are semantic references. verify_move reconstructs the result independently and checks equation 3 per edit, with 16 attack tests. Interface generate-block members are reachable through a port or virtual interface; bind to a bare instance name is found; nested struct members get their container key. Escaped identifiers join FileFacts::words (FACTS_FORMAT 23); generate-scoped bind shorthand resolves. Scope reuses index_order. Files topo #68-#70. Co-Authored-By: Claude Mythos 5.2 --- crates/lucisv_mcp/tests/qa_m7.rs | 7 +- crates/lucisv_server/src/candidates.rs | 30 +- .../src/check/in_place_attacks.rs | 346 ++++++++++++++ crates/vlog_refactor/src/check/ledger.rs | 4 + .../vlog_refactor/src/check/ledger/windows.rs | 132 ++++++ crates/vlog_refactor/src/check/mod.rs | 31 +- .../vlog_refactor/src/rename/connections.rs | 56 ++- crates/vlog_refactor/src/rename/scoped.rs | 43 +- crates/vlog_refactor/src/scope.rs | 15 +- .../vlog_refactor/tests/qa_rename_implicit.rs | 24 +- .../vlog_refactor/tests/qa_warning_scope.rs | 44 ++ .../vlog_refactor/tests/rename_dpi_export.rs | 71 +++ crates/vlog_semantic/src/bind/item.rs | 9 +- crates/vlog_semantic/src/facts.rs | 9 +- crates/vlog_semantic/src/lib.rs | 16 +- crates/vlog_semantic/src/words.rs | 29 +- .../vlog_semantic/src/workspace/hierarchy.rs | 54 ++- crates/vlog_semantic/src/workspace/index.rs | 12 +- crates/vlog_semantic/src/workspace/record.rs | 13 +- crates/vlog_semantic/tests/semantic_r8.rs | 257 ++++++++++ docs/features/semantic-refactor-r8/README.md | 444 ++++++++++++++++++ docs/repository-analysis.md | 7 +- .../content/docs/reference/architecture.md | 5 +- .../src/content/docs/reference/rust-api.md | 10 +- docs/topo.md | 23 +- 25 files changed, 1596 insertions(+), 95 deletions(-) create mode 100644 crates/vlog_refactor/src/check/in_place_attacks.rs create mode 100644 crates/vlog_refactor/src/check/ledger/windows.rs create mode 100644 crates/vlog_refactor/tests/rename_dpi_export.rs create mode 100644 crates/vlog_semantic/tests/semantic_r8.rs create mode 100644 docs/features/semantic-refactor-r8/README.md diff --git a/crates/lucisv_mcp/tests/qa_m7.rs b/crates/lucisv_mcp/tests/qa_m7.rs index 98aaa22..6053ebb 100644 --- a/crates/lucisv_mcp/tests/qa_m7.rs +++ b/crates/lucisv_mcp/tests/qa_m7.rs @@ -807,10 +807,11 @@ fn qa_rework_an_escaped_net_is_still_found_through_the_index() { } #[test] -#[ignore = "QA re-check finding R2"] fn qa_rework_an_escaped_local_outline_lists_is_found() { - // The word census holds identifier-shaped words only, so `declared.rs` - // never opens a file for an escaped name the index does not record. + // QA re-check finding R2, closed in Round 8: the word census holds an + // escaped identifier as its token spells it (`FACTS_FORMAT` 23), so + // `declared.rs` opens the file for an escaped name the index does not + // record as a unit or member. let text_g = "module g (input logic clk, output logic o);\n function automatic logic fn(input logic x);\n logic \\loc.v ;\n \\loc.v = x;\n return \\loc.v ;\n endfunction\n assign o = fn(clk);\nendmodule\n"; let tree = Tree::with(&[("rtl/g.sv", text_g)]); assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3")); diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index eed6cb9..4fb86ae 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -148,6 +148,7 @@ impl Candidates { let mut out = Candidates::default(); out.take_index_tables(index); for (path, words) in words { + let words = insertable(words); for word in &words { *out.word_files.entry(word.clone()).or_default() += 1; } @@ -311,7 +312,7 @@ impl Candidates { /// Make `words` this file's words, adjusting the workspace-wide table. fn set_words(&mut self, path: &Path, words: Vec) { let mut touched = HashMap::new(); - self.count_words(path, words, &mut touched); + self.count_words(path, insertable(words), &mut touched); self.merge_words(touched); } @@ -531,6 +532,16 @@ impl Candidates { } } +/// A file's census without its escaped identifiers. Since `FACTS_FORMAT` 23 +/// the census holds `\\my.sig` as written, which is what every pre-filter that +/// reads it wants; completion is the one reader that *inserts* a word, and an +/// escaped identifier inserted without its terminating space runs into +/// whatever follows it, so this table never offers one. +fn insertable(mut words: Vec) -> Vec { + words.retain(|word| !word.starts_with('\\')); + words +} + /// Keep the best `cap` hits, in order, and throw the rest away. /// /// Bounded rather than sorted whole, because the two are not the same price at @@ -977,6 +988,23 @@ mod tests { assert!(!names.contains(&"string_only_name"), "a string is not code: {names:?}"); } + /// The census holds `\\esc.sig` since `FACTS_FORMAT` 23; completion, the + /// one reader that inserts a word, still never offers it — neither from a + /// whole build nor from one file's words handed over afterwards. + #[test] + fn an_escaped_identifier_is_never_offered_as_a_word() { + let text = "module a;\n logic \\esc.sig ;\n logic plain;\nendmodule\n"; + assert!(words_in(text).contains(&"\\esc.sig".to_string()), "the census holds it"); + let mut candidates = built(&[("/rtl/a.sv", text)]); + let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect(); + assert!( + names.contains(&"plain") && !names.iter().any(|w| w.starts_with('\\')), + "{names:?}" + ); + candidates.set_file_words(Path::new("/rtl/b.sv"), words_in(text)); + assert!(!candidates.words("").iter().any(|w| w.starts_with('\\'))); + } + /// An interface is instantiated exactly as a module is, so it belongs in /// the module table the completion tier and `has_module` read /// (`docs/features/interface-semantics/README.md`). diff --git a/crates/vlog_refactor/src/check/in_place_attacks.rs b/crates/vlog_refactor/src/check/in_place_attacks.rs new file mode 100644 index 0000000..13c8edc --- /dev/null +++ b/crates/vlog_refactor/src/check/in_place_attacks.rs @@ -0,0 +1,346 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Attack pairs for equation 3 against an independent `after` +//! (`docs/topo.md` §2.9-32, CLAUDE.md invariant 4; `ledger/windows.rs`). +//! +//! Every test goes through the production [`verify_move`] with a real +//! [`Scope`] and raw [`TextEdit`]s. The first is extract-module QA's Finding +//! QA-1 pair, which the verifier accepted before this round: each edit is +//! well-formed, every count balances, and the only thing wrong is *where* a +//! never-dropped piece ended up. The rest pin what must still pass, so the +//! new rule is proven to tighten and not to refuse a real plan. + +use std::path::{Path, PathBuf}; + +use vlog_parser::span::TextRange; + +use super::{verify_move, verify_splice, Moving}; +use crate::rename::Scope; +use crate::{apply, Home, TextEdit}; + +/// A module whose region holds a comment the extraction carries, with a second, +/// unrelated comment outside the region and a line it could be moved onto. +const SOURCE: &str = "module m (\n input logic a,\n input logic b,\n output logic q,\n output logic r\n);\n logic s;\n assign s = a & b; // the and\n assign q = s; // stray\n assign r = a;\nendmodule\n"; + +const WHAT: &str = "extracting `sum` out of `m`"; + +/// The extraction the engine really makes of `assign s = a & b; // the and`: +/// `m.sv`'s replacement edits, `sum.sv`'s insertion and the region. +fn extraction() -> (Vec, Vec, TextRange) { + extraction_of(SOURCE) +} + +/// [`extraction`] of a variant of [`SOURCE`] that keeps its region. +fn extraction_of(source: &str) -> (Vec, Vec, TextRange) { + let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())]; + let start = source.find("assign s").expect("region start") as u32; + let end = source.find("// the and").expect("region end") as u32 + 10; + let edit = + crate::extract_module(&files, Path::new("/rtl/m.sv"), start, end, "sum", Home::NewFile) + .expect("the extraction the attacks corrupt"); + let m = edit.edits_for(&PathBuf::from("/rtl/m.sv")).to_vec(); + let n = edit.edits_for(&PathBuf::from("/rtl/sum.sv")).to_vec(); + let region = m.first().expect("the replacement").range; + (m, n, region) +} + +/// Verify a plan as the engine does, `m.sv` the source and `sum.sv` the file +/// that receives. +fn verified(m_edits: &[TextEdit], n_edits: &[TextEdit], region: TextRange) -> Result<(), String> { + verified_in(SOURCE, "", m_edits, n_edits, region) +} + +/// [`verified`] over `source` for `m.sv` and `sum` for `sum.sv`. +fn verified_in( + source: &str, + sum: &str, + m_edits: &[TextEdit], + n_edits: &[TextEdit], + region: TextRange, +) -> Result<(), String> { + let files = vec![ + (PathBuf::from("/rtl/m.sv"), source.to_string()), + (PathBuf::from("/rtl/sum.sv"), sum.to_string()), + ]; + let mut scope = Scope::build(&files); + let at = |name: &str| scope.index_of(Path::new(name)).expect(name); + let (m, n) = (at("/rtl/m.sv"), at("/rtl/sum.sv")); + let edits = vec![(m, m_edits.to_vec()), (n, n_edits.to_vec())]; + let moving = vec![Moving::source(m, region), Moving::destination(n)]; + verify_move(&mut scope, &edits, &["m", "sum"], WHAT, &moving) +} + +/// An edit replacing the first `old` in `text` after `from` with `new`. +fn replacing(text: &str, from: &str, old: &str, new: &str) -> TextEdit { + let base = text.find(from).expect("anchor"); + let at = (base + text[base..].find(old).expect("text to replace")) as u32; + TextEdit { range: TextRange::new(at, at + old.len() as u32), new_text: new.to_string() } +} + +/// An insertion of `new` right after the first `after` in `text`. +fn inserting(text: &str, after: &str, new: &str) -> TextEdit { + let at = (text.find(after).expect("anchor") + after.len()) as u32; + TextEdit { range: TextRange::empty(at), new_text: new.to_string() } +} + +/// The extraction's own edits to `m.sv` plus `more`, in order. +fn with(mut m: Vec, more: Vec) -> Vec { + m.extend(more); + m.sort_by_key(|edit| (edit.range.start, edit.range.end)); + m +} + +/// `// stray` deleted from `assign q = s;` and written back onto +/// `assign r = a;`, as two well-formed edits, beside the real extraction. +fn relocated(mut m: Vec) -> Vec { + let stray = SOURCE.find(" // stray").expect("stray") as u32; + let r_end = SOURCE.find("assign r = a;").expect("line r") as u32 + 13; + m.push(TextEdit { range: TextRange::new(stray, stray + 9), new_text: String::new() }); + m.push(TextEdit { range: TextRange::empty(r_end), new_text: " // stray".to_string() }); + m.sort_by_key(|edit| edit.range.start); + m +} + +#[test] +fn the_real_extraction_still_verifies() { + let (m, n, region) = extraction(); + assert_eq!(verified(&m, &n, region), Ok(())); +} + +#[test] +fn a_same_file_relocation_written_as_two_well_formed_edits_is_rejected() { + // Finding QA-1. Every count balances — one `// stray` before, one after, + // one deleted, one written — and the positional comparison agrees, because + // it re-walks the very edits it is checking. Only the edit that deleted + // the comment can say it was not written back where it was. + let (m, n, region) = extraction(); + let m = relocated(m); + let after = apply(SOURCE, &m); + assert_eq!(after.matches("// stray").count(), 1, "the counts balance"); + assert!(after.contains("assign r = a; // stray"), "and the comment moved: {after}"); + let message = verified(&m, &n, region).expect_err("a relocated comment is a refusal"); + assert!(message.contains("`// stray`"), "{message}"); + assert!(message.contains("not write it back where it was"), "{message}"); + assert!(message.contains("m.sv"), "{message}"); +} + +#[test] +fn a_relocation_inside_the_destination_is_rejected_too() { + // The receiving file's surplus is the transit, but what its own edit + // deletes still has to come back in that edit. `sum.sv` here already holds + // a comment, which a second edit moves to the end. + let (m, mut n, region) = extraction(); + let held = "// held\n"; + let files = vec![ + (PathBuf::from("/rtl/m.sv"), SOURCE.to_string()), + (PathBuf::from("/rtl/sum.sv"), held.to_string()), + ]; + for edit in &mut n { + edit.range = TextRange::new(0, held.len() as u32); + } + let end = held.len() as u32; + n.push(TextEdit { range: TextRange::empty(end), new_text: held.to_string() }); + let mut scope = Scope::build(&files); + let at = |name: &str| scope.index_of(Path::new(name)).expect(name); + let (mi, ni) = (at("/rtl/m.sv"), at("/rtl/sum.sv")); + let edits = vec![(mi, m), (ni, n)]; + let moving = vec![Moving::source(mi, region), Moving::destination(ni)]; + let message = verify_move(&mut scope, &edits, &["m", "sum"], WHAT, &moving) + .expect_err("a relocated comment in the destination is a refusal"); + assert!(message.contains("`// held`"), "{message}"); + assert!(message.contains("sum.sv"), "{message}"); +} + +#[test] +fn an_edit_that_writes_back_the_comment_it_deletes_still_verifies() { + // The control for the pair above: the same deletion, written back by the + // edit that made it, is an edit around the comment and nothing else. + let (mut m, n, region) = extraction(); + let line = SOURCE.find("assign q = s; // stray").expect("line q") as u32; + m.push(TextEdit { + range: TextRange::new(line, line + 22), + new_text: "assign q = s ; // stray".to_string(), + }); + m.sort_by_key(|edit| edit.range.start); + assert_eq!(verified(&m, &n, region), Ok(())); +} + +/// A **control**, not an attack on the new code: a sender writing a comment +/// it never deleted was refused before this round too (equation 2, "never +/// duplicated"). Kept to pin that the per-edit rule, asked after the +/// transit, does not replace that sentence with its own. +#[test] +fn control_a_sender_edit_that_invents_a_comment_keeps_its_old_refusal() { + let (m, n, region) = extraction(); + let m = with(m, vec![inserting(SOURCE, "assign r = a;", " // stray")]); + let message = verified(&m, &n, region).expect_err("an invented copy is a refusal"); + assert!(message.contains("never duplicated"), "{message}"); + assert!(!message.contains("stays with") && !message.contains("where it was"), "{message}"); +} + +#[test] +fn overlapping_edits_that_apply_would_skip_are_refused_whole() { + // `apply` skips an edit that starts inside the one before it; a client + // would not. The reconstruction refuses the plan rather than verify a file + // nobody will see. + let (mut m, n, region) = extraction(); + let inside = m[0].range.start + 2; + m.push(TextEdit { range: TextRange::new(inside, inside + 1), new_text: "x".to_string() }); + let message = verified(&m, &n, region).expect_err("overlapping edits are a refusal"); + assert!(message.contains("overlap or fall outside"), "{message}"); +} + +#[test] +fn an_edit_past_the_end_of_the_file_is_refused_whole() { + let (mut m, n, region) = extraction(); + let past = SOURCE.len() as u32 + 4; + m.push(TextEdit { range: TextRange::new(past, past + 1), new_text: String::new() }); + let message = verified(&m, &n, region).expect_err("an edit past the end is a refusal"); + assert!(message.contains("overlap or fall outside"), "{message}"); +} + +#[test] +fn a_one_file_refactoring_may_still_carry_a_comment_between_its_edits() { + // The per-edit rule is the move's: a splice keeps its per-file contract, + // which is how the ANSI conversion writes a body comment onto a header + // port. Same relocation as the attack, no move named — accepted. + let text = "module m (a);\n input logic a; // the port\n wire w;\nendmodule\n"; + let files = vec![(PathBuf::from("/rtl/m.sv"), text.to_string())]; + let comment = text.find(" // the port").expect("comment") as u32; + let wire_end = text.find("wire w;").expect("wire") as u32 + 7; + let edits = vec![ + TextEdit { range: TextRange::new(comment, comment + 12), new_text: String::new() }, + TextEdit { range: TextRange::empty(wire_end), new_text: " // the port".to_string() }, + ]; + let mut scope = Scope::build(&files); + let m = scope.index_of(Path::new("/rtl/m.sv")).expect("m"); + assert_eq!(verify_splice(&mut scope, &[(m, edits)], "m", "moving a comment"), Ok(())); +} + +// ---------------------------------------------------------------------- +// QA's re-attack pairs (fix round 1): shapes the first eight did not cover. +// Each is accepted with `reconstruct` and `windows_match` disabled. +// ---------------------------------------------------------------------- + +/// [`SOURCE`] with a second, unrelated comment of the same text on line `r`. +const DUPS: &str = "module m (\n input logic a,\n input logic b,\n output logic q,\n output logic r\n);\n logic s;\n assign s = a & b; // the and\n assign q = s; // dup\n assign r = a; // dup\nendmodule\n"; + +#[test] +fn a_relocation_into_the_receivers_own_insertion_is_rejected() { + // Two receiver edits: the insertion at 0 writes the module and the + // comment `sum.sv` already held; the second deletes that comment where it + // was. Receivers may write the transit, not carry their own pieces. + let (m, mut n, region) = extraction(); + let held = "// held\n"; + for edit in &mut n { + edit.new_text.push_str(held); + } + n.push(TextEdit { range: TextRange::new(0, held.len() as u32), new_text: String::new() }); + let message = verified_in(SOURCE, held, &m, &n, region).expect_err("refused"); + assert!(message.contains("`// held`") && message.contains("sum.sv"), "{message}"); +} + +#[test] +fn a_dropped_comment_replaced_by_an_identical_copy_elsewhere_is_rejected() { + // `// dup` is written twice in `m.sv`. One copy is deleted and a copy of + // the same text inserted beside the other: same count, same texts. + let (m, n, region) = extraction_of(DUPS); + let m = with( + m, + vec![ + replacing(DUPS, "assign q", " // dup", ""), + inserting(DUPS, "assign r = a; // dup", "\n // dup"), + ], + ); + let message = verified_in(DUPS, "", &m, &n, region).expect_err("refused"); + assert!(message.contains("`// dup`"), "{message}"); +} + +#[test] +fn a_dropped_comment_laundered_through_the_other_copys_edit_is_rejected() { + // The second copy's own edit deletes it and writes it back — twice. That + // edit balances its own copy and then some; the first copy's edit lost it. + let (m, n, region) = extraction_of(DUPS); + let m = with( + m, + vec![ + replacing(DUPS, "assign q", " // dup", ""), + replacing(DUPS, "assign r", " // dup", " // dup\n // dup"), + ], + ); + let message = verified_in(DUPS, "", &m, &n, region).expect_err("refused"); + assert!(message.contains("`// dup`"), "{message}"); +} + +#[test] +fn an_attribute_relocated_between_two_edits_is_rejected() { + let source = SOURCE.replace(" assign q = s; // stray", " (* keep *) assign q = s;"); + let (m, n, region) = extraction_of(&source); + let m = with( + m, + vec![ + replacing(&source, " (* keep", "(* keep *) ", ""), + replacing(&source, " assign r", "assign r", "(* keep *) assign r"), + ], + ); + let message = verified_in(&source, "", &m, &n, region).expect_err("refused"); + assert!(message.contains("the attribute `(* keep *)`"), "{message}"); + assert!(!message.contains("a attribute"), "the article is right: {message}"); +} + +#[test] +fn two_comments_swapped_between_two_edits_are_rejected() { + let source = SOURCE.replace("assign r = a;", "assign r = a; // other"); + let (m, n, region) = extraction_of(&source); + let m = with( + m, + vec![ + replacing(&source, "assign q", " // stray", " // other"), + replacing(&source, "assign r", " // other", " // stray"), + ], + ); + let after = apply(&source, &m); + assert!(after.contains("assign q = s; // other") && after.contains("assign r = a; // stray")); + let message = verified_in(&source, "", &m, &n, region).expect_err("refused"); + assert!(message.contains("m.sv"), "{message}"); +} + +/// One file's edits through `verify_splice`, where the reconstruction is asked +/// of every refactoring, move or not. +fn spliced(text: &str, edits: Vec) -> Result<(), String> { + let files = vec![(PathBuf::from("/rtl/m.sv"), text.to_string())]; + let mut scope = Scope::build(&files); + let m = scope.index_of(Path::new("/rtl/m.sv")).expect("m"); + verify_splice(&mut scope, &[(m, edits)], "m", "editing `m`") +} + +#[test] +fn edits_out_of_order_are_refused_whole() { + // Each edit is fine on its own; `apply` takes the later one and then + // skips the earlier, which starts before its cursor. + let text = "module m;\n wire a;\n wire b;\nendmodule\n"; + let edits = vec![replacing(text, "wire b", "b", "b2"), replacing(text, "wire a", "a", "a2")]; + let message = spliced(text, edits).expect_err("unsorted edits are a refusal"); + assert!(message.contains("overlap or fall outside"), "{message}"); +} + +#[test] +fn an_edit_that_splits_a_character_is_refused_whole() { + let text = "module m;\n // café\n wire a;\nendmodule\n"; + let inside = (text.find('é').expect("é") + 1) as u32; + let edits = vec![TextEdit { range: TextRange::new(inside, inside), new_text: "x".into() }]; + let message = spliced(text, edits).expect_err("a mid-character edit is a refusal"); + assert!(message.contains("overlap or fall outside"), "{message}"); +} + +#[test] +fn a_reversed_range_is_refused_whole() { + let text = "module m;\n wire a;\nendmodule\n"; + let at = text.find("wire").expect("wire") as u32; + let edits = + vec![TextEdit { range: TextRange { start: at + 4, end: at }, new_text: "x".into() }]; + let message = spliced(text, edits).expect_err("a reversed range is a refusal"); + assert!(message.contains("overlap or fall outside"), "{message}"); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_refactor/src/check/ledger.rs b/crates/vlog_refactor/src/check/ledger.rs index 8ce0c53..df26f70 100644 --- a/crates/vlog_refactor/src/check/ledger.rs +++ b/crates/vlog_refactor/src/check/ledger.rs @@ -20,6 +20,10 @@ use crate::TextEdit; use super::{Moving, Origin}; +mod windows; + +pub(super) use windows::reconstruct; + // ---------------------------------------------------------------------- // lexical splice // ---------------------------------------------------------------------- diff --git a/crates/vlog_refactor/src/check/ledger/windows.rs b/crates/vlog_refactor/src/check/ledger/windows.rs new file mode 100644 index 0000000..8591393 --- /dev/null +++ b/crates/vlog_refactor/src/check/ledger/windows.rs @@ -0,0 +1,132 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Equation 3 against an **independent** `after` (`docs/topo.md` §2.9-32). +//! +//! [`super::Ledger`]'s third equation, `has == had - gone + wrote`, used to be +//! asked of a text [`crate::apply`] had built out of the very edits it was +//! checking, so it could only ever agree with them: a never-dropped piece +//! deleted by one edit and written back by another, somewhere else in the same +//! file, balances every count and every position the edits themselves declare. +//! Extract-module's QA re-attack (Finding QA-1) found the shape. Two things +//! close it. +//! +//! 1. **A second reconstruction.** [`reconstruct`] splices the edits into the +//! old text from the last one backwards, refusing rather than skipping an +//! edit that overlaps another or runs past the end — where `apply` walks +//! forwards and silently drops such an edit. The verifier reads the file the +//! reconstruction produced, and refuses a plan on which the two disagree. +//! 2. **Equation 3, held per edit**, in a file a move names. Each edit's window +//! in the reconstructed text is located by offsets alone — the edits before +//! it shift it by their length change — and the never-dropped pieces the +//! *re-lexed file* holds inside that window are counted, not the pieces the +//! edit's own text lexes to in isolation. Per edit `e` and text `t`: +//! `has_e == gone_e - out_e` for a file that sends (`>=` for a text a +//! refactoring [`super::generated`] itself), and `has_e >= gone_e` for a +//! file that receives, whose surplus is the transit the file-level +//! equations and rule 4 already bound. A comment written back by the edit +//! that deleted it passes; one moved to another edit's window does not. +//! +//! Only a file the move names is held to the second rule. A refactoring that +//! stays inside one file legitimately carries a piece from one edit to another +//! — the ANSI conversion writes a body declaration's comment onto the header +//! port it becomes — and keeps exactly the per-file contract it always had. +//! Every real move today writes one edit per named file. + +use vlog_parser::span::TextRange; + +use crate::TextEdit; + +use super::{generated, overlaps, tally_into, times, within, Kept, Split, Tally}; + +/// The text `edits` make of `before`, spliced from the last edit backwards — +/// or `None` when the edits are not a plan any client could apply: out of +/// order, overlapping, past the end, or splitting a character. +pub(in crate::check) fn reconstruct(before: &str, edits: &[TextEdit]) -> Option { + let mut floor = 0u32; + for edit in edits { + let (start, end) = (edit.range.start, edit.range.end); + let in_text = |at: u32| before.is_char_boundary(at as usize); + if start < floor || end < start || !in_text(start) || !in_text(end) { + return None; + } + floor = end; + } + let mut out = before.to_string(); + for edit in edits.iter().rev() { + out.replace_range(edit.range.start as usize..edit.range.end as usize, &edit.new_text); + } + Some(out) +} + +impl Split { + /// Equation 3 per edit, for a file a move names with `region` (empty for + /// a file that only receives): every never-dropped piece an edit deletes + /// outside the region is written back inside that same edit's window of + /// the reconstructed text, and a sender's window holds nothing else. + pub(in crate::check) fn windows_match( + &self, + edits: &[TextEdit], + region: TextRange, + shown: &str, + what: &str, + ) -> Result<(), String> { + let receives = region.is_empty(); + let mut shift: i64 = 0; + for edit in edits { + let start = edit.range.start as i64 + shift; + let window = TextRange::new(start as u32, (start + edit.new_text.len() as i64) as u32); + shift += edit.new_text.len() as i64 - edit.range.len() as i64; + let (has, stays) = self.window_counts(edit.range, window, region); + let mut texts: Vec<&Kept> = has.keys().chain(stays.keys()).collect(); + texts.sort_unstable(); + texts.dedup(); + let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0); + for key in texts { + let (held, owed) = (count(&has, key), count(&stays, key)); + let surplus_allowed = receives || generated(&key.1); + if held < owed || (held > owed && !surplus_allowed) { + return Err(moved_within(key, held, owed, shown, what)); + } + } + } + Ok(()) + } + + /// One edit's two counts: the never-dropped pieces the reconstructed file + /// holds inside `window`, and the old ones the edit's `range` deletes that + /// do not leave through `region`. + fn window_counts( + &self, + range: TextRange, + window: TextRange, + region: TextRange, + ) -> (Tally, Tally) { + let mut has = Tally::new(); + let inside = |span: &TextRange| window.start <= span.start && span.end <= window.end; + tally_into(&mut has, self.new.iter().filter(|(span, _)| inside(span)).map(|(_, p)| p)); + let mut stays = Tally::new(); + let deleted = |span: &TextRange| { + !range.is_empty() && overlaps(range, *span) && !within(region, *span) + }; + tally_into(&mut stays, self.old.iter().filter(|(span, _)| deleted(span)).map(|(_, p)| p)); + (has, stays) + } +} + +/// The refusal for a piece one edit deleted and another wrote — or that an +/// edit wrote without deleting it. +fn moved_within(key: &Kept, held: usize, owed: usize, shown: &str, what: &str) -> String { + let Kept(noun, text) = key; + match held < owed { + true => format!( + "{what} would delete the {noun} `{text}` in {shown} and not write it back where it was; only the text a move carries may take one elsewhere, and {noun}s are never dropped, so nothing was edited." + ), + false => format!( + "{what} would write the {noun} `{text}` {} in {shown} at an edit that deletes it {}; {noun}s are never duplicated, so nothing was edited.", + times(held), + times(owed) + ), + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_refactor/src/check/mod.rs b/crates/vlog_refactor/src/check/mod.rs index 55f2265..2dda898 100644 --- a/crates/vlog_refactor/src/check/mod.rs +++ b/crates/vlog_refactor/src/check/mod.rs @@ -21,6 +21,8 @@ mod after; mod implicit; +#[cfg(test)] +mod in_place_attacks; mod ledger; #[cfg(test)] mod qa_block_attacks; @@ -44,7 +46,7 @@ use crate::trace::VerifyTrace; use crate::{apply, Shift, TextEdit}; use after::{after_index, after_print}; -use ledger::{overlaps, pieces_match, region_of, Split, Transit}; +use ledger::{overlaps, pieces_match, reconstruct, region_of, Split, Transit}; /// Check the whole edit, or refuse it whole. pub(crate) fn verify( @@ -308,23 +310,35 @@ pub(crate) fn verify_move( transit.copy(&scope.name_of(path), text, copied.region, what)?; } - for ((i, edits), (path, text)) in edits.iter().zip(&edited) { + // Equation 3 per edit (§2.9-32), asked once the transit has had its say + // so the sentence a refusal gives is the most specific one available. + let mut in_place: Result<(), String> = Ok(()); + for ((i, edits), (path, applied)) in edits.iter().zip(&edited) { let Some(before) = scope.text(*i) else { return Err(abandoned) }; let shown = scope.name_of(path); - let split = Split::read(before, text, edits, &shown, what)?; + // The file the ledger reads is reconstructed independently of + // `apply`, which skips an edit it cannot place rather than refusing. + let text = match reconstruct(before, edits) { + Some(text) if text == *applied => text, + _ => return Err(unplaceable(&shown, what)), + }; + let split = Split::read(before, &text, edits, &shown, what)?; match region_of(moving, *i) { // A file the move names balances against the pieces in transit // rather than on its own; its positional comparison is unchanged. Some(region) => { transit.add(&scope.name_of(path), region, &split, edits); split.positions_match(edits, &shown, what)?; + if in_place.is_ok() { + in_place = split.windows_match(edits, region, &shown, what); + } } None => pieces_match(&split, edits, &shown, what)?, } // A tolerant parse of a file that was already broken still reports its // old diagnostics, so the bar is "no *new* one", not "none". let (before_count, after_count) = - (parse_source_tolerant(before).1.len(), parse_source_tolerant(text).1.len()); + (parse_source_tolerant(before).1.len(), parse_source_tolerant(&text).1.len()); if after_count > before_count { return Err(format!( "{what} would leave {} unparseable; no edits were made.", @@ -333,6 +347,7 @@ pub(crate) fn verify_move( } } transit.check(what)?; + in_place?; let shifts = Shifts::new(scope, edits, ""); let excluded = Excluded::new(scope, edits); @@ -375,6 +390,14 @@ pub(crate) fn verify_move( Ok(()) } +/// The refusal for edits no client could apply as written: out of order, +/// overlapping, past the end of the file or inside a character. +fn unplaceable(shown: &str, what: &str) -> String { + format!( + "{what} would make edits to {shown} that overlap or fall outside it, so lucisv cannot say what the file would become; no edits were made." + ) +} + /// The byte ranges each refactoring deliberately changed, in the coordinates /// of the text before the edits and of the text after them. Names inside them /// are the ones the user asked to move, so they are the only ones the diff --git a/crates/vlog_refactor/src/rename/connections.rs b/crates/vlog_refactor/src/rename/connections.rs index b585bd1..7dbfc8b 100644 --- a/crates/vlog_refactor/src/rename/connections.rs +++ b/crates/vlog_refactor/src/rename/connections.rs @@ -27,6 +27,7 @@ use std::collections::HashMap; use vlog_parser::ast::PortList; +use vlog_parser::span::TextRange; use vlog_parser::{parse_source_tolerant, LineIndex}; use vlog_semantic::{ScopeKind, Surface, SymbolId, SymbolKind}; @@ -281,7 +282,8 @@ impl<'a> Scope<'a> { let Some(text) = self.text(i).filter(wanted) else { continue }; let (tree, _) = parse_source_tolerant(text); for site in sites(&tree.items).iter().filter(|s| s.bind.is_some()) { - match self.bind_reaches(i, site, module) { + let visible = self.visible_target(i, site); + match self.bind_reaches(i, site, module, visible) { Reach::Module => self.signal_site(walk, i, text, site, rewrite)?, Reach::Maybe => self.signal_site(walk, i, text, site, false)?, Reach::Elsewhere => {} @@ -302,7 +304,13 @@ impl<'a> Scope<'a> { /// `module` itself — maybe, which refuses what it would bind: the verifier /// cannot name an instance's scope, so a rewrite there would be refused /// anyway, and saying so up front is the clearer sentence. - fn bind_reaches(&self, file: usize, site: &Site, module: &str) -> Reach { + fn bind_reaches( + &self, + file: usize, + site: &Site, + module: &str, + visible: Option, + ) -> Reach { let target = match site.bind_target() { Ok(Some(target)) => target, Ok(None) => return Reach::Elsewhere, @@ -314,33 +322,59 @@ impl<'a> Scope<'a> { if !self.index.units(target).is_empty() { return Reach::Elsewhere; } - let owners = self.instance_owners(file, site, target); + let owners = self.instance_owners(file, site, target, visible); match owners.is_empty() || owners.contains(&module) { true => Reach::Maybe, false => Reach::Elsewhere, } } + /// The name span of the declaration a `bind` at `site` sees under its + /// lone target's name, by upward lookup from the directive's own scope — + /// or `None` when nothing in this file answers. An instance inside one of + /// the enclosing module's generate blocks is in a scope of its own and is + /// not seen from outside it (QA note 1, `tests/qa_rename_implicit.rs`). + fn visible_target(&mut self, file: usize, site: &Site) -> Option { + let Ok(Some(target)) = site.bind_target() else { return None }; + let target = target.to_string(); + let semantics = &self.analysis(file)?.semantics; + let id = nearest(semantics, site.instance.span.start, &target)?; + semantics.symbol(id).map(|symbol| symbol.name_span) + } + /// The modules an instance named `target` instantiates, as a `bind` /// written at `site` sees them. A bare instance name is found by upward - /// name resolution from the bind's own scope (§23.11), so the instances - /// the **enclosing module** declares answer first — `bind dut … (.*)` in - /// sram_ctrl's bench means that bench's `dut`, not entropy_src's — and - /// only when it declares none does every instance of that name count. - fn instance_owners(&self, file: usize, site: &Site, target: &str) -> Vec<&str> { + /// name resolution from the bind's own scope (§23.11), so the instance + /// that lookup finds in the **enclosing module** — `visible` — answers + /// first: `bind dut … (.*)` in sram_ctrl's bench means that bench's `dut`, + /// not entropy_src's. Only when it finds none does every instance of that + /// name count — and one inside a generate block of the enclosing module + /// is one it does not find. + fn instance_owners( + &self, + file: usize, + site: &Site, + target: &str, + visible: Option, + ) -> Vec<&str> { let here = self.file_id(file); let at = site.instance.span.start; let named = |edge: &vlog_semantic::InstantiationEdge| { edge.instances.iter().any(|instance| instance.name == target) }; - let enclosing = |edge: &vlog_semantic::InstantiationEdge| { - Some(edge.file) == here && edge.owner.span.contains(at) + let seen = |edge: &vlog_semantic::InstantiationEdge| { + Some(edge.file) == here + && edge.owner.span.contains(at) + && edge + .instances + .iter() + .any(|instance| instance.name == target && Some(instance.name_span) == visible) }; // Keyed by the module *instantiated*, which is what the bind reaches. let mut local: Vec<&str> = Vec::new(); let mut anywhere: Vec<&str> = Vec::new(); for (instantiated, edges) in self.index.instantiations() { - if edges.iter().any(|edge| named(edge) && enclosing(edge)) { + if edges.iter().any(seen) { local.push(instantiated); } if edges.iter().any(named) { diff --git a/crates/vlog_refactor/src/rename/scoped.rs b/crates/vlog_refactor/src/rename/scoped.rs index 3bdfc20..735f122 100644 --- a/crates/vlog_refactor/src/rename/scoped.rs +++ b/crates/vlog_refactor/src/rename/scoped.rs @@ -291,8 +291,10 @@ fn bare_unbound_uses( } /// H3: the byte ranges of the `bind` statements in one file whose target is -/// `unit` — by name, or by an instance path, which lucisv cannot follow to a -/// unit and so counts — from `bind` to its `;`. +/// `unit` — by name, by an instance path, which lucisv cannot follow to a +/// unit and so counts, or by the bare name of an instance of `unit` the same +/// text declares (L-6: `bind u_m chk …` written inside the parent) — from +/// `bind` to its `;`. pub(super) fn binds_into(tokens: &[Token], unit: &str) -> Vec { let mut out = Vec::new(); for (i, token) in tokens.iter().enumerate() { @@ -303,7 +305,7 @@ pub(super) fn binds_into(tokens: &[Token], unit: &str) -> Vec { } let Some(target) = tokens.get(i + 1) else { continue }; let path = tokens.get(i + 2).is_some_and(|t| t.is_sym(".") || t.is_sym("[")); - if target.text != unit && !path { + if target.text != unit && !path && !instantiates_as(tokens, unit, &target.text) { continue; } let Some(end) = tokens[i..].iter().find(|t| t.is_sym(";")) else { continue }; @@ -312,6 +314,41 @@ pub(super) fn binds_into(tokens: &[Token], unit: &str) -> Vec { out } +/// Whether `tokens` instantiate `unit` under the instance name `name`: +/// `unit name`, or `unit #(…) name`, anywhere in the text. A lexical answer +/// for a lexical scan — the parent that writes `bind u_m …` is the text that +/// declares `u_m`, which is the shape IEEE 1800 §23.11 names. +fn instantiates_as(tokens: &[Token], unit: &str, name: &str) -> bool { + let is_unit = |t: &Token| t.kind == TokenKind::Ident && t.text == unit; + tokens.iter().enumerate().filter(|(_, t)| is_unit(t)).any(|(i, _)| { + let mut at = i + 1; + if tokens.get(at).is_some_and(|t| t.is_sym("#")) { + at = past_parens(tokens, at + 1); + } + tokens.get(at).is_some_and(|t| t.kind == TokenKind::Ident && t.text == name) + }) +} + +/// The index just past the balanced `( … )` starting at `at`, or `at` itself +/// when no `(` is there. +fn past_parens(tokens: &[Token], at: usize) -> usize { + if !tokens.get(at).is_some_and(|t| t.is_sym("(")) { + return at; + } + let mut depth = 0usize; + for (j, token) in tokens.iter().enumerate().skip(at) { + if token.is_sym("(") { + depth += 1; + } else if token.is_sym(")") { + depth -= 1; + if depth == 0 { + return j + 1; + } + } + } + tokens.len() +} + fn push_defines(out: &mut Defs, defines: &vlog_parser::defines::DefineTable) { for define in defines.entries() { let params = define.params.clone().unwrap_or_default(); diff --git a/crates/vlog_refactor/src/scope.rs b/crates/vlog_refactor/src/scope.rs index 4789888..6cec7a2 100644 --- a/crates/vlog_refactor/src/scope.rs +++ b/crates/vlog_refactor/src/scope.rs @@ -32,8 +32,8 @@ use std::path::{Path, PathBuf}; use vlog_parser::parse_source_tolerant; use vlog_semantic::{ - analyze, resolve_external, ExternalResolutions, FileFacts, FileId, IndexBuilder, Semantics, - WorkspaceIndex, + analyze, index_order, resolve_external, ExternalResolutions, FileFacts, FileId, IndexBuilder, + Semantics, WorkspaceIndex, }; use crate::trace::IndexTrace; @@ -229,12 +229,11 @@ impl<'a> Scope<'a> { known: Option<&dyn KnownFacts>, trace: &mut IndexTrace, ) -> Scope<'a> { - let mut sources: Vec<(&Path, &str)> = - files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect(); - // The same normalization `WorkspaceIndex::build` applies: a stable - // sort by path, then the first copy of a repeated path wins. - sources.sort_by(|a, b| a.0.cmp(b.0)); - sources.dedup_by(|a, b| a.0 == b.0); + // The same normalization `WorkspaceIndex::build` applies, from the + // function it applies it with: a stable sort by path, then the first + // copy of a repeated path wins. + let sources: Vec<(&Path, &str)> = + index_order(files.iter().map(|(p, t)| (p.as_path(), t.as_str()))); let mut building = Building { builder: IndexBuilder::new(), kept: HashMap::new(), known, trace }; diff --git a/crates/vlog_refactor/tests/qa_rename_implicit.rs b/crates/vlog_refactor/tests/qa_rename_implicit.rs index bc380f4..f9bce89 100644 --- a/crates/vlog_refactor/tests/qa_rename_implicit.rs +++ b/crates/vlog_refactor/tests/qa_rename_implicit.rs @@ -454,14 +454,13 @@ fn qa_b_a_bind_onto_a_name_no_indexed_instance_has_is_refused() { assert!(refusal.contains("`c_u` at bind.sv:2"), "{refusal}"); } -/// QA note 1 (non-blocking, lead-accepted gap): an instance inside a generate -/// block of the enclosing module is counted as the enclosing module's own. -/// Upward resolution from `a` does not see `a.g.u`, so `bind u` here reaches -/// the parent's `u` — a `cnt` — and its `.err_o` binds `cnt`'s renamed port. -/// The engine skips it; the verifier prints a bind onto an instance as -/// opaque on both sides, so nothing refuses and the shorthand is cut. +/// QA note 1, closed in Round 8 (`docs/features/semantic-refactor-r8`): an +/// instance inside a generate block of the enclosing module is not the +/// enclosing module's own. Upward resolution from `a` does not see `a.g.u`, +/// so `bind u` here may reach the parent's `u` — a `cnt` — whose `.err_o` +/// binds `cnt`'s renamed port. The engine used to count `a.g.u` as visible, +/// skip the bind, and cut the shorthand; it now refuses. #[test] -#[ignore = "QA note 1: accepted generate-block gap"] fn qa_b_a_generate_scoped_instance_is_not_the_enclosing_modules_own() { let a = "module a;\n logic clk_i, err_o;\n if (1) begin : g\n fifo u (.clk_i, .err_o);\n end\n bind u chk c_u (.clk_i, .err_o);\nendmodule\n"; let p = "module p;\n logic clk_i, err_o;\n a u_a ();\n cnt u (.clk_i, .err_o);\nendmodule\n"; @@ -470,4 +469,15 @@ fn qa_b_a_generate_scoped_instance_is_not_the_enclosing_modules_own() { assert!(refusal.contains("`c_u`"), "{refusal}"); } +/// The other half of QA note 1: a `bind` written *inside* the generate block +/// sees that block's own `u` — a fifo — first, so it never reaches `p.u`. +#[test] +fn a_bind_inside_the_generate_block_sees_the_blocks_own_instance() { + let a = "module a;\n logic clk_i, err_o;\n if (1) begin : g\n fifo u (.clk_i, .err_o);\n bind u chk c_u (.clk_i, .err_o);\n end\nendmodule\n"; + let p = "module p;\n logic clk_i, err_o;\n a u_a ();\n cnt u (.clk_i, .err_o);\nendmodule\n"; + let (texts, _) = rename_cnt_err(&[("a.sv", a), ("p.sv", p)]) + .expect("g's own `u` is a fifo: the bind never sees cnt's err_o"); + assert_eq!(texts[3], a, "a.sv untouched"); +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_refactor/tests/qa_warning_scope.rs b/crates/vlog_refactor/tests/qa_warning_scope.rs index c9a111a..d52c33b 100644 --- a/crates/vlog_refactor/tests/qa_warning_scope.rs +++ b/crates/vlog_refactor/tests/qa_warning_scope.rs @@ -419,6 +419,50 @@ endmodule } } +/// oct_review L-6: `bind u_m chk …` written inside the parent, the target a +/// bare **instance** name (IEEE 1800 §23.11), binds into `m` as surely as +/// `bind m chk …` does — so a macro argument inside it is news. A bare target +/// naming an instance of another module is not. +#[test] +fn l6_a_bind_onto_a_bare_instance_of_the_unit_is_a_bind_into_it() { + let module = "module m (input logic clk);\n logic state_q;\nendmodule\n"; + let other = "module o (input logic clk);\nendmodule\n"; + let chk = "module chk (input logic s);\nendmodule\n"; + let top = "module top (input logic clk); + m u_m (.clk); + o u_o (.clk); + bind u_m chk u_a (.s(`Q(state_q))); + bind u_o chk u_b (.s(`Q(state_q))); +endmodule +"; + let files = + [("defs.svh", Q_DEFS), ("m.sv", module), ("o.sv", other), ("chk.sv", chk), ("top.sv", top)]; + let (_, warnings) = run(&files, "m.sv", "logic ", "state_q", "state_r").expect("renames"); + assert!(said(&warnings, "top.sv", 4), "HIDDEN USE: {warnings:#?}"); + assert!(!said(&warnings, "top.sv", 5), "u_o is an `o`: {warnings:#?}"); +} + +/// oct_review L-5: renaming a variable inside an interface's generate block +/// edits the paths that reach it through an interface port and through a +/// virtual interface, rather than warning that they could not be resolved. +#[test] +fn l5_a_path_through_an_interface_port_into_its_generate_block_is_renamed() { + let ifc = "interface bus_if (input logic clk); + logic data; + if (1) begin : g_mon + logic seen; + end +endinterface +"; + let user = "module u (bus_if bus, output logic o);\n assign o = bus.g_mon.seen;\nendmodule\n"; + let tb = "module tb;\n virtual bus_if vif;\n initial $display(vif.g_mon.seen);\nendmodule\n"; + let files = [("bus_if.sv", ifc), ("u.sv", user), ("tb.sv", tb)]; + let (texts, warnings) = run(&files, "bus_if.sv", "logic ", "seen", "seen_q").expect("renames"); + assert!(texts[1].contains("bus.g_mon.seen_q;"), "{}", texts[1]); + assert!(texts[2].contains("vif.g_mon.seen_q)"), "{}", texts[2]); + assert!(!warnings.iter().any(|w| w.contains("could not be resolved")), "{warnings:#?}"); +} + /// H4: a fragment that declares its own `mem` is never rewritten; a fragment /// only an unrelated module includes stays silent. #[test] diff --git a/crates/vlog_refactor/tests/rename_dpi_export.rs b/crates/vlog_refactor/tests/rename_dpi_export.rs new file mode 100644 index 0000000..c36f2c2 --- /dev/null +++ b/crates/vlog_refactor/tests/rename_dpi_export.rs @@ -0,0 +1,71 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! §2.9-31: a DPI export's name is a reference to the subroutine it exports, +//! so renaming the subroutine renames the export with it — and the C linkage +//! name, which no SystemVerilog declaration answers, is left alone. +//! `docs/features/semantic-refactor-r8/README.md`. + +use std::path::PathBuf; + +use vlog_refactor::{find_references, rename}; + +const DPI: &str = "module m; + function automatic int get_v(); + return 1; + endfunction + task automatic poke(); + endtask + export \"DPI-C\" function get_v; + export \"DPI-C\" c_poke = task poke; + initial poke(); +endmodule +"; + +fn renamed(at_needle: &str, new: &str) -> String { + let path = PathBuf::from("/rtl/m.sv"); + let files = vec![(path.clone(), DPI.to_string())]; + let at = DPI.find(at_needle).expect("needle") as u32; + let edit = rename(&files, &path, at, new).expect("renames"); + let mut out = String::new(); + let mut cursor = 0usize; + for e in edit.edits_for(&path) { + out.push_str(&DPI[cursor..e.range.start as usize]); + out.push_str(&e.new_text); + cursor = e.range.end as usize; + } + out.push_str(&DPI[cursor..]); + out +} + +#[test] +fn renaming_an_exported_function_renames_its_export() { + let out = renamed("get_v()", "read_v"); + assert!(out.contains("function automatic int read_v();"), "{out}"); + assert!(out.contains("export \"DPI-C\" function read_v;"), "{out}"); + assert!(!out.contains("get_v"), "{out}"); +} + +#[test] +fn renaming_an_exported_task_keeps_its_c_linkage_name() { + let out = renamed("poke();\n endtask", "kick"); + assert!(out.contains("export \"DPI-C\" c_poke = task kick;"), "{out}"); + assert!(out.contains("initial kick();"), "{out}"); +} + +#[test] +fn renaming_from_the_export_renames_the_declaration() { + let out = renamed("get_v;", "read_v"); + assert!(out.contains("function automatic int read_v();"), "{out}"); +} + +#[test] +fn the_export_is_one_of_the_functions_references() { + let path = PathBuf::from("/rtl/m.sv"); + let files = vec![(path.clone(), DPI.to_string())]; + let at = DPI.find("get_v()").expect("decl") as u32; + let found = find_references(&files, &path, at, false).expect("references"); + let export = DPI.find("get_v;").expect("export") as u32; + assert!(found.iter().any(|(p, range)| *p == path && range.start == export), "{found:?}"); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/vlog_semantic/src/bind/item.rs b/crates/vlog_semantic/src/bind/item.rs index 0bfbf22..e53bcf7 100644 --- a/crates/vlog_semantic/src/bind/item.rs +++ b/crates/vlog_semantic/src/bind/item.rs @@ -188,8 +188,13 @@ impl<'a> Binder<'a> { // A macro invocation standing as an item may declare names this // crate never sees (`Binder::mark_macro_declarations`). ItemKind::MacroItem(_) => self.mark_macro_declarations(scope), - ItemKind::Export(ExportDecl::Dpi(_)) - | ItemKind::Directive(_) + // A DPI export names a subroutine declared in the scope it is + // written in (IEEE 1800 §35.5.4), never outward; its `c_name =` + // is a C linkage name, which no declaration answers (§2.9-31). + ItemKind::Export(ExportDecl::Dpi(dpi)) => { + self.use_name(scope, &dpi.name.text, dpi.name.span, Target::InScope); + } + ItemKind::Directive(_) | ItemKind::Timeunit(_) | ItemKind::Error(_) // A null item (`;`) declares nothing and references nothing. diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index d655ba4..2cde321 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -174,7 +174,14 @@ use crate::workspace::{ /// answer find-references and the rename of `dut`'s members as though no DV /// file's `force tb.dut.…` named them. See /// `docs/features/top-rooted-paths/README.md`. -pub const FACTS_FORMAT: u32 = 22; +/// 22 → 23 (2026-11-26, semantic-refactor-r8): no new field, three census +/// changes. The `W` group holds escaped identifiers as their token spells them +/// (`\my.sig`), so a pre-filter on the census opens a file that writes only +/// the escaped spelling; a DPI export's name is a reference to the subroutine +/// it exports (§2.9-31); and an interface's named generate block is on its +/// connection surface (oct_review L-5). A 0.66.x store would miss all three. +/// See `docs/features/semantic-refactor-r8/README.md`. +pub const FACTS_FORMAT: u32 = 23; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index 5996c8c..593bc88 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -297,12 +297,22 @@ impl Semantics { /// index never files it — and its key is qualified by the enclosing unit /// and marked as the subroutine's (`m.ff().fb`), so it can never be the /// key a module `ff`'s block `fb` is filed under (QA F4). + /// + /// An **inline nested** struct member (`struct packed { … } ctrl;` inside + /// `reg2hw_t`) is keyed the same way — its container's key and its name, + /// `reg2hw_t.ctrl` — which is the key the index files its fields under + /// (oct_review L-10). pub fn member_key(&self, scope: ScopeId) -> Option { let owner = self.scope(scope)?.owner.and_then(|id| self.symbol(id))?; - if owner.kind != SymbolKind::Block { - return Some(owner.name.clone()); + match owner.kind { + SymbolKind::Block => { + Some(format!("{}.{}", self.block_parent_key(owner.scope)?, owner.name)) + } + SymbolKind::StructMember => { + Some(format!("{}.{}", self.member_key(owner.scope)?, owner.name)) + } + _ => Some(owner.name.clone()), } - Some(format!("{}.{}", self.block_parent_key(owner.scope)?, owner.name)) } /// The key part a block declared in `scope` hangs off: the enclosing diff --git a/crates/vlog_semantic/src/words.rs b/crates/vlog_semantic/src/words.rs index cb70415..87519bc 100644 --- a/crates/vlog_semantic/src/words.rs +++ b/crates/vlog_semantic/src/words.rs @@ -30,8 +30,11 @@ //! What is *not* here is as load-bearing as what is. Comments are trivia and //! a string literal is one `String` token, so neither can contribute; inside //! raw text, where a string is not its own token, the quoted run is skipped by -//! hand for the same reason. Numbers, a sized literal's base and an escaped -//! identifier are not names either. See +//! hand for the same reason. Numbers and a sized literal's base are not names +//! either. An escaped identifier *is* one, and is written down as the token +//! spells it (`\\my.sig`), since Round 8 — before that, a rename or `find` +//! pre-filtering on the census never opened a file that only wrote the +//! escaped spelling (`docs/features/semantic-refactor-r8/README.md`). See //! `docs/features/semantic-lints-on/README.md`. use std::collections::HashSet; @@ -58,13 +61,15 @@ pub fn harvest(tokens: &[Token]) -> Vec { seen.extend(raw_words(raw)); continue; } - // A plain identifier is one word: itself. An escaped identifier - // (`\my-port`) is not — inserting one needs a trailing space to - // terminate it, which a plain word has no way to promise, and the - // backslash is part of the name everywhere else in lucisv. - if matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent) - && !token.text.starts_with('\\') - { + // An identifier is one word: itself. An escaped identifier + // (`\my-port`) is too, spelled as the token is — backslash included, + // terminating whitespace not — because that is the spelling every + // symbol, reference and pre-filter in lucisv looks it up by (Round 8, + // `FACTS_FORMAT` 23). Completion does not offer one: inserting it + // needs a trailing space a plain word has no way to promise, so + // `lucisv_server::candidates` filters it out of the one reader that + // inserts. + if matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent) { seen.insert(token.text.as_str()); } } @@ -244,9 +249,11 @@ mod tests { } #[test] - fn an_escaped_identifier_is_not_a_word() { + fn an_escaped_identifier_is_a_word_spelled_as_its_token() { + // Backslash kept, terminating space dropped: the spelling a symbol of + // that name carries, and so the one a pre-filter looks up. let words = harvest_text("module m;\n wire \\odd-name ;\nendmodule\n"); - assert_eq!(words, vec!["m"], "got {words:?}"); + assert_eq!(words, vec!["\\odd-name", "m"], "got {words:?}"); } #[test] diff --git a/crates/vlog_semantic/src/workspace/hierarchy.rs b/crates/vlog_semantic/src/workspace/hierarchy.rs index 0faa75c..d186fda 100644 --- a/crates/vlog_semantic/src/workspace/hierarchy.rs +++ b/crates/vlog_semantic/src/workspace/hierarchy.rs @@ -45,19 +45,23 @@ use super::{Def, WorkspaceIndex}; /// other. The instances are in it for the hop as much as for themselves: /// `u_a.u_b.sig` needs `u_b`'s declared type to know where `sig` lives. /// -/// An **interface** is the 2026-09-01 exception and is unchanged: its signals -/// *are* its connection surface, because `virtual bus_if vif; vif.data` is how -/// every DV testbench reaches `data` and `vif` is a variable, not an instance. -/// It gains its instances hierarchically for the same hop reason, and nothing -/// else moves. +/// An **interface** is the 2026-09-01 exception: its signals *are* its +/// connection surface, because `virtual bus_if vif; vif.data` is how every DV +/// testbench reaches `data` and `vif` is a variable, not an instance. Its named +/// generate blocks join that surface too (oct_review L-5, Round 8): an +/// interface port or a virtual interface is read through the connection +/// surface, and `bus.g_mon.seen` / `vif.g_mon.seen` are paths into the block. +/// It gains its instances hierarchically for the same hop reason as a module. /// /// A **named generate block** (and a named procedural block) is on its -/// module's or interface's hierarchical surface, and has only that surface -/// itself: `u_x.g_lane[0].lane_q` names the block and then its variable -/// (§23.6, §27.4), and no connection list can name either. What a block -/// exports is what a path may select from it — its nets, variables, instances, -/// parameters and nested blocks — under the synthesized key -/// `record::block_key` gives it. +/// module's hierarchical surface (an interface's connection surface, above), +/// and a module's block has only that surface itself: `u_x.g_lane[0].lane_q` +/// names the block and then its variable (§23.6, §27.4), and no connection +/// list can name either. What a block exports is what a path may select from +/// it — its nets, variables, instances, parameters and nested blocks — under +/// the synthesized key `record::block_key` gives it. An **interface's** block +/// exports the same members on the connection surface instead +/// ([`surface_in`]), exactly as the interface's own signals are. /// /// A `typedef struct`/`union` exports its fields, and a field that is itself /// an inline aggregate exports its own — which is what a generated register @@ -112,8 +116,9 @@ pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option Some(Surface::Connection), - SymbolKind::Instance | SymbolKind::Block => Some(Surface::Hierarchical), + | SymbolKind::Clocking + | SymbolKind::Block => Some(Surface::Connection), + SymbolKind::Instance => Some(Surface::Hierarchical), _ => None, }, SymbolKind::Block => match member { @@ -129,6 +134,29 @@ pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option Option { + let surface = surface_of(unit, member)?; + match (root, unit) { + (SymbolKind::Interface, SymbolKind::Block) => Some(Surface::Connection), + _ => Some(surface), + } +} + /// `member` of `unit` in one surface: the connection records, and — for /// [`Surface::Hierarchical`] — the hierarchical-only ones after them. /// diff --git a/crates/vlog_semantic/src/workspace/index.rs b/crates/vlog_semantic/src/workspace/index.rs index 5feb4f2..cfe8b74 100644 --- a/crates/vlog_semantic/src/workspace/index.rs +++ b/crates/vlog_semantic/src/workspace/index.rs @@ -611,12 +611,14 @@ impl WorkspaceIndex { /// Generic in what rides beside the path — a borrowed `&str` for a caller that /// holds the texts, an owned `String` for one that is handing them over — so a /// scan that owns its work list gets the same ordering from the same function -/// rather than sorting for itself. -pub fn index_order(files: impl IntoIterator) -> Vec<(PathBuf, T)> { - let mut sources: Vec<(PathBuf, T)> = files.into_iter().collect(); - sources.sort_by(|a, b| a.0.cmp(&b.0)); +/// rather than sorting for itself. Generic in the path too — an owned +/// `PathBuf` or a borrowed `&Path` — so `vlog_refactor::Scope`, which borrows +/// both halves, gets this ordering rather than re-deriving it (§2.9-12). +pub fn index_order, T>(files: impl IntoIterator) -> Vec<(P, T)> { + let mut sources: Vec<(P, T)> = files.into_iter().collect(); + sources.sort_by(|a, b| a.0.as_ref().cmp(b.0.as_ref())); // A path handed over twice is one file; the first copy wins. - sources.dedup_by(|a, b| a.0 == b.0); + sources.dedup_by(|a, b| a.0.as_ref() == b.0.as_ref()); sources } diff --git a/crates/vlog_semantic/src/workspace/record.rs b/crates/vlog_semantic/src/workspace/record.rs index f5a5287..1fb0b30 100644 --- a/crates/vlog_semantic/src/workspace/record.rs +++ b/crates/vlog_semantic/src/workspace/record.rs @@ -397,7 +397,7 @@ fn facts_from_analysis( continue; } facts.units.push(Decl::unit(unit, src, lines)); - collect_members(sem, &unit.name, unit, lines, &mut facts.members); + collect_members(sem, &unit.name, unit, unit.kind, lines, &mut facts.members); } // The **connection** surface only. A `Local` posting exists so that a // declaration another file can point at carries its own file's uses @@ -534,10 +534,15 @@ fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> { /// struct `typedef` nested in a package is reachable as `cls::x` / `bus_t::f` /// without the package in the path. The exception is an **inline nested** /// struct member, which has no type name at all: see [`nested_key`]. +/// +/// `root` is the kind of the unit a named block's chain hangs off — the unit +/// itself, unless `unit` is a block — because an interface's blocks export +/// on a different surface from a module's ([`hierarchy::surface_in`]). fn collect_members( sem: &Semantics, key: &str, unit: &Symbol, + root: SymbolKind, lines: &LineIndex, out: &mut Vec<(String, Decl)>, ) { @@ -548,7 +553,7 @@ fn collect_members( let Some(member) = sem.symbol(id) else { continue; }; - let Some(surface) = hierarchy::surface_of(unit.kind, member.kind) else { + let Some(surface) = hierarchy::surface_in(root, unit.kind, member.kind) else { continue; }; if member.name_span.is_empty() { @@ -569,9 +574,9 @@ fn collect_members( // inline-aggregate shape: no type name, so a synthesized key. The // scope tree is acyclic, so this recursion terminates. if matches!(member.kind, SymbolKind::Class | SymbolKind::Typedef | SymbolKind::Covergroup) { - collect_members(sem, &member.name, member, lines, out); + collect_members(sem, &member.name, member, member.kind, lines, out); } else if let Some(nested) = nested { - collect_members(sem, &nested, member, lines, out); + collect_members(sem, &nested, member, root, lines, out); } } } diff --git a/crates/vlog_semantic/tests/semantic_r8.rs b/crates/vlog_semantic/tests/semantic_r8.rs new file mode 100644 index 0000000..ddbb09b --- /dev/null +++ b/crates/vlog_semantic/tests/semantic_r8.rs @@ -0,0 +1,257 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Round 8's semantic edge cases (`docs/features/semantic-refactor-r8`): +//! a DPI export's name is a reference (§2.9-31); a path through an interface +//! port or virtual interface into the interface's generate block resolves +//! (oct_review L-5); `Semantics::member_key` names an inline nested struct +//! member's fields by the key the index files them under (L-10); and an +//! escaped identifier is in a file's word census (`FACTS_FORMAT` 23). + +use std::path::{Path, PathBuf}; + +use vlog_parser::parse_source; +use vlog_semantic::{ + analyze, resolve_external, Def, ExternalTarget, FileFacts, Semantics, Surface, SymbolKind, + WorkspaceIndex, FACTS_FORMAT, +}; + +fn sem(src: &str) -> Semantics { + let file = parse_source(src).expect("fixture must parse"); + analyze(&file, src) +} + +fn index(files: &[(&str, &str)]) -> WorkspaceIndex { + WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src))) +} + +/// Offset of the `n`th (0-based) occurrence of `needle`. +fn nth(src: &str, needle: &str, n: usize) -> u32 { + src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32 +} + +/// The name of the in-file declaration the use at `offset` resolves to. +fn resolved_name(s: &Semantics, offset: u32) -> Option<(String, SymbolKind)> { + let id = s.reference_at(offset)?.resolved()?; + s.symbol(id).map(|symbol| (symbol.name.clone(), symbol.kind)) +} + +/// The workspace's answer for the use at `offset` in `src`. +fn external(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option { + let s = sem(src); + let id = s.reference_id_at(offset)?; + resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned() +} + +// ---------------------------------------------------------------------- +// §2.9-31: DPI-export names +// ---------------------------------------------------------------------- + +const DPI: &str = "module m; + function automatic int get_v(); + return 1; + endfunction + task automatic poke(); + endtask + export \"DPI-C\" function get_v; + export \"DPI-C\" c_poke = task poke; +endmodule +"; + +#[test] +fn a_dpi_export_names_the_function_it_exports() { + let s = sem(DPI); + let at = nth(DPI, "get_v", 1); + assert_eq!(resolved_name(&s, at), Some(("get_v".to_string(), SymbolKind::Function))); +} + +#[test] +fn a_dpi_export_with_a_linkage_name_names_the_task_and_not_the_c_name() { + let s = sem(DPI); + let at = nth(DPI, "poke", 2); + assert_eq!(resolved_name(&s, at), Some(("poke".to_string(), SymbolKind::Task))); + // `c_poke` is a C linkage name — no SystemVerilog declaration answers it, + // and nothing is recorded for it. + assert!(s.reference_at(nth(DPI, "c_poke", 0)).is_none(), "the C name is not a reference"); +} + +#[test] +fn every_use_of_the_exported_function_includes_the_export() { + let s = sem(DPI); + let decl = + s.symbols().iter().position(|symbol| symbol.name == "get_v").expect("get_v is declared"); + let uses: Vec = s + .references() + .iter() + .filter(|r| r.resolved().is_some_and(|id| id.0 as usize == decl)) + .map(|r| r.name_span.start) + .collect(); + assert!(uses.contains(&nth(DPI, "get_v", 1)), "the export is a use: {uses:?}"); +} + +#[test] +fn a_dpi_export_in_a_package_names_the_packages_function() { + let src = "package p;\n function void f();\n endfunction\n export \"DPI-C\" function f;\nendpackage\n"; + let s = sem(src); + assert_eq!(resolved_name(&s, nth(src, "f;", 0)), Some(("f".to_string(), SymbolKind::Function))); +} + +#[test] +fn a_dpi_export_never_reaches_outside_its_own_scope() { + // IEEE 1800 §35.5.4: the exported subroutine is declared in the scope the + // export is written in. A same-named function elsewhere is not it, and a + // miss records nothing rather than an unresolved use to warn about. + let src = + "function void f();\nendfunction\nmodule m;\n export \"DPI-C\" function f;\nendmodule\n"; + let s = sem(src); + assert!(s.reference_at(nth(src, "f;", 0)).is_none(), "nothing in `m` declares `f`"); +} + +// ---------------------------------------------------------------------- +// oct_review L-5: interface port / virtual interface into a generate block +// ---------------------------------------------------------------------- + +const BUS_IF: &str = "interface bus_if (input logic clk); + logic data; + if (1) begin : g_mon + logic seen; + end +endinterface +"; + +#[test] +fn a_path_through_an_interface_port_into_its_generate_block_resolves() { + let user = "module u (bus_if bus, output logic o);\n assign o = bus.g_mon.seen;\nendmodule\n"; + let ws = index(&[("bus_if.sv", BUS_IF), ("u.sv", user)]); + let def = external(&ws, user, nth(user, "seen", 0)).expect("the tail resolves"); + assert_eq!((def.kind, ws.path(def.file)), (SymbolKind::Var, Some(Path::new("bus_if.sv")))); + let block = external(&ws, user, nth(user, "g_mon", 0)).expect("the block resolves"); + assert_eq!(block.kind, SymbolKind::Block); +} + +#[test] +fn a_path_through_a_virtual_interface_into_its_generate_block_resolves() { + let tb = "module tb;\n virtual bus_if vif;\n initial $display(vif.g_mon.seen);\nendmodule\n"; + let ws = index(&[("bus_if.sv", BUS_IF), ("tb.sv", tb)]); + let def = external(&ws, tb, nth(tb, "seen", 0)).expect("the tail resolves"); + assert_eq!(def.kind, SymbolKind::Var); +} + +#[test] +fn the_interfaces_generate_block_is_still_not_on_a_modules_connection_surface() { + // The widening is the interface's alone: a module's block stays + // hierarchical-only, so no connection list can name it. + let m = "module m;\n if (1) begin : g\n logic s;\n end\nendmodule\n"; + let ws = index(&[("m.sv", m), ("bus_if.sv", BUS_IF)]); + assert!(ws.member_in("m", "g", Surface::Connection).is_empty()); + assert!(!ws.member_in("m", "g", Surface::Hierarchical).is_empty()); + assert!(!ws.member_in("bus_if", "g_mon", Surface::Connection).is_empty()); +} + +// QA-R8-1 (fix round 1): the L-5 widening is the interface's alone. A +// module's generate-block internals stay exactly as on trunk — not workspace +// symbols, not declared names, not part of the symbol view, and answered by +// `hierarchical_declarations`. + +const MODULE_BLOCK: &str = + "module m;\n if (1) begin : g_lane\n logic lane_q;\n end\nendmodule\n"; + +#[test] +fn a_modules_block_internals_are_not_workspace_symbols() { + let ws = index(&[("m.sv", MODULE_BLOCK)]); + assert!(ws.workspace_symbols("lane_q").is_empty(), "an internal net is not a symbol"); + let found: Vec<&str> = ws.hierarchical_declarations("lane_q").map(|(unit, _)| unit).collect(); + assert_eq!(found, ["m.g_lane"], "the hierarchical census answers instead"); +} + +#[test] +fn a_modules_block_internals_are_not_declared_names_or_in_the_symbol_view() { + let facts = FileFacts::of(PathBuf::from("m.sv"), MODULE_BLOCK); + let (symbols, _) = facts.declared_names(); + assert!(!symbols.contains("lane_q"), "{symbols:?}"); + assert!(!symbols.contains("g_lane"), "{symbols:?}"); + // The symbol view is what `declares_the_same` compares: renaming a block's + // internal net moves no workspace symbol, so the two declare the same. + let renamed = FileFacts::of(PathBuf::from("m.sv"), &MODULE_BLOCK.replace("lane_q", "lane_d")); + assert!(facts.declares_the_same(&renamed), "a block-internal edit moves no symbol"); +} + +#[test] +fn an_interfaces_block_members_are_listed_like_its_own_signals() { + // The interface's own `data` is a connection member and so a workspace + // symbol; its block and the block's `seen` are now the same kind of + // member, and are listed the same way. + let ws = index(&[("bus_if.sv", BUS_IF)]); + let listed = |name: &str| -> Vec> { + ws.workspace_symbols(name) + .iter() + .filter(|symbol| symbol.name == name) + .map(|symbol| symbol.container.map(str::to_string)) + .collect() + }; + assert_eq!(listed("data"), [Some("bus_if".to_string())]); + assert_eq!(listed("g_mon"), [Some("bus_if".to_string())]); + assert_eq!(listed("seen"), [Some("bus_if.g_mon".to_string())]); + assert_eq!(ws.hierarchical_declarations("seen").count(), 0); + let facts = FileFacts::of(PathBuf::from("bus_if.sv"), BUS_IF); + let (symbols, _) = facts.declared_names(); + assert!(symbols.contains("data") && symbols.contains("g_mon") && symbols.contains("seen")); +} + +#[test] +fn a_typedef_named_like_a_module_does_not_share_its_blocks_connection_key() { + // QA's LOW collision: the typedef's inline member `g_lane` and the + // module's block `g_lane` are both keyed `m.g_lane`. On trunk only the + // typedef's fields are on the connection surface there, and so again. + let pkg = "package p;\n typedef struct packed {\n struct packed {\n logic q;\n } g_lane;\n } m;\nendpackage\n"; + let ws = index(&[("p.sv", pkg), ("m.sv", MODULE_BLOCK)]); + assert!(ws.member_in("m.g_lane", "lane_q", Surface::Connection).is_empty()); + assert!(!ws.member_in("m.g_lane", "q", Surface::Connection).is_empty()); + assert!(!ws.member_in("m.g_lane", "lane_q", Surface::Hierarchical).is_empty()); +} + +// ---------------------------------------------------------------------- +// oct_review L-10: member_key for inline nested struct members +// ---------------------------------------------------------------------- + +#[test] +fn member_key_names_a_nested_struct_members_fields_by_the_index_key() { + let src = "package p; + typedef struct packed { + struct packed { + logic q; + } ctrl; + } reg2hw_t; +endpackage +"; + let s = sem(src); + let q = s.symbols().iter().find(|symbol| symbol.name == "q").expect("q"); + let key = s.member_key(q.scope).expect("the field's scope has a key"); + assert_eq!(key, "reg2hw_t.ctrl", "the key the index files `q` under"); + let ws = index(&[("p.sv", src)]); + assert!(!ws.member_in(&key, "q", Surface::Connection).is_empty(), "and it finds it"); + let ctrl = s.symbols().iter().find(|symbol| symbol.name == "ctrl").expect("ctrl"); + assert_eq!(s.member_key(ctrl.scope).as_deref(), Some("reg2hw_t"), "the outer one unchanged"); +} + +// ---------------------------------------------------------------------- +// escaped identifiers in the word census, FACTS_FORMAT 23 +// ---------------------------------------------------------------------- + +#[test] +fn an_escaped_identifier_is_in_the_word_census_as_it_is_spelled() { + let src = "module g;\n logic \\loc.v ;\n assign \\loc.v = 1'b0;\nendmodule\n"; + let facts = FileFacts::of(PathBuf::from("g.sv"), src); + assert!(facts.words().iter().any(|w| w == "\\loc.v"), "{:?}", facts.words()); + let ws = index(&[("g.sv", src), ("h.sv", "module h;\nendmodule\n")]); + let files: Vec<&Path> = ws.files_mentioning("\\loc.v").filter_map(|id| ws.path(id)).collect(); + assert_eq!(files, [Path::new("g.sv")]); +} + +#[test] +fn the_facts_format_is_23() { + // Escaped words, DPI-export references and the interface's block surface + // all change what a record holds; one bump for the three. + assert_eq!(FACTS_FORMAT, 23); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/docs/features/semantic-refactor-r8/README.md b/docs/features/semantic-refactor-r8/README.md new file mode 100644 index 0000000..fa44df4 --- /dev/null +++ b/docs/features/semantic-refactor-r8/README.md @@ -0,0 +1,444 @@ + + +# semantic & refactor edge cases (Round 8) + +## Goal + +Close `docs/topo.md` §2.9 rows 12, 31 and 32 and `oct_review.md` L-5, L-6 +and L-10, plus the two parked edge cases the Round 7–12 handoff names: an +escaped identifier missing from `FileFacts::words` (so a census pre-filter +never opened a file that only wrote the escaped spelling — `lucisv_mcp` +`qa_m7.rs` R2) and a generate-scoped instance mistaken for the enclosing +module's own by a `bind u` shorthand rename (`vlog_refactor` +`qa_rename_implicit.rs` QA note 1). A bug-fix round: no features beyond the +six items. The persisted census changes three ways, so `FACTS_FORMAT` goes +22 → 23 **once** for all of them. + +## Assumptions + +- **#12.** `index_order` sorts with `Path`'s `Ord` and keeps the first copy of + a repeated path. Making it generic in the path type (`P: AsRef`) + orders a `&Path` exactly as the `PathBuf` it borrows from, so `Scope`'s + sources are byte-identical to before. +- **#31.** A DPI export's subroutine is declared in the scope the export is + written in (IEEE 1800 §35.5.4), so the name is bound `Target::InScope` — a + miss records nothing rather than an unresolved use to warn about. The + `c_name =` half is a C linkage name and is never a reference. `*::*` + package exports are unchanged. +- **#32.** Every real move today (`extract_module` to a new file, + `inline_module`) writes **one** edit per file it names in `moving`, so the + per-edit rule cannot refuse a real plan; the same-file extraction passes no + `moving` and keeps the per-file contract. A refactoring that stays in one + file may still carry a comment from one edit to another (the ANSI + conversion does), so the per-edit rule applies only to files a move names. +- **#32.** A piece is inside an edit's window only when it lies wholly inside + it; a piece straddling a window edge counts nowhere and so fails the rule — + the conservative direction. +- **L-5.** Hierarchical references through an interface port and through a + virtual interface into a named generate block of the interface are legal; + only blocks move to the interface's connection surface — its instances + stay hierarchical, as before. +- **L-5 (fix round 1).** Only an **interface's** named blocks (and blocks + nested in them) export their members on the connection surface + (`hierarchy::surface_in`, rooted at the unit the block chain hangs off). A + module's block members stay hierarchical-only, exactly as on trunk. The + first cut filed every block's members on the connection table, which leaked + module generate-block internals into the workspace-symbol listing (QA-R8-1). +- **L-6.** The bare-instance shape is recognised lexically, in the text that + holds the `bind`: `unit name` or `unit #(…) name`. A bare target naming an + instance declared in another file (upward resolution past the file) is not + recognised — the same scope as every other lexical H3 scan; such a `bind` + is still covered by the engine's `connections.rs` walk, which resolves + instances through the index. +- **L-10.** `member_key` of a scope owned by a `StructMember` is its + container's key, `.`, its name — `record::nested_key`'s spelling. Only a + struct member that opens a scope owns one, which is exactly the set + `nested_key` keys. +- **Escaped words.** An escaped identifier is spelled in the census as its + token is: backslash included, terminating whitespace not (`\my.sig`), the + spelling every symbol and pre-filter uses. Completion — the one reader that + inserts a word — filters escaped words out of its table. +- **Generate-scoped `bind u`.** "The enclosing module's own instance" is the + declaration upward lookup from the `bind` finds (`sites::nearest`). An + instance in a generate block is not found from outside the block, and is + found from inside it. + +## Handshakes + +- **`vlog_semantic::index_order`** is now generic in the path: + `index_order, T>(impl IntoIterator) -> Vec<(P, T)>`. + Source-compatible for every existing caller (`PathBuf` infers as before); + `vlog_refactor::Scope::assemble` calls it with `&Path`. +- **`FACTS_FORMAT` 22 → 23.** No field changes; three census changes: the `W` + group holds escaped identifiers; a DPI export's name is a reference; an + interface's named generate block, and the members of blocks inside an + interface, are filed on the connection surface (a module's blocks are + unchanged). Fix round 1 changed which records carry which surface tag + relative to the first cut; nothing was ever committed or released at 23, so + 23 names exactly one layout — this one — and needs no second bump. Every store written by 0.66.x is discarded whole by + the header check (`lucisv_server::index_cache`, `lucisv_mcp::cache`); the + existing "every other format" loops (`index_cache.rs` `1..FACTS_FORMAT`, + `qa_m6.rs` `FACTS_FORMAT - 1`) now cover 22. +- **`FileFacts::words` / `words::harvest`** now include escaped identifiers. + Readers: `lucisv_mcp` `declared.rs` and `diagnostics.rs` (pre-filter and + census — wanted), `lucisv_server::rename_trace` (census — wanted), the + semantic-lint mention guard in `lucisv` and `lucisv_server` (an escaped name + another file writes is now seen as mentioned — fewer false positives), and + completion. **Out-of-scope edit, flagged:** `lucisv_server/src/candidates.rs` + gains `insertable`, applied in `from_words` and `set_words`, so completion + never offers an escaped word, plus one test. +- **`Semantics::member_key`** now answers `reg2hw_t.ctrl` for an inline nested + struct member's scope (was `ctrl`). Consumers: `lucisv_server` `nav.rs`, + `same_file.rs`, `completion/related.rs` — each passes the key to + `member_in`, which now finds what the index filed. +- **Interface block members in the symbol listings (fix round 1, + deliberate).** An interface's own signals are connection members and so + `workspace_symbols` entries, `declared_names`, part of `symbol_view`, and + exported references. An interface's block members are now the same kind of + member and are treated the same way: `seen` of `bus_if.g_mon` is listed with + container `bus_if.g_mon`, `g_mon` with container `bus_if`, and neither is in + `hierarchical_declarations`. A **module's** block members are unchanged from + trunk on all four queries (pinned in `tests/semantic_r8.rs`). OpenTitan + `hw/ip` workspace-symbol count: see the fix-round-1 work log. +- **Key collision (QA LOW).** A typedef `m` with an inline nested member + `g_lane` and a module `m` with block `g_lane` share the key `m.g_lane`, as on + trunk; the module's block members are again on the hierarchical table only, + so `member_in("m.g_lane", "lane_q", Connection)` is empty as on trunk. An + *interface* `m` with a block `g_lane` beside such a typedef would merge both + on the connection table — the same by-name merge the member table already + has for every unit name, not new. +- **Pre-existing OpenTitan test failures, for the lead** (identical on trunk + `e229ff9`, not fixed here): see the fix-round-1 work log for each one's + outcome on this tree against trunk. +- **`check::verify_move`** (and so `verify_splice`) refuses edits that are out + of order, overlap, run past the end or split a character; no caller in the + workspace produces such a plan (the full `vlog_refactor` suite is green). +- Sync points touched for the number: `crates/vlog_semantic/src/facts.rs`, + `docs/topo.md` (lines stating the number only: the header paragraph, the + `vlog_semantic` module note, the package-reexports row's "codec is N now", + the ownership table, the workspace contract row), + `docs/site/src/content/docs/reference/rust-api.md`, + `docs/repository-analysis.md` (current-state lines; the historical + "top-rooted … = 22" left alone), `crates/vlog_semantic/src/words.rs`, + `crates/lucisv_server/src/candidates.rs` (doc). Tests assert the number via + the constant everywhere; `tests/semantic_r8.rs` pins 23. + +## Status / TODO + +- [x] #12 `Scope::assemble` uses `index_order` (pure refactor). +- [x] #32 independent reconstruction + per-edit equation 3 for move-named + files; Finding QA-1 pair proven accepted before, refused after. +- [x] L-6 bare-instance `bind` target in `scoped::binds_into`. +- [x] Generate-scoped `bind u` shorthand (`connections.rs`); test un-ignored. +- [x] #31 DPI-export names bound as `InScope` references. +- [x] L-5 interface generate blocks on the connection surface. +- [x] L-10 `member_key` for inline nested struct members. +- [x] Escaped identifiers in the word census; completion filters them; + `qa_m7.rs` test un-ignored. +- [x] `FACTS_FORMAT` 22 → 23 and every sync point. +- [x] Gates (fmt, clippy, guarded crate tests, OpenTitan ignored tests, + stamp) — see Work log. +- [x] Fix round 1: QA-R8-1 (module blocks back to trunk, interface blocks + only), architecture.md codec, article, QA's attack shapes as tests, real + OpenTitan runs compared with trunk. + +## Work log + +**2026-11-26 — dev.** Order: the `vlog_refactor`-only items first (#12, #32, +L-6, generate-scoped `bind u`), then every `vlog_semantic` census change +together so `FACTS_FORMAT` moved once. + +- **#12.** `index_order` made generic in the path type; `Scope::assemble` + replaces its hand-written sort/dedup with it. No new test (pure move); the + `vlog_refactor` suite is unchanged and green. +- **#32.** New `check/ledger/windows.rs`. `reconstruct` splices the edits in + from the last backwards and refuses out-of-order, overlapping, out-of-range + or mid-character edits — `apply` skips such an edit silently, so the two + disagreeing is now a refusal (`unplaceable`). The ledger reads the + reconstructed text. `Split::windows_match` holds equation 3 per edit in a + file the move names: each edit's window is located in the reconstructed + text by offsets alone, and the never-dropped pieces the re-lexed file holds + there must equal what the edit deleted outside the region (sender; `>=` for + `generated` text) or at least that (receiver). It is asked after + `Transit::check`, so every existing refusal keeps its sentence. Attack + module `check/in_place_attacks.rs` (8 tests): the QA-1 pair, a destination + relocation, a sender inventing a comment, overlapping and past-the-end + edits, and three accept controls (the real extraction, an edit rewriting + around its own comment, a one-file splice carrying a comment between + edits). Proof of tightening: with `in_place?` and the reconstruction + disabled, four of the eight fail (both relocations, overlap, past-end). + No check loosened. +- **L-6.** `scoped::binds_into` also counts a `bind` whose bare target the + same text instantiates as `unit` (`instantiates_as`, `past_parens`). Test + `qa_warning_scope::l6_…` (failed first: no warning; also pins that a bind + onto another module's instance stays silent). +- **Generate-scoped `bind u`.** `connections.rs` asks `visible_target` — the + declaration `sites::nearest` finds from the `bind` — and counts an + enclosing-module instance as the bind's own only when it is that one. + `qa_rename_implicit::qa_b_a_generate_scoped_instance_is_not_the_enclosing_modules_own` + un-ignored (failed first); added + `a_bind_inside_the_generate_block_sees_the_blocks_own_instance`. +- **#31.** `bind/item.rs`: `ExportDecl::Dpi` binds `dpi.name` as + `Target::InScope`. Tests in `vlog_semantic/tests/semantic_r8.rs` (resolution, + task with `c_name =`, package scope, no outward reach) and + `vlog_refactor/tests/rename_dpi_export.rs` (rename from either end, the C + name untouched, `find_references` includes the export). +- **L-5.** `hierarchy::surface_of`: `Interface` → `Block` is `Connection`; + `Block` → members are `Connection` (the second hop failed without it — a + block has one surface). Tests: resolution through an interface port and a + virtual interface, a module's block still off the connection surface, and + `qa_warning_scope::l5_…` (the rename edits both paths, no "could not be + resolved"). +- **L-10.** `Semantics::member_key` keys a `StructMember`-owned scope as + `{container key}.{name}`. Test: `reg2hw_t.ctrl`, and `member_in` finds `q`. +- **Escaped words.** `words::harvest` keeps escaped identifiers; + `words.rs`'s own test flipped to the new contract; + `lucisv_server::candidates::insertable` keeps them out of completion (test + `an_escaped_identifier_is_never_offered_as_a_word`). + `qa_m7::qa_rework_an_escaped_local_outline_lists_is_found` un-ignored. +- **`FACTS_FORMAT` 23** with its history entry in `facts.rs`; sync points as + listed in Handshakes. + +**2026-11-26 — dev, fix round 1** (QA-R8-1 and the lead's rulings). + +- **QA-R8-1.** `Block` → members are back to `Hierarchical` in + `hierarchy::surface_of`. New `hierarchy::surface_in(root, unit, member)` + puts a block's members on the connection surface only when the block chain + hangs off an **interface**; `record::collect_members` carries that `root` + (the unit itself, kept through nested blocks and inline struct members, + reset at a nested class/typedef/covergroup). Tests in `tests/semantic_r8.rs`, + three of which fail against the first cut: + `a_modules_block_internals_are_not_workspace_symbols` (`workspace_symbols` + empty, `hierarchical_declarations` = `m.g_lane`), + `…_not_declared_names_or_in_the_symbol_view` (`declared_names`, and + `declares_the_same` across a block-internal rename), + `a_typedef_named_like_a_module_does_not_share_its_blocks_connection_key` + (QA's LOW collision: `member_in("m.g_lane","lane_q",Connection)` empty), and + `an_interfaces_block_members_are_listed_like_its_own_signals` (the + deliberate choice, see Handshakes). `bus.g_mon.seen` / `vif.g_mon.seen` + still resolve (semantic tests) and rename (`qa_warning_scope::l5_…`). +- **OpenTitan `hw/ip` workspace symbols** (temporary probe, removed after + measuring: `WorkspaceIndex::build` over every `.sv/.v/.svh/.vh` under + `hw/ip`, 1,870 files, `workspace_symbols("").len()`, release, guarded): trunk + `e229ff9` **41,621** (QA's number), this tree **41,684**, first cut 43,670. + The 63 extra entries were diffed by `(name, container, kind)`: none + removed, and every addition belongs to one of nine interfaces + (`adc_ctrl_fsm_sva_if`, `csrng_cov_if`, `edn_cov_if`, `keymgr_dpe_if`, + `lc_tx_cov_array_if`, `otbn_trace_if`, `rom_ctrl_{,compare_,fsm_}bound_if`): + 26 blocks (container the interface) and 37 block members (33 variables, 4 + instances; container `iface.block`). That is exactly the L-5 change with + the listing rule an interface's own signals already follow. +- **`FACTS_FORMAT` 23** still names one layout: this one. Nothing was + committed or released at 23, so the first cut's layout was never stored by + anything the lead ships. +- **LOW:** `architecture.md` current-state sentence → codec 23 (its v0.61–0.66 + history line keeps 22); `windows.rs` refusal no longer says "take a + attribute" (pinned by `an_attribute_relocated_between_two_edits_is_rejected`). +- **Test quality.** `a_sender_edit_that_invents_a_comment_is_rejected` renamed + `control_…_keeps_its_old_refusal` and documented as a control (it also + asserts the new rule's sentence does not replace the old one). Added QA's + uncovered shapes as permanent tests: relocation into the receiver's own + insertion (two receiver edits), a dropped comment replaced by an + identical-text copy, the same laundered through the other copy's edit, an + attribute relocation, a swap of two comments between two edits, and the + unplaceable shapes (out of order, mid-character, reversed range; overlap and + past-end were already there). With `reconstruct` and `windows_match` + disabled, **12 of 16** fail; the other 4 are the three accept controls and + the old-refusal control. (The first identical-copy draft put the copy on + the same line, where `// dup // dup` lexes as one comment and the old + checks already refused it; moved to its own line.) +- **OpenTitan ignored tests, run for real** (`LUCISV_OPENTITAN` / + `LUCISV_BIND_ROOT` = `/Users/lucio/repo/opentitan`, guard `-t 1200` because + these index all of OpenTitan; none was killed), each also run on a detached + trunk worktree (`e229ff9`, separate target dir, removed afterwards) and + diffed (test names, panics, assertion text, warnings; thread ids and + timings masked): + - `lucisv_server --test opentitan_references`: 2/2 pass, as on trunk. + - `vlog_refactor --test opentitan_top_rooted`: 1 pass, assertion failure at + line 110, stack overflow in `the_whole_tree_…` — **identical to trunk** + (warnings included). + - `lucisv_mcp --test opentitan`: 1 pass, 2 failures (`:209` earlgrey + instance set, `:122` navigation `entropy_src_core.sv:3092`) — **identical + to trunk**. + - `vlog_refactor --test rename_bind` (ignored test): stack overflow — + **identical to trunk**. + All four are pre-existing and not fixed here (lead ruling). + +## QA log + +**2026-11-26 — QA (Opus 5.5).** Verdict: **FAIL** (one blocking finding, +QA-R8-1; everything else passes). Experiments ran in a scratch copy of the +working tree and in a detached trunk worktree (`e229ff9`), each with its own +target dir. Nothing experimental was left in this tree, and OpenTitan +`status --porcelain` was empty at the end. + +Gates: `cargo fmt --all -- --check` clean; `cargo clippy --workspace +--all-targets` clean; guarded `cargo test -p` all green: vlog_semantic 449/0 +(4 ignored), vlog_refactor 785/0 (5), vlog_linter 711/0, lucisv 162/0, +lucisv_server 2196/0 (52), lucisv_mcp 400/0 (3). `stamp_author.py --check` +clean. Release `lucisv check opentitan/hw`: 1,178, and the output is +byte-identical to trunk's (the mention guard did not move any rule). +`lucisv --check --no-cache opentitan/hw`: 3,967 would reformat + 72 +unchanged = 4,039 / 4,046 (7 parse failures), 0 verification failures. + +OpenTitan ignored tests, run with `LUCISV_OPENTITAN` set (without it, +`opentitan_top_rooted` and `opentitan_references` **skip silently in +0.00 s**): `opentitan_references` 2/2 pass. `opentitan_top_rooted` (1 +assertion failure plus 1 stack overflow), `lucisv_mcp --test opentitan` (2 +failures) and `rename_bind` (stack overflow) fail **identically on trunk**. +They are pre-existing, not this round's. + +#32 verifier: compared every check before and after. Nothing is loosened. +The same refusals run in the same order, `reconstruct` must equal `apply`'s +text, and `in_place?` only adds a refusal. Re-attack: 16 new pairs in a +scratch module. Ten of them are relocations: across two receiver edits, into +the receiver's insertion, a dropped `// dup` "replaced" by an identical-text +copy, the same thing laundered through the other dup's edit, an attribute, a +line comment, a generated `/* TODO: connect */`, a move into the region's +replacement text, and a swap of two comments between two edits. With the +pieces-match cases and the unplaceable shapes (unsorted, mid-character, +reversed), that is 11 refused that the new checks catch: all 11 are accepted +with `reconstruct` and `windows_match` disabled. Five more were already +refused by the old rules: duplicated transit (×2), `moving` naming only one +file (×2), and generated text laundering a moved comment. The dev's 8 tests +were confirmed the same way: 4 fail without the new code, 3 are accept +controls, and `a_sender_edit_that_invents_a_comment_is_rejected` was refused +before too. A directive relocated between two edits is still accepted, the +same as trunk: a directive is not a never-dropped piece. No false refusals: +all 13 public planners over LF / CRLF / non-ASCII / CRLF+non-ASCII +(add/remove port, propagate, expand `.*`, ANSI, organize imports including +offset 0, extract NewFile/SameFile ending at EOF, inline, rename) give the +same outcome as trunk. Hand-built splices with two inserts at one offset, an +edit at offset 0, an edit at EOF and adjacent edits verify. `Plan::settle` +sorts by (start, end), and extract/inline write one edit per moved file. + +#31: function and task, export before and after the declaration, exported +twice, `c_name =` (including a `c_name` spelled like a signal in scope), +interface, package and generate block, an undeclared name (records nothing, +rename at it refused), DPI imports unchanged, `*::*` unchanged. OpenTitan +`otbn_*` exports: 1 → 2 references and a clean rename (trunk 1 + warning). +L-10: nested-in-nested, union, interface typedef, and a same-named outer +typedef `ctrl` (trunk resolved the inner `q` to it) all improve; enum +unchanged. Generate-scoped `bind u`: nested, sibling, same name in the block +and the module (each side), and for-generate all behave per upward lookup. A +format-22 `index-cache-mcp` written by the trunk binary is discarded and +rebuilt by the new binary; the escaped `find` succeeds, and warm reuse works. + +Findings: + +- **QA-R8-1 (MEDIUM, blocking, this round)** — `workspace/hierarchy.rs:133` + (`Block` → members `Connection`) files the members of **every module's** + named block on the connection table. That puts them in + `workspace_symbols`, `declared_names` and `symbol_view`. Input: + `module m; if (1) begin : g_lane logic lane_q; end endmodule`. Expected + (trunk, and `index.rs:139-147`: "A module's internal net is not a + workspace symbol"): `workspace_symbols("lane_q")` empty and `lane_q` in + `hierarchical_declarations`. Actual: `lane_q@m.g_lane` listed and + `hierarchical_declarations` empty. On OpenTitan `hw/ip` the listing grows + 41,621 → 43,670. The Handshakes section names no `workspace/symbol` + consumer. +- LOW (this round): `docs/site/.../reference/architecture.md:55` still says + "codec **22**" in a current-state sentence. `docs/topo.md:376` still says + "DPI-export names remain unbound" (the lead's file). +- LOW (this round): `ledger/windows.rs:122` produces "take a attribute". +- LOW (this round): a typedef `m` with an inline nested member `g_lane` and a + module `m` with block `g_lane` now share the Connection key `m.g_lane` + (trunk merged them on the Hierarchical surface only). +- INFO (pre-existing): `\foo ` and `foo` are not one identifier anywhere. A + rename of `foo` silently misses `u.\foo ` in another file. The MCP log + calls a format-22 store "not written by lucisv 0.66.2". `verify_move` is + 115 lines (99 on trunk). +- Largest changed production files: `rename/connections.rs` 503, `facts.rs` + 467, `check/mod.rs` 444, `candidates.rs` 440, `bind/item.rs` 408. None of + them is over 600. + +**2026-11-26 — QA re-check of fix round 1 (Opus 5.5).** Verdict: **PASS**. +QA-R8-1 is closed, and every lesser item is fixed or accepted. A detached +trunk worktree (`e229ff9`) and a scratch copy of the tree were used, each with +its own target dir, and both were removed afterwards. OpenTitan +`status --porcelain` is empty. + +- **QA-R8-1 closed.** The module-block input matches trunk on + `workspace_symbols`, `hierarchical_declarations`, `member_in` on both + surfaces and the in-file postings (`posts [0]`, as on trunk), so `nav.rs` + `hierarchical_only` takes the trunk path for a module block. The + typedef-`m` / module-`m` key collision is back to trunk. +- **`root` threading.** 13 shapes were diffed against trunk: a block inside a + for-generate in an interface, blocks nested two deep, a module instantiated + inside an interface block, a class / typedef / covergroup / localparam / + procedural block inside an interface block, an interface nested in a + module, a program, an interface instance inside a module's block, modport + and virtual-interface paths, a `bind` into an interface block, and a direct + interface instance next to one inside a block. + - Every difference is an interface block or an interface block's member. + - The internals of `leaf` (`inner`, `leaf.lg.leaf_blk`) are unchanged. + - Class, typedef and covergroup members are unchanged, as on trunk. + - Program and module-with-class cases are identical to trunk. +- **OpenTitan `hw/ip`.** Workspace symbols go from 41,621 to 41,684. The + diff is additions only, all in nine interfaces: 26 blocks, 33 vars and 4 + instances. +- **L-5.** `bus.g_mon.seen` and `vif.g_mon.seen` are posted (2 uses). + Connection listings are sane: `bus_if` lists `[d, g_mon, mp]`, and + `bus_if.g_mon` lists `[seen]`. `qa_warning_scope::l5_…` (rename edits both + paths, no "could not be resolved") is green. +- **LOW items.** `architecture.md:55` now says codec 23 (`:89` is + historical). The `windows.rs` refusal now reads "take one elsewhere". The + collision is back to trunk. With `reconstruct` and `windows_match` disabled + in the scratch copy, 12 of `in_place_attacks.rs`'s 16 tests fail and the 4 + labelled controls pass, as claimed. +- **Gates.** fmt clean, clippy 0 warnings, stamp clean. Guarded `cargo test + -p`, all green: + + | crate | passed | ignored | + |---|---|---| + | vlog_semantic | 453 | 4 | + | vlog_refactor | 793 | 5 | + | lucisv_server | 2196 | 52 | + | lucisv_mcp | 400 | 3 | + | lucisv | 162 | 0 | + | vlog_linter | 711 | 0 | + +- **OpenTitan sweeps.** `lucisv check` gives 1,178 findings, byte-identical + to trunk. `--check --no-cache` gives 3,967 + 72 = 4,039 / 4,046 with 0 + verification failures. +- **OpenTitan ignored tests** (`LUCISV_OPENTITAN` set). `opentitan_references` + passes 2/2. `opentitan_top_rooted`, `lucisv_mcp --test opentitan` and + `rename_bind` fail identically to trunk. `guard -t 1200` killed nothing. +- **LOW (this round).** An instance inside an interface's block goes on the + connection surface and is listed as a workspace symbol + (`bus_if.g.u_inblk`; 4 on OpenTitan). The interface's direct instances stay + hierarchical-only and unlisted (`u_direct`). So the claim "listed like the + interface's own signals" holds for signals and parameters, but not for + instances. This is not a regression: a block instance is only reachable + through a connection read that trunk could not make at all. +- **INFO (pre-existing).** `bus.mp.g_mon.seen` is not posted (a modport is not + a path scope). A modport does not restrict which block members a + `bus_if.mp` port reaches, just as it does not restrict the interface's + signals. + +## Review + +**2026-11-26 — lead: accepted after two QA passes.** + +- Delivered: §2.9 #12, #31 and #32 (closed in `docs/topo.md`), `oct_review.md` + L-5, L-6 and L-10, escaped identifiers in `FileFacts::words` + (`FACTS_FORMAT` 23), and the generate-scoped `bind` shorthand; both + previously ignored tests are un-ignored and pass. +- #32 tightens the verifier and loosens nothing: QA compared every check + against trunk, ran 13 real planners over LF/CRLF/non-ASCII text with + identical outcomes, and wrote 16 attack pairs of its own, 11 of which trunk + accepted. +- The first cut of L-5 moved every module's block members onto the connection + surface (QA-R8-1); fix round 1 restricted it to interface blocks. OpenTitan + `hw/ip` workspace symbols: 41,621 → 41,684, additions only, all under nine + interfaces. +- Out-of-lane edit accepted: `lucisv_server/src/candidates.rs` keeps escaped + words out of the completion table, forced by the shared word census. +- Filed for later: §2.9 #68 (three ignored OpenTitan tests that fail on trunk + once `LUCISV_OPENTITAN` is set — the dev's first report counted their silent + skip as a pass), #69 (instances inside interface blocks are listed, direct + ones are not), #70 (`\\foo ` vs `foo` across files). +- OpenTitan: `lucisv check hw` byte-identical to trunk (1,178); format + 4,039/4,046 with 0 verification failures. + + diff --git a/docs/repository-analysis.md b/docs/repository-analysis.md index 366a728..6906f73 100644 --- a/docs/repository-analysis.md +++ b/docs/repository-analysis.md @@ -53,7 +53,7 @@ that future changes must preserve. |---|---| | `crates/vlog_parser` | Lexer/trivia, strict and tolerant recursive descent, AST/spans; `src/lib.rs`, `parser/`, `ast/` | | `crates/vlog_formatter` | AST → document IR → printer, presets/auto styles (`style.rs`, `auto.rs`), alignment, fences/selection ranges, equivalence & convergence; `format/mod.rs`, `verify.rs` | -| `crates/vlog_semantic` | File binding/resolution, workspace facts (`FACTS_FORMAT = 22`) and member lookup; `bind/`, `resolve.rs`, `workspace/{mod,index,update,reexport,hierarchy,path_units}.rs`, `facts.rs`, `imports.rs` | +| `crates/vlog_semantic` | File binding/resolution, workspace facts (`FACTS_FORMAT = 23`) and member lookup; `bind/`, `resolve.rs`, `workspace/{mod,index,update,reexport,hierarchy,path_units}.rs`, `facts.rs`, `imports.rs` | | `crates/vlog_linter` | 74-rule registry (`registry.rs::all_rules`: 7 Error, 24 Warning, 43 Style; 51 always on, 6 workspace-default, 17 opt-in; 10 Safe + 1 Unsafe fix), lazy semantics, options, inline/external waivers; `lib.rs`, `context.rs`, `registry.rs`, `waiver_file.rs` | | `crates/vlog_refactor` | Rename/references (`find_references_{with,batch,batch_with}`, `after_dot`, `home_set_for`/`home_sets_for`, `enclosing_unit`, deterministic `carry.rs`), ports, imports, extract/inline module (`extract/` CRLF-aware), instantiation plans, whole-edit verification; `scope.rs`, `rename/`, `ports/`, `imports.rs`, `extract/`, `inline/`, `check/` | | `crates/lucisv_core` | Config (`STYLE_NAMES`, `FileConfig`), filelists, cycle-aware tracked walks and warning channel, format cache (7-field `Entry` incl. `style` & `uvm_utils_indent`), unified diffs, atomic replacement; no language-engine dependency | @@ -103,8 +103,9 @@ advertised. `WorkspaceIndex::remove_file` tombstones closed out-of-scope buffers in-place while keeping slot IDs stable until `merge`/`absorb` (callers iterate `live_files()`), symlinked files resolve deterministically by `(dev, ino)` / canonical path without basename gating, and open `doc.large` buffers retain -their on-disk index record (subject to `maxFileSize`). `FACTS_FORMAT` is **22** -(`20` bind connections, `21` generate blocks, `22` top-rooted paths). +their on-disk index record (subject to `maxFileSize`). `FACTS_FORMAT` is **23** +(`20` bind connections, `21` generate blocks, `22` top-rooted paths, `23` Round 8's +escaped words, DPI-export references and interface generate blocks). **MCP & refactor parity:** `lucisv-mcp` checks disk stamps (including `first_mono` settlement for future mtimes) before serving answers, implements `KnownFacts` on diff --git a/docs/site/src/content/docs/reference/architecture.md b/docs/site/src/content/docs/reference/architecture.md index 7577b09..cfab81d 100644 --- a/docs/site/src/content/docs/reference/architecture.md +++ b/docs/site/src/content/docs/reference/architecture.md @@ -52,9 +52,10 @@ lucisv follows the same separation of concerns that makes ruff fast and maintain overlay disk facts. Scans publish index/include/completion batches together, while `server/ahead.rs` answers eligible read-only buffer requests and viewport colours mid-scan when preconditions hold and `after_scan` stages workspace-wide - mutators until `scanning` completes. Closed-file facts persist under codec **22**, + mutators until `scanning` completes. Closed-file facts persist under codec **23**, including package re-exports, tagged connection/hierarchical surfaces, `bind` - connections, generate blocks, and top-rooted paths; `WorkspaceIndex::remove_file` + connections, generate blocks, top-rooted paths, escaped identifiers in the word + census, and DPI-export references; `WorkspaceIndex::remove_file` tombstones removed entries without shifting live `FileId`s. `lucisv_mcp` composes the six reusable libraries directly over stdio (never `lucisv_server`), tracks disk timestamps cleanly (`Stamp::first_mono`), and implements `KnownFacts` on diff --git a/docs/site/src/content/docs/reference/rust-api.md b/docs/site/src/content/docs/reference/rust-api.md index a3c8b32..9081282 100644 --- a/docs/site/src/content/docs/reference/rust-api.md +++ b/docs/site/src/content/docs/reference/rust-api.md @@ -10,7 +10,7 @@ description: Navigational index of the main public APIs in lucisv’s reusable R This is a navigational API index, not source documentation. It summarizes the main public callable surface of the six reusable library crates in the workspace; command-line and language-server binaries are documented in their dedicated references. This index reflects **v0.66.2** (through Round 3 at committed `69383ea`), -including named formatter styles, selection formatting, codec-22 workspace facts, +including named formatter styles, selection formatting, codec-23 workspace facts (Round 8), tombstone index removal, and cached `find_references_*` / home-set APIs. For the complete signatures and fields, run `cargo doc --workspace --no-deps`; this hand-maintained index is not an exhaustive replacement for rustdoc. The parser's strict and tolerant entry @@ -165,11 +165,13 @@ tombstones slots without shifting live `FileId`s (use `live_files()` rather than indexing `0..files().len()`); `absorb` compacts tombstones and `fingerprint` remaps dense IDs cleanly. -`FACTS_FORMAT` is **22** in this snapshot. Cached facts include +`FACTS_FORMAT` is **23** in this snapshot. Cached facts include normal/macro identifier censuses, package re-export edges (`RX`), declaration/reference surface tags, `bind` target connections (`20`), generate-block scopes (`21`), -and top-rooted paths (`22`); `Def::lines.positions` can carry `DeclPositions` with -UTF-16 ranges for file-scope declarations. Any persisted shape or fact-census +top-rooted paths (`22`), and escaped identifiers in the word census, DPI-export +references and interface generate blocks on the connection surface (`23`); +`Def::lines.positions` can carry `DeclPositions` with UTF-16 ranges for +file-scope declarations. Any persisted shape or fact-census change needs a codec-version decision so stale caches cannot silently omit answers. ### Import usage diff --git a/docs/topo.md b/docs/topo.md index b6ac4ed..4b9781e 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -39,12 +39,12 @@ viewport-highlight and fast-actions; updated **2026-11-26** through (`71d13b5`); committed snapshot: **`69383ea`**. Nine workspace crates (CLI + LSP + MCP + six libraries); **75** registered lint rules (`8` error, `24` warning, `43` style); persisted facts codec -**22** (`FACTS_FORMAT = 22`). Releases `v0.50.0`–`v0.66.2` and Rounds 1–3 closed +**23** (`FACTS_FORMAT = 23`, Round 8). Releases `v0.50.0`–`v0.66.2` and Rounds 1–3 closed TODO §55 (`state/` decomposition), call hierarchy, top-rooted paths, range/selection formatting, sticky scroll, auto-`end` and instantiation highlighting, the eight-item overnight queue (TODO §71), `instance-folding` (TODO §72), and Round 1–3 correctness, -ordering, index-lifecycle, and MCP hardening items. After Rounds 4–7, §2.9 keeps open handshakes `#12`, `#31–32`, `#58–60`, `#64`, and -`#67` (filed by Round 7). +ordering, index-lifecycle, and MCP hardening items. After Rounds 4–8, §2.9 keeps open handshakes `#58–60`, `#64`, `#67` (filed by Round 7) +and `#68–70` (filed by Round 8). See [repository-analysis.md](repository-analysis.md) for evidence and validation. Feature QA logs and TODO checkboxes remain the acceptance authority; remote artifact verification and manual editor acceptance were not repeated here. @@ -249,7 +249,7 @@ the last three localized-reindex's; `WorkspaceIndex`: units, members, defines, i inheritance edge tables, incremental `update_file`/`remove_file`, reference postings, `files_spelling`, batch `absorb`, declaration `DeclLines`, `fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache; -`FACTS_FORMAT` is **22**, since §65.4); +`FACTS_FORMAT` is **23**, since Round 8); `instantiations.rs`, `classes.rs` (the shared walks, lifted from the server so the index census and the request handlers cannot drift); `imports.rs` (`import_usage`, `import_scopes`, `unused_imports`, `Exports`, `PackageExports`) @@ -373,7 +373,7 @@ output after content changes, and keep historical measurements dated. | walk-cycles / small-items-4 | core directory identity set and warning sink ↔ CLI/server walk callers; parser delay-comment fields and `ExprKind::Type` → formatter and instance planning | Released in v0.43–0.44; warning paths continue without changing CLI status, direct missing inputs remain errors | | didopen-cost | `undriven-net` local guards → existing `MentionOracle` predicate; diagnostics equality → server publish/request ordering | Released in v0.44.0; no new async work or index API | | type-name-spans | parser `DataType::name_span`/`segments`, disable-target span → binder `exact_or_empty` and census | Released in v0.45.0; `scan.rs` deleted; source text remains the exact-span oracle | -| package-reexports | binder export references → `FileFacts` RX group (introduced at codec 18; the codec is 22 now) ↔ workspace `reexport.rs` and shared member queries | Released in v0.45.0; package exports add no local import; DPI-export names remain unbound | +| package-reexports | binder export references → `FileFacts` RX group (introduced at codec 18; the codec is 23 now) ↔ workspace `reexport.rs` and shared member queries | Released in v0.45.0; package exports add no local import; DPI-export names bound since Round 8 (§2.9 #31) | | hierarchical-tail | `Surface` tags on declarations/references, codec 19 ↔ `workspace/hierarchy.rs`, member-tail resolution, completion and rename source selection | Released in v0.45.0; §2.9-23 closed; connection surface stays unchanged, instance tails read the hierarchical surface | | expand-wildcard / convert-to-ansi | `ports/{expand,ansi,merge}.rs` ↔ whole-edit verifier; server `ports.rs`, commands and action titles ↔ extension manifest; refactor → formatter test-only edge | Released in v0.46.0; explicit unmatched-port warnings and conservative merge/refusal rules | | organize-imports | semantic `imports.rs` → linter `unused-import` and refactor `imports.rs`; server `imports.rs` ↔ `source.organizeImports` / `lucisv.organizeImports` | Released in v0.47.0; 74 rules, new rule default off; package re-exports count as usage | @@ -747,7 +747,7 @@ update the filing README(s) and this file. | ~~9~~ | ~~Chasing `InheritedCandidate` through the member tables (in-file and cross-file) + hover for `extends`~~ — **delivered 2026-09-01 by class-member-access**: `resolve::member_in_chain` walks the in-file `extends` chain, `WorkspaceIndex::base_of` + `member_chain` walk it across files (inside `follow_one`, so hover and cross-file references agree), both cycle-guarded; `this.x`/`super.x` misses ride the same loop. `extends` hover/definition on the base name was already answered by overlay-promotion's type-position promotion. Residue filed in TODO §15 round 2: a `base` field on `ReferenceFact` so `this.x` misses get index postings too | class-semantics | ~~vlog_semantic~~ done | | ~~10~~ | ~~`Fmt::raw_text`'s string-crossing path emits a `Doc::Text` carrying newlines~~ — **delivered 2026-08-26 (`53f2269`)**: both `raw_text` and the parameterized-type `#( … )` now emit `Doc::Inline`, whose printer arm resumes measuring from the text's own last line. directive-split's README (QA round 3 note) still documents it as open and should be struck there too | directive-split QA | ~~vlog_formatter~~ done | | ~~11~~ | ~~Corpus scripts match `parse error:` / `lex error:` / `verification failed:` textually; a structured `--output-format json` for format mode would remove it~~ — **closed 2026-11-26 by `cli-path-r5` (Round 5A):** added `--output-format json` for CLI format mode (`main.rs`/`args.rs`, preserving frozen 0/1/2 exit codes) and wired `tools/corpus_check.sh` + `scripts/score.sh` to consume JSON with `classify_text_error` text fallback. | corpus-check | ~~crates/lucisv~~ done | -| 12 | `vlog_refactor::scope::Scope::build` re-derives sort-and-dedup by hand; could call `index_order` | indexing-ux | vlog_refactor | +| ~~12~~ | ~~`vlog_refactor::scope::Scope::build` re-derives sort-and-dedup by hand; could call `index_order`~~ — **closed 2026-11-26 by `semantic-refactor-r8` (Round 8):** `index_order` is generic over `P: AsRef` and `Scope::assemble` calls it; pure refactor. | indexing-ux | ~~vlog_refactor~~ done | | ~~13~~ | ~~Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap~~ — **delivered 2026-09-01 by struct-members**: anonymous enum variants land in the enclosing scope via the shared `bind_enum_body`; an anonymous `struct {…} s;` declarator and every inline nested struct field carry their own `Struct` child scope, and `member_scope` accepts any symbol whose child scope is a `Struct` scope. Residue filed in the struct-members README: cross-file anonymous struct *variables*, `typeDefinition` inside an anonymous aggregate written as a data declaration | types-decls | ~~vlog_semantic~~ done | | ~~14~~ | ~~A `program` node with `name_span`/`end_label_span` for linked editing~~ — **delivered by vendor-formal-grammar (0.30.0)**: `parser/item.rs` routes `program` to `parse_module("endprogram")`; the resulting `ItemKind::Module` carries both spans and `linked.rs::module_pairs` consumes them. Confirmed in the 2026-09-04 source audit. | linked-editing | ~~vlog_parser~~ done | | ~~15~~ | ~~Bind semantics: whether a `bind`'s target scope and connections should resolve through the workspace index (today only the instantiated module name is recorded)~~ — **delivered 2026-09-02 by bind-semantics**: `BindDirective::target` is `Vec`; a lone target binds as `Target::Module`, an instance path records nothing (a guess would be a wrong answer); each connection's port half is `Target::Port(inst.module)` and its expression half `Target::BindScope` — the target's own scope first (`resolve::in_bind_target`, `None` on a miss because generate blocks open scopes of their own), the workspace's one-segment member path when the target lives elsewhere, the writing scope last. `FACTS_FORMAT` 14 → 15 | bind | ~~vlog_semantic~~ done | @@ -766,8 +766,8 @@ update the filing README(s) and this file. | ~~28~~ | ~~**Project lint selection is not consumed by the server.** `enabled_rules` reads `ClientSettings`; `configured` reads project rule options and line length only. `[lint] select/ignore` currently controls CLI runs, while the editor needs `lucisv.lint.select/ignore`. Decide and test a common precedence contract before claiming project-wide parity.~~ — **closed by §42 (0.43.0):** `enabled_rules` picks the editor's list when set, else the project's, key by key (the CLI's `pick`); rejected project entries logged once with file:line | repository audit, 2026-09-04 | lucisv_server | | ~~29~~ | ~~An unknown rule name in the **editor's** `lucisv.lint.select`/`ignore` is still dropped silently, while §42 logs the same mistake in a project file (and `lucisv.lint.options` logs its bad entries). Wants the same once-only log through `notification.rs`.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.1):** `settings::rules` records every dropped name in `ClientSettings::lint_name_warnings` as `lucisv.lint.: unknown rule: `; `apply_settings` logs what the previous settings value did not already say — once per (setting, name), re-armed by a changed list. | lint-config-contract (QA) | lucisv_server | | ~~30~~ | ~~**An unreadable directory aborts the whole walk.** `Walk::dir` propagates `read_dir`'s error with `?`, so one permission-denied directory anywhere under the start — reachable now that a symlink to an outside directory is followed once (§2.9-8's ruling) — drops every file already found and fails the run. Found by walk-cycles' QA on a link to `/`. Wanted: skip the directory and say so through a warning channel the walk does not have today (the filelist-missing-file precedent), which is also where a dangling source link's warning belongs.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.2):** `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink; an unreadable directory, an unreadable `.gitignore` and a dangling source link are warned about (`warning: : ` on the CLI's stderr before the report, exit code unchanged; logged once per scan by the server through `report_scope`) and the walk continues. | walk-cycles (QA) | lucisv_core / lucisv / lucisv_server | -| 31 | **DPI-export name binding remains open.** Package re-export resolution closed §2.9-16, but the name in a DPI export is still not a semantic reference. Keep this separate from the delivered package-member traversal. | dpi-export request (b); package-reexports | vlog_semantic | -| 32 | **The refactoring verifier does not catch a same-file relocation of a never-dropped piece written as two well-formed edits** (delete here, insert there): `verify_move` computes `after` by applying the edits, so `positions_match`'s reconstruction cannot diverge from it and equation 3 of the ledger is unreachable through any real caller. No planner produces the shape today. Wanted: an independent `after` (the client's applied text, or a second reconstruction) and a test that isolates equation 3. Found by extract-module's QA re-attack. | extract-inline-module (QA) | vlog_refactor | +| ~~31~~ | ~~**DPI-export name binding remains open.** Package re-export resolution closed §2.9-16, but the name in a DPI export is still not a semantic reference. Keep this separate from the delivered package-member traversal.~~ — **closed 2026-11-26 by `semantic-refactor-r8` (Round 8):** a DPI export's name is bound as an `InScope` reference (`vlog_semantic/src/bind/item.rs`); the `c_name =` linkage name is never one; definition, references and rename work from either end (`FACTS_FORMAT` 23). | dpi-export request (b); package-reexports | ~~vlog_semantic~~ done | +| ~~32~~ | ~~**The refactoring verifier does not catch a same-file relocation of a never-dropped piece written as two well-formed edits** (delete here, insert there): `verify_move` computes `after` by applying the edits, so `positions_match`'s reconstruction cannot diverge from it and equation 3 of the ledger is unreachable through any real caller. No planner produces the shape today. Wanted: an independent `after` (the client's applied text, or a second reconstruction) and a test that isolates equation 3. Found by extract-module's QA re-attack.~~ — **closed 2026-11-26 by `semantic-refactor-r8` (Round 8):** `verify_move` reconstructs `after` independently (refusing unsorted, overlapping, past-end and character-splitting edits) and checks equation 3 per edit on windows of the re-lexed file (`check/ledger/windows.rs`); 16 attack tests in `check/in_place_attacks.rs`, 12 of which fail without the new checks. Nothing loosened. | extract-inline-module (QA) | ~~vlog_refactor~~ done | | ~~33~~ | ~~**`module_sources`' fan-out has no rung for a file that reaches an instance through an intermediate module it does not itself instantiate** (a bench naming `wrap.u_S.x` where `wrap` instantiates `S`): inline-module's hierarchical-reference refusal sees only the handed files, so such a reference is missed. Wanted: a transitive-instantiators rung (§49's hierarchical surface knows the path) in `module_sources` for the refactorings that must see every hierarchical use. Found by §53.2's QA.~~ — **closed 2026-09-07 by perf5-p2 (TODO §60.2): a fifth, opt-in rung** `Workspace::module_sources_reaching(file, modules, Reach { scopes })` in `lucisv_server/src/module_select.rs` — every file whose *token census* (`WorkspaceIndex::files_mentioning`, i.e. `FileFacts::words`) writes the dissolved instance's name down. That is exactly the set `no_hierarchy` can refuse from, so the selected set answers the refusal as the whole workspace does (asserted engine-run-twice on six shapes; QA attacked seven more incl. `$root`, a macro-built `bind` path, an escaped identifier, a generate label). **The transitive-instantiator walk this row asked for was implemented and rejected:** a `bind tb.u_wrapper.u_top.u_sub …` in an SVA file that instantiates nothing in the chain has no instantiation edge for any walk to follow — structurally weaker, confirmed by QA. Only inline-module asks for the rung (extract and ports pass `Reach::none()`, unchanged in answer and cost); worst corpus cost 2 % of files on a command, +1.2 ms at the measured site. | extract-inline-module (QA) | lucisv_server / vlog_refactor | | ~~34~~ | ~~**The format cache omits `Config::uvm_utils_indent`.** CLI `args.rs::config_with` applies the key, but `main.rs::entry_for` and core `cache::Entry` serialize/compare only content, line length and indent (plus the store version). On one UVM class: cache a clean verdict with the option false, change only the option to true, then cached `--check` exits 0 while `--no-cache --check` exits 1. Wanted: key/equality/codec coverage for the option and a regression for both toggle directions. Until fixed, use `--no-cache` or delete the format cache after toggling. See repository-analysis.md for the bounded reproduction.~~ — **fixed 2026-09-07 (TODO §59, 0.50.0):** `Entry` carries `uvm_utils_indent`, `entry_for` fills it, the store line has it as a fourth field; a well-formed five-field (0.49.0) line is dropped individually like another version's entry; the audit's probe is `changing_uvm_utils_indent_invalidates_the_entry` in `lucisv/tests/cli.rs`, both directions. | repository audit, 2026-09-07 | lucisv_core / lucisv | | ~~35~~ | ~~**MCP-5 → `vlog_parser`:** lift the server's `expand.rs` (one-step macro expansion) into `vlog_parser::defines` as a pure move so `lucisv-mcp`'s `defines` can offer expansion~~ — *moot since M7: `defines` folded into `find`, which lists a macro's definitions and no expansion* | mcp-navigation | ~~vlog_parser~~ moot | @@ -803,6 +803,9 @@ update the filing README(s) and this file. | ~~65~~ | ~~**`ci.yml` runs `cargo test --workspace` bare in both jobs**, not through `tools/guard.sh` as CLAUDE.md's runaway guard asks of every `cargo test`; predates 0.65.9 for the macOS job, the Linux runner is resource-capped. Recorded, not judged (topo refresh 2026-11-19)~~ — **closed 2026-11-26 by `ci-gates-r4` (Round 4A):** `tools/guard.sh` uses POSIX `ps -Ao pid=,ppid=`, validates flags, closes fd 3, and wraps `cargo test --workspace` in both `checks` (`-m 8 -t 1800`) and `linux` (`-m 6 -t 1800`) jobs of `.gitea/workflows/ci.yml` (plus `linux` in `release.yml`). | topo refresh (draft discrepancy 10) | ~~CI (lead)~~ done | | ~~66~~ | ~~**The `cross` gate step reports `SKIPPED (no toolchain)` rather than failing** when `~/.rustup/toolchains/stable-aarch64-apple-darwin` is absent, so a green `gates.sh` on another machine does not prove the cross build (topo refresh 2026-11-19)~~ — **closed 2026-11-26 by `ci-gates-r4` (Round 4A):** `tools/gates.sh` fails missing cross toolchain by default (opt-in `--allow-skip-cross` only) and adds the `stamp` step (`python3 tools/stamp_author.py --check`) matching `ci.yml`. | topo refresh (draft discrepancy 11) | ~~tools/ (`gates.sh`, lead)~~ done | | 67 | **`lucisv_core::config::parse_array` splits `lucisv.toml` arrays at every comma, quoted or not**, so a glob such as `"**/{a,b}/*"` in `exclude` or a waiver path with a comma is cut in two. Rule options were given a quote-aware splitter in Round 7 (`vlog_linter/src/options/list.rs`); the config arrays want the same treatment and a regression. | linter-hardening-r7 (dev) | lucisv_core | +| 68 | **Three ignored OpenTitan tests fail on trunk when actually run** (they skip silently in 0.00 s unless `LUCISV_OPENTITAN` is set, so nobody saw): `vlog_refactor --test opentitan_top_rooted` (assertion at :110 and a stack overflow in `the_whole_tree_…`), `lucisv_mcp --test opentitan` (2 failures: earlgrey instance set at :209, navigation at :122), `vlog_refactor --test rename_bind -- --ignored` with `LUCISV_BIND_ROOT` (stack overflow). Identical before and after Round 8. Wanted: a diagnosis of each (the two overflows first), and a skip that says it skipped. | semantic-refactor-r8 (QA) | vlog_refactor / lucisv_mcp | +| 69 | **An instance inside an interface's generate block is on the connection surface and listed as a workspace symbol; the interface's direct instances are neither** (`interface bus_if; leaf u_direct(); if (1) begin : g leaf u_inblk(); end endinterface`). Four entries on OpenTitan `hw/ip`. Wanted: one rule for both. | semantic-refactor-r8 (QA re-check) | vlog_semantic | +| 70 | **`\\foo ` and `foo` are never treated as one identifier across files**: a rename of `foo` silently misses `u.\\foo ` written in another file, with no warning (IEEE 1800 §5.6.1 makes them the same name). Round 8 put escaped spellings in `FileFacts::words` as written; the pre-filter and the resolver still compare spellings. Same on trunk before Round 8. | semantic-refactor-r8 (QA) | vlog_semantic / vlog_refactor | --- @@ -823,7 +826,7 @@ untouched, reusing existing arms. |---|---| | `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, decomposition-parser, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port*, *null-items*, *constraint-bodies*, *covergroup-bodies*, *fragment-mode*, *vendor-formal-grammar*, *comment-slots*, *bind-semantics*, *sva-bodies* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) | | `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter, decomposition-formatter, and the layout halves of constraint-bodies, covergroup-bodies, comment-slots, bind-semantics and sva-bodies (`format/`), format-styles (`style.rs`, `auto.rs`, `align.rs` mode) | -| `vlog_semantic` | vlog-semantic (`bind/`, `resolve.rs`, `model.rs`), workspace-index (`workspace/`), decomposition-semantic, class-semantics, interface-semantics, class-member-access, struct-members, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` and `Semantics::symbols_named`), hover-line-index (`DeclLines`, facts codec), vscode-hierarchy-sidebar's declaration/instance positions, scan-interleave (`WorkspaceIndex::absorb`), semantic-lints-on's word census, bind-semantics and sva-bodies, refactor-rename's performance amendment (`files_spelling`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`, facts-from-analysis), incremental-index (`update_file`, edge/reference tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; `FACTS_FORMAT` 22; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives), localized-reindex (`workspace/{dependents,references,replace}.rs`), index-lifecycle-r2 (`tombstoned` mask + `live_files()` in `workspace/{mod,index,update}.rs`) | +| `vlog_semantic` | vlog-semantic (`bind/`, `resolve.rs`, `model.rs`), workspace-index (`workspace/`), decomposition-semantic, class-semantics, interface-semantics, class-member-access, struct-members, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` and `Semantics::symbols_named`), hover-line-index (`DeclLines`, facts codec), vscode-hierarchy-sidebar's declaration/instance positions, scan-interleave (`WorkspaceIndex::absorb`), semantic-lints-on's word census, bind-semantics and sva-bodies, refactor-rename's performance amendment (`files_spelling`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`, facts-from-analysis), incremental-index (`update_file`, edge/reference tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; `FACTS_FORMAT` 23; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives), localized-reindex (`workspace/{dependents,references,replace}.rs`), index-lifecycle-r2 (`tombstoned` mask + `live_files()` in `workspace/{mod,index,update}.rs`) | | `vlog_linter` | linter-core, lint-harness, lint-rules-2, semantic-lints (`signals.rs`), semantic-lints-on (workspace oracle), one-parse (`context.rs`) | | `vlog_refactor` | refactor (plan), refactor-rename (including `prepare_rename_here` / `rename_name_at` selector half), refactor-ports (including module-target selectors), refactor-instantiate, references-nav (whole-scope equivalence oracle), and the refactor half of decomposition-semantic; expand-wildcard and convert-to-ansi (`ports/`), organize-imports (`imports.rs`), extract-inline-module (`extract/`, `inline/`, `check/ledger.rs`), refactor-correctness-r1 (UTF-8 `skip_string`, deterministic `carry.rs`, `enclosing_unit`, `ports/remove.rs` span fix, `extract` CRLF preservation), mcp-hardening-r3 (`find_references_{with,batch,batch_with}`, `after_dot`, `home_set_for`/`home_sets_for`) | | `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`), format-styles (`STYLE_NAMES`, cache `style` field) | @@ -933,7 +936,7 @@ ownership explicitly. | `lucisv_server/src/server/ahead.rs` (`answer_from_the_buffer`, `REACH`, `can_reach`) + `same_file.rs` | fast-actions (viewport-highlight's colour exemption moved here); amended by `server-ordering-r1` (`renamed_here` `enclosed_by_unit`, `take_ahead_applied`) | `process_batch`, `set_aside`, `answer_ahead_of`, `open_then_widen`, `answer_ahead_mid_widen`, `answer_held_ahead`; `viewport.rs` (`colours_may_go_ahead`, `coloured_ahead`); every `same_file` handler (hover, nav, symbols, folding, selection, linked editing, highlights, references, prepareRename, signature help) | The precondition is stated once, on `answer_from_the_buffer`, and nowhere else; a new place that offers a request early calls it, never a copy. `REACH` lists what is **proved** harmless — a notification without a row waits, a handler that starts touching a buffer it does not name moves its row to `Any`, a new `Pending` kind is classified in `can_reach`. `same_file::answered_by_the_buffer` must change with any handler arm that starts reading the index or the overlay (and `same_file::renamed_here` stays aligned with `rename_preflight` via `enclosed_by_unit` for duplicate-unit ambiguity); `fast_actions_differential.rs` (early == settled) is the alarm. | | `lucisv_server/src/state/` (`state.rs` until TODO §55) | lucisv-server; amended by filelist, index-scope, scan-interleave, indexing-ux, incremental-index, index-persistence, hover-line-index, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`), refactor performance fan-outs, index-lifecycle-r2 (`reconcile.rs`, `ScanAbsorbed`, `(dev, ino)` symlink dedup, `close_and_reconcile`, `doc.large` disk preservation) | every handler | `Workspace` is immutable through request handlers except the interior-mutable four-entry/8 MiB `FileView` cache. The scope ladder (filelist > `index.scope: "workspace"` > folder-scope at shipped depth 2; a rootless session never climbs; it reads flat at depth 0 and walks descendants at positive depth (including the default 2)) and open-buffer overlay are contracts. `Scan` has whole/widen shapes (`ScanAbsorbed` tracks mid-scan absorbed buffers for `closing_affects_running_scan`) and one step/finish path; index/candidate/include prefixes publish together. Discovery, widen, overlays, and handlers (`index_path_for`/`is_same_file`) deduplicate symlinked files by `(dev, ino)` / canonical path to one lexicographically smallest spelling without basename gating, while disk records stay indexed for `doc.large` (subject to `maxFileSize`). `module_sources`, `rename_sources`, and `include_sources` must remain supersets of what their engines can edit/refuse over; `rename_sources` falls back to `sources()` when an ambiguous posting prevents a proven bound. `update_one` and a completed scan must equal a fresh build (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. **(2026-09-12)** `Document::new`'s derivations are individually traced (`lint_trace::Rebuild`), so a stage added to or removed from that constructor wants a `Rebuild` variant beside it. | | `lucisv_server/src/settings.rs` | editor-settings | folders-and-config, indexing-ux, index-scope, index-persistence, inline-templates, will-save-wait-until, filelist, large-file-mode | One parser for both doors (push and pull, via `from_section` re-wrapping). Every key drops garbage independently; defaults that are not "silence" (1 MiB cap, log on, persist on, 4 MiB large-file threshold) are hand-written in `Default`. `set_client_settings` returns whether a reindex is owed — new keys must decide that question explicitly. | -| `vlog_semantic/src/workspace/` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope, hover-line-index, scan-interleave, member semantics, semantic-lints-on, bind-semantics, SVA bodies, refactor-rename performance, index-lifecycle-r2 (`tombstoned` mask + `live_files()`) | server state, hierarchy/lens/type-hierarchy, refactor, completion, semantic lints, `lucisv_mcp` | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change (current 22), edge/posting tables built by the same lifted walks the engines use. `DeclLines` must round-trip and participate in `fingerprint`; `absorb` compacts tombstones and must equal one build over the resulting record set; `remove_file` tombstones in-place without shifting `FileId`s (all callers use `live_files()`, never `0..files().len()`); `files_spelling` must continue to include unresolved non-empty external/inherited paths or rename loses its dangling-use refusal; `FileFacts::words` is the shared project mention/completion census. | +| `vlog_semantic/src/workspace/` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope, hover-line-index, scan-interleave, member semantics, semantic-lints-on, bind-semantics, SVA bodies, refactor-rename performance, index-lifecycle-r2 (`tombstoned` mask + `live_files()`) | server state, hierarchy/lens/type-hierarchy, refactor, completion, semantic lints, `lucisv_mcp` | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change (current 23), edge/posting tables built by the same lifted walks the engines use. `DeclLines` must round-trip and participate in `fingerprint`; `absorb` compacts tombstones and must equal one build over the resulting record set; `remove_file` tombstones in-place without shifting `FileId`s (all callers use `live_files()`, never `0..files().len()`); `files_spelling` must continue to include unresolved non-empty external/inherited paths or rename loses its dangling-use refusal; `FileFacts::words` is the shared project mention/completion census. | | `vlog_refactor/src/rename/` | refactor-rename; shared by references-nav, the performance wave, refactor-correctness-r1, mcp-hardening-r3 | server rename/prepareRename/references and port refactor verification, `lucisv_mcp` | `Scope` remains the whole-scope authority and `collect_occurrences` the one rename/references walk. `enclosing_unit` (shared with `rename_preflight` and `same_file::renamed_here`) guards duplicate file-scope units for members/ports/blocks. `references.rs` (`find_references_with`/`find_references_batch_with`) reuses `&dyn KnownFacts`, and `after_dot` / `home_set_for` / `home_sets_for` are shared with `lucisv_mcp`. The fast `prepare_rename_here` answer/refusal and `rename_name_at` target are parity contracts, not alternate semantics. Any new refusal must be expressible on the fast path or force a deferral; any new occurrence shape must be reflected in the server fan-out or trigger its all-sources fallback. | | `vlog_parser/src/token.rs` keyword table | completion-core (`KEYWORDS` export) | lexer, pairs.rs, editor grammar (test-locked), completion | Adding a keyword = lexer change + `pairs.rs` re-check + a hand edit to the grammar (`tests/grammar.rs` names the missing word) + potentially `verify.rs`-adjacent behavior. dv-statements added `randcase`/`let` to `is_keyword` and recorded it as shared with the adjacent lexer-cleanup round — the precedent for treating this file as coordinated even between back-to-back rounds. | | `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, verbose-timing, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). `lucisv.verbose` is special: it changes a spawn argument and therefore restarts the server instead of flowing through the ordinary settings push. Version number is one of the four version files. |