From ca83f6f99f43e8aa5e44ab118c55e78b901c6310 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 14 Oct 2026 13:33:27 -0700 Subject: [PATCH] =?UTF-8?q?Review=20lows=20L-1=E2=80=93L-4,=20L-12,=20L-13?= =?UTF-8?q?:=20end=20labels,=20duplicate=20generate=20labels,=20dotted=20c?= =?UTF-8?q?omments,=20lex-failure=20fallbacks,=20file=20naming?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - L-1: an unowned block's closing label is a use of a same-named block only for block constructs and only when it spells the construct's own opening label (use_block_end_label); a mismatched `end : a` or an `endfunction : g` beside block `g` records nothing. - L-2: duplicate-declaration stays silent for two block labels only when both may be arms of one generate if/case; sibling `for` blocks and a procedural block beside a generate one are reported in either order. OpenTitan check: 1 158 findings, identical to 0.60.0. - L-3: a block comment between `.` and the name is still dotted. - L-4: a bind file that does not lex counts as binding (K2); a pasted fragment that does not lex is said, not skipped. - L-12: no unchecked slice in rename/arms.rs. - L-13: expand/ansi/inline/extract messages name files by Scope::name_of. 7 tests (L-3/L-4's fail with the fixes disabled). Per-crate suites under the guard: 80 suites, 5 085 passed, 0 failed, 51 ignored (one combined run was cut at 1 800 s in vlog_refactor/tests/corpus.rs with syspolicyd at 95 % — the §65.3 stall). Co-Authored-By: Claude Opus 5.5 --- .../src/rules/duplicate_declaration.rs | 88 +++++++++++++++---- crates/vlog_refactor/src/extract/boundary.rs | 15 +--- crates/vlog_refactor/src/extract/mod.rs | 4 +- crates/vlog_refactor/src/inline/mod.rs | 12 ++- crates/vlog_refactor/src/ports/ansi.rs | 12 ++- crates/vlog_refactor/src/ports/expand.rs | 22 +++-- crates/vlog_refactor/src/ports/offer.rs | 6 +- crates/vlog_refactor/src/rename/arms.rs | 3 +- crates/vlog_refactor/src/rename/scoped.rs | 45 +++++++--- crates/vlog_refactor/tests/expand.rs | 15 ++++ .../tests/rename_warning_scope.rs | 47 ++++++++++ crates/vlog_semantic/src/bind/generate.rs | 9 +- crates/vlog_semantic/src/bind/mod.rs | 46 +++++++--- crates/vlog_semantic/src/bind/stmt.rs | 50 +++++++---- crates/vlog_semantic/tests/generate_blocks.rs | 24 +++++ docs/features/generate-label-rename/README.md | 25 ++++++ oct_review.md | 12 +-- 17 files changed, 330 insertions(+), 105 deletions(-) diff --git a/crates/vlog_linter/src/rules/duplicate_declaration.rs b/crates/vlog_linter/src/rules/duplicate_declaration.rs index af4a68a..c88b1a2 100644 --- a/crates/vlog_linter/src/rules/duplicate_declaration.rs +++ b/crates/vlog_linter/src/rules/duplicate_declaration.rs @@ -4,7 +4,8 @@ use crate::context::LintContext; use crate::registry::Rule; use crate::severity::Severity; use crate::violation::Violation; -use vlog_semantic::{ScopeKind, Symbol, SymbolKind}; +use vlog_parser::span::TextRange; +use vlog_semantic::{Duplicate, ScopeId, ScopeKind, Semantics, Symbol, SymbolKind}; /// See [`Rule::doc`]. pub struct DuplicateDeclaration; @@ -60,7 +61,7 @@ impl Rule for DuplicateDeclaration { let mut out = Vec::new(); for duplicate in semantics.duplicates() { let Some(first) = semantics.symbol(duplicate.first) else { continue }; - if !collides(semantics, duplicate.kind, first) { + if !collides(semantics, duplicate, first) { continue; } let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind); @@ -85,27 +86,70 @@ impl Rule for DuplicateDeclaration { } } -/// Whether a declaration of kind `kind` written after `first`, of one name in +/// Whether a declaration `duplicate` written after `first`, of one name in /// one scope, is an error: both of a kind written once and once only /// ([`plain`]); or a **block label** beside any other kind of declaration — /// a net, a variable, a parameter, an instance, a port, a genvar, a typedef, /// a function or task (a label and those share one namespace, IEEE 1800 -/// §3.13); or two labels of named **procedural** blocks (generate-label-rename -/// F3, R4). Two *generate* arms carrying one label are not: only one arm of -/// an `if`/`case` elaborates (§27.5). -fn collides(semantics: &vlog_semantic::Semantics, kind: SymbolKind, first: &Symbol) -> bool { - match (kind == SymbolKind::Block, first.kind == SymbolKind::Block) { - (false, false) => plain(kind) && plain(first.kind), - (true, true) => !opens_a_generate_scope(semantics, first), +/// §3.13); or two block labels unless both may be arms of one generate +/// `if`/`case`, of which only one elaborates (§27.5). A procedural block and +/// a `for` generate block are never such an arm, whichever comes first +/// (generate-label-rename F3, R4; review L-2). +fn collides(semantics: &Semantics, duplicate: &Duplicate, first: &Symbol) -> bool { + match (duplicate.kind == SymbolKind::Block, first.kind == SymbolKind::Block) { + (false, false) => plain(duplicate.kind) && plain(first.kind), + (true, true) => { + let second = shape_at(semantics, duplicate.scope, duplicate.name_span); + shape_of(semantics, first) != LabelShape::Arm || second != LabelShape::Arm + } _ => true, } } -/// Whether a block label names a generate block — its scope is a generate -/// scope — rather than a procedural `begin`/`fork` or a statement label. -fn opens_a_generate_scope(semantics: &vlog_semantic::Semantics, label: &Symbol) -> bool { - let child = label.child_scope.and_then(|id| semantics.scope(id)); - child.is_some_and(|scope| scope.kind == ScopeKind::Generate) +/// What a block label names, as far as two labels of one name may coexist. +#[derive(PartialEq)] +enum LabelShape { + /// A procedural `begin`/`fork` or a statement label. + Procedural, + /// A generate block that may be one arm of an `if`/`case`. + Arm, + /// A `for` generate block: its scope hangs off the loop header. + Loop, +} + +/// The shape of a declared label, read off the scope it opened. +fn shape_of(semantics: &Semantics, label: &Symbol) -> LabelShape { + let Some(child) = label.child_scope.and_then(|id| semantics.scope(id)) else { + return LabelShape::Procedural; + }; + match (child.kind, child.parent == Some(label.scope)) { + (ScopeKind::Generate, true) => LabelShape::Arm, + (ScopeKind::Generate, false) => LabelShape::Loop, + _ => LabelShape::Procedural, + } +} + +/// The shape of a redeclared label, which owns no scope: read off the scope +/// written at its name — a generate scope of `declared_in` holding it is an +/// arm, unless a generate scope inside that one holds it too (a `for` +/// header, then its body). No scope holding it is a statement label. +fn shape_at(semantics: &Semantics, declared_in: ScopeId, name: TextRange) -> LabelShape { + let holding = |id: &ScopeId| { + semantics.scope(*id).filter(|s| s.span.start <= name.start && name.end <= s.span.end) + }; + let Some(outer) = + semantics.scope(declared_in).and_then(|s| s.children.iter().find_map(holding)) + else { + return LabelShape::Procedural; + }; + if outer.kind != ScopeKind::Generate { + return LabelShape::Procedural; + } + let inner = outer.children.iter().filter_map(holding).any(|s| s.kind == ScopeKind::Generate); + match inner { + true => LabelShape::Loop, + false => LabelShape::Arm, + } } /// True for the declaration kinds that may be written **once** and once only. @@ -180,6 +224,20 @@ mod tests { assert!(violations(case).is_empty()); } + /// Review L-2: a `for` generate block is never an arm, and a procedural + /// block beside a generate block is flagged whichever comes first. + #[test] + fn flags_sibling_loops_and_a_procedural_block_beside_a_generate_one() { + let lp = " for (genvar i = 0; i < 2; i++) begin : g\n end\n"; + let arm = " if (1) begin : g\n end\n"; + let proc = " initial begin : g\n end\n"; + for (one, two) in [(lp, lp), (arm, lp), (lp, arm), (proc, arm), (arm, proc)] { + let src = format!("module m;\n{one}{two}endmodule\n"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{src}: {found:?}"); + } + } + #[test] fn flags_two_signals_of_one_name() { let src = "module m;\n logic a;\n logic a;\nendmodule\n"; diff --git a/crates/vlog_refactor/src/extract/boundary.rs b/crates/vlog_refactor/src/extract/boundary.rs index 8981477..1768acd 100644 --- a/crates/vlog_refactor/src/extract/boundary.rs +++ b/crates/vlog_refactor/src/extract/boundary.rs @@ -16,14 +16,11 @@ //! work log. use std::collections::HashMap; -use std::path::{Path, PathBuf}; use vlog_parser::ast::{ItemKind, SourceFile}; use vlog_parser::span::TextRange; use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind}; -use crate::rename::display; - use super::flow; use super::region::Region; use super::render::{self, Param, Port}; @@ -148,18 +145,14 @@ impl Crossing { pub(super) fn warnings( &self, new_name: &str, - created: &Option, - file: &Path, + created: Option<&str>, + file: &str, ) -> Vec { let mut out = Vec::new(); out.push(match created { - Some(path) => format!( - "`{new_name}` was written to a new file, `{}`.", - display(path) - ), + Some(path) => format!("`{new_name}` was written to a new file, `{path}`."), None => format!( - "`{new_name}` was written below its neighbour in `{}`: this editor did not say it can create files, so lucisv did not make one.", - display(file) + "`{new_name}` was written below its neighbour in `{file}`: this editor did not say it can create files, so lucisv did not make one." ), }); out.push(format!( diff --git a/crates/vlog_refactor/src/extract/mod.rs b/crates/vlog_refactor/src/extract/mod.rs index f74ef5c..32d7191 100644 --- a/crates/vlog_refactor/src/extract/mod.rs +++ b/crates/vlog_refactor/src/extract/mod.rs @@ -254,7 +254,9 @@ impl Extraction { out.push((path.to_path_buf(), file_edits)); } out.sort_by(|a, b| a.0.cmp(&b.0)); - Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) }) + let created = created.as_deref().map(|path| scope.name_of(path)); + let warnings = crossing.warnings(new_name, created.as_deref(), &scope.name_of(file)); + Ok(Extraction { edits: out, warnings }) } } diff --git a/crates/vlog_refactor/src/inline/mod.rs b/crates/vlog_refactor/src/inline/mod.rs index 896bcb5..bc684bd 100644 --- a/crates/vlog_refactor/src/inline/mod.rs +++ b/crates/vlog_refactor/src/inline/mod.rs @@ -114,7 +114,7 @@ pub fn inline_module( let mut scope = Scope::build(files); let Some(here) = scope.index_of(file) else { return Err(not_in_scope(file)) }; let Some(text) = scope.text(here) else { return Err(not_in_scope(file)) }; - let tree = parsed(text, file)?; + let tree = parsed(text, &scope.name_of(file))?; let Some(found) = Site::read(&tree, text, offset) else { return Err(NOTHING.to_string()) }; let site = found?; @@ -126,7 +126,7 @@ pub fn inline_module( let there = declaring_file(&scope, here, &site)?; let Some(source_text) = scope.text(there) else { return Err(abandoned(&site)) }; let source_path = scope.path(there).unwrap_or(Path::new("?")).to_path_buf(); - let source_tree = parsed(source_text, &source_path)?; + let source_tree = parsed(source_text, &scope.name_of(&source_path))?; let source = Source::read(&source_tree, source_text, scope.index(), &site.target)?; same_timescale(text, source_text, &site.target)?; no_hierarchy(&scope, &site)?; @@ -222,7 +222,7 @@ fn declaring_file(scope: &Scope<'_>, here: usize, site: &Site<'_>) -> Result, site: &Site<'_>) -> Result<(), String> { // odds and ends // ---------------------------------------------------------------------- -fn parsed(text: &str, path: &Path) -> Result { +fn parsed(text: &str, shown: &str) -> Result { let (tree, diagnostics) = parse_source_tolerant(text); match diagnostics.first() { None => Ok(tree), Some(problem) => Err(format!( "{} does not parse ({} at line {}), so lucisv will not inline through it.", - display(path), - problem.message, - problem.line + shown, problem.message, problem.line )), } } diff --git a/crates/vlog_refactor/src/ports/ansi.rs b/crates/vlog_refactor/src/ports/ansi.rs index 39b133e..4395d98 100644 --- a/crates/vlog_refactor/src/ports/ansi.rs +++ b/crates/vlog_refactor/src/ports/ansi.rs @@ -64,7 +64,7 @@ pub(super) fn plan_convert( let Some((module, _)) = find_module(&tree, &name) else { return Err(format!("lucisv can no longer find the declaration of `{name}`.")); }; - let ports = convert_header(file, &diagnostics, module)?; + let ports = convert_header(&scope.name_of(file), &diagnostics, module)?; let site = locate_module(scope, ModuleRef::Name(&name))?; if site.file != i { return Err(elsewhere(&name)); @@ -83,13 +83,13 @@ pub(super) fn plan_convert( /// Split out of [`plan_convert`] so the code-action offer earns the same /// refusals from the buffer's own parse (take 5 §P1c, `ports::offer`). pub(super) fn convert_header<'t>( - file: &Path, + shown: &str, diagnostics: &[ParseDiagnostic], module: &'t Module, ) -> Result, String> { let name = &module.name; let ports = header(module)?; - unparsed(file, diagnostics)?; + unparsed(shown, diagnostics)?; let names = header_names(module, &ports)?; if !module.port_directives.is_empty() { return Err(format!( @@ -186,14 +186,12 @@ fn header_names(module: &Module, ports: &[&NonAnsiPort]) -> Result, /// The refusal a file that does not parse earns. Stricter than the verifier's /// "no *new* diagnostic" rule, and for the same reason the `.*` expansion is: /// a header lucisv misread is a header whose ports it would declare twice. -fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> { +fn unparsed(shown: &str, diagnostics: &[ParseDiagnostic]) -> Result<(), String> { match diagnostics.first() { None => Ok(()), Some(problem) => Err(format!( "{} does not parse ({} at line {}), so lucisv will not convert its ports to ANSI.", - display(file), - problem.message, - problem.line + shown, problem.message, problem.line )), } } diff --git a/crates/vlog_refactor/src/ports/expand.rs b/crates/vlog_refactor/src/ports/expand.rs index 7dffea1..fa996d3 100644 --- a/crates/vlog_refactor/src/ports/expand.rs +++ b/crates/vlog_refactor/src/ports/expand.rs @@ -26,7 +26,7 @@ use vlog_parser::span::TextRange; use vlog_parser::{parse_source_tolerant, LineIndex, ParseDiagnostic}; use vlog_semantic::SymbolKind; -use crate::rename::{display, Scope}; +use crate::rename::Scope; use crate::TextEdit; use super::add::not_indexed; @@ -55,7 +55,7 @@ pub(super) fn plan_expand( let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) }; let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) }; let (tree, diagnostics) = parse_source_tolerant(text); - unparsed(file, &diagnostics)?; + unparsed(&scope.name_of(file), &diagnostics)?; let Wildcard { instantiation, instance, conns, wildcard } = wildcard_at(&tree.items, offset)?; if !instance.conn_directives.is_empty() { return Err(directives(&instance.name, "connection list")); @@ -86,7 +86,7 @@ pub(super) fn plan_expand( let mut plan = Plan { sites: 1, ..Plan::default() }; plan.add(i, replacement(text, previous, at, &connections)); if !unbound.is_empty() { - plan.warnings.push(unbound_warning(text, file, instance, &unbound)); + plan.warnings.push(unbound_warning(text, &scope.name_of(file), instance, &unbound)); } plan.expected.push((i, expected(text, &site.name, instance, conns, wildcard, &missing))); Ok(Expansion { site, plan, count: connections.len(), instance: instance.name.clone() }) @@ -95,14 +95,12 @@ pub(super) fn plan_expand( /// The refusal a file that does not parse earns. A connection list lucisv /// misread is a list whose ports it would connect twice, so — unlike the /// verifier's "no *new* diagnostic" rule — this one asks for none at all. -fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> { +fn unparsed(shown: &str, diagnostics: &[ParseDiagnostic]) -> Result<(), String> { match diagnostics.first() { None => Ok(()), Some(problem) => Err(format!( "{} does not parse ({} at line {}), so lucisv will not expand a `.*` in it.", - display(file), - problem.message, - problem.line + shown, problem.message, problem.line )), } } @@ -195,19 +193,19 @@ fn unconnected( let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) }; let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) }; let (tree, diagnostics) = parse_source_tolerant(text); - unconnected_in(path, &tree, &diagnostics, &site.name, conns) + unconnected_in(&scope.name_of(path), &tree, &diagnostics, &site.name, conns) } /// [`unconnected`] over the declaring file's parse, which the code-action /// offer makes once instead of once per refactoring (take 5 §P1c). pub(super) fn unconnected_in( - path: &Path, + shown: &str, tree: &SourceFile, diagnostics: &[ParseDiagnostic], module: &str, conns: &[ListElem], ) -> Result, String> { - unparsed(path, diagnostics)?; + unparsed(shown, diagnostics)?; let Some((declaration, _)) = find_module(tree, module) else { return Err(not_indexed(module)); }; @@ -311,13 +309,13 @@ fn replacement(text: &str, previous: u32, at: TextRange, connections: &[String]) vec![replace(format!("{first},")), insert(after.at, format!("{br}{}", rest.join(&separator)))] } -fn unbound_warning(text: &str, file: &Path, instance: &Instance, unbound: &[String]) -> String { +fn unbound_warning(text: &str, shown: &str, instance: &Instance, unbound: &[String]) -> String { let lines = LineIndex::new(text); format!( "no net, variable or port named {} is declared where `{}` is instantiated ({}:{}), so `.*` never bound {} — lucisv wrote {} unconnected.", unbound.iter().map(|n| format!("`{n}`")).collect::>().join(", "), instance.name, - display(file), + shown, lines.line_col(instance.name_span.start).0, if unbound.len() == 1 { "it" } else { "them" }, if unbound.len() == 1 { "it" } else { "them" }, diff --git a/crates/vlog_refactor/src/ports/offer.rs b/crates/vlog_refactor/src/ports/offer.rs index cfc8c0d..e656a23 100644 --- a/crates/vlog_refactor/src/ports/offer.rs +++ b/crates/vlog_refactor/src/ports/offer.rs @@ -47,7 +47,7 @@ use super::list::{append_to_list, conn_list_open, elem_spans}; use super::propagate::{connections_of, instance_at, missing_ports}; use super::remove::{body_uses_in, disconnections_in, header_removal, port_at}; use super::{port_action_modules_in, sites_phrase, Plan}; -use crate::scope::BaseNames; +use crate::scope::{display, BaseNames}; /// Which of the four port refactorings an offer names. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -376,7 +376,7 @@ fn expansion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option< let at = files.declaring(buffer.tree, &module_name)?; let missing = { let (path, tree, diagnostics) = files.declaration(buffer, at)?; - unconnected_in(path, tree, diagnostics, &module_name, conns).ok()? + unconnected_in(&display(path), tree, diagnostics, &module_name, conns).ok()? }; if missing.is_empty() { return None; @@ -402,7 +402,7 @@ fn conversion(buffer: &Buffer<'_>, files: &mut Files<'_>, offset: u32) -> Option module_at(&buffer.tree.items, offset, &mut found); let name = found?; let (module, _) = find_module(buffer.tree, &name)?; - let ports = convert_header(buffer.file, buffer.diagnostics, module).ok()?; + let ports = convert_header(&display(buffer.file), buffer.diagnostics, module).ok()?; if files.declaring(buffer.tree, &name)? != Declared::Here { return None; } diff --git a/crates/vlog_refactor/src/rename/arms.rs b/crates/vlog_refactor/src/rename/arms.rs index 32b5ebc..e5ef67d 100644 --- a/crates/vlog_refactor/src/rename/arms.rs +++ b/crates/vlog_refactor/src/rename/arms.rs @@ -36,7 +36,8 @@ impl<'a> Scope<'a> { .filter_map(|arm| sem.scope(arm)?.lookup_local(&target.name)) .filter_map(|other| sem.symbol(other)) .map(|other| { - let line = text[..other.name_span.start as usize].matches('\n').count() + 1; + let before = text.get(..other.name_span.start as usize).unwrap_or_default(); + let line = before.matches('\n').count() + 1; format!( "`{}` is also declared at {where_}:{line}, in another arm labelled `{dotted}`; a path `{dotted}.{}` now names only the renamed arm's declaration, and that one was left unchanged.", target.name, target.name diff --git a/crates/vlog_refactor/src/rename/scoped.rs b/crates/vlog_refactor/src/rename/scoped.rs index 4258508..e29aeb0 100644 --- a/crates/vlog_refactor/src/rename/scoped.rs +++ b/crates/vlog_refactor/src/rename/scoped.rs @@ -195,7 +195,8 @@ fn files_binding_into(scope: &Scope, unit: &str, carriers: &Carriers) -> Vec Scope<'a> { if !super::contains_word(text, &name) { continue; } - let Ok(tokens) = vlog_parser::tokenize(text) else { continue }; - let Some(analysis) = self.analysis(file) else { continue }; + let shown = self.name_at(file); + let relation = match included { + true => format!("a file `{declaring}` includes"), + false => format!("a file that includes `{declaring}` or is included with it"), + }; + // A fragment that does not lex cannot be scanned: say it spells + // the name rather than drop it (review L-4). + let tokens = vlog_parser::tokenize(text).ok(); + let (Some(tokens), Some(analysis)) = (tokens, self.analysis(file)) else { + out.push(format!( + "{shown}: `{name}` is spelled in {relation}, which lucisv could not read, and was left unchanged." + )); + continue; + }; let edited: Vec = edits .iter() .filter(|(i, _)| *i == file) @@ -232,13 +245,8 @@ impl<'a> Scope<'a> { continue; } let at = lines.iter().map(u32::to_string).collect::>().join(","); - let relation = match included { - true => format!("a file `{declaring}` includes"), - false => format!("a file that includes `{declaring}` or is included with it"), - }; out.push(format!( - "{}:{at}: `{name}` is used in {relation} and was left unchanged; lucisv does not rename inside `included text.", - self.name_of(self.path(file).unwrap_or(std::path::Path::new("?"))) + "{shown}:{at}: `{name}` is used in {relation} and was left unchanged; lucisv does not rename inside `included text." )); } out @@ -363,14 +371,20 @@ pub(super) fn spellings(text: &str, name: &str) -> (Vec, bool) { (bare, dotted) } -/// Whether `before` ends in a `.`, past blanks and `` `` `` pastes -/// (`` u_m.``sig `` pastes a path). +/// Whether `before` ends in a `.`, past blanks, `` `` `` pastes +/// (`` u_m.``sig `` pastes a path) and block comments (`u_m./*x*/sig`, +/// review L-3). fn after_dot(before: &str) -> bool { let mut rest = before.trim_end(); - while let Some(shorter) = rest.strip_suffix("``") { - rest = shorter.trim_end(); + loop { + if let Some(shorter) = rest.strip_suffix("``") { + rest = shorter.trim_end(); + } else if let Some(open) = rest.strip_suffix("*/").and_then(|r| r.rfind("/*")) { + rest = rest[..open].trim_end(); + } else { + return rest.ends_with('.'); + } } - rest.ends_with('.') } #[cfg(test)] @@ -384,5 +398,8 @@ mod tests { assert_eq!(spellings("x(state_qq, my_state_q)", "state_q"), (vec![], false)); assert_eq!(spellings("u_m.``state_q", "state_q"), (vec![], true)); assert_eq!(spellings("pre``state_q", "state_q"), (vec![5], false)); + assert_eq!(spellings("u_m./*x*/state_q", "state_q"), (vec![], true)); + assert_eq!(spellings("u_m. /* c */ state_q", "state_q"), (vec![], true)); + assert_eq!(spellings("/* a. */ state_q", "state_q"), (vec![9], false)); } } diff --git a/crates/vlog_refactor/tests/expand.rs b/crates/vlog_refactor/tests/expand.rs index 8de43ff..c217f8a 100644 --- a/crates/vlog_refactor/tests/expand.rs +++ b/crates/vlog_refactor/tests/expand.rs @@ -412,3 +412,18 @@ fn an_unbound_escaped_port_is_terminated_too() { let (_, diagnostics) = vlog_parser::parse_source_tolerant(&text); assert!(diagnostics.is_empty(), "{diagnostics:?}\n{text}"); } + +/// Review L-13: a refusal names a file by its path when another file of the +/// set shares its base name, as every other refactoring's message does. +#[test] +fn a_file_that_does_not_parse_is_named_by_its_path_when_its_name_is_shared() { + let broken = "module top;\n sub u (.*);\n assign = ;\nendmodule\n"; + let set = files(&[ + ("/w/a/top.sv", broken), + ("/w/b/top.sv", "module other;\nendmodule\n"), + ("/w/sub.sv", "module sub (input logic clk);\nendmodule\n"), + ]); + let refusal = expand_wildcard(&set, &PathBuf::from("/w/a/top.sv"), at(broken, ".*")) + .expect_err("refused"); + assert!(refusal.starts_with("/w/a/top.sv does not parse"), "{refusal}"); +} diff --git a/crates/vlog_refactor/tests/rename_warning_scope.rs b/crates/vlog_refactor/tests/rename_warning_scope.rs index 002403b..4f51ce3 100644 --- a/crates/vlog_refactor/tests/rename_warning_scope.rs +++ b/crates/vlog_refactor/tests/rename_warning_scope.rs @@ -124,3 +124,50 @@ fn an_edited_use_in_an_include_related_file_is_not_said_to_be_left_unchanged() { let left = edit.warnings.iter().any(|w| w.contains("n.sv:2") && w.contains("left unchanged")); assert!(!left, "{:#?}", edit.warnings); } + +/// The warnings of renaming the first `logic state_q` in `m.sv` among `files`. +fn warnings_renaming_m_state_q(files: &[(&str, &str)]) -> Vec { + let text = files.iter().find(|(n, _)| *n == "m.sv").map(|(_, t)| *t).expect("m.sv"); + let at = text.find("logic state_q").expect("decl") as u32 + 6; + let set = workspace(files); + rename(&set, &PathBuf::from("/rtl/m.sv"), at, "state_r").expect("renames").warnings +} + +/// Review L-3: a comment between the `.` and the name is still a path. +#[test] +fn a_path_with_a_comment_after_its_dot_is_said() { + let m = "module m (input logic clk);\n logic state_q;\nendmodule\n"; + let tb = "module tb;\n m u_m (.clk(1'b0));\n initial $display(\"%b\", `Q(u_m. /* c */ state_q));\nendmodule\n"; + let warnings = warnings_renaming_m_state_q(&[ + ("defs.svh", "`define Q(x) x\n"), + ("m.sv", m), + ("tb.sv", tb), + ]); + assert!(warnings.iter().any(|w| w.contains("tb.sv:3")), "{warnings:#?}"); +} + +/// Review L-4: a file that spells `bind` but does not lex is counted as +/// binding into the module, so the macros it invokes are followed. +#[test] +fn a_bind_file_that_does_not_lex_still_makes_its_macros_home() { + let m = "module m (input logic clk);\n logic state_q;\nendmodule\n"; + let binds = "module binds;\n bind m chk u_chk (.s(`SIG));\n initial $display(\"unterminated);\nendmodule\n"; + let warnings = warnings_renaming_m_state_q(&[ + ("defs.svh", "`define SIG state_q\n"), + ("m.sv", m), + ("binds.sv", binds), + ]); + assert!(warnings.iter().any(|w| w.contains("defs.svh:1")), "{warnings:#?}"); +} + +/// Review L-4: an included fragment that does not lex is said, not skipped. +#[test] +fn an_included_fragment_that_does_not_lex_is_said() { + let m = "module m (output logic o);\n logic state_q;\n`include \"frag.svh\"\nendmodule\n"; + let frag = " assign o = state_q;\n initial $display(\"unterminated);\n"; + let warnings = warnings_renaming_m_state_q(&[("m.sv", m), ("frag.svh", frag)]); + assert!( + warnings.iter().any(|w| w.contains("frag.svh") && w.contains("could not read")), + "{warnings:#?}" + ); +} diff --git a/crates/vlog_semantic/src/bind/generate.rs b/crates/vlog_semantic/src/bind/generate.rs index 42adb5d..7543293 100644 --- a/crates/vlog_semantic/src/bind/generate.rs +++ b/crates/vlog_semantic/src/bind/generate.rs @@ -73,6 +73,13 @@ impl<'a> Binder<'a> { self.scopes[inner.0 as usize].owner = Some(sym); } self.bind_items(&b.items, inner); - self.use_end_label(declared_in, inner, b.end_label.as_ref(), b.end_label_span); + let opening = b.label.as_deref(); + self.use_block_end_label( + declared_in, + inner, + opening, + b.end_label.as_ref(), + b.end_label_span, + ); } } diff --git a/crates/vlog_semantic/src/bind/mod.rs b/crates/vlog_semantic/src/bind/mod.rs index 730b44b..bfd9c5e 100644 --- a/crates/vlog_semantic/src/bind/mod.rs +++ b/crates/vlog_semantic/src/bind/mod.rs @@ -353,21 +353,47 @@ impl<'a> Binder<'a> { label: Option<&String>, span: Option, ) { - let (Some(label), Some(span)) = (label, span) else { - return; - }; // `None` when the declaration was a redeclaration and bound no symbol - // of its own; the label is then left unrecorded, as it was before — - // except for a block. Two arms of one generate `if`/`case` may carry - // the same label (IEEE 1800 §27.5), and the second arm's opening label - // is already a use of the first declaration; its closing label is the - // same name and must be the same use, or a rename rewrites one of the - // pair and leaves `end : old` closing `begin : new`. + // of its own; the label is then left unrecorded. + let owner = self.scopes[body.0 as usize].owner; + self.record_end_label(scope, owner, label, span); + } + + /// [`Self::use_end_label`] for a block (`begin`/`fork`, a generate + /// block), whose own opening label is `opening` — the `begin : lbl` name + /// or the `lbl:` prefix. An unowned block may still close with its opening + /// label: the second arm of a generate `if`/`case` carrying the first's + /// label (IEEE 1800 §27.5), whose opening label is already a use of the + /// first declaration, and the prefix form, which declares a label but no + /// owned scope. That closing label is a use of the first same-scope + /// **block** of the name, or a rename rewrites one of the pair and leaves + /// `end : old` closing `begin : new`. A closing label that does not spell + /// the opening one records nothing (review L-1). + pub(super) fn use_block_end_label( + &mut self, + scope: ScopeId, + body: ScopeId, + opening: Option<&str>, + label: Option<&String>, + span: Option, + ) { let owner = self.scopes[body.0 as usize].owner.or_else(|| { + let label = label.filter(|l| opening == Some(l.as_str()))?; let first = *self.scopes[scope.0 as usize].names.get(label)?; (self.symbols[first.0 as usize].kind == SymbolKind::Block).then_some(first) }); - let Some(sym) = owner else { + self.record_end_label(scope, owner, label, span); + } + + /// Records an end label as a use of `owner` when it spells its name. + fn record_end_label( + &mut self, + scope: ScopeId, + owner: Option, + label: Option<&String>, + span: Option, + ) { + let (Some(label), Some(span), Some(sym)) = (label, span, owner) else { return; }; if self.symbols[sym.0 as usize].name != *label { diff --git a/crates/vlog_semantic/src/bind/stmt.rs b/crates/vlog_semantic/src/bind/stmt.rs index 820780b..8635c2d 100644 --- a/crates/vlog_semantic/src/bind/stmt.rs +++ b/crates/vlog_semantic/src/bind/stmt.rs @@ -81,24 +81,35 @@ impl<'a> Binder<'a> { } } + /// A `begin`/`fork` block: its own label (if any) declared in `scope` + /// with the block's scope, its statements, and its closing label, which + /// may also close a `prefix:` statement label. + fn bind_block(&mut self, stmt: &'a Stmt, scope: ScopeId, prefix: Option<&str>) { + let (StmtKind::Block { label, label_span, stmts, end_label, end_label_span, .. } + | StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. }) = + &stmt.kind + else { + return; + }; + let inner = match (label, *label_span) { + (Some(label), Some(ls)) => self.declare_with_scope( + scope, + label, + SymbolKind::Block, + ls, + stmt.span, + ScopeKind::Block, + ), + _ => self.new_scope(ScopeKind::Block, scope, stmt.span), + }; + self.bind_stmts(stmts, inner); + let opening = label.as_deref().or(prefix); + self.use_block_end_label(scope, inner, opening, end_label.as_ref(), *end_label_span); + } + pub(super) fn bind_stmt(&mut self, stmt: &'a Stmt, scope: ScopeId) { match &stmt.kind { - StmtKind::Block { label, label_span, stmts, end_label, end_label_span, .. } - | StmtKind::ForkJoin { label, label_span, stmts, end_label, end_label_span, .. } => { - let inner = match (label, *label_span) { - (Some(label), Some(ls)) => self.declare_with_scope( - scope, - label, - SymbolKind::Block, - ls, - stmt.span, - ScopeKind::Block, - ), - _ => self.new_scope(ScopeKind::Block, scope, stmt.span), - }; - self.bind_stmts(stmts, inner); - self.use_end_label(scope, inner, end_label.as_ref(), *end_label_span); - } + StmtKind::Block { .. } | StmtKind::ForkJoin { .. } => self.bind_block(stmt, scope, None), StmtKind::If { cond, then, els, .. } => { self.bind_expr(cond, scope); self.bind_stmt(then, scope); @@ -115,7 +126,12 @@ impl<'a> Binder<'a> { // names its block (IEEE 1800 §9.3.5). StmtKind::Labeled { name, name_span, stmt: inner } => { self.declare(scope, name, SymbolKind::Block, *name_span, stmt.span); - self.bind_stmt(inner, scope); + match &inner.kind { + StmtKind::Block { .. } | StmtKind::ForkJoin { .. } => { + self.bind_block(inner, scope, Some(name)) + } + _ => self.bind_stmt(inner, scope), + } } StmtKind::Import(paths) => { for path in paths { diff --git a/crates/vlog_semantic/tests/generate_blocks.rs b/crates/vlog_semantic/tests/generate_blocks.rs index 6b38790..6ba0011 100644 --- a/crates/vlog_semantic/tests/generate_blocks.rs +++ b/crates/vlog_semantic/tests/generate_blocks.rs @@ -114,6 +114,30 @@ fn a_prefix_statement_label_owns_its_closing_label() { assert_eq!(resolution(&s, at(src, "end : lbl", 0, 6)), label); } +/// Review L-1: an unowned block's closing label is a use of a same-named +/// block only when it spells the block's own opening label; a mismatched +/// `end : a` closing `b: begin` records nothing. +#[test] +fn a_closing_label_that_does_not_spell_the_opening_one_attaches_to_nothing() { + let src = + "module e;\n initial begin : a\n end : a\n initial b: begin\n end : a\nendmodule\n"; + let s = sem(src); + let a = declared(&s, src, "begin : a", 8); + assert_eq!(resolution(&s, at(src, "end : a", 0, 6)), a, "a's own closing label"); + assert!(s.reference_at(at(src, "end : a", 1, 6)).is_none(), "b's mismatched closing label"); +} + +/// Review L-1: an `endfunction : g` beside a generate block `g` (a duplicate +/// the linter reports) is not a use of the block. +#[test] +fn a_subroutines_closing_label_is_never_a_use_of_a_same_named_block() { + let src = "module e;\n if (1) begin : g\n end : g\n function automatic logic g();\n return 1'b0;\n endfunction : g\nendmodule\n"; + let s = sem(src); + let block = declared(&s, src, "begin : g", 8); + let closing = s.reference_at(at(src, "endfunction : g", 0, 14)).map(|r| r.resolution.clone()); + assert_ne!(closing, Some(block), "endfunction : g is not the block's"); +} + #[test] fn an_index_is_walked_only_where_the_link_has_members_of_its_own() { let src = "module t (output logic o); diff --git a/docs/features/generate-label-rename/README.md b/docs/features/generate-label-rename/README.md index 59894d2..14dd6a6 100644 --- a/docs/features/generate-label-rename/README.md +++ b/docs/features/generate-label-rename/README.md @@ -625,6 +625,31 @@ name bare (`DefineSite::default_bare`, scanned in stale doc comment ("rework 5 does not") is corrected. Topo row 40's second half is marked answered; the CHANGELOG's two scoping bullets are merged. +**2026-10-14 — fixes for review L-1–L-4, L-12, L-13.** +- L-1 (`vlog_semantic/src/bind/mod.rs`): the closing-label fallback for an + unowned block now applies only to block constructs and only when the + closing label spells the construct's own opening label (`begin : x` or the + `x:` prefix); `use_block_end_label` beside the strict `use_end_label`. + A mismatched `end : a` closing `b: begin` and an `endfunction : g` beside + block `g` record nothing. Tests: `vlog_semantic/tests/generate_blocks.rs` (2). +- L-2 (`vlog_linter` `duplicate-declaration`): two block labels are silent + only when both may be arms of one generate `if`/`case`; a `for` block or a + procedural block beside a generate block is reported whichever comes first. + OpenTitan `lucisv check hw`: 1 158 findings, identical to 0.60.0. +- L-3 (`rename/scoped.rs::after_dot`): a block comment between the `.` and + the name (`u_m./*x*/state_q`) is still dotted. +- L-4: a file that spells `bind` but does not lex counts as binding into the + unit (K2), and an include-related fragment that does not lex is said + ("could not read") instead of skipped. +- L-12 (`rename/arms.rs`): `text.get(..)` instead of an unchecked slice. +- L-13: the `.*` expansion, ANSI conversion, inline and extract messages name + files by `Scope::name_of`. Test: `tests/expand.rs`. +L-3/L-4 tests (`tests/rename_warning_scope.rs`, 3) fail with the fixes +disabled. Workspace suite: one full run cut by the guard at 1 800 s in +`vlog_refactor/tests/corpus.rs` with `syspolicyd` at 95 % and +`mediaanalysisd` at 90 % CPU while a second worktree ran its own suite +(the §65.3 stall); re-run per crate, each under its own guard. + ## QA log **2026-09-30 — QA agent (Opus).** Verdict: **PASS with findings** — no diff --git a/oct_review.md b/oct_review.md index 848785b..7ab79e7 100644 --- a/oct_review.md +++ b/oct_review.md @@ -108,7 +108,7 @@ It is a read-only review. The only file written is this one. ## LOW -### L-1. The closing-label fallback attaches a mismatched label to the wrong block (confirmed bug) +### L-1. The closing-label fallback attaches a mismatched label to the wrong block (confirmed bug) — **FIXED 2026-10-14** - **Where:** `vlog_semantic/src/bind/mod.rs:366-369` (`use_end_label`). - **The cause:** when the body has no owner, the fallback takes the first same-scope symbol named like the *closing* label, if it is a `Block`. It never compares against the opening label of the construct being closed. The later `name != label` check is then trivially true. I confirmed this in the code. @@ -130,19 +130,19 @@ It is a read-only review. The only file written is this one. - **Effect:** only already-invalid code reaches this. - **Suggested fix:** limit the fallback to block constructs. For the `lbl: begin` form, compare against the statement's own label. -### L-2. `duplicate-declaration` misses repeated generate labels, and the result depends on order +### L-2. `duplicate-declaration` misses repeated generate labels, and the result depends on order — **FIXED 2026-10-14** - **Where:** `vlog_linter/src/rules/duplicate_declaration.rs:97-103` (`collides`, the `(true,true)` arm). - **The cause:** the arm skips any pair whose first label opens a generate scope. That is meant for the arms of one `if`/`case`, but it also hides two sibling `for … begin : g` loops. Both elaborate, so that is a compile error. - **Order dependence:** `initial begin : g` followed by `if (1) begin : g` is flagged; the reverse order is not. - This is not a regression. -### L-3. Dotted detection skips only whitespace +### L-3. Dotted detection skips only whitespace — **FIXED 2026-10-14** - **Where:** `scoped.rs:~309` (`spellings`). - **Missed shapes:** `u_m.``state_q`, `u_m./*x*/state_q`, and a macro argument `` `Q(u_m. /* c */ state_q) `` are all treated as bare and silenced in non-home files (reviewer B, repros PL, PM, PE). -### L-4. A file that fails to lex drops its warnings without saying so +### L-4. A file that fails to lex drops its warnings without saying so — **FIXED 2026-10-14** - `files_binding_into` (`scoped.rs:171`) treats a lex failure as "no bind", so the macros invoked there are not followed (repro PH: an unterminated string in `binds.sv`). - `fragment_use_warnings` (`scoped.rs:~190`) silently skips a fragment that fails to lex or analyse. @@ -186,12 +186,12 @@ It is a read-only review. The only file written is this one. - Two regions that each declare `genvar i;` now give `duplicate-declaration`. This is correct per IEEE 1800 §27.3, and the opentitan differential shows no change. - Older Verilog-2001-style code will see new findings. The CHANGELOG mentions the scope change but not this lint consequence. -### L-12. Unchecked slice in library code +### L-12. Unchecked slice in library code — **FIXED 2026-10-14** - **Where:** `vlog_refactor/src/rename/arms.rs:39`, `text[..other.name_span.start as usize]` with a `""` fallback for `text`. - It panics only if the analysis and the text disagree. `.get(..)` would follow the no-panic rule. -### L-13. R1 is incomplete +### L-13. R1 is incomplete — **FIXED 2026-10-14** - These multi-file messages still use bare `display()` instead of `name_of`: - `inline/mod.rs:225` and `:313`;