Rename warns about macro arguments it did not read; Scope at the crate root; lucisv check --rules-doc

TODO section 29; closes docs/topo.md 2.9-18 (server half) and 2.9-5;
the second half of coverage_gaps M12.
FileFacts::macro_words - the identifier-shaped words seen inside macro
invocations, directive lines and attributes (words::harvest_raw, which
shares its raw-token match with harvest so the two cannot drift) -
tag MW, FACTS_FORMAT 16 -> 17 (+3.1 percent corpus / +1.7 percent
opentitan store, measured). WorkspaceIndex::files_naming_in_macros is
files_mentioning's twin, and lucisv_server::rename appends one warning
per such file that lies outside the set rename_sources built: no new
rung, nothing read, 58 files in 186 microseconds for clk on opentitan.
Pinned by a three-file case and its no-double-warning control, run by
QA against the real server; QA also found an organic instance in
opentitan (cipher_crypt inside a DV_CHECK_FATAL) that 0.33.0 never
mentioned. vlog_refactor's Scope moves to the crate root (pure move,
counts identical). lucisv check --rules-doc prints rules_markdown(),
takes no files, is lint-only; the example binary is gone.
3 226 tests / 48 binaries, corpus 814/820, opentitan check byte-
identical to 0.33.0.

docs/features/macro-word-census/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-03 02:41:15 -07:00
1 parent d1821ff859
commit 40a7b478c5
20 files changed
+1136 -74

No files matched your search

+14 -8
View File
@@ -3111,15 +3111,21 @@ amendments in refactor-rename / semantic-lints-on / index-persistence /
lint-rules-2 READMEs, TODO §29. Runs in parallel with §30 (disjoint
files; topo: §29 touches the FACTS handshake, §30 the AST — no shared
edge).
- [ ] 29.1 `Scope` at the crate root, counts identical
- [ ] 29.2 `harvest_raw` + `FileFacts::macro_words` (FACTS 17) +
- [x] 29.1 `Scope` at the crate root, counts identical
- [x] 29.2 `harvest_raw` + `FileFacts::macro_words` (FACTS 17) +
`files_naming_in_macros` + the server warning; the three-file pin
and its control
- [ ] 29.3 `--rules-doc`; usage text; tests; example removed;
`docs/lint-rules.md` regenerated if present
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus gate 814/820;
store measurement (+bytes for `M` on corpus and opentitan, expect
small); opentitan read-only sweep unchanged
and its control — the group's tag is `MW`, not `M` (already the
member group); no new `Workspace` rung (`rename_sources` returns
the path set the server subtracts)
- [x] 29.3 `--rules-doc`; usage text; tests; example removed;
`docs/lint-rules.md` regenerated if present — it is not present,
and the docs-site rules page is hand-written prose, not generated
text, so there was nothing to regenerate and no drift test
- [x] Gates: fmt/clippy/`cargo test --workspace` (3 226/0/42 over 48
binaries, from 3 215/0/40); corpus gate 814/820, the same six;
store measurement +123 402 bytes (+3.11 %) on the corpus and
+743 873 (+1.66 %) on opentitan; opentitan `lucisv check` sweep
byte-identical, working tree untouched
- [ ] QA: rename of `clk` in an opentitan IP with the server, timing
before/after (must not regress; the warning list must name only
files outside the source set), the pins re-derived
+32 -3
View File
@@ -71,6 +71,9 @@ pub struct Options {
pub select: Vec<String>,
/// `check` only: rules to drop from whatever `--select` left.
pub ignore: Vec<String>,
/// `check` only: print the generated rule reference and exit, reading no
/// file at all.
pub rules_doc: bool,
/// Files, directories, or the single input `-`.
pub inputs: Vec<String>,
/// `-f`: EDA filelists whose files are added to [`Options::inputs`].
@@ -200,6 +203,11 @@ CHECK OPTIONS (`lucisv check` only):
--fix apply safe fixes and write the files back
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
one yet, so today this changes nothing)
--rules-doc print the rule reference — every rule, what it
reports and whether it has a fix — as Markdown on
stdout and exit 0. Generated from the registry, so
it always describes the rules this build ships;
takes no files and lints nothing
Suppress a finding with a comment: `// lucisv: waive <rule>` on the line
itself or on the line above it, or a `// lucisv: waive-start <rule>` /
@@ -290,6 +298,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
unsafe_fixes: false,
select: Vec::new(),
ignore: Vec::new(),
rules_doc: false,
inputs: Vec::new(),
filelists: Vec::new(),
};
@@ -369,6 +378,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--ignore requires a value")?;
opts.ignore.extend(split_rules(&v));
}
"--rules-doc" => opts.rules_doc = true,
"-h" | "--help" => {
print_help();
std::process::exit(0);
@@ -382,9 +392,16 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
s => opts.inputs.push(s.to_string()),
}
}
// A filelist is an input like any other, so `-f files.f` alone is a
// complete command line and needs no positional argument.
if opts.inputs.is_empty() && opts.filelists.is_empty() {
// `--rules-doc` prints the rule reference and reads nothing, so it is the
// one invocation with no input at all — and being given one means the
// caller expected files to be linted, which they would not be.
if opts.rules_doc {
if !opts.inputs.is_empty() || !opts.filelists.is_empty() {
return Err("--rules-doc takes no files".to_string());
}
} else if opts.inputs.is_empty() && opts.filelists.is_empty() {
// A filelist is an input like any other, so `-f files.f` alone is a
// complete command line and needs no positional argument.
return Err("no input files (try `lucisv --help`)".to_string());
}
// Repeating the flag is the same as one comma-separated list; both spell
@@ -427,6 +444,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
(opts.output_format != OutputFormat::Text, "--output-format"),
(!opts.select.is_empty(), "--select"),
(!opts.ignore.is_empty(), "--ignore"),
(opts.rules_doc, "--rules-doc"),
];
let format_only = [
(opts.check, "--check"),
@@ -595,4 +613,15 @@ mod tests {
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
}
#[test]
fn rules_doc_is_the_one_check_that_needs_no_input() {
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
// ... and refuses one, rather than accepting a path it would not read.
assert!(parse(&["check", "--rules-doc", "rtl"]).is_err());
assert!(parse(&["check", "--rules-doc", "-f", "a.f"]).is_err());
// Lint-only, like every other `check` flag.
assert!(parse(&["--rules-doc"]).is_err());
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
}
}
+6
View File
@@ -84,6 +84,12 @@ fn run(opts: &Options) -> ExitCode {
/// `lucisv check`: the linter over the same file set the formatter would take.
fn run_check(opts: &Options) -> ExitCode {
// Before any rule is selected and before any path is gathered: the rule
// reference is a property of the build, not of a run over files.
if opts.rules_doc {
print!("{}", vlog_linter::rules_markdown());
return ExitCode::SUCCESS;
}
// The command line's own names are checked before anything is walked, so
// a typo'd `--select` fails in milliseconds rather than after the scan.
// A `lucisv.toml`'s names are checked per file below, where they are read.
+40
View File
@@ -1880,3 +1880,43 @@ fn a_signal_named_only_inside_a_macro_argument_is_not_reported_unused() {
"a string's contents are not mentions"
);
}
/// `lucisv check --rules-doc` prints the generated rule reference and nothing
/// else. Generated from the registry, so a rule added without documentation
/// still shows up here — which is the whole point of the flag.
#[test]
fn rules_doc_prints_the_generated_reference() {
let out = run(&["check", "--rules-doc"]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert_eq!(text.lines().next(), Some("# lucisv lint rules"), "{text}");
for rule in vlog_linter::all_rules() {
let heading = format!("\n## {}\n", rule.name());
assert_eq!(
text.matches(&heading).count(),
1,
"`{}` wants exactly one section in the reference",
rule.name()
);
}
// The flag is the tool now, so it agrees with the library by construction.
assert_eq!(text, vlog_linter::rules_markdown());
}
/// The flag lints nothing, so a path beside it is a command line that means
/// two different things — refused rather than silently ignored.
#[test]
fn rules_doc_refuses_files_and_belongs_to_check() {
let dir = TempDir::new("rulesdoc");
let file = dir.write("m.sv", FORMATTED);
let out = run(&["check", "--rules-doc", &file]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("--rules-doc takes no files"), "{}", stderr(&out));
let out = run(&["format", "--rules-doc"]);
assert_eq!(code(&out), 2);
assert!(
stderr(&out).contains("--rules-doc is only valid for `lucisv check`"),
"{}",
stderr(&out)
);
}
+124 -3
View File
@@ -13,11 +13,13 @@
#![allow(clippy::mutable_key_type)]
use std::collections::HashMap;
use std::path::PathBuf;
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
use vlog_parser::LineIndex;
use crate::convert::Positions;
use crate::locate::display_name;
use crate::state::Workspace;
use crate::uri::path_to_uri;
@@ -59,8 +61,9 @@ pub fn rename(
// is the one voice that decides, and it decides over the files below. A
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
// the engine will say so, and saying it is cheap either way.
let sources = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(&path, &name, Some(new_name)),
let old_name = vlog_refactor::rename_name_at(&doc.semantics, offset);
let sources = match &old_name {
Some(name) => ws.rename_sources(&path, name, Some(new_name)),
None => ws.sources(),
};
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
@@ -90,7 +93,43 @@ pub fn rename(
.collect(),
);
}
Ok((WorkspaceEdit::new(changes), refactoring.warnings))
let mut warnings = refactoring.warnings;
if let Some(name) = &old_name {
warnings.extend(unread_macro_warnings(ws, name, &sources));
}
Ok((WorkspaceEdit::new(changes), warnings))
}
/// One sentence per file that writes the old name inside a macro invocation,
/// a directive line or an attribute and was **not** among the files the engine
/// was handed.
///
/// The engine warns about a macro argument in every file it reads, but the
/// fan-out that decides which files those are has no rung for a file whose
/// only relationship to the name is that text — deliberately: the census of
/// every file merely *spelling* `clk` is untagged, and a rung on it would
/// re-read the workspace and bring back the 2.5–3.0 s cost
/// `prepare_rename_here` removed (`docs/topo.md` §2.9-18). So the index
/// answers the narrower question instead — which files name it in text
/// nothing can edit — off a table it already holds, reading no file and
/// parsing nothing. The rename stays as fast as it was and stops being silent
/// about the one shape it cannot see.
///
/// Subtracting the handed set leaves out every open buffer too, because
/// [`Workspace::rename_sources`] puts every open buffer in it.
fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String)]) -> Vec<String> {
let index = ws.index();
index
.files_naming_in_macros(name)
.filter_map(|file| index.path(file))
.filter(|path| !sources.iter().any(|(handed, _)| handed == path))
.map(|path| {
format!(
"`{name}` also appears inside a macro invocation in {}, which this rename did not read; check it by hand — a macro argument cannot be edited.",
display_name(path)
)
})
.collect()
}
const UNSAVED: &str = "lucisv can only rename inside a saved file.";
@@ -851,4 +890,86 @@ mod tests {
let changes = edit.changes.expect("changes");
assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the buffer's instantiation");
}
/// `sub.sv` declares the port, `top.sv` connects it, and `far.svh` names
/// it inside a macro invocation and has no other relationship to anything
/// in the rename — so the fan-out does not hand it to the engine and the
/// engine cannot warn about it. The census does: §2.9-18's server half.
const M_SUB: &str = "module sub (output logic sig);\n assign sig = 1'b0;\nendmodule\n";
const M_TOP: &str = "module top;\n logic w;\n sub u_sub (.sig(w));\nendmodule\n";
const M_FAR: &str = "`uvm_info(\"x\", $sformatf(\"%0d\", sig), UVM_LOW)\n";
/// The workspace of the two pins below, with `top.sv` open. `far` is what
/// `far.svh` holds, which is the only difference between them.
fn macro_workspace(tree: &Tree, far: &str) -> (Workspace, Uri) {
tree.write("sub.sv", M_SUB);
let top = tree.write("top.sv", M_TOP);
tree.write("far.svh", far);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), M_TOP.to_string());
(ws, uri)
}
/// How often a warning naming `far.svh` is in the list.
fn far_warnings(warnings: &[String]) -> usize {
warnings.iter().filter(|w| w.contains("far.svh")).count()
}
#[test]
fn a_file_that_only_names_the_symbol_in_a_macro_is_warned_about_unread() {
let tree = Tree::new("macrocensus");
let (ws, uri) = macro_workspace(&tree, M_FAR);
// The premise: `far.svh` is in no rung of the fan-out, so the engine
// never sees it. Asked of the same function `rename` asks.
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
assert!(
!handed.iter().any(|(path, _)| path.ends_with("far.svh")),
"premise: the engine is not handed far.svh — {handed:?}"
);
let (edit, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames");
let changes = edit.changes.expect("changes");
assert_eq!(changes.len(), 2, "the declaration's file and the connection's");
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
assert_eq!(changes.get(&sub_uri).map(Vec::len), Some(2), "the port and its assignment");
assert_eq!(changes.get(&uri).map(Vec::len), Some(1), "the `.sig(` connection");
assert!(
!changes.contains_key(&path_to_uri(&tree.path.join("far.svh")).expect("uri")),
"a macro argument is never edited"
);
assert_eq!(far_warnings(&warnings), 1, "{warnings:?}");
let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named");
assert!(warning.contains("`sig`"), "{warning}");
assert!(warning.contains("this rename did not read"), "{warning}");
assert!(warning.contains("a macro argument cannot be edited"), "{warning}");
}
/// The control: give `far.svh` a reason to be read — it instantiates
/// `sub` — and it *is* a source, so the engine's own macro-argument
/// warning covers it and this one must stay quiet. Exactly one warning
/// names the file either way; two would be the bug.
#[test]
fn a_macro_file_the_rename_does_read_is_warned_about_exactly_once() {
let tree = Tree::new("macrocontrol");
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
let (ws, uri) = macro_workspace(&tree, &far);
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
assert!(
handed.iter().any(|(path, _)| path.ends_with("far.svh")),
"premise: instantiating `sub` puts far.svh in the source set"
);
let (_, warnings) = rename(&ws, &uri, at(M_TOP, "sig(w)"), "probe").expect("renames");
assert_eq!(far_warnings(&warnings), 1, "no double warning: {warnings:?}");
let warning = warnings.iter().find(|w| w.contains("far.svh")).expect("named");
assert!(
warning.contains("one opaque token"),
"and it is the engine's sentence, not the census's: {warning}"
);
}
}
@@ -1,10 +0,0 @@
//! Prints the generated rule reference.
//!
//! `cargo run -p vlog_linter --example rules_markdown > docs/lint-rules.md`.
//! This exists because the CLI flag that will do the same (`lucisv check
//! --rules-doc`) belongs to `crates/lucisv` and is not wired yet — see the
//! Handshakes section of `docs/features/lint-rules-2/README.md`.
fn main() {
print!("{}", vlog_linter::rules_markdown());
}
+1
View File
@@ -32,6 +32,7 @@ mod instantiate;
mod ports;
mod references;
mod rename;
mod scope;
pub use references::find_references;
+6 -5
View File
@@ -8,16 +8,17 @@
//!
//! This file is the rename itself: the entry points, the new-name check, the
//! walk from a cursor to the declaration it means, the occurrences of that
//! declaration, and the refusal sentences. `scope` is the in-scope workspace
//! every refactoring in this crate reads through, and `warnings` is what a
//! finished rename says about the occurrences it could not edit.
//! declaration, and the refusal sentences. `crate::scope` is the in-scope
//! workspace every refactoring in this crate reads through, and `warnings` is
//! what a finished rename says about the occurrences it could not edit.
mod scope;
#[cfg(test)]
mod tests;
mod warnings;
pub(crate) use scope::{display, Scope};
// The rename was the first refactoring, so most of the crate still spells the
// workspace `crate::rename::Scope`. It lives at `crate::scope` now (§29.1).
pub(crate) use crate::scope::{display, Scope};
pub use warnings::contains_word;
use std::path::{Path, PathBuf};
+1 -1
View File
@@ -16,8 +16,8 @@ use vlog_semantic::{ExternalTarget, ReferenceId, Resolution};
use crate::TextEdit;
use super::scope::{display, Scope};
use super::Target;
use crate::scope::{display, Scope};
impl<'a> Scope<'a> {
/// What the rename could not account for: the name inside `` `define``
@@ -1,7 +1,8 @@
//! The in-scope files, the index built from them, and the analyses computed
//! so far — what every refactoring in this crate reads the workspace through.
//! Nothing here is specific to a rename; it lives under `rename` because the
//! rename was the first refactoring and the others borrowed its workspace.
//! Nothing here is specific to a rename: `ports`, `references` and
//! `instantiate` read the same workspace, which is why it sits at the crate
//! root rather than under one of them.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -25,7 +26,7 @@ pub(crate) struct Scope<'a> {
/// `WorkspaceIndex::build` does it, so index `i` and `FileId(i)`'s texts
/// agree.
sources: Vec<(&'a Path, &'a str)>,
pub(super) index: WorkspaceIndex,
pub(crate) index: WorkspaceIndex,
/// Source index → the index's own file id.
file_ids: Vec<Option<FileId>>,
cache: HashMap<usize, Analysis>,
@@ -67,7 +68,7 @@ impl<'a> Scope<'a> {
&self.sources
}
pub(super) fn file_id(&self, i: usize) -> Option<FileId> {
pub(crate) fn file_id(&self, i: usize) -> Option<FileId> {
self.file_ids.get(i).copied().flatten()
}
+24 -1
View File
@@ -110,7 +110,18 @@ use crate::workspace::{
/// **wrong answer** (a signal reported unused because the only file that
/// reads it reads it in an assertion), not a missing one. See
/// `docs/features/sva-bodies/README.md`.
pub const FACTS_FORMAT: u32 = 16;
///
/// 16 → 17 (2026-09-02, macro-word census): a new `MW` group — the raw half
/// of the identifier census (`vlog_semantic::words::harvest_raw`), the words a
/// file writes only inside a macro invocation, a directive line or an
/// attribute. It is a new field, so an older record would be read short by
/// one group, and it is what a rename's "I could not read this file" warning
/// is answered from: a store written by a 0.33.0 build holds no `MW` group at
/// all and would answer "no file names it in a macro" for every file it
/// cached — silence about a macro argument the rename really did leave
/// behind, which is the failure the warning exists to prevent. See
/// `docs/features/macro-word-census/README.md`.
pub const FACTS_FORMAT: u32 = 17;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
@@ -168,6 +179,13 @@ impl FileFacts {
for word in &self.words {
out.text(word);
}
// The raw half, written separately rather than derived on the way in:
// deriving it would need the file's tokens, which is the parse this
// store exists to skip. Two letters because `M` is the member group.
out.tag("MW", self.macro_words.len());
for word in &self.macro_words {
out.text(word);
}
Some(out.out)
}
@@ -226,6 +244,10 @@ impl FileFacts {
for _ in 0..input.tag("W")? {
words.push(input.text()?);
}
let mut macro_words = Vec::new();
for _ in 0..input.tag("MW")? {
macro_words.push(input.text()?);
}
if !input.done() {
return None;
}
@@ -238,6 +260,7 @@ impl FileFacts {
subclasses,
references,
words,
macro_words,
})
}
}
+112 -18
View File
@@ -19,6 +19,12 @@
//! `vlog_linter::signals`'s in-file mention guard already does, for the same
//! reason.
//!
//! **And it is written down twice.** [`harvest`] folds raw text into the union
//! census, which is the answer three readers want; [`harvest_raw`] returns the
//! raw half alone, which is what tells a rename that a file's *only*
//! relationship to a name is text nothing can edit. Both branch on
//! [`raw_text`], so they cannot come to disagree about what raw text is.
//!
//! 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
@@ -44,26 +50,66 @@ use vlog_parser::tokenize;
pub fn harvest(tokens: &[Token]) -> Vec<String> {
let mut seen: HashSet<&str> = HashSet::new();
for token in tokens {
match token.kind {
// A macro invocation is an `Ident` whose text is the whole
// invocation, backtick and arguments included — raw text, split
// below. So are a directive line and an attribute.
TokenKind::Ident if token.text.starts_with('`') => {
seen.extend(raw_words(&token.text));
}
TokenKind::Directive | TokenKind::Attribute => {
seen.extend(raw_words(&token.text));
}
// 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.
TokenKind::Ident | TokenKind::SystemIdent if !token.text.starts_with('\\') => {
seen.insert(token.text.as_str());
}
_ => {}
// Raw text first, and the one place that decides what raw text is —
// so the union census and the macro half of it below cannot disagree.
if let Some(raw) = raw_text(token) {
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('\\')
{
seen.insert(token.text.as_str());
}
}
sorted(seen)
}
/// The **raw half** of [`harvest`]: every distinct identifier-shaped word
/// written inside a token the parser never looked into — a macro invocation,
/// a directive line, an attribute — and nothing else, sorted.
///
/// A subset of [`harvest`] by construction: the two share [`raw_text`] and
/// [`raw_words`], so a word is in this list only if it is in that one. What it
/// adds is *where*: a name here was seen only as unparsed text, so no
/// refactoring can edit it and no reference table records it. That is what
/// lets a rename name the files it could not read —
/// [`crate::WorkspaceIndex::files_naming_in_macros`], and
/// `docs/features/macro-word-census/README.md`.
///
/// A word written both ways — `sig` as a plain identifier *and* inside a
/// `` `uvm_info `` argument — is in both lists: this says a macro names it,
/// never that only a macro does.
pub fn harvest_raw(tokens: &[Token]) -> Vec<String> {
let mut seen: HashSet<&str> = HashSet::new();
for token in tokens {
if let Some(raw) = raw_text(token) {
seen.extend(raw_words(raw));
}
}
sorted(seen)
}
/// The whole text of a token the parser never looked inside — a macro
/// invocation (an `Ident` whose text is the entire invocation, backtick and
/// arguments included), a directive line, an attribute — or `None` for a
/// token that is not one.
///
/// The single definition of "raw", read by both harvests.
fn raw_text(token: &Token) -> Option<&str> {
match token.kind {
TokenKind::Ident if token.text.starts_with('`') => Some(&token.text),
TokenKind::Directive | TokenKind::Attribute => Some(&token.text),
_ => None,
}
}
/// One census's collected words as the canonical value both harvests return.
fn sorted(seen: HashSet<&str>) -> Vec<String> {
let mut words: Vec<String> = seen.into_iter().map(str::to_string).collect();
words.sort_unstable();
words
@@ -213,6 +259,54 @@ mod tests {
assert_eq!(harvest(&tokens), harvest_text(src));
}
fn harvest_raw_text(text: &str) -> Vec<String> {
harvest_raw(&tokenize(text).expect("lexes"))
}
/// The census's whole point: a word seen only as a plain identifier is not
/// in the raw half, and a word seen only inside a macro argument is.
#[test]
fn the_raw_half_holds_only_words_seen_as_raw_text() {
let raw = harvest_raw_text(
"module tb;\n wire only_plain;\n\
\x20 `uvm_info(\"tag\", $sformatf(\"%0d\", dut.only_macro), UVM_LOW)\nendmodule\n",
);
assert_eq!(raw, vec!["$sformatf", "UVM_LOW", "dut", "only_macro", "uvm_info"], "{raw:?}");
assert!(!raw.contains(&"only_plain".to_string()), "a plain identifier is not raw: {raw:?}");
assert!(!raw.contains(&"tb".to_string()), "{raw:?}");
// A directive line and an attribute are raw text too, by the same
// rule and through the same split.
let raw = harvest_raw_text("`ifdef USE_A\n(* keep_hierarchy *)\nmodule m;\nendmodule\n");
assert_eq!(raw, vec!["USE_A", "ifdef", "keep_hierarchy"], "{raw:?}");
}
/// The invariant the store and the rename both lean on. Proven on shapes
/// that mix the two halves, so a drift in either scan shows up here.
#[test]
fn the_raw_half_is_a_subset_of_the_whole_census() {
for src in [
"module m;\n wire clk;\n `ASSIGN(clk, rst_n)\nendmodule\n",
"`define W 8\nmodule m #(parameter int W = `W) (input logic [W-1:0] d);\nendmodule\n",
"module m;\n initial `uvm_fatal(\"t\", \"boom\")\nendmodule\n",
"module m;\n wire a;\nendmodule\n",
"",
] {
let all = harvest_text(src);
for word in harvest_raw_text(src) {
assert!(all.contains(&word), "`{word}` is raw but not in the census of {src:?}");
}
}
}
/// A word written both ways is in both lists: the raw half says a macro
/// names it, not that only a macro does.
#[test]
fn a_word_written_both_ways_is_in_both_halves() {
let src = "module m;\n wire sig;\n `PROBE(sig)\nendmodule\n";
assert!(harvest_raw_text(src).contains(&"sig".to_string()));
assert!(harvest_text(src).contains(&"sig".to_string()));
}
/// An unterminated quote inside raw text must not run the scan off the
/// end, and must not swallow the words before it.
#[test]
@@ -293,6 +293,35 @@ impl WorkspaceIndex {
.map(|(id, _)| FileId(id as u32))
}
/// Every file that writes the word `name` inside a macro invocation, a
/// directive line or an attribute — text lucisv never looked into.
///
/// The twin of [`WorkspaceIndex::files_mentioning`], over
/// [`FileFacts::macro_words`] instead of the union census and by the same
/// binary search per record. The narrower question, and the one a
/// refactoring asks: a name here has no reference, no declaration and no
/// edge, so nothing can edit it and nothing else in the index knows it is
/// there. A rename that never read the file can still *name* it —
/// `docs/features/macro-word-census/README.md`.
///
/// The answer is a superset of the files a macro *argument* names it in:
/// a directive line (`` `ifdef sig ``) and an attribute count too, and the
/// macro's own name is a word. Erring towards saying so is deliberate —
/// the alternative is silence about text the rename really did leave
/// behind.
pub fn files_naming_in_macros<'a>(
&'a self,
name: &'a str,
) -> impl Iterator<Item = FileId> + 'a {
self.facts
.iter()
.enumerate()
.filter(move |(_, facts)| {
facts.macro_words.binary_search_by(|w| w.as_str().cmp(name)).is_ok()
})
.map(|(id, _)| FileId(id as u32))
}
/// Whether any file **other than** `except` writes the word `name` down.
///
/// The question a cross-file lint guard actually asks, answered without
+47 -17
View File
@@ -121,6 +121,17 @@ pub struct FileFacts {
/// [`WorkspaceIndex::files_mentioning`] answers from, and what the
/// completion word table is built from.
pub(crate) words: Vec<String>,
/// The raw half of that census, sorted — [`crate::words::harvest_raw`]'s
/// answer, and a subset of [`FileFacts::words`] by construction.
///
/// Every word here was seen only inside a token the parser never looked
/// into: a macro invocation, a directive line, an attribute. Kept apart
/// from `words` because the two answer different questions — `words` says
/// "this file names it", which is what a lint guard wants, and this says
/// "and text nothing can edit is where", which is what a rename has to
/// warn about. What [`WorkspaceIndex::files_naming_in_macros`] answers
/// from; see `docs/features/macro-word-census/README.md`.
pub(crate) macro_words: Vec<String>,
}
/// One reference contribution before the workspace's declarations are merged.
@@ -194,15 +205,7 @@ impl FileFacts {
lines: &LineIndex,
tokens: &[Token],
) -> FileFacts {
facts_from_analysis(
path,
tree,
defines.clone(),
sem,
src,
lines,
crate::words::harvest(tokens),
)
facts_from_analysis(path, tree, defines.clone(), sem, src, lines, Census::of(tokens))
}
/// This file's identifier census — every distinct identifier-shaped word
@@ -211,21 +214,47 @@ impl FileFacts {
&self.words
}
/// The raw half of that census — every word this file writes only inside
/// a macro invocation, a directive line or an attribute, sorted
/// ([`crate::words::harvest_raw`]).
pub fn macro_words(&self) -> &[String] {
&self.macro_words
}
/// The file these facts were read from.
pub fn path(&self) -> &Path {
&self.path
}
}
/// One file's two identifier censuses, both read off the same token stream:
/// the union every mention question is answered from, and the raw half a
/// rename warns from. Carried together so the two can never be built from
/// different lexes of the same file.
#[derive(Default)]
struct Census {
words: Vec<String>,
macro_words: Vec<String>,
}
impl Census {
fn of(tokens: &[Token]) -> Census {
Census {
words: crate::words::harvest(tokens),
macro_words: crate::words::harvest_raw(tokens),
}
}
}
/// Parse one file and read off what it declares and what it points at.
pub(super) fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines, words) = parse_and_collect(src);
let (tree, defines, census) = parse_and_collect(src);
let sem = analyze(&tree, src);
// One pass over the source's newlines, so every declaration below can be
// given its line without anyone reading the file again later. It is a
// percent of the parse it sits beside (`docs/perf/README.md`).
let lines = LineIndex::new(src);
facts_from_analysis(path, &tree, defines, &sem, src, &lines, words)
facts_from_analysis(path, &tree, defines, &sem, src, &lines, census)
}
/// Read off what one file contributes, from its finished analysis.
@@ -236,7 +265,7 @@ fn facts_from_analysis(
sem: &Semantics,
src: &str,
lines: &LineIndex,
words: Vec<String>,
census: Census,
) -> FileFacts {
let mut facts = FileFacts {
path,
@@ -246,7 +275,8 @@ fn facts_from_analysis(
instantiations: edges_of(tree, src, lines),
subclasses: inheritance_of(tree),
references: Vec::new(),
words,
words: census.words,
macro_words: census.macro_words,
};
let Some(file_scope) = sem.scope(sem.file_scope()) else {
return facts;
@@ -426,21 +456,21 @@ fn nested_key(key: &str, member: &Symbol) -> Option<String> {
}
/// Parse one file and read its `` `define`` table off the same token stream.
fn parse_and_collect(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Vec<String>) {
fn parse_and_collect(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Census) {
match tokenize(src) {
Ok(tokens) => {
let defines = collect_defines(&tokens);
// Harvested before the parser takes the tokens: one lex feeds the
// tree, the `define` table and the census, which is what makes the
// census free here.
let words = crate::words::harvest(&tokens);
(parse_tolerant(tokens, src).0, defines, words)
let census = Census::of(&tokens);
(parse_tolerant(tokens, src).0, defines, census)
}
// The lexer is all-or-nothing, so a file that does not lex contributes
// no declarations at all — but it still gets a file id, and
// `parse_source_tolerant` gives back the same one-error-node tree
// every other consumer sees.
Err(_) => (parse_source_tolerant(src).0, DefineTable::default(), Vec::new()),
Err(_) => (parse_source_tolerant(src).0, DefineTable::default(), Census::default()),
}
}
+164
View File
@@ -2413,3 +2413,167 @@ fn a_name_only_a_macro_argument_spells_is_in_the_census() {
]);
assert!(with_ifdef.mentioned_outside("gated", with_ifdef.file_id(Path::new("/w/a.sv"))));
}
/// The raw half of the census, as the index answers it: a file whose only
/// relationship to a name is a macro argument is named, a file that declares
/// or uses the name as a plain identifier is not, and a file that does both
/// is (the census says "a macro names it", never "only a macro does").
#[test]
fn files_naming_in_macros_is_the_raw_half_of_the_census() {
let ws = index(&[
("/w/sub.sv", "module sub;\n wire sig;\nendmodule\n"),
("/w/top.sv", "module top;\n sub u_sub ();\n assign x = u_sub.sig;\nendmodule\n"),
("/w/far.svh", "`uvm_info(\"x\", $sformatf(\"%0d\", sig), UVM_LOW)\n"),
("/w/both.sv", "module both;\n wire sig;\n `PROBE(sig)\nendmodule\n"),
]);
let named: Vec<&Path> = ws.files_naming_in_macros("sig").filter_map(|id| ws.path(id)).collect();
assert_eq!(named, vec![Path::new("/w/both.sv"), Path::new("/w/far.svh")], "{named:?}");
// Every one of them is in the union census too — the subset invariant,
// asserted through the index rather than only in `words`.
let mentioning: Vec<&Path> = ws.files_mentioning("sig").filter_map(|id| ws.path(id)).collect();
for path in &named {
assert!(mentioning.contains(path), "{path:?} is raw but not mentioned");
}
assert_eq!(mentioning.len(), 4, "all four spell it: {mentioning:?}");
// A name nothing writes in raw text at all.
assert_eq!(ws.files_naming_in_macros("u_sub").count(), 0);
}
/// The `MW` group survives the round trip in both directions, and a record
/// written before it — a `FACTS_FORMAT` 16 store — is dropped rather than
/// read short by a group.
#[test]
fn the_macro_word_group_round_trips_and_a_format_16_record_is_rejected() {
for src in [
"module tb;\n wire clk;\n `uvm_info(\"t\", $sformatf(\"%0d\", probe), UVM_LOW)\nendmodule\n",
// ... and the record with an empty `MW` group, which is most files.
"module plain;\n wire clk;\nendmodule\n",
] {
let facts = FileFacts::of(PathBuf::from("/w/r.sv"), src);
let line = facts.encode().expect("encodes");
let back = FileFacts::decode(&line).expect("decodes");
assert_eq!(back, facts, "every field, the macro words included");
assert_eq!(back.encode(), Some(line.clone()), "and re-encodes byte for byte");
// The raw half is a subset of the census, over the stored record.
for word in back.macro_words() {
assert!(back.words().contains(word), "`{word}` is raw but not in the census");
}
// What format 16 wrote: everything up to and including the `W` group.
let fields: Vec<&str> = line.split('\t').collect();
let at = fields.iter().rposition(|field| *field == "MW").expect("MW tag");
let format_16 = fields[..at].join("\t");
assert!(
FileFacts::decode(&format_16).is_none(),
"a format-16 record decoded as a format-17 one: {format_16}"
);
}
}
/// A `probe` named only inside a macro argument is in `MW`; a `clk` named only
/// as a plain identifier is not. The store's own view of the split.
#[test]
fn a_stored_record_separates_the_macro_words_from_the_plain_ones() {
let facts = FileFacts::of(
PathBuf::from("/w/tb.sv"),
"module tb;\n wire clk;\n `PROBE(probe)\nendmodule\n",
);
let back = FileFacts::decode(&facts.encode().expect("encodes")).expect("decodes");
assert_eq!(back.macro_words(), ["PROBE", "probe"], "{:?}", back.macro_words());
assert!(back.words().contains(&"clk".to_string()));
}
/// What the macro-word census costs a store, measured rather than guessed.
///
/// `#[ignore]`d and asserting nothing — the house shape for a measurement
/// probe (`crates/vlog_semantic/tests/member_access.rs`). It walks the
/// directory named by `LUCISV_STORE_ROOT` (the corpus, or an OpenTitan
/// checkout), encodes every file's record and reports what the `MW` group
/// adds to it, which is exactly the delta a `FACTS_FORMAT` 16 store would
/// not have held. Run with
/// `LUCISV_STORE_ROOT=… cargo test -p vlog_semantic --test workspace -- \
/// --ignored --nocapture the_macro_word_group`.
#[test]
#[ignore = "measurement over a source tree, printed rather than asserted"]
fn the_macro_word_group_costs_this_many_store_bytes() {
let Ok(root) = std::env::var("LUCISV_STORE_ROOT") else {
eprintln!("LUCISV_STORE_ROOT unset — skipping");
return;
};
let mut files = Vec::new();
collect_sources(Path::new(&root), &mut files);
files.sort();
let (mut total, mut macro_bytes, mut records, mut with_words) = (0usize, 0usize, 0usize, 0);
for path in &files {
let Ok(src) = std::fs::read_to_string(path) else { continue };
let facts = FileFacts::of(path.clone(), &src);
let Some(line) = facts.encode() else { continue };
// Everything from the `MW` tag to the end of the record is the group,
// separator included: what format 16 did not write.
let at = line.rfind("\tMW\t").expect("every record has the group");
records += 1;
total += line.len() + 1;
macro_bytes += line.len() - at;
with_words += usize::from(!facts.macro_words().is_empty());
}
let percent = if total == 0 { 0.0 } else { 100.0 * macro_bytes as f64 / total as f64 };
println!(
"{root}: {records} records, {total} store bytes, {macro_bytes} of them the MW group \
({percent:.2}%), {with_words} records with at least one macro word"
);
}
/// Every Verilog source under `dir`, recursively.
fn collect_sources(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_sources(&path, out);
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
out.push(path);
}
}
}
/// What the rename's new warning pass costs, measured on the same tree.
///
/// The pass is one [`WorkspaceIndex::files_naming_in_macros`] walk — the same
/// linear walk with a binary search per record that `files_mentioning` has
/// always been, over a shorter list — so this reports both side by side. Same
/// `#[ignore]`d shape and same `LUCISV_STORE_ROOT` as the probe above.
#[test]
#[ignore = "measurement over a source tree, printed rather than asserted"]
fn the_macro_census_walk_costs_this_much_per_rename() {
let Ok(root) = std::env::var("LUCISV_STORE_ROOT") else {
eprintln!("LUCISV_STORE_ROOT unset — skipping");
return;
};
let mut files = Vec::new();
collect_sources(Path::new(&root), &mut files);
files.sort();
let sources: Vec<(PathBuf, String)> = files
.iter()
.filter_map(|path| Some((path.clone(), std::fs::read_to_string(path).ok()?)))
.collect();
let ws = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str())));
for name in ["clk", "rst_ni", "u_dut"] {
let start = std::time::Instant::now();
let mut raw = 0;
for _ in 0..100 {
raw = ws.files_naming_in_macros(name).count();
}
let raw_each = start.elapsed() / 100;
let start = std::time::Instant::now();
let mut all = 0;
for _ in 0..100 {
all = ws.files_mentioning(name).count();
}
let all_each = start.elapsed() / 100;
println!(
"{root}: `{name}` — files_naming_in_macros {raw} files in {raw_each:?}, \
files_mentioning {all} files in {all_each:?}"
);
}
}
+21
View File
@@ -420,6 +420,27 @@ a **wrong** answer (a signal reported unused because the file that reads it
happened to be cached), not a missing one. See
`docs/features/semantic-lints-on/README.md`.
**`FACTS_FORMAT` 17 (2026-09-02, `macro-word-census`)** adds one more group,
**`MW`**, written after `W`: the *raw half* of the same census
(`vlog_semantic::words::harvest_raw`) — the words a file writes only inside a
macro invocation, a directive line or an attribute, sorted. Two letters
because the single letter `M` is already the member group; the framing is
untouched, and `Reader::tag` compares a marker whole, so a two-letter tag is a
tag like any other. It is written beside `W` rather than carved out of it: the
lint rules' mention guard wants the union, and the rename wants the half
nothing can edit. What it costs, measured the same way:
| tree | records | store at format 17 | `MW` bytes | delta |
|---|---:|---:|---:|---:|
| `corpus/` | 860 | 3 971 684 | 123 402 | **+3.11 %** |
| opentitan | 3 979 | 44 858 329 | 743 873 | **+1.66 %** |
The bump is a correctness bump for the same reason 13 was: a 0.33.0 store
holds no `MW` group at all, so a rename over a half-cached workspace would
answer "no file names it in a macro" for exactly the files the store had — and
silence about a macro argument the rename left behind is the failure the new
warning exists to prevent. See `docs/features/macro-word-census/README.md`.
### Why one line per record
Because it is what makes the append log crash-safe with no framing of its own.
+11 -4
View File
@@ -80,10 +80,17 @@ assumed.
**Requested of others (not done here)**
- *`crates/lucisv`'s owner (concurrent this round)*: a `lucisv check --rules-doc`
flag that prints `vlog_linter::rules_markdown()` to stdout and exits 0.
One `println!`; no other wiring. Until then the same output is available as
`cargo run -p vlog_linter --example rules_markdown`.
- ~~*`crates/lucisv`'s owner (concurrent this round)*: a `lucisv check
--rules-doc` flag that prints `vlog_linter::rules_markdown()` to stdout and
exits 0. One `println!`; no other wiring. Until then the same output is
available as `cargo run -p vlog_linter --example rules_markdown`.~~
**Delivered 2026-09-02 (`macro-word-census`, TODO §29.3, topo §2.9-5):**
`lucisv check --rules-doc` prints it and exits 0, before rule selection and
before any path is gathered; it is lint-only and takes no files. The example
binary is removed — the flag is the tool now. Pinned in
`crates/lucisv/tests/cli.rs` (`rules_doc_prints_the_generated_reference`
asserts every registered rule has exactly one section, and that the output
equals `rules_markdown()`).
- *config-discovery's owner*: the `lint` key in `lucisv.toml` is what
per-rule naming-style configuration waits on — the shape wanted is
`[lint.parameter-name-style] style = "CamelCase"` picking one of the named
+461
View File
@@ -0,0 +1,461 @@
# macro-word census (TODO §29)
## Goal
Three independent small items, one lane. **29.1** moves
`vlog_refactor::rename::scope` to the crate root: the in-scope workspace every
refactoring in the crate reads through was never rename-specific, and `ports`,
`references` and `instantiate` all reached it through `rename`. A pure move.
**29.2** is the substantive one and closes the server half of `docs/topo.md`
§2.9-18. A rename says nothing about a file whose *only* relationship to the
renamed name is a macro argument, because `Workspace::rename_sources` has no
rung that finds such a file and the engine can only warn about files it was
handed. The lead's ruling was that the missing rung must not be built — the
union census (`FileFacts::words`) is untagged, so a rung on it would re-read
every file spelling `clk` and bring back the 2.5–3.0 s `prepareRename` cost —
and that a *separate* per-file census of the words a file writes only in
unparsed text is the answer instead: something the server can **warn from
without reading a byte**. That census is `FileFacts::macro_words`
(`FACTS_FORMAT` 16 → 17), harvested by `vlog_semantic::words::harvest_raw`,
asked of `WorkspaceIndex::files_naming_in_macros`, and appended as one warning
per unread file by `lucisv_server::rename`. **29.3** wires
`vlog_linter::rules_markdown()` — which has had only an example binary since
lint-rules-2 — to `lucisv check --rules-doc`, closing §2.9-5.
## Assumptions
- **"Raw text" is exactly three token shapes**, and they are the three
`vlog_semantic::words::harvest` already treated as raw: an `Ident` whose text
starts with a backtick (a macro invocation, arguments included), a
`Directive` and an `Attribute`. `harvest_raw` shares the predicate
(`words::raw_text`) and the splitter (`words::raw_words`) with `harvest`, so
the two cannot come to disagree about what counts.
- **The raw census is therefore a superset of "names it in a macro
*argument*"**: `` `ifdef sig ``, `(* keep = sig *)` and the macro's own name
are in it too. Erring wide is deliberate — the alternative is silence about
text the rename really did leave behind, which is the failure §2.9-18 is
about. The engine's own warning, which is precise, still covers every file
the engine read; this one only speaks for files it did not.
- **`words` is untouched.** The lint rules' mention guard wants the union — a
signal read only inside a `` `uvm_info `` argument is mentioned — so the raw
half is written *beside* `words`, never carved out of it. Every word in
`macro_words` is also in `words`; pinned in both `words.rs` and over a stored
record.
- **`fingerprint` is unchanged.** The census is derived from the same text by
the same lex, so a second count would witness nothing the `words=` count does
not already witness (a record lost, duplicated, or attached to the wrong
file).
- **A file that does not lex contributes no macro words**, the same
all-or-nothing answer it already gives for `words` and for the parse.
- **Subtracting the handed source set is enough to exclude open buffers.**
`Workspace::rename_sources` puts every open buffer in the set it returns, so
the server's filter needs no separate open-buffer pass. If that ever stops
being true, the pin
`a_file_that_only_names_the_symbol_in_a_macro_is_warned_about_unread` still
passes but the warning could name a buffer the user has open — worth knowing.
- **`--rules-doc` describes the build, not a run.** It is handled before rule
selection and before any path is gathered, so it cannot be affected by
`--select`, a `lucisv.toml`, or a file that does not lex.
## Handshakes
**Consumed**
- `vlog_parser::token::{Token, TokenKind}` — unchanged; `harvest_raw` reads the
same three kinds `harvest` does.
- `vlog_refactor::rename_name_at` (server) — already consumed; the server now
keeps the name it returns rather than dropping it into the `match`, to ask
the index the same question the engine was asked.
- `crate::locate::display_name` (server) — how a file is named in a message,
the same file-name-only rule the engine's `Scope::display` uses.
- `vlog_linter::{rules_markdown, all_rules}` — `rules_markdown` was already
public; `all_rules` is read by the new CLI test only.
**Promised**
- `vlog_semantic::words::harvest_raw(&[Token]) -> Vec<String>` — sorted,
deduplicated, a subset of `harvest`'s answer over the same tokens.
- `vlog_semantic::FileFacts::macro_words() -> &[String]` — the same list, per
stored record.
- `vlog_semantic::WorkspaceIndex::files_naming_in_macros(&str) -> impl
Iterator<Item = FileId>` — the twin of `files_mentioning`, same linear walk
with a binary search per record, over the shorter list.
- **`FACTS_FORMAT` 16 → 17**, recorded in `facts.rs`'s doc comment with its
reason: a 0.33.0 store holds no `MW` group and would answer "no file names it
in a macro" for every file it cached — silence about a macro argument the
rename really did leave behind, which is a wrong answer rather than a missing
one. `lucisv_server::index_cache` stamps `FACTS_FORMAT` into its header
already, so a store written by 0.33.0 is discarded whole with no change here.
- **The record format gains one group, `MW`**, written after `W`. Two letters
because the single letter `M` is the member group; the format's tags are
arbitrary strings and `Reader::tag` compares them whole, so this is a tag
like any other. A record without it does not decode (pinned).
- `lucisv check --rules-doc` — prints `vlog_linter::rules_markdown()` on stdout
and exits 0. Lint-only; takes no files (a path beside it is a usage error).
**Requested of others (not done here)**
- *The lead*: strike `docs/topo.md` §2.9-18 (server half delivered) and §2.9-5
(`--rules-doc` delivered). This lane does not edit `topo.md`.
- *Nobody*: `crates/lucisv_server/src/perf.rs` has no probe for a rename over a
real tree, so the warning pass's cost is measured in this lane's own
`#[ignore]`d probe in `vlog_semantic/tests/workspace.rs` instead of beside
the other rename measurements. A probe in `perf.rs` would be the better home;
`perf.rs` is outside this lane's file ownership, so it is filed, not written.
## Status / TODO
- [x] 29.1 `Scope` at the crate root, counts identical
- [x] 29.2a `words::harvest_raw`, sharing `raw_text`/`raw_words` with `harvest`
- [x] 29.2b `FileFacts::macro_words`, `FACTS_FORMAT` 16 → 17, `MW` group
- [x] 29.2c `WorkspaceIndex::files_naming_in_macros`
- [x] 29.2d the server's warning, appended in `lucisv_server::rename::rename`
- [x] 29.2e the pins: `harvest_raw` units, codec round-trip with and without
`MW`, the format-16 rejection, the three-file server pin and its control
- [x] 29.2f the README amendments (refactor-rename, semantic-lints-on,
index-persistence)
- [x] 29.3 `--rules-doc`, usage text, tests, example binary removed
- [x] Store measurement on corpus and on OpenTitan
- [x] Gates: fmt, clippy, `cargo test --workspace`, corpus gate, OpenTitan
read-only sweep
## Work log
### 2026-09-02 — 29.1, `Scope` at the crate root
`git mv crates/vlog_refactor/src/rename/scope.rs
crates/vlog_refactor/src/scope.rs`; `lib.rs` gains `mod scope;`
(crate-private). `rename/mod.rs` keeps `pub(crate) use crate::scope::{display,
Scope};` so every in-crate path that spells `crate::rename::Scope` — `check.rs`,
`references.rs`, all five `ports/` modules — still resolves untouched, which is
what keeps this a move rather than a rename of nine files. `warnings.rs`, the
one importer that spelled it `super::scope::`, had to change and now says
`crate::scope::`. The `//!` loses its "it lives under `rename` because …"
sentence and gains the real reason it is at the root.
Two visibility spellings changed with no semantic effect: `Scope::index` and
`Scope::file_id` were `pub(super)`, which at the crate root means the crate.
Written as `pub(crate)` so the word says what it does.
Proof: `cargo test -p vlog_refactor` 86/5/52/63/0 — identical to the counts
TODO §29 recorded — and `cargo test --workspace` 3 215 passed over 48 binaries,
also identical. No public path changed (`Scope` is `pub(crate)`).
### 2026-09-02 — 29.3, `lucisv check --rules-doc`
`Options::rules_doc`, parsed from `--rules-doc`, listed in
`check_flag_scopes`'s `lint_only` table (so `lucisv --rules-doc` says "only
valid for `lucisv check`") and documented in the usage text under CHECK
OPTIONS. The "no input files" check grew one branch: `--rules-doc` is the one
invocation that needs no input, and being *given* one is a usage error
(`--rules-doc takes no files`) rather than a path silently ignored.
`run_check` prints `vlog_linter::rules_markdown()` and returns 0 before
`select_rules` and before `gather`, so the answer is a property of the build.
`crates/vlog_linter/examples/rules_markdown.rs` removed — the flag is the tool
now, which is what its own doc comment said it was waiting for.
No `docs/lint-rules.md` is checked in, so there was nothing to regenerate and
no drift test to write. `docs/site/src/content/docs/reference/rules.md` was
considered and is **not** generated text — it is a hand-written page with its
own "Purpose" column, a badge and prose — so it is not a drift-test candidate
either, and it is outside this lane's files.
Tests: `crates/lucisv/tests/cli.rs`
`rules_doc_prints_the_generated_reference` (first line, exactly one `## <name>`
section per registered rule, and the whole output equal to
`vlog_linter::rules_markdown()`) and
`rules_doc_refuses_files_and_belongs_to_check`; `args.rs`
`rules_doc_is_the_one_check_that_needs_no_input`.
### 2026-09-02 — 29.2, the macro-word census and the warning it enables
**`words::harvest_raw`.** The raw-token match moved into `raw_text(&Token) ->
Option<&str>` and both harvests branch on it, which is the whole
anti-drift argument: there is one definition of "the parser never looked inside
this token". `harvest`'s body is otherwise unchanged (the macro-invocation arm
already came before the plain-`Ident` arm, and a backticked `Ident` still never
reaches the plain arm), and the shared `sorted()` gives both the same canonical
value. Pinned: the raw half holds only words seen as raw text, it is a subset of
the whole census over five shapes, and a word written both ways is in both.
**`FileFacts::macro_words`.** A `Census { words, macro_words }` struct now
carries both halves from the one lex through `parse_and_collect` and
`facts_from_analysis`, so the two can never be built from different lexes of the
same file — which also kept `facts_from_analysis` from growing a second
positional `Vec<String>` parameter. `FileFacts::from_analysis` (the server's
open-buffer path) builds it with `Census::of(tokens)`, so a buffer and its file
on disk answer alike.
`FACTS_FORMAT` 16 → 17 with the reason in the doc comment. The group is
written as **`MW`**, not `M` as §29 sketched: `M` is already the member group,
and while a positional format could carry two `M` tags unambiguously, a reader
of `facts.rs` could not. Tags are compared whole by `Reader::tag`, so a
two-letter tag costs nothing. `update_file` / `absorb` / `remove_file` swap
whole records and carry the new field with no change, as expected; `fingerprint`
is deliberately untouched.
**`files_naming_in_macros`.** `files_mentioning`'s twin, same walk, over
`macro_words`. Documented as a superset of "names it in a macro argument", with
the reason.
**The server warning.** `lucisv_server::rename::rename` keeps the name
`rename_name_at` returned and, after the engine answers, appends
`unread_macro_warnings`: every file `files_naming_in_macros(old)` names that is
not among the paths `rename_sources` handed the engine. **No new rung and no
new `Workspace` method** — `rename_sources` already *returns* the path set it
built, so the subtraction reads it directly; `state.rs` is untouched. Open
buffers need no separate pass because `rename_sources` puts every one of them in
that set. When the cursor is on nothing the whole workspace goes to the engine,
so there is nothing outside the handed set and no warning is computed at all.
Pins (`crates/lucisv_server/src/rename.rs`): the three-file case —
`sub.sv` declares `output logic sig`, `top.sv` connects `.sig(w)`, `far.svh`
holds one `` `uvm_info(…, sig, …) `` line and nothing else — asserts the
premise (`far.svh` is not in `rename_sources`'s result), that the rename edits
`sub.sv` and `top.sv` and not `far.svh`, and that exactly one warning names
`far.svh` with the census's sentence. The control gives `far.svh` an
instantiation of `sub`, asserts it *is* a source, and demands exactly one
warning naming it — the engine's "one opaque token" sentence, not the census's.
No double warning.
A deviation from §29's sketch worth naming: the sketch had `top.sv` use
`u.sig`, a hierarchical tail. That shape is `docs/topo.md` §2.9-23 — a
cross-file instance-member tail does not resolve for rename, so `top.sv` would
not be edited and the pin would have asserted the gap rather than the feature.
The pin uses a port and a connection instead, which is the same three-file
topology with the edit actually happening.
**Store measurement** (`the_macro_word_group_costs_this_many_store_bytes`, an
`#[ignore]`d probe over `LUCISV_STORE_ROOT`, the house shape):
| tree | records | store bytes | `MW` bytes | share | records with ≥1 macro word |
|---|---|---|---|---|---|
| `corpus/` | 860 | 3 971 684 | **+123 402** | +3.11 % | 562 |
| OpenTitan | 3 979 | 44 858 329 | **+743 873** | +1.66 % | 3 174 |
Small, as expected: the raw half is a few dozen words per file where the union
census is hundreds, and OpenTitan's larger files dilute it further.
**Cost of the warning pass** (`the_macro_census_walk_costs_this_much_per_rename`,
same probe file, release build, mean of 100):
| tree | name | `files_naming_in_macros` | `files_mentioning` |
|---|---|---|---|
| OpenTitan `hw/ip` (1 8xx files) | `clk` | 14 files, 69 µs | 77 files, 177 µs |
| OpenTitan `hw/ip` | `rst_ni` | 95 files, 53 µs | 648 files, 155 µs |
| OpenTitan (3 979 files) | `clk` | 58 files, 186 µs | 253 files, 528 µs |
| OpenTitan | `rst_ni` | 172 files, 140 µs | 1 164 files, 466 µs |
Under 0.2 ms over the whole tree, against a rename that costs hundreds of
milliseconds — and it reads no file, which is the property that made this the
ruling instead of the rung.
**Gates.** `cargo fmt -p` for `vlog_refactor`, `vlog_semantic`,
`lucisv_server`, `lucisv`; `cargo clippy --all-targets --workspace` 0 warnings;
`cargo test --workspace` **3 226 passed, 0 failed, 42 ignored, 48 binaries**
(baseline 3 215 / 40 / 48 — eleven new tests and two new `#[ignore]`d
measurement probes); `scripts/corpus_gate.sh` **814/820**, the same six
failures by the same categories; the OpenTitan `lucisv check` sweep is
**byte-identical** to the one the pre-existing 0.33.0 release binary produces
(223 violations, 1 file that cannot be lexed), and
`git -C … opentitan status --porcelain` shows only the three files it showed
before.
## QA log
### 2026-09-03 — verification, all in `.claude/worktrees/small-1` at `a4b8ca0`
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` clean, 0 warnings, and no new `#[allow]` in any file this lane
touched. `cargo test --workspace --no-fail-fast`: summed **3 226 passed, 0
failed, 42 ignored, over 48 binaries** (42 `Running` lines + 6 `Doc-tests`
sections) — matches the dev's claim exactly. `git diff --stat d1821ff --
crates/vlog_formatter/src/verify.rs` empty. `git diff --stat d1821ff
--name-only` is exactly the §29 ownership list: `vlog_refactor` (lib.rs,
scope.rs moved, rename/{mod,warnings}.rs), `vlog_semantic`
(facts.rs/words.rs/workspace/{index,record}.rs + tests), `lucisv_server/src/
rename.rs`, `lucisv` (args.rs/main.rs/tests/cli.rs), `vlog_linter/examples/
rules_markdown.rs` (deleted), the four amended READMEs, the new
`macro-word-census` README, and `TODO.md`. Nothing outside scope.
**29.1.** `git diff d1821ff -- crates/vlog_refactor` is exactly the described
move: `mod scope;` in `lib.rs`, the re-export path change in `rename/mod.rs`
(`super::scope::` → `crate::scope::`), the same in `warnings.rs`, the `//!`
sentence swap, and the two `pub(super)` → `pub(crate)` visibility words on
`Scope::index`/`Scope::file_id`. Nothing else changed in the crate.
**29.2 census correctness.** Read `words::raw_text`/`harvest_raw`/`raw_words`
in `crates/vlog_semantic/src/words.rs`. Wrote my own probe (temporary,
untracked `crates/vlog_semantic/tests/qa29_probe.rs`, run once via `cargo
test -p vlog_semantic --test qa29_probe` then deleted — never left in the
tree) over five hand-made shapes plus a comment case: a name only in a macro
argument, only as a plain identifier, in both, inside a string literal inside
a macro (must not count), inside a comment (must not count), and an escaped
identifier (must not count) — all 7 assertions passed, confirming
`harvest_raw ⊆ harvest` and the per-shape membership independently of the
dev's own tests. Codec: `the_macro_word_group_round_trips_and_a_format_16_
record_is_rejected` and `the_census_round_trips_through_the_record_format`
read as claimed — a record with and without `MW` round-trips, and truncating
the fields before the `MW` tag (what format 16 wrote) makes `decode` return
`None`. `fingerprint` claim confirmed by reading `workspace/update.rs:142`:
`fingerprint()` counts only `facts.words.len()`, never touches
`macro_words`, and `git diff d1821ff -- crates/vlog_semantic/src/workspace/
update.rs` is empty — the file is untouched by this lane, so the "unchanged"
claim is true by construction, not just assertion.
**29.2 the warning, end to end, real binary.** Built `lucisv-server` and
wrote a throwaway e2e test (untracked `crates/lucisv_server/tests/
qa29_rename_e2e.rs`, modeled on `tests/e2e.rs`'s framing helpers, run once
then deleted) that spawns the real binary, speaks framed JSON-RPC over
stdio, and reproduces the three-file pin independently of the dev's Rust-
level test: `sub.sv`/`top.sv`/`far.svh` on disk, `initialize` +
`didChangeConfiguration` (workspace scope) + `didOpen(top.sv)` +
`textDocument/rename` of `sig` at the `.sig(w)` connection. Result: the edit
touches exactly `sub.sv` and `top.sv` (not `far.svh`); exactly one
`window/logMessage` warning names `far.svh`, with the census's sentence
("this rename did not read ... a macro argument cannot be edited"). The
control (`far.svh` also instantiates `sub`) produces exactly one warning
naming it — the engine's own "one opaque token" sentence — no double
warning. Both pass.
**29.2 on OpenTitan, real tree, read-only.** `git -C opentitan status
--porcelain` before touching anything showed only the three pre-existing
modified files (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/
ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`) — unchanged after every rename
request below, confirmed again at the end. Renaming `clk_i` (aes_core.sv)
and `idle` (aes_idle_check.sv) produced only the engine's own pre-existing
warning sentences ("appears in the arguments of the macro invocation" /
"in the body of macro") — common names pull in most of the fan-out via
rung 1's declaration walk, leaving nothing census-only, which is itself a
useful negative check (no spurious census warnings on real code). To find a
positive, organic instance I wrote a throwaway probe (`git worktree add
.claude/worktrees/qa-play-29 a4b8ca0`, one `#[ignore]`d test appended to
`rename.rs`'s own `mod tests`, removed with the worktree afterward) that
scans every word `aes_core.sv` declares for one where `files_naming_in_
macros` names a file `rename_sources` does not hand the engine. It found
`cipher_crypt` (declared `sp2v_e cipher_crypt;`, aes_core.sv:178) named
inside `` `DV_CHECK_FATAL(uvm_hdl_read(cipher_crypt_path, cipher_crypt)) ``
at `aes_reseed_vseq.sv:151` — grepped and confirmed genuine, a coincidental
name collision with that file's own unrelated local `bit cipher_crypt;`
(line 100), no reference relationship. Renaming `cipher_crypt` →
`cipher_crypt2` with the real server against the real tree: edit touches
only `aes_core.sv` (3 ranges — the declaration and its two uses), 2 engine
warnings for the file's own two `` `ASSERT `` lines it did read, and exactly
**one** census warning naming `aes_reseed_vseq.sv`, worded exactly as
promised. Built the 0.33.0 binary from the `v0.33.0` tag in a throwaway
worktree and re-ran the identical rename against a store of its own: it
produces only the 2 engine warnings — the `aes_reseed_vseq.sv` warning is
categorically absent, which is the silent gap §29.2 closes, demonstrated
end to end on real, unmodified OpenTitan source (not a synthetic fixture).
**Timing.** Built both a `v0.33.0` release binary (throwaway worktree) and
the dev's release binary, each warmed against its own persistent store
directory (distinct `FACTS_FORMAT`s cannot share one), and timed only the
`textDocument/rename` round trip via a small streaming harness (spawn,
drain until indexing quiesces, then time request→response). For
`cipher_crypt` (the realistic, narrow-fan-out case): baseline 20.8/27.4/22.9
ms, dev 24.6/20.8/20.8 ms — indistinguishable, no measurable regression. For
`clk_i` (a maximal, ~650-file fan-out dominated entirely by the pre-existing
engine walk): baseline 7 104–7 173 ms, dev 7 182–7 247 ms over 4 runs each —
a consistent but small ~70 ms (~1%) gap at this extreme. That total includes
everything the round trip does (fan-out, engine analysis, cache decode of
the wider per-file record), not only the isolated walk the dev's own probe
measured directly (~0.2 ms over the whole tree); I did not further isolate
the source of the ~70 ms and flag it MEDIUM rather than a blocker, since (a)
it appears only at an extreme, uncommonly-large fan-out no real rename
target should usually reach, (b) it is two orders of magnitude below the
already-accepted ~7 s cost of that fan-out itself, and (c) the dev's own
narrowly-scoped measurement of the actual new code path is independently
reproducible and small. Re-ran the dev's own ignored probes directly:
`the_macro_word_group_costs_this_many_store_bytes` over `corpus/` gives
**860 records, 3 971 684 store bytes, 123 402 MW bytes (3.11%), 562 with a
macro word** — byte-identical to the dev's numbers — and over `opentitan`
gives **3 979 records, 44 858 329 bytes, 743 873 MW bytes (1.66%), 3 174**,
also identical.
**Format-16 → 17 store rebuild.** Built a scratch one-file workspace, ran
the 0.33.0 binary against a fresh store directory (header written:
`lucisv-index-cache 2 16 0.33.0`), then ran the dev binary against the
*same* store directory: the header flips to `... 17 0.33.0` and the single
record is rewritten in full (new checksum, new `MW 4 ...` group appended) —
a whole-record rebuild, not a patch, exactly as `IndexCache::open`'s
header-mismatch-discards-everything logic (unmodified by this lane —
confirmed via `git diff d1821ff -- crates/lucisv_server/src/index_cache.rs`
being empty) predicts. No explicit "stale store" log line exists or is
claimed; the discard is silent by construction, which matches the README.
**29.3.** `lucisv check --rules-doc` prints the reference and exits 0; the
output has exactly 17 `## <name>` sections, matching
`vlog_linter::registry::all_rules().len()` (17). `lucisv check --rules-doc
<file>` and `lucisv --rules-doc <file>` both exit 2 with "`--rules-doc`
takes no files"; `lucisv --rules-doc` (no file, format mode) exits 2 with
"`--rules-doc` is only valid for `lucisv check`". `crates/vlog_linter/
examples/` no longer exists. The flag is documented under `CHECK OPTIONS
(`lucisv check` only):` in `--help`. `cargo test -p lucisv rules_doc` — all
3 tests pass (`args::tests::rules_doc_is_the_one_check_that_needs_no_input`,
`cli::rules_doc_prints_the_generated_reference`,
`cli::rules_doc_refuses_files_and_belongs_to_check`).
**Store growth / corpus / OpenTitan sweep.** `scripts/corpus_gate.sh
corpus` (main tree's corpus, this worktree has none of its own): **814/820
(99.3%)**, same five failure categories the dev listed. Built a `v0.33.0`
release `lucisv` from the tag in a throwaway worktree and ran `lucisv check`
over OpenTitan with both binaries: identical exit code 2, identical line
count (225), **identical MD5** — byte-for-byte the same 223 violations plus
the same 1 file that cannot be lexed. OpenTitan `git status --porcelain`
unchanged (only the three pre-existing files) throughout every experiment
in this QA pass.
**Docs.** All four README amendments (`refactor-rename`,
`semantic-lints-on`, `index-persistence`, `lint-rules-2`) spot-checked
against the code and measurements above and read as true. `git diff
d1821ff -- docs/topo.md` is empty, matching this lane's own claim that it
does not edit `topo.md` — §2.9-5/§2.9-18 remain open there, correctly left
for the lead to strike. `TODO.md` §29's four checked items match verified
reality; the QA line is closed by this pass.
**Housekeeping.** All experiments used either untracked scratch test files
in the dev worktree (created, run, then deleted — `git status --porcelain`
confirmed clean before and after) or the required throwaway worktrees
(`qa-play-29`, `qa-play-29-baseline`, `qa-play-29-v33`, all branched from
`a4b8ca0`/`v0.33.0` and removed with `git worktree remove --force` when
done). No tracked file in `.claude/worktrees/small-1` was touched other
than this README. Noted in passing, not caused by this QA pass and outside
its scope: `master` and `.claude/worktrees/small-2` changed during this
session (a `small-2` merge landed on `master`) — that was other, concurrent
activity in this multi-lane workflow, not a QA action; `small-1` was never
touched by it.
**Findings.** None forcing rework. One MEDIUM note: a ~1% (~70 ms)
end-to-end timing gap at an extreme, uncommon fan-out size (`clk_i` across
all of OpenTitan) that I could not further isolate within this pass; not
reproduced at a realistic fan-out size, and small next to the ~7 s baseline
cost of that fan-out itself. Everything else — correctness, the warning's
edit/no-edit/no-double-warning behavior on both a crafted pin and an
organic OpenTitan example, the format bump and its silent whole-store
rebuild, `--rules-doc`, store growth, and documentation — verified exactly
as claimed.
**Verdict: PASS.**
## Review
**2026-09-02 — lead.** Accepted. The census does what the §2.9-18
ruling asked and nothing more: a second sorted list per file, read from
the same lex, consulted by binary search, and the server *warns* from it
without reading a file — 58 files in 186 µs on opentitan, against the
2.5–3.0 s a `files_mentioning` rung would have cost. QA's organic find
(`cipher_crypt` named inside a `` `DV_CHECK_FATAL `` in a sequence file
that 0.33.0's rename never mentioned) is the whole point of the item in
one example. The three decisions are right: `MW` because `M` is taken;
no new rung because `rename_sources` already returns the set it built;
and the pin retargeted to a shape that actually resolves rather than
one that would have pinned §2.9-23's gap as if it were this item's.
`--rules-doc` is small and complete, and removing the example binary is
the right call now that the flag exists. The `Scope` move is a pure
move with counts identical. The MEDIUM timing note (≈70 ms at an
extreme fan-out, invisible at a realistic one, unisolated) is recorded
and not chased: the pass is measured at 0.2 ms and the gap sits inside
the pre-existing fan-out. Filed by the dev and accepted: a `perf.rs`
probe for the rename warning pass. Ships in 0.34.0.
+24
View File
@@ -1824,3 +1824,27 @@ would pull in every file that writes the word `clk`, and `rename_sources`
`prepare_rename_here` exists to avoid. Accepting the cost, capping the extra
set, or answering it in the server from the index without reading anything are
three real options; the round has no evidence for choosing and does not.
**§2.9-18 closed, 2026-09-02 (`macro-word-census`, TODO §29.2): the third
option.** The lead ruled against the rung, for the reason above, and for a
*second* census instead — one the server can warn from without reading a byte.
`vlog_semantic::words::harvest_raw` harvests the words a file writes only
inside a macro invocation, a directive line or an attribute; they are stored
per file as `FileFacts::macro_words` (`FACTS_FORMAT` 16 → 17) and asked of
`WorkspaceIndex::files_naming_in_macros`, the twin of `files_mentioning` over
the shorter list. `lucisv_server::rename::rename` appends one sentence per file
that census names and `rename_sources` did **not** hand the engine:
> `` `sig` `` also appears inside a macro invocation in `far.svh`, which this
> rename did not read; check it by hand — a macro argument cannot be edited.
No rung was added and `Workspace` gained no method: `rename_sources` already
returns the path set it built, so the server subtracts it directly — which also
excludes every open buffer, because that set contains them. The engine's own
`macro_use_warnings` is unchanged and still speaks for every file the engine
read, so a file that *is* a source is warned about exactly once, in the
engine's more precise words (pinned by the control test
`a_macro_file_the_rename_does_read_is_warned_about_exactly_once`). The pass
costs under 0.2 ms over all 3 979 OpenTitan files and reads nothing, so the
`prepare_rename_here` cost stays gone. Details and measurements:
`docs/features/macro-word-census/README.md`.
+14
View File
@@ -183,6 +183,20 @@ their arguments" is exactly what `FileFacts::words` now holds, and
stop losing its informational macro-argument warnings — not wired here, filed
in Handshakes.
**Amended 2026-09-02 (`macro-word-census`, TODO §29.2).** It could not be read
as it stands: this census folds the raw words *into* the plain ones, so it
answers "does this file name `clk`" and not "does it name `clk` where nothing
can edit it" — and a rename asking the first question would pull in every file
writing `clk`. So the same split is written down a second time, beside this
one, and this one is **unchanged**: `words::harvest_raw` returns the raw half
alone, stored as `FileFacts::macro_words` (`FACTS_FORMAT` 16 → 17, `MW`) and
queried through `files_naming_in_macros`. Both harvests branch on the same
`words::raw_text` predicate and split with the same `raw_words`, so the table
above describes both and they cannot drift. The lint rules keep reading
`words`, deliberately: a signal read only inside a `` `uvm_info `` argument
*is* mentioned, and the union is the false-negative-safe answer.
See `docs/features/macro-word-census/README.md`.
### Why there is no inverted index
The obvious shape is `BTreeMap<String, Vec<FileId>>`, built in