Files
lucisv/crates/vlog_refactor/src/ports/ansi.rs
T
lucioandClaude Opus 5.5 ca83f6f99f Review lows L-1–L-4, L-12, L-13: end labels, duplicate generate labels, dotted comments, lex-failure fallbacks, file naming
- 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 <[email protected]>
2026-10-14 13:33:27 -07:00

524 lines
21 KiB
Rust

//! Converting a Verilog-2001 header to an ANSI one: `module m (a, b);` with
//! `input a; output [7:0] b; reg [7:0] b;` in the body becomes
//! `module m (input a, output reg [7:0] b);` with the body declarations gone.
//!
//! **The edit is insertions, never a rewrite of the list.** Each header name
//! keeps the bytes it already occupies; what an ANSI port adds is written
//! *around* it — the direction, type and packed dimensions just before the
//! name, an unpacked dimension just after it. Two things follow from that, and
//! both are the reason it is done this way:
//!
//! * The header's own layout, commas and comments are not touched at all, so a
//! one-per-line list stays one per line and a comment written beside a port
//! name stays beside it.
//! * `Shift::map` maps the port's name span onto exactly the bytes the name
//! occupies afterwards, so `check::verify_splice`'s resolution check — which
//! requires every reference outside the edits to resolve to the *same*
//! declaration, at the same place — passes. A conversion that replaced the
//! element wholesale would move the declaration the body's references point
//! at, and the verifier would rightly refuse the whole refactoring.
//!
//! The merge itself is `merge.rs` (IEEE 1800 §23.2.2.2). This file locates the
//! module, refuses everything lucisv will not convert, decides where each
//! absorbed declaration's comments go, and writes the edits.
use std::path::Path;
use vlog_parser::ast::{
GenBlock, GenElse, Item, ItemKind, ListElem, Module, NonAnsiPort, PortList,
};
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic};
use crate::rename::{display, Scope};
use crate::TextEdit;
use super::add::{body_directives, nesting_of, Directive, Nesting};
use super::find::{find_module, locate_module, module_at, not_in_scope, ModuleSite};
use super::list::{after_same_line_comments, comma_after, insert, line_indent, whole_line};
use super::merge::{absorb, Absorbed};
use super::{shape, ModuleRef, Plan};
/// One planned conversion: what to edit, and what the title will promise.
pub(super) struct Conversion {
pub(super) site: ModuleSite,
pub(super) plan: Plan,
/// How many ports the header declares — what the code action counts.
pub(super) count: usize,
}
pub(super) fn plan_convert(
scope: &mut Scope,
file: &Path,
offset: u32,
) -> Result<Conversion, String> {
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);
let mut found = None;
module_at(&tree.items, offset, &mut found);
let Some(name) = found else {
return Err("there is no module declaration at this position.".to_string());
};
let Some((module, _)) = find_module(&tree, &name) else {
return Err(format!("lucisv can no longer find the declaration of `{name}`."));
};
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));
}
let mut plan = Plan::default();
plan.add(i, convert_edits(text, file, module, &ports)?);
plan.expected.push((i, shape(text, &name)));
Ok(Conversion { site, plan, count: ports.len() })
}
/// Everything the conversion refuses **before** it asks where the module is
/// declared: the header it needs, the parse, a name written twice, a directive
/// in the port list, a declaration hidden in a generate region.
///
/// 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>(
shown: &str,
diagnostics: &[ParseDiagnostic],
module: &'t Module,
) -> Result<Vec<&'t NonAnsiPort>, String> {
let name = &module.name;
let ports = header(module)?;
unparsed(shown, diagnostics)?;
let names = header_names(module, &ports)?;
if !module.port_directives.is_empty() {
return Err(format!(
"`{name}`'s port list carries compiler directives, so which ports it declares depends on the configuration; lucisv does not preprocess, so it made no edits."
));
}
if let Some(hidden) = in_generate(&module.items, &names) {
return Err(format!(
"`{name}` declares `{hidden}` inside a generate region, where lucisv will not read a port's declaration; it made no edits."
));
}
Ok(ports)
}
/// The sentence a module whose indexed declaration is elsewhere earns.
pub(super) fn elsewhere(name: &str) -> String {
format!(
"`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits."
)
}
/// The conversion's edits, once the module's declaration is known to be the
/// cursor's own file: the insertions around each header name, then the
/// deletions of the body declarations they absorbed.
pub(super) fn convert_edits(
text: &str,
file: &Path,
module: &Module,
ports: &[&NonAnsiPort],
) -> Result<Vec<TextEdit>, String> {
let name = &module.name;
let names: Vec<String> = ports.iter().map(|port| port.name.clone()).collect();
let absorbed = absorb(text, name, &module.items, &names)?;
attributes_clear(name, &absorbed)?;
directives_clear(text, file, module, &absorbed)?;
let comments = comments_of(text, file)?;
let mut edits = Vec::new();
// One declaration may declare several ports (`input a, b;`), and its
// comments belong to the first of them: written onto both they would be
// duplicated, which is as much a corruption as dropping them.
let mut claimed: Vec<TextRange> = Vec::new();
for (port, absorbed) in ports.iter().zip(&absorbed) {
edits.append(&mut port_edits(text, name, port, absorbed, &comments, &mut claimed)?);
}
edits.append(&mut deletions(text, name, &absorbed, &comments)?);
Ok(edits)
}
/// The non-ANSI port list this conversion needs, or the sentence saying why
/// there is not one.
fn header(module: &Module) -> Result<Vec<&NonAnsiPort>, String> {
let name = &module.name;
if module.kw == "interface" || module.kw == "program" {
return Err(format!(
"`{name}` is an `{}`, not a module, and lucisv does not convert an {}'s non-ANSI header in this round; it made no edits.",
module.kw, module.kw
));
}
let ports = match &module.ports {
PortList::NonAnsi(ports) => ports,
PortList::Ansi(_) => {
return Err(format!(
"`{name}`'s header already declares its ports ANSI-style, so there is nothing to convert."
))
}
PortList::Empty | PortList::None => {
return Err(format!("`{name}` declares no ports, so there is nothing to convert."))
}
};
if ports.iter().any(ListElem::is_error) {
return Err(format!(
"`{name}`'s header writes a port expression (IEEE 1800 §23.2.2.1's `.a({{x,y}})` or `{{x,y}}`), which has no ANSI spelling; lucisv made no edits."
));
}
Ok(ports.iter().filter_map(ListElem::ok).collect())
}
/// The header's names in header order, with a repeated one refused: a list
/// that names a port twice is not one lucisv will guess at.
fn header_names(module: &Module, ports: &[&NonAnsiPort]) -> Result<Vec<String>, String> {
let mut names: Vec<String> = Vec::new();
for port in ports {
if names.contains(&port.name) {
return Err(format!(
"`{}`'s header names `{}` twice; lucisv will not guess which port that is.",
module.name, port.name
));
}
names.push(port.name.clone());
}
Ok(names)
}
/// 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(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.",
shown, problem.message, problem.line
)),
}
}
/// A header port declared inside a generate construct is a declaration in
/// another scope, which lucisv will not absorb into the header.
fn in_generate(items: &[Item], names: &[String]) -> Option<String> {
fn walk(items: &[Item], names: &[String], inside: bool, found: &mut Option<String>) {
for item in items {
match &item.kind {
ItemKind::PortDecl(decl) if inside => {
named(decl.declarators.iter().map(|d| &d.name), names, found);
}
ItemKind::DataDecl(decl) if inside => {
named(decl.declarators.iter().map(|d| &d.name), names, found);
}
ItemKind::GenerateRegion { items, .. } => walk(items, names, true, found),
ItemKind::GenBlock(block) => walk(&block.items, names, true, found),
ItemKind::GenFor(gen) => block(&gen.body, names, found),
ItemKind::GenCase(gen) => {
for arm in &gen.items {
block(&arm.body, names, found);
}
}
ItemKind::GenIf(gen) => {
block(&gen.then, names, found);
let mut els = gen.els.as_deref();
while let Some(next) = els {
match next {
GenElse::If(_, gen) => {
block(&gen.then, names, found);
els = gen.els.as_deref();
}
GenElse::Block(b) => {
block(b, names, found);
els = None;
}
}
}
}
_ => {}
}
}
}
fn block(b: &GenBlock, names: &[String], found: &mut Option<String>) {
walk(&b.items, names, true, found);
}
fn named<'a>(
declared: impl Iterator<Item = &'a String>,
names: &[String],
found: &mut Option<String>,
) {
for name in declared {
if found.is_none() && names.contains(name) {
*found = Some(name.clone());
}
}
}
let mut found = None;
walk(items, names, false, &mut found);
found
}
/// Refuse a declaration that carries an attribute instance.
///
/// `Item.span` covers the `(* ... *)` written before it, so the deletion takes
/// the attribute with the declaration and only the *comments* are carried onto
/// the port — a silent loss of something that changes what a synthesizer does.
/// Where an attribute belongs in an ANSI port list is a design question rather
/// than a merge rule, so the conversion refuses instead of guessing, the same
/// way it refuses an initialiser or a qualifier. `check::never_dropped` counts
/// attributes too, so a planner that ever misses one is refused a second time.
fn attributes_clear(module: &str, absorbed: &[Absorbed<'_>]) -> Result<(), String> {
for port in absorbed {
for item in &port.items {
let Some(attr) = item.meta.attrs.first() else { continue };
return Err(format!(
"`{}` on `{module}`'s declaration of `{}` would be dropped, and lucisv does not decide where an attribute belongs in an ANSI port list; move the attribute onto the port by hand, and it made no edits.",
attr.text.trim(),
port.name
));
}
}
Ok(())
}
/// lucisv does not preprocess, so a declaration it deletes must not be one an
/// `` `ifdef`` arm holds, and no directive may stand between the declarations
/// it deletes: either way the body it leaves behind is one no configuration
/// ever had.
fn directives_clear(
text: &str,
file: &Path,
module: &Module,
absorbed: &[Absorbed<'_>],
) -> Result<(), String> {
let directives = body_directives(module);
if directives.is_empty() {
return Ok(());
}
let spans: Vec<TextRange> =
absorbed.iter().flat_map(|a| a.items.iter().map(|i| i.span)).collect();
let (Some(first), Some(last)) =
(spans.iter().map(|span| span.start).min(), spans.iter().map(|span| span.end).max())
else {
return Ok(());
};
let region = format!("`{}`'s body", module.name);
for span in &spans {
depth_zero(&directives, span.start, &region)?;
}
match directives.iter().find(|d| d.span.start >= first && d.span.start < last) {
None => Ok(()),
Some(directive) => Err(format!(
"a compiler directive (`{}` at {}:{}) is written among the declarations converting `{}` would delete, so lucisv does not know what the body it leaves behind would say; it made no edits.",
directive.text.trim().lines().next().unwrap_or_default().trim_end(),
display(file),
LineIndex::new(text).line_col(directive.span.start).0,
module.name
)),
}
}
/// Refuse a declaration that stands inside a conditional arm.
fn depth_zero(directives: &[Directive], at: u32, region: &str) -> Result<(), String> {
let mut depth = 0i32;
for directive in directives.iter().filter(|d| d.span.start < at) {
match nesting_of(&directive.text) {
Nesting::Open => depth += 1,
Nesting::Close => depth -= 1,
Nesting::Neither => {}
}
}
match depth {
0 => Ok(()),
_ => Err(format!(
"{region} is conditionally compiled, and one of the declarations the conversion would delete stands inside an `ifdef arm; a port declared in one arm does not exist in the other, so lucisv made no edits."
)),
}
}
/// Every comment in the file, with the bytes it occupies — the same pieces
/// `check::pieces` reads, so a comment this file moves is a comment the
/// verifier can account for.
fn comments_of(text: &str, file: &Path) -> Result<Vec<(TextRange, String)>, String> {
let Ok(tokens) = tokenize(text) else {
return Err(format!("{} does not lex, so lucisv will not edit it.", display(file)));
};
let mut out: Vec<(TextRange, String)> = Vec::new();
let mut push = |comment: &Comment| out.push((comment.span, comment.text.clone()));
for token in &tokens {
token.leading.iter().for_each(&mut push);
if let Some(trailing) = &token.trailing {
push(trailing);
}
}
out.sort_by_key(|(span, _)| (span.start, span.end));
out.dedup_by_key(|(span, _)| *span);
Ok(out)
}
/// The comments one absorbed declaration carries, and the bytes a deletion
/// must therefore cover.
#[derive(Default)]
struct Carried {
before: Vec<String>,
after: Vec<String>,
}
/// What one body item takes with it: its own bytes plus the comments written
/// before and after it, which move onto the ANSI port.
fn carried(
text: &str,
module: &str,
item: &Item,
comments: &[(TextRange, String)],
) -> Result<(TextRange, Carried), String> {
let start = item.meta.leading.first().map_or(item.span.start, |c| c.span.start);
let end = item.meta.trailing.as_ref().map_or(item.span.end, |c| c.span.end);
let mut carried = Carried::default();
for (span, comment) in
comments.iter().filter(|(span, _)| span.start >= start && span.end <= end)
{
if span.start >= item.span.start && span.end <= item.span.end {
return Err(format!(
"`{module}` writes the comment `{comment}` inside a declaration the conversion would delete, and lucisv will not decide where a comment written inside a declaration goes in an ANSI port; it made no edits."
));
}
match span.end <= item.span.start {
true => carried.before.push(comment.clone()),
false => carried.after.push(comment.clone()),
}
}
Ok((whole_line(text, TextRange::new(start, end)), carried))
}
/// The insertions that turn one header name into an ANSI port declaration.
///
/// The comments the absorbed declarations carried go in one of two places.
/// The first choice, for a comment written *after* a declaration, is the end
/// of the port's own line — where the source had it, relative to what it
/// describes. That is only free when nothing else is written there and the
/// header wrote no comment of its own beside the port, and there is exactly
/// one of them. Everything else goes on its own line above the port, which
/// always works for a list written one port per line; a list written on one
/// line takes a block comment inline and refuses a `//`.
fn port_edits(
text: &str,
module: &str,
port: &NonAnsiPort,
absorbed: &Absorbed<'_>,
comments: &[(TextRange, String)],
claimed: &mut Vec<TextRange>,
) -> Result<Vec<TextEdit>, String> {
let mut moved = Carried::default();
for item in &absorbed.items {
let (_, carried) = carried(text, module, item, comments)?;
// A declaration this port shares with an earlier one has already
// handed its comments over; taking them again would write them twice.
if claimed.contains(&item.span) {
continue;
}
claimed.push(item.span);
moved.before.extend(carried.before);
moved.after.extend(carried.after);
}
let at = tail(text, port);
// Exactly one comment may go beside the port, because two comments landing
// on one line become *one* comment — a `//` runs to the end of the line and
// the lexer merges what follows it into the same trailing comment — and a
// refactoring that joins two comments the source kept apart is one the
// verifier rightly refuses. The rest go above.
let beside = moved.after.len() == 1
&& after_same_line_comments(text, at).at == at
&& line_free(text, at);
let mut above = moved.before;
if !beside {
above.extend(moved.after.iter().cloned());
}
let mut edits = vec![insert(port.span.start, prefix(text, module, port, absorbed, &above)?)];
if !absorbed.unpacked.is_empty() {
edits.push(insert(port.span.end, absorbed.unpacked.clone()));
}
if beside {
edits.push(insert(at, format!(" {}", moved.after.join(" "))));
}
Ok(edits)
}
/// What is written just before the port's name: the comments its declarations
/// carried, then the declaration itself.
fn prefix(
text: &str,
module: &str,
port: &NonAnsiPort,
absorbed: &Absorbed<'_>,
above: &[String],
) -> Result<String, String> {
let mut out = String::new();
match own_line(text, port.span.start) {
Some(indent) => {
for comment in above {
out.push_str(comment);
out.push('\n');
out.push_str(&indent);
}
}
None => {
for comment in above {
if !inline_safe(comment) {
return Err(format!(
"the comment `{comment}` on `{module}`'s declaration of `{}` would have to move into a port list written on one line, where it would swallow the rest of it; break `{module}`'s port list across lines first, and lucisv made no edits.",
absorbed.name
));
}
out.push_str(comment);
out.push(' ');
}
}
}
out.push_str(&absorbed.prefix);
Ok(out)
}
/// Where a port's trailing comment goes: past the `,` that follows the name,
/// or — for the last port — straight after it.
fn tail(text: &str, port: &NonAnsiPort) -> u32 {
comma_after(text, port.span.end).map_or(port.span.end, |comma| comma + 1)
}
/// The deletions that take the absorbed body declarations away, comments
/// included: each one moved onto its port above.
fn deletions(
text: &str,
module: &str,
absorbed: &[Absorbed<'_>],
comments: &[(TextRange, String)],
) -> Result<Vec<TextEdit>, String> {
let mut ranges: Vec<TextRange> = Vec::new();
for item in absorbed.iter().flat_map(|a| a.items.iter()) {
let (range, _) = carried(text, module, item, comments)?;
if !ranges.contains(&range) {
ranges.push(range);
}
}
Ok(ranges.into_iter().map(|range| TextEdit { range, new_text: String::new() }).collect())
}
/// The indentation of the line `at` starts, or `None` when something else is
/// written on that line before it.
fn own_line(text: &str, at: u32) -> Option<String> {
let indent = line_indent(text, at);
let start = (at as usize).checked_sub(indent.len())?;
(start == 0 || text.as_bytes().get(start - 1) == Some(&b'\n')).then_some(indent)
}
/// Whether the rest of the line from `at` is blank — which is what makes room
/// for a `//` comment.
fn line_free(text: &str, at: u32) -> bool {
text.get(at as usize..)
.is_none_or(|rest| rest.split('\n').next().is_none_or(|line| line.trim().is_empty()))
}
/// Whether a comment can be written in the middle of a line: a block comment
/// that stays on it.
fn inline_safe(comment: &str) -> bool {
comment.starts_with("/*") && !comment.contains('\n')
}