- 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]>
463 lines
18 KiB
Rust
463 lines
18 KiB
Rust
//! Which names cross the selection's boundary, and what the new module's
|
|
//! header is therefore made of.
|
|
//!
|
|
//! `flow` says what is *done* to each name on each side; this says what each
|
|
//! crossing name **becomes** — a port, a parameter, a copied `import`, or a
|
|
//! refusal. Three closures run here, and they are one closure really: the
|
|
//! signals the selection reads and drives, the parameters they and their own
|
|
//! types depend on, and the imports the whole of that needs to resolve.
|
|
//!
|
|
//! The last of the three is the subtle one. What the new module has to be able
|
|
//! to resolve is not "the names the selection writes down" but that *plus the
|
|
//! type names of its own header* — a port declared `input logic [N-1:0] a`
|
|
//! names `N` even though no statement in the selection does, and a port typed
|
|
//! `word_t` needs whatever import supplied it. Both were found by the corpus
|
|
//! and opentitan trials rather than by reasoning; see the feature README's
|
|
//! work log.
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use vlog_parser::ast::{ItemKind, SourceFile};
|
|
use vlog_parser::span::TextRange;
|
|
use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind};
|
|
|
|
use super::flow;
|
|
use super::region::Region;
|
|
use super::render::{self, Param, Port};
|
|
use super::{count, escaped, header_names, inside, inside_module, lost_name};
|
|
use super::{outside_module, outside_module_member};
|
|
use super::{slice, unmovable};
|
|
|
|
// ----------------------------------------------------------------------
|
|
// the boundary
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Everything that crosses the selection's boundary, classified.
|
|
pub(super) struct Crossing {
|
|
pub(super) ports: Vec<Port>,
|
|
pub(super) params: Vec<Param>,
|
|
pub(super) imports: Vec<String>,
|
|
}
|
|
|
|
impl Crossing {
|
|
pub(super) fn read(
|
|
text: &str,
|
|
semantics: &Semantics,
|
|
region: &Region<'_>,
|
|
flow: &flow::Flow,
|
|
packages: &[(String, TextRange)],
|
|
new_file: bool,
|
|
) -> Result<Crossing, String> {
|
|
let mut ports: Vec<(TextRange, Port)> = Vec::new();
|
|
let mut params: Vec<(TextRange, Param)> = Vec::new();
|
|
let module = region.module_name().to_string();
|
|
let mut wanted: Vec<String> = Vec::new();
|
|
// Names a `package` of this file declares. `N` reaches one the way
|
|
// `M` does — through a qualified spelling, or through an import of
|
|
// that package which the new module is given a copy of.
|
|
let mut from_package: Vec<(String, String)> = Vec::new();
|
|
|
|
for (n, symbol) in semantics.symbols().iter().enumerate() {
|
|
let sides = flow.sides(SymbolId(n as u32));
|
|
let declared_inside = inside(region, symbol.name_span);
|
|
if declared_inside {
|
|
if sides.used_outside() {
|
|
return Err(escaped(&symbol.name));
|
|
}
|
|
continue;
|
|
}
|
|
if !sides.used_inside() {
|
|
continue;
|
|
}
|
|
// A module, an interface and a package are visible from every
|
|
// file of the design, so one declared beside `M` is one `N` can
|
|
// reach too — they never become ports and never refuse.
|
|
if matches!(
|
|
symbol.kind,
|
|
SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package
|
|
) {
|
|
continue;
|
|
}
|
|
if !inside_module(region, symbol.name_span) {
|
|
// Not a port: a name the module itself does not declare is
|
|
// one the new module reaches the way `M` did, or one `visible`
|
|
// below refuses because a file of its own would not see it.
|
|
if let Some(package) = package_of(packages, symbol.name_span) {
|
|
from_package.push((package.to_string(), symbol.name.clone()));
|
|
}
|
|
continue;
|
|
}
|
|
match symbol.kind {
|
|
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var => {
|
|
let dir = direction(&symbol.name, sides)?;
|
|
let Some(site) = render::site_of(region.module, &symbol.name) else {
|
|
return Err(lost_name(&symbol.name));
|
|
};
|
|
let port = render::port(text, &module, &symbol.name, &site, dir)?;
|
|
ports.push((symbol.name_span, port));
|
|
}
|
|
SymbolKind::Param | SymbolKind::LocalParam => wanted.push(symbol.name.clone()),
|
|
kind => return Err(unmovable(&symbol.name, &module, kind)),
|
|
}
|
|
}
|
|
|
|
// A **port's own type** may name a parameter — `input logic [N-1:0] a`
|
|
// — and that parameter crosses the boundary as squarely as one the
|
|
// selection reads, or the new module's header names nothing. So does
|
|
// a parameter's type, and a parameter's default; the three are one
|
|
// closure, run below until nothing new is wanted.
|
|
let declared = declarations(semantics, region);
|
|
for (_, port) in &ports {
|
|
for word in &port.names {
|
|
depends(&declared, &module, &port.name, word, &mut wanted)?;
|
|
}
|
|
}
|
|
let mut seen: Vec<String> = Vec::new();
|
|
while let Some(name) = wanted.pop() {
|
|
if seen.contains(&name) {
|
|
continue;
|
|
}
|
|
let Some(site) = render::site_of(region.module, &name) else {
|
|
return Err(lost_name(&name));
|
|
};
|
|
let param = render::param(text, &module, &name, &site)?;
|
|
for word in ¶m.names {
|
|
depends(&declared, &module, &name, word, &mut wanted)?;
|
|
}
|
|
let span = span_of(semantics, region, &name);
|
|
params.push((span, param));
|
|
seen.push(name);
|
|
}
|
|
|
|
ports.sort_by_key(|(span, _)| (span.start, span.end));
|
|
params.sort_by_key(|(span, _)| (span.start, span.end));
|
|
let needed = needed(text, semantics, flow, &ports, ¶ms);
|
|
visible(text, semantics, region, packages, &needed, &module, new_file)?;
|
|
let imports = imports(semantics, region, packages, &needed);
|
|
reachable(text, &needed, &from_package, &imports)?;
|
|
Ok(Crossing {
|
|
ports: ports.into_iter().map(|(_, port)| port).collect(),
|
|
params: params.into_iter().map(|(_, param)| param).collect(),
|
|
imports,
|
|
})
|
|
}
|
|
|
|
pub(super) fn warnings(
|
|
&self,
|
|
new_name: &str,
|
|
created: Option<&str>,
|
|
file: &str,
|
|
) -> Vec<String> {
|
|
let mut out = Vec::new();
|
|
out.push(match created {
|
|
Some(path) => format!("`{new_name}` was written to a new file, `{path}`."),
|
|
None => format!(
|
|
"`{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!(
|
|
"lucisv gave `{new_name}` {} and {} from the names the selection reads and drives; check the directions before you rely on them.",
|
|
count(self.ports.len(), "port"),
|
|
count(self.params.len(), "parameter"),
|
|
));
|
|
if !self.imports.is_empty() {
|
|
out.push(format!(
|
|
"`{new_name}` imports {}, which the selection needed.",
|
|
self.imports.iter().map(|path| format!("`{path}`")).collect::<Vec<_>>().join(", ")
|
|
));
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
/// The direction one crossing signal's port gets, or the sentence saying why
|
|
/// lucisv will not decide.
|
|
fn direction(name: &str, sides: flow::Sides) -> Result<&'static str, String> {
|
|
if sides.inside_unknown {
|
|
return Err(format!(
|
|
"the selection passes `{name}` to a task or function, and only that routine's declaration says whether it is an argument in or out; lucisv will not guess a port direction from it."
|
|
));
|
|
}
|
|
if !sides.inside_write {
|
|
return Ok("input");
|
|
}
|
|
if sides.outside_write {
|
|
return Err(format!("`{name}` is driven on both sides of the selection."));
|
|
}
|
|
if sides.outside_unknown {
|
|
return Err(format!(
|
|
"the selection drives `{name}`, and something outside it passes the same name to a task or function, which may drive it too; lucisv will not make it an output over that."
|
|
));
|
|
}
|
|
Ok("output")
|
|
}
|
|
|
|
/// One identifier written in a header lucisv is about to move: a parameter it
|
|
/// has to carry across too, a keyword or a package name it can ignore, or a
|
|
/// declaration of `M`'s that a header in another module could not name.
|
|
fn depends(
|
|
declared: &HashMap<&str, SymbolKind>,
|
|
module: &str,
|
|
owner: &str,
|
|
word: &str,
|
|
wanted: &mut Vec<String>,
|
|
) -> Result<(), String> {
|
|
match declared.get(word) {
|
|
// A keyword (`logic`, `int`), a system function, or a name that comes
|
|
// from somewhere `visible` and `reachable` judge on their own terms.
|
|
None => Ok(()),
|
|
Some(SymbolKind::Param | SymbolKind::LocalParam) => {
|
|
wanted.push(word.to_string());
|
|
Ok(())
|
|
}
|
|
Some(_) => Err(header_names(module, owner, word)),
|
|
}
|
|
}
|
|
|
|
/// Every name the module's own scope declares, with its kind — what a
|
|
/// parameter default is checked against.
|
|
fn declarations<'s>(semantics: &'s Semantics, region: &Region<'_>) -> HashMap<&'s str, SymbolKind> {
|
|
semantics
|
|
.symbols()
|
|
.iter()
|
|
.filter(|symbol| inside_module(region, symbol.name_span))
|
|
.map(|symbol| (symbol.name.as_str(), symbol.kind))
|
|
.collect()
|
|
}
|
|
|
|
/// Where the module declares `name`, for ordering a header the way the source
|
|
/// orders its declarations.
|
|
fn span_of(semantics: &Semantics, region: &Region<'_>, name: &str) -> TextRange {
|
|
semantics
|
|
.symbols()
|
|
.iter()
|
|
.find(|symbol| symbol.name == name && inside_module(region, symbol.name_span))
|
|
.map_or(TextRange::empty(0), |symbol| symbol.name_span)
|
|
}
|
|
|
|
/// Every name the new module has to be able to resolve for itself: the names
|
|
/// the selection writes down, plus the type names its own header will carry.
|
|
///
|
|
/// A header type is matched by the *text* the declaration wrote — the port's
|
|
/// prefix is that text — so a `word_t` in a port list is the same reference the
|
|
/// import judgement asks about, and not a second reading of it.
|
|
fn needed<'s>(
|
|
text: &str,
|
|
semantics: &'s Semantics,
|
|
flow: &flow::Flow,
|
|
ports: &[(TextRange, Port)],
|
|
params: &[(TextRange, Param)],
|
|
) -> Vec<&'s vlog_semantic::Reference> {
|
|
let mut out: Vec<&vlog_semantic::Reference> =
|
|
flow.inside.iter().filter_map(|n| semantics.references().get(*n)).collect();
|
|
let header: Vec<&str> = ports
|
|
.iter()
|
|
.map(|(_, port)| port.prefix.as_str())
|
|
.chain(params.iter().map(|(_, param)| param.prefix.as_str()))
|
|
.collect();
|
|
for reference in semantics.references() {
|
|
let written = slice(text, reference.name_span);
|
|
if written.is_empty() {
|
|
continue;
|
|
}
|
|
if header.iter().any(|prefix| prefix.split_whitespace().any(|word| word == written)) {
|
|
out.push(reference);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The `import` paths the new module gets: the ones written in `M` that one of
|
|
/// the names it needs could have come through.
|
|
fn imports(
|
|
semantics: &Semantics,
|
|
region: &Region<'_>,
|
|
packages: &[(String, TextRange)],
|
|
needed: &[&vlog_semantic::Reference],
|
|
) -> Vec<String> {
|
|
let Some(scope) = semantics
|
|
.symbol_at(region.module.name_span.start)
|
|
.and_then(|id| semantics.symbol(id))
|
|
.and_then(|symbol| symbol.child_scope)
|
|
.and_then(|id| semantics.scope(id))
|
|
else {
|
|
return Vec::new();
|
|
};
|
|
let mut out = Vec::new();
|
|
for import in &scope.imports {
|
|
let path = import.path();
|
|
if out.contains(&path) {
|
|
continue;
|
|
}
|
|
if needed.iter().any(|r| supplied_by(semantics, packages, import, r)) {
|
|
out.push(path);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Whether a use of a name could have come through an import of `package`.
|
|
///
|
|
/// Two shapes, because the binder answers them differently. A package
|
|
/// **another file** declares leaves an [`Resolution::ExternalCandidate`] whose
|
|
/// `paths` name it; a package **this file** declares is resolved on the spot,
|
|
/// and what says so is that the declaration sits inside that package's own
|
|
/// item span.
|
|
fn supplied_by(
|
|
semantics: &Semantics,
|
|
packages: &[(String, TextRange)],
|
|
import: &vlog_semantic::Import,
|
|
reference: &vlog_semantic::Reference,
|
|
) -> bool {
|
|
if !import.supplies(&reference.name) {
|
|
return false;
|
|
}
|
|
let package = import.package.as_str();
|
|
match &reference.resolution {
|
|
// The binder writes the import paths it walked into `paths`, in the
|
|
// spelling the source wrote them (`p::*`, `p::w_t`) — so the question
|
|
// is whether this very import is one of them, not whether some path
|
|
// happens to end in the name.
|
|
Resolution::ExternalCandidate { paths, .. }
|
|
| Resolution::InheritedCandidate { paths, .. } => {
|
|
paths.iter().any(|path| *path == import.path())
|
|
}
|
|
Resolution::Resolved(symbol) => semantics
|
|
.symbol(*symbol)
|
|
.and_then(|symbol| package_of(packages, symbol.name_span))
|
|
.is_some_and(|declared_in| declared_in == package),
|
|
Resolution::NotFound => false,
|
|
}
|
|
}
|
|
|
|
/// Every name the new module needs has to be one a file of its own can see: a
|
|
/// declaration of `M`'s own (which becomes a port or a parameter), a unit of
|
|
/// the design (a module, an interface, a package), or a member of a package.
|
|
///
|
|
/// What this refuses is the rest — a `typedef`, a `localparam` or a class
|
|
/// written at the **file scope** of `M`'s file, which is a compilation-unit
|
|
/// declaration and reaches exactly the files that were compiled with it. It
|
|
/// runs over the names the new module writes down *and* the type names of its
|
|
/// own header, so a port typed with a file-scope `typedef` is refused as
|
|
/// squarely as a body reference to one.
|
|
fn visible(
|
|
text: &str,
|
|
semantics: &Semantics,
|
|
region: &Region<'_>,
|
|
packages: &[(String, TextRange)],
|
|
needed: &[&vlog_semantic::Reference],
|
|
module: &str,
|
|
new_file: bool,
|
|
) -> Result<(), String> {
|
|
if !new_file {
|
|
return Ok(());
|
|
}
|
|
for reference in needed {
|
|
let Resolution::Resolved(id) = reference.resolution else { continue };
|
|
let Some(symbol) = semantics.symbol(id) else { continue };
|
|
if inside_module(region, symbol.name_span) {
|
|
continue;
|
|
}
|
|
if package_of(packages, symbol.name_span).is_some() {
|
|
continue;
|
|
}
|
|
if matches!(symbol.kind, SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package) {
|
|
continue;
|
|
}
|
|
// A field of a struct and a signal of an interface each have a
|
|
// declaration of their own, and naming it is not what the user needs
|
|
// to read: what crosses the boundary is `s` or `bus`, and `f` is a
|
|
// name of *its* type. So the head goes first when there is one.
|
|
return Err(match access_head(text, reference.name_span) {
|
|
Some(head) => outside_module_member(head, &symbol.name, module),
|
|
None => outside_module(&symbol.name, module),
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The head of a member access, if the reference is one: `s` in `s.f`, `bus`
|
|
/// in `bus.data`, and `u` in `u.v.w`.
|
|
///
|
|
/// Read from the text rather than from the tree because that is where the
|
|
/// question is cheap and exact: a reference's own span is the field, and what
|
|
/// precedes it — a `.` and an identifier — is the thing the field belongs to.
|
|
fn access_head(text: &str, span: TextRange) -> Option<&str> {
|
|
let (mut at, mut head) = dotted_word_before(text, span.start as usize)?;
|
|
while let Some((start, word)) = dotted_word_before(text, at) {
|
|
at = start;
|
|
head = word;
|
|
}
|
|
Some(head)
|
|
}
|
|
|
|
/// The identifier written immediately before `at` and a `.`, with where it
|
|
/// starts: `("s", …)` for `s.` and nothing at all for anything else.
|
|
fn dotted_word_before(text: &str, at: usize) -> Option<(usize, &str)> {
|
|
let rest = text.get(..at)?.trim_end().strip_suffix('.')?.trim_end();
|
|
let start = rest
|
|
.char_indices()
|
|
.rev()
|
|
.take_while(|(_, c)| c.is_alphanumeric() || *c == '_' || *c == '$')
|
|
.last()
|
|
.map(|(i, _)| i)?;
|
|
let word = rest.get(start..)?;
|
|
match word.starts_with(|c: char| c.is_ascii_digit()) {
|
|
true => None,
|
|
false => Some((start, word)),
|
|
}
|
|
}
|
|
|
|
/// A name a `package` of this file declares reaches the new module only if the
|
|
/// new module can spell it: either every use writes the package out
|
|
/// (`w_pkg::word_t`), or `M` imports it and lucisv copied that import across.
|
|
fn reachable(
|
|
text: &str,
|
|
needed: &[&vlog_semantic::Reference],
|
|
from_package: &[(String, String)],
|
|
imports: &[String],
|
|
) -> Result<(), String> {
|
|
for (package, name) in from_package {
|
|
let unqualified = needed
|
|
.iter()
|
|
.filter(|reference| reference.name == *name)
|
|
.any(|reference| !qualified(text, reference.name_span));
|
|
if !unqualified {
|
|
continue;
|
|
}
|
|
let imported = imports
|
|
.iter()
|
|
.any(|path| path == &format!("{package}::*") || path == &format!("{package}::{name}"));
|
|
if !imported {
|
|
return Err(format!(
|
|
"the selection uses `{name}`, which `{package}` declares, without writing `{package}::` in front of it and without an `import` lucisv could carry across; write the package out, or import it where the new module can see it."
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Whether a name is written with its package in front of it: `w_pkg::word_t`.
|
|
fn qualified(text: &str, span: TextRange) -> bool {
|
|
text.get(..span.start as usize).is_some_and(|head| head.trim_end().ends_with("::"))
|
|
}
|
|
|
|
/// The `package` of this file whose body holds `span`, if any.
|
|
fn package_of(packages: &[(String, TextRange)], span: TextRange) -> Option<&str> {
|
|
packages
|
|
.iter()
|
|
.find(|(_, at)| at.start <= span.start && span.end <= at.end)
|
|
.map(|(name, _)| name.as_str())
|
|
}
|
|
|
|
/// Every `package` this file declares, with the bytes it occupies.
|
|
pub(super) fn packages(tree: &SourceFile) -> Vec<(String, TextRange)> {
|
|
tree.items
|
|
.iter()
|
|
.filter_map(|item| match &item.kind {
|
|
ItemKind::Package { name, .. } => Some((name.clone(), item.span)),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|