diff --git a/README.md b/README.md index 2ecb371..e6f05fc 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,7 @@ makes an editor's red squiggle worth believing. | `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) | | `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) | | `unused-waiver` | style | — | waivers that suppress nothing | +| `unused-import` † | style | safe | no `import` nothing in the scope reaches through (off by default; stays off without a project) | | `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class | | `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class | | `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name | diff --git a/TODO.md b/TODO.md index 421fa4c..656423b 100644 --- a/TODO.md +++ b/TODO.md @@ -711,7 +711,7 @@ section only tracks the milestones. (the define-table README's promised follow-up); version 0.5.0 with a CHANGELOG entry covering M7–M14. - [ ] Backlog (extract module, inline, ~~`.*` expansion~~, ~~ANSI - conversion~~, organize imports, …) — triaged in the umbrella README after M5. + conversion~~, ~~organize imports~~, …) — triaged in the umbrella README after M5. **`.*` expansion shipped 2026-09-05 (§50, `docs/features/expand-wildcard/README.md`)**: the wildcard written out as the named connections it stands for, per IEEE 1800 §23.3.2.4, with a code @@ -730,6 +730,19 @@ section only tracks the milestones. than moves — where a `(* ... *)` belongs in an ANSI port list, and whether the same one may be split across the ports a multi-name declaration declares, is a design question the merge rule does not answer. + **Organize imports shipped 2026-09-05 (§52, + `docs/features/organize-imports/README.md`)**: the imports nothing uses + removed, exact duplicates merged and the run at a scope's top sorted, with a + `source.organizeImports` code action, `lucisv.organizeImports`, and the same + judgement as the `unused-import` lint rule. It leaves three things behind, + added to this backlog: **a module header's `import`** (`module m import + p::*;`), which is judged but never moved because it has no line of its own; + **an unused import carrying a comment**, kept with a warning rather than + deleted, because the comment would have to go with it; and — the one that + decides how useful the feature is on real verification code — **a scope + holding a macro call or a `` `include ``**, which lucisv refuses to judge at + all: 32 of the corpus's 40 multi-import scopes and 33 of 33 OpenTitan UVM env + packages. ## 9. LSP 3.18 protocol audit (2026-08-26) @@ -5143,11 +5156,119 @@ so the editor squiggles what the action would delete. organized into scratch copies, counts, and every "unused" claim checked by grep for the package's members in the file. -- [ ] 52.1 engine: used/unused, sort, dedup, refusals -- [ ] 52.2 `unused-import` rule + safe fix + toggle -- [ ] 52.3 code action (`source.organizeImports`, lazy) + command -- [ ] docs; §8 line annotated; README/site rows (lead) -- [ ] Gates (guarded); byte-identity vs 0.46.0; corpus census -- [ ] QA: every "unused" claim attacked (shadowing, nested scopes, +- [x] 52.1 engine: used/unused, sort, dedup, refusals +- [x] 52.2 `unused-import` rule + safe fix + toggle +- [x] 52.3 code action (`source.organizeImports`, lazy) + command +- [x] docs; §8 line annotated; README/site rows (lead) +- [x] Gates (guarded); byte-identity vs 0.46.0; corpus census +- [x] QA: every "unused" claim attacked (shadowing, nested scopes, re-exports, macros, directives, unknown packages); the verifier attack pair; opentitan UVM packages + +## 53. Extract module and inline module (planned 2026-09-05) — the dearest §8 refactorings + +One lane after §52 merges (two sub-lanes in sequence if the first alone +takes a round), §36's protocol. Feature README: +`docs/features/extract-inline-module/README.md`. Ships in 0.47.0 with §52. +Both are lexical refactorings over a verified whole edit, like §50/§51: +one plan through `vlog_refactor`'s splice and `check.rs` (`pieces_match`, +`never_dropped`, the resolution check), with a refusal sentence for every +shape lucisv cannot judge. + +### 53.1 Extract module + +Input: a selection covering **whole module items** (one or more +contiguous `always`/`assign`/instantiation/declaration/generate items) +inside module `M`, and a name `N` for the new module. Output: a new +module `N` holding the items, with ports and parameters inferred, and the +selection replaced by an instantiation `N u_N (...)` rendered by +`instantiation_plan` over the new module's text (so the skeleton and the +instantiation can never disagree). + +- **Ports, from dataflow across the region boundary**, using the file's + `Semantics` (symbols and references with spans): a name declared + *outside* the region (in `M`, including its ports) and referenced + *inside* becomes a port — `input` when only read inside, `output` when + written inside (assign LHS, always LHS, an instantiation's output + connection is unknown without the instantiated module's declaration — + look it up through the index; refuse when unknown) and read or written + outside, both → refuse ("`x` is driven on both sides of the selection"). + A name declared *inside* and referenced outside → refuse ("move the + declaration of `x` out of the selection first"). The port's type is the + declaration's own text in `M` (net/var kind, signing, packed dims — + the §51 merge machinery renders it); an unpacked dim → refuse this + round. A parameter of `M` referenced inside becomes a parameter of `N` + with `M`'s default, passed through `#(.P(P))`. Imports of `M` used + inside are copied into `N` (§52's judgement says which are used). +- **The new module's home:** a new file `N.sv` beside `M`'s file when the + client advertises `workspace.workspaceEdit.documentChanges` with + `CreateFile` support (VS Code does); otherwise `N` is written below `M` + in the same file. Say which happened in the action's warning list. +- **Refusals** (each a sentence): the selection does not cover whole + items; it contains a port declaration, a `parameter`/`localparam` + declaration, a `genvar`, a `bind`, a macro call or conditional + directive, a task/function used on both sides, a hierarchical + reference crossing the boundary (`u_x.sig` in either direction — the + §49 surface says whether the head is inside), an interface-typed name + crossing, a name with an unpacked dimension crossing, an + `initial`/`final` block (testbench code; refuse this round, say so), a + `timescale`/`default_nettype` in force that `N.sv` would not inherit + (a new file: copy the directive or refuse — refuse), `N` already + declared in the workspace, `M` declared twice. +- **Server:** code action `lucisv: extract selection into module…` under + `refactor.extract` (lazy), whose resolve asks the client for the name + through a command with a `showInputBox`-style flow: since LSP has no + input prompt, the action carries a default name (`M_extracted`) and the + VS Code extension wraps the command `lucisv.extractModule [uri, range, + name]` with an input box (one function in `editors/vscode/extension.js`; + other clients pass the name themselves). Say so in the docs. +- Tests: a combinational region (inputs + one output); a sequential + region (clk/rst become inputs, the register an output); a region using + a parameter and an import; every refusal; the round trip `extract → + inline` (53.2) returns the original file modulo layout (formats to + the same text — pin as byte-equal after formatting both); corpus: five + hand-picked regions in scratch copies, each result (both files) parses, + formats, converges, and the whole design's reference counts match + before/after (the census over the two files together). + +### 53.2 Inline module + +Input: the cursor on an instantiation `S u_S (...)` of a module `S` +declared exactly once in the workspace. Output: the instantiation +replaced by `S`'s items with `S`'s port names replaced by the connected +names, `S`'s parameters by their override or default values as +`localparam`s, and every internal name prefixed `u_S_` unless no name in +`M` collides (then unprefixed — say which in the warning list); `S`'s +imports copied into `M` if `M` lacks them. + +- **Refusals:** a connection that is an expression rather than a plain + name or literal ("connect `.a(x+1)` to a named wire first"); a `.*` + ("expand `.*` first" — §50); positional connections ("convert to named + first"); an unconnected input; any hierarchical reference to `u_S` from + anywhere in the workspace (the §49 hierarchical surface: `u_S.x` in any + file → refuse, naming the file); `S` with a `generate` that declares + names reachable hierarchically (`u_S.gen.x` — same rule); `S` + declared twice or unknown; `S` with ports of interface type, with + `inout` ports, with unpacked-array ports, or with an `initial`/`final` + (refuse this round); a macro call or conditional directive in `S`; + `S`'s `timescale` differing from `M`'s file; a name collision that + prefixing cannot resolve (an escaped name). +- **Server:** code action `lucisv: inline `S` here` under `refactor.inline` + (lazy), command `lucisv.inlineModule [uri, position]`. +- Tests: a two-port module inlined into its instantiator (round trip + with 53.1); a parameterized module with an override; a name collision + (prefixed); every refusal; the verifier's resolution check on the + result; corpus: five instantiations of small `common_cells` modules + inlined in scratch copies, each result parses, formats, converges, and + a `lucisv check --select unused-signal,undriven-net` census over the + result is unchanged in count from the original two files. + +- [ ] 53.1 extract: dataflow ports, parameters, imports, the new file, + refusals, action + command + extension input box +- [ ] 53.2 inline: substitution, prefixing, refusals, action + command +- [ ] the extract → inline round trip pinned +- [ ] docs; §8 lines annotated; site rows (lead) +- [ ] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks +- [ ] QA: dataflow direction attacked (every statement kind that writes + a name), boundary-crossing shapes, collisions, the round trip, the + client-capability fallback, opentitan scratch trials diff --git a/crates/lucisv/src/lint.rs b/crates/lucisv/src/lint.rs index fd9b452..9323b2c 100644 --- a/crates/lucisv/src/lint.rs +++ b/crates/lucisv/src/lint.rs @@ -71,6 +71,11 @@ pub struct Census { /// declarations that disagree. Empty when no enabled rule asked for it — /// building it costs a parse of every file in the run. interfaces: HashMap>, + /// Package name → the names it exports, `None` for a package the run + /// cannot answer for: one declared twice, or one re-exporting from + /// another package (only a whole-project index settles that). Empty + /// unless `unused-import` is enabled. + packages: HashMap>>, } impl Census { @@ -85,30 +90,49 @@ impl Census { /// of every file on top of the lex the word census already pays for, so /// it is built only when some enabled rule asks — measured on opentitan /// `hw/` in `docs/features/linter-expansion-1/README.md`. - fn of(jobs: &[Job], interfaces: bool) -> Census { - type PerFile = (Vec, Vec<(String, Option)>); + fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census { + type PerFile = ( + Vec, + Vec<(String, Option)>, + Vec<(String, Option>)>, + ); let per_file: Vec = jobs .par_iter() .map(|job| { let Ok(src) = std::fs::read_to_string(&job.path) else { - return (Vec::new(), Vec::new()); + return (Vec::new(), Vec::new(), Vec::new()); + }; + let exports = match packages { + true => vlog_linter::package_exports(&job.path, &src), + false => Vec::new(), }; if !interfaces { - return (words::harvest_text(&src), Vec::new()); + return (words::harvest_text(&src), Vec::new(), exports); } // One lex for both halves: the parse is what the interface // table needs, and its tokens are the word census's. let parsed = ParsedSource::parse(&src); - (words::harvest(parsed.tokens()), vlog_linter::module_interfaces(parsed.file())) + ( + words::harvest(parsed.tokens()), + vlog_linter::module_interfaces(parsed.file()), + exports, + ) }) .collect(); let mut files: HashMap = HashMap::new(); let mut units: HashMap> = HashMap::new(); - for (words, declared) in per_file { + let mut exported: HashMap>> = HashMap::new(); + for (words, declared, exports) in per_file { for word in words { *files.entry(word).or_default() += 1; } + // A package name the run declares twice is a package the run + // cannot answer for, whatever the two say — the same rule the + // workspace index applies, where two `units` is `Ambiguous`. + for (name, names) in exports { + exported.entry(name).and_modify(|held| *held = None).or_insert(names); + } for (name, interface) in declared { // Two declarations of one name answer only when they agree; // anything else is a question the run cannot settle. @@ -122,7 +146,7 @@ impl Census { .or_insert(interface); } } - Census { files, interfaces: units } + Census { files, interfaces: units, packages: exported } } /// How many files in the run write `name` down. @@ -134,6 +158,15 @@ impl Census { fn interface(&self, name: &str) -> Option { self.interfaces.get(name)?.clone() } + + /// What the run says the package `name` exports. + fn package(&self, name: &str) -> vlog_linter::Exports { + match self.packages.get(name) { + Some(Some(names)) => vlog_linter::Exports::Known(names.clone()), + Some(None) => vlog_linter::Exports::Ambiguous, + None => vlog_linter::Exports::Unknown, + } + } } /// One file's view of the census: everything the project says, minus what @@ -158,6 +191,13 @@ impl MentionOracle for Elsewhere<'_> { fn module_interface(&self, name: &str) -> Option { self.census.interface(name) } + + /// The run's package table, whole-run for the same reason the interface + /// table is: a package is imported as often by the file that declares it + /// as by any other, and there is nothing here to subtract. + fn package_exports(&self, name: &str) -> vlog_linter::Exports { + self.census.package(name) + } } /// Resolve the run: the rules for each file, and whether a census is owed. @@ -183,9 +223,14 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res let options = rule_options(&file_config)?; jobs.push(Job { path, config, rules, options }); } - let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace())); - let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule))); - let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces)); + let asks = |wants: fn(&'static dyn Rule) -> bool| { + jobs.iter().any(|job| job.rules.iter().any(|rule| wants(*rule))) + }; + let wanted = asks(|rule| rule.needs_workspace()) || asks(reads_packages); + let interfaces = asks(reads_interfaces); + let packages = asks(reads_packages); + let census = (workspace && wanted) + .then(|| Census::of(&jobs, workspace && interfaces, workspace && packages)); let mut enabled: Vec<&'static str> = jobs.iter().flat_map(|job| job.rules.iter().map(|rule| rule.name())).collect(); enabled.sort_unstable(); @@ -276,6 +321,12 @@ fn reads_interfaces(rule: &'static dyn Rule) -> bool { matches!(rule.name(), "unknown-port" | "unknown-parameter") } +/// The rule that reads the package table, which costs an index of every file +/// in the run on top of the word census. +fn reads_packages(rule: &'static dyn Rule) -> bool { + rule.name() == "unused-import" +} + /// The command line's list when it said anything, else the config file's. fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] { if cli.is_empty() { diff --git a/crates/lucisv_server/src/imports.rs b/crates/lucisv_server/src/imports.rs new file mode 100644 index 0000000..08dda99 --- /dev/null +++ b/crates/lucisv_server/src/imports.rs @@ -0,0 +1,381 @@ +//! Organize imports on the wire: `textDocument/codeAction` under LSP's own +//! `source.organizeImports` kind, and `workspace/executeCommand` for the +//! editors that have no lightbulb. +//! +//! Protocol only. The edit is `vlog_refactor::organize_imports`; this module +//! decides which files that engine is handed, turns its answer into a +//! `WorkspaceEdit`, and turns its refusal into a request error. +//! +//! **The kind is `source.organizeImports` and nothing else.** That is the +//! kind an editor's organize-on-save asks for by name, and filing the action +//! under a second `refactor.rewrite.*` kind as well would mean a client +//! asking for both got the same action twice. +//! +//! **The file set.** An `import` binds names in the scope that wrote it, so +//! the edit never leaves the cursor's own file — but *judging* it needs every +//! file that could supply a name through one of those imports: the file +//! declaring each imported package, every file declaring a package of that +//! name (so an ambiguity the index can see is one the engine sees too), and +//! the same again for every package those re-export from (§48). That closure +//! is a handful of files on any workspace, which is what lets this run on a +//! cursor rather than on a whole-workspace read. See +//! `docs/features/organize-imports/README.md`. + +// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours. +#![allow(clippy::mutable_key_type)] + +use std::path::{Path, PathBuf}; + +use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Position, Uri, WorkspaceEdit}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::state::Workspace; + +/// Organize the imports at a position: `[uri, position]`. +pub const ORGANIZE_IMPORTS: &str = "lucisv.organizeImports"; + +/// Every command this module executes. +pub fn commands() -> Vec { + vec![ORGANIZE_IMPORTS.to_string()] +} + +/// The kind LSP reserves for this action, which is what an editor's +/// organize-on-save asks for. +pub fn kind() -> CodeActionKind { + CodeActionKind::SOURCE_ORGANIZE_IMPORTS +} + +/// The action at a position, carrying its computed edit — what a client +/// without `codeAction/resolve` gets, and what [`resolve`] re-runs. +pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() }; + let Ok((edit, removed, sorted)) = vlog_refactor::organize_counts(&files, &path, offset) else { + return Vec::new(); + }; + let Ok(edit) = crate::ports::workspace_edit(ws, &edit) else { return Vec::new() }; + vec![CodeActionOrCommand::CodeAction(CodeAction { + title: vlog_refactor::organize_title(removed, sorted), + kind: Some(kind()), + edit: Some(edit), + ..Default::default() + })] +} + +/// The same action **without** its edit — the offer a client that can +/// `codeAction/resolve` is sent. +/// +/// The counts in the title are the engine's own, computed over the same file +/// set [`resolve`] will use, so the offer and the resolution cannot disagree +/// about what the action promises. +pub fn offers( + ws: &Workspace, + uri: &Uri, + position: Position, + offset: u32, +) -> Vec { + let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() }; + let Ok((_, removed, sorted)) = vlog_refactor::organize_counts(&files, &path, offset) else { + return Vec::new(); + }; + let title = vlog_refactor::organize_title(removed, sorted); + let data = serde_json::to_value(Offer { uri: uri.clone(), position }).ok(); + vec![CodeActionOrCommand::CodeAction(CodeAction { + title, + kind: Some(kind()), + data, + ..Default::default() + })] +} + +/// The edit for an offered action, computed now that the user has picked it. +pub fn resolve(ws: &Workspace, action: CodeAction) -> Result { + if action.edit.is_some() { + return Ok(action); + } + let offer: Offer = action + .data + .clone() + .and_then(|data| serde_json::from_value(data).ok()) + .ok_or_else(|| NOT_OURS.to_string())?; + // A buffer that has grown past the large-file threshold since it was + // offered an action is refused here rather than parsed — `ports::resolve` + // draws the same line, and for the same reason. + let doc = ws.document(&offer.uri).filter(|doc| !doc.large).ok_or_else(|| GONE.to_string())?; + let offset = doc.positions().offset(offer.position); + code_actions(ws, &offer.uri, offset) + .into_iter() + .find_map(|offered| match offered { + CodeActionOrCommand::CodeAction(found) => Some(found), + CodeActionOrCommand::Command(_) => None, + }) + .map(|mut resolved| { + resolved.data = action.data; + resolved + }) + .ok_or_else(|| GONE.to_string()) +} + +/// Run `lucisv.organizeImports`, or say why it cannot run. +pub fn execute( + ws: &Workspace, + arguments: &[Value], +) -> Result<(WorkspaceEdit, Vec), String> { + let uri: Uri = + arguments.first().and_then(|value| serde_json::from_value(value.clone()).ok()).ok_or_else( + || format!("{ORGANIZE_IMPORTS} wants a document URI as its first argument."), + )?; + let position: Position = arguments + .get(1) + .and_then(|value| serde_json::from_value(value.clone()).ok()) + .ok_or_else(|| format!("{ORGANIZE_IMPORTS} wants a position as its second argument."))?; + let doc = ws + .document(&uri) + .ok_or_else(|| "lucisv can only organize the imports of an open file.".to_string())?; + let offset = doc.positions().offset(position); + let (path, files) = at(ws, &uri, offset).ok_or_else(|| NOTHING.to_string())?; + let refactoring = vlog_refactor::organize_imports(&files, &path, offset)?; + Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings)) +} + +/// The cursor's file and the files the engine needs to judge its imports, or +/// nothing when there is no import run at this position at all. +/// +/// The cheap gate first: `imported_packages` is one parse of one buffer and +/// answers "nothing here" for almost every cursor, which is what keeps a +/// `textDocument/codeAction` on every keystroke off the index. +fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> { + let doc = ws.document(uri)?; + let path = doc.path.clone()?; + let packages = vlog_refactor::imported_packages(&doc.text, offset); + if packages.is_empty() { + return None; + } + let files = sources(ws, &path, &doc.text, &packages); + Some((path, files)) +} + +/// The buffer, plus every file that declares one of the named packages or one +/// of the packages those re-export from. +/// +/// **Every** declaration of a name, not the first: two packages called +/// `foo_pkg` is exactly the ambiguity the engine refuses over, and handing it +/// one of them would hide the refusal instead of making it. +/// +/// `pub(crate)` for the test that pins exactly this set. +pub(crate) fn sources( + ws: &Workspace, + path: &Path, + text: &str, + packages: &[String], +) -> Vec<(PathBuf, String)> { + let mut sources = vec![(path.to_path_buf(), text.to_string())]; + let mut queue: Vec = packages.to_vec(); + let mut seen: Vec = Vec::new(); + while let Some(name) = queue.pop() { + if seen.contains(&name) { + continue; + } + for def in ws.index().units(&name) { + let Some(declared_in) = ws.index().path(def.file) else { continue }; + if sources.iter().any(|(held, _)| held == declared_in) { + continue; + } + if let Some(text) = ws.text_of(declared_in) { + sources.push((declared_in.to_path_buf(), text)); + } + } + let onward: Vec = + ws.index().reexported_packages(&name).iter().map(|p| (*p).to_string()).collect(); + queue.extend(onward); + seen.push(name); + } + sources +} + +/// What a lazily-offered action carries in place of its edit. +#[derive(Serialize, Deserialize)] +struct Offer { + uri: Uri, + position: Position, +} + +const GONE: &str = "the action is no longer available."; +const NOT_OURS: &str = "this code action carries no lucisv import organization to resolve."; +const NOTHING: &str = "there is no import run to organize at this position."; + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + use lsp_types::{Range, TextEdit}; + use std::fs; + + /// A scratch workspace root. Removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("lucisv_server_imports_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + const A_PKG: &str = "package a_pkg;\n typedef int a_t;\nendpackage\n"; + const B_PKG: &str = "package b_pkg;\n typedef int b_t;\nendpackage\n"; + const TOP: &str = "module top;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendmodule\n"; + + /// A three-file workspace with `top.sv` open. + fn opened(tree: &Tree) -> (Workspace, Uri) { + tree.write("a_pkg.sv", A_PKG); + tree.write("b_pkg.sv", B_PKG); + let top = tree.write("top.sv", TOP); + 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(), TOP.to_string()); + (ws, uri) + } + + /// The byte offset of a needle in `TOP`. + fn at(needle: &str) -> u32 { + TOP.find(needle).expect("needle") as u32 + } + + fn edits_of(action: &CodeAction, uri: &Uri) -> Vec { + action + .edit + .as_ref() + .expect("an edit") + .changes + .as_ref() + .expect("changes") + .get(uri) + .cloned() + .unwrap_or_default() + } + + fn only(actions: Vec) -> Vec { + actions + .into_iter() + .filter_map(|a| match a { + CodeActionOrCommand::CodeAction(action) => Some(action), + CodeActionOrCommand::Command(_) => None, + }) + .collect() + } + + #[test] + fn a_cursor_on_the_import_run_is_offered_the_action_with_its_counts() { + let tree = Tree::new("offer"); + let (ws, uri) = opened(&tree); + let actions = only(code_actions(&ws, &uri, at("import a_pkg"))); + let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") }; + assert_eq!(action.title, "lucisv: organize imports (removes 1, sorts 1)"); + assert_eq!(action.kind, Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS)); + let edits = edits_of(action, &uri); + assert_eq!(edits.len(), 1, "{edits:?}"); + assert_eq!(edits[0].new_text, " import b_pkg::*;"); + } + + #[test] + fn a_cursor_in_the_body_is_offered_nothing() { + let tree = Tree::new("body"); + let (ws, uri) = opened(&tree); + assert!(code_actions(&ws, &uri, at("b_t q")).is_empty()); + } + + #[test] + fn the_lazy_offer_carries_no_edit_and_resolve_supplies_one() { + let tree = Tree::new("resolve"); + let (ws, uri) = opened(&tree); + let position = Position { line: 1, character: 2 }; + let offered = only(offers(&ws, &uri, position, at("import a_pkg"))); + let [offer] = offered.as_slice() else { panic!("one offer, got {offered:?}") }; + assert!(offer.edit.is_none(), "the offer reads no fan-out"); + assert!(offer.data.is_some(), "and carries what resolve needs"); + let resolved = resolve(&ws, offer.clone()).expect("resolves"); + assert_eq!(resolved.title, offer.title, "the title never changes under the user"); + assert_eq!(edits_of(&resolved, &uri).len(), 1); + } + + #[test] + fn an_action_from_somewhere_else_is_not_ours_to_resolve() { + let tree = Tree::new("not_ours"); + let (ws, _) = opened(&tree); + let stranger = CodeAction { title: "someone else's".into(), ..Default::default() }; + assert_eq!(resolve(&ws, stranger), Err(NOT_OURS.to_string())); + } + + #[test] + fn the_command_organizes_at_a_position() { + let tree = Tree::new("command"); + let (ws, uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(Position { line: 1, character: 2 }).expect("position"), + ]; + let (edit, warnings) = execute(&ws, &arguments).expect("organizes"); + assert!(warnings.is_empty(), "{warnings:?}"); + let edits = edit.changes.as_ref().expect("changes").get(&uri).expect("this file").clone(); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0].new_text, " import b_pkg::*;"); + } + + #[test] + fn the_command_says_why_when_there_is_nothing_to_organize() { + let tree = Tree::new("nothing"); + let (ws, uri) = opened(&tree); + let arguments = vec![ + serde_json::to_value(&uri).expect("uri"), + serde_json::to_value(Position { line: 3, character: 2 }).expect("position"), + ]; + assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string())); + } + + #[test] + fn the_file_set_is_the_buffer_and_the_packages_it_imports() { + let tree = Tree::new("sources"); + let (ws, uri) = opened(&tree); + let path = ws.document(&uri).expect("open").path.clone().expect("path"); + let files = sources(&ws, &path, TOP, &["a_pkg".to_string(), "b_pkg".to_string()]); + let mut names: Vec = files + .iter() + .map(|(p, _)| p.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()) + .collect(); + names.sort(); + assert_eq!(names, vec!["a_pkg.sv", "b_pkg.sv", "top.sv"]); + } + + #[test] + fn a_client_asking_only_for_organize_imports_is_answered() { + // The way organize-on-save asks: `only: ["source.organizeImports"]`. + let filter = [CodeActionKind::SOURCE_ORGANIZE_IMPORTS]; + assert!(crate::code_action::wanted(Some(&filter), &kind())); + assert!(!crate::code_action::wanted( + Some(&filter), + &CodeActionKind::new(crate::ports::REFACTOR_PORTS) + )); + // And a request for the quick fixes alone does not reach us. + let quick = [CodeActionKind::QUICKFIX]; + assert!(!crate::code_action::wanted(Some(&quick), &kind())); + let _ = Range::default(); + } +} diff --git a/crates/lucisv_server/src/lint.rs b/crates/lucisv_server/src/lint.rs index 29b8106..e90f1db 100644 --- a/crates/lucisv_server/src/lint.rs +++ b/crates/lucisv_server/src/lint.rs @@ -28,8 +28,8 @@ use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString}; use lucisv_core::config::FileConfig; use vlog_formatter::fence::{self, Region}; use vlog_linter::{ - default_rules, lint_with, workspace_rules, ExternalWaivers, LintContext, MentionOracle, - ModuleInterface, Rule, RuleOptions, Severity, Violation, + default_rules, lint_with, workspace_rules, Exports, ExternalWaivers, LintContext, + MentionOracle, ModuleInterface, Rule, RuleOptions, Severity, Violation, }; use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex}; @@ -382,6 +382,18 @@ impl MentionOracle for IndexMentions<'_> { } Some(interface) } + + /// Every name a package exports, read off the index's member table — the + /// same `WorkspaceIndex` answer `vlog_refactor`'s organize-imports engine + /// gets, so the squiggle and the lightbulb cannot disagree about which + /// import is dead. + /// + /// `Unknown` for a package the index does not hold and `Ambiguous` for one + /// it holds twice; `vlog_semantic::import_usage` refuses to judge in either + /// case rather than guess. + fn package_exports(&self, package: &str) -> Exports { + vlog_semantic::PackageExports::exports(self.index, package) + } } /// The document's own parse products, lent to the linter — "one parse, two @@ -516,6 +528,23 @@ mod tests { (ws, uri) } + #[test] + fn the_index_answers_what_a_package_exports() { + // The handshake `unused-import` reads: the server's oracle hands the + // rule the very member table `vlog_refactor`'s engine reads, so a + // squiggle and a lightbulb cannot disagree about a dead import. + let index = WorkspaceIndex::build([( + PathBuf::from("/rtl/a_pkg.sv"), + "package a_pkg;\n typedef int a_t;\nendpackage\n", + )]); + let oracle = IndexMentions { index: &index, own: None }; + match oracle.package_exports("a_pkg") { + Exports::Known(names) => assert!(names.iter().any(|n| n == "a_t"), "{names:?}"), + other => panic!("an indexed package is known: {other:?}"), + } + assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown); + } + #[test] fn a_tab_becomes_one_warning_carrying_its_rule_name() { let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n"); diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 9609b43..268957c 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -18,6 +18,7 @@ mod folding; mod format; mod hierarchy; mod hover; +mod imports; mod includes; mod index_cache; mod inlay; @@ -260,6 +261,7 @@ fn capabilities() -> ServerCapabilities { CodeActionKind::QUICKFIX, CodeActionKind::new(code_action::FIX_ALL), CodeActionKind::new(ports::REFACTOR_PORTS), + imports::kind(), ]), work_done_progress_options: WorkDoneProgressOptions::default(), // The quick fixes are complete when they are offered; the port @@ -397,10 +399,11 @@ fn capabilities() -> ServerCapabilities { } } -/// Every command this server executes: the three port refactorings, the -/// instantiation skeleton, and the jump the code lens hangs off. +/// Every command this server executes: the port refactorings, organize +/// imports, the instantiation skeleton, and the jump the code lens hangs off. fn commands() -> Vec { let mut commands = ports::commands(); + commands.extend(imports::commands()); commands.extend(instantiate::commands()); commands.extend(lens::commands()); commands diff --git a/crates/lucisv_server/src/ports.rs b/crates/lucisv_server/src/ports.rs index 4ef4c08..43aa97c 100644 --- a/crates/lucisv_server/src/ports.rs +++ b/crates/lucisv_server/src/ports.rs @@ -349,6 +349,7 @@ pub fn execute( // its own `WorkspaceEdit`, but `server.rs` routes every non-lens // `workspace/executeCommand` through here — this is the one place an // edit-producing command is handed to `Server::deliver`. + crate::imports::ORGANIZE_IMPORTS => return crate::imports::execute(ws, arguments), crate::instantiate::INSTANTIATE => { return crate::instantiate::execute(ws, arguments).map(|edit| (edit, Vec::new())) } diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index 4bd2d5e..acd3b3c 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -45,8 +45,8 @@ use super::client::ms; use super::Server; use crate::{ code_action, completion, design_hierarchy, file_ops, folding, format, hierarchy, hover, - includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename, selection, signature, - symbols, tokens, type_def, type_hierarchy, + imports, includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename, selection, + signature, symbols, tokens, type_def, type_hierarchy, }; impl Server { @@ -268,13 +268,30 @@ impl Server { false => ports::code_actions(&self.workspace, &uri, offset), }); } + // Organizing imports is filed under LSP's own + // `source.organizeImports`, which is the kind an editor's + // organize-on-save asks for by name. + if code_action::wanted(only.as_deref(), &imports::kind()) { + let offset = doc.positions().offset(p.range.start); + actions.extend(match self.abilities.code_action_resolve { + true => imports::offers(&self.workspace, &uri, p.range.start, offset), + false => imports::code_actions(&self.workspace, &uri, offset), + }); + } to_value(actions) }), // The edit for an action offered without one. An action that // already carries its edit comes straight back, so a client that // resolves everything it is offered is answered too. CodeActionResolveRequest::METHOD => decode(request).and_then(|action: CodeAction| { - match ports::resolve(&self.workspace, action) { + // Each family resolves its own offers: the two carry different + // `data`, and the kind the client hands back says which. + let organize = action.kind.as_ref() == Some(&imports::kind()); + let resolved = match organize { + true => imports::resolve(&self.workspace, action), + false => ports::resolve(&self.workspace, action), + }; + match resolved { Ok(resolved) => to_value(resolved), Err(message) => Err(Failure::Request(message)), } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 898f9e9..e5d54a1 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -8529,3 +8529,105 @@ endmodule let _ = std::fs::remove_dir_all(&dir); } + +/// Two packages and a module importing both, for organize-imports. +const IMPORTS_A: &str = "package a_pkg;\n typedef int a_t;\nendpackage\n"; +const IMPORTS_B: &str = "package b_pkg;\n typedef int b_t;\nendpackage\n"; +const IMPORTS_TOP: &str = + "module top;\n import b_pkg::*;\n import a_pkg::*;\n a_t p;\n b_t q;\nendmodule\n"; + +#[test] +fn organize_imports_is_offered_under_its_own_kind_and_runs_as_a_command() { + // What only an e2e test can check: that `source.organizeImports` is + // advertised and honoured as an `only` filter — which is exactly how an + // editor's organize-on-save asks — and that the command reaches the + // engine with its arguments intact. + let dir = temp_dir("organize_imports"); + for (name, text) in [("a_pkg.sv", IMPORTS_A), ("b_pkg.sv", IMPORTS_B), ("top.sv", IMPORTS_TOP)] + { + std::fs::write(dir.join(name), text).expect("write"); + } + let root = format!("file://{}", dir.display()); + let top_uri = format!("file://{}", dir.join("top.sv").display()); + + let open = |uri: &str, text: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(text).expect("json") + )) + }; + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + open(&top_uri, IMPORTS_TOP), + // The cursor on the first import, asking for organize-imports alone. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":1,"character":2}},"end":{{"line":1,"character":2}}}},"context":{{"diagnostics":[],"only":["source.organizeImports"]}}}}}}"# + )), + // The same cursor asking for quick fixes alone gets none of it. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":1,"character":2}},"end":{{"line":1,"character":2}}}},"context":{{"diagnostics":[],"only":["quickfix"]}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.organizeImports","arguments":["{top_uri}",{{"line":1,"character":2}}]}}}}"# + )), + // A cursor in the body has nothing to organize, and says so. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"workspace/executeCommand","params":{{"command":"lucisv.organizeImports","arguments":["{top_uri}",{{"line":3,"character":2}}]}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + // 1. The kind and the command are advertised. + let capabilities = &messages.iter().find(|m| m["id"] == 1).expect("initialize response") + ["result"]["capabilities"]; + let kinds = capabilities["codeActionProvider"]["codeActionKinds"] + .as_array() + .expect("the kinds are listed"); + assert!(kinds.iter().any(|k| k == "source.organizeImports"), "{kinds:#?}"); + let commands = capabilities["executeCommandProvider"]["commands"] + .as_array() + .expect("the commands are listed"); + assert!(commands.iter().any(|c| c == "lucisv.organizeImports"), "{commands:#?}"); + + // 2. `only: ["source.organizeImports"]` returns exactly this action. + let offered = messages.iter().find(|m| m["id"] == 2).expect("codeAction response")["result"] + .as_array() + .expect("an array of actions") + .clone(); + let action = offered + .iter() + .find(|a| a["kind"] == "source.organizeImports") + .unwrap_or_else(|| panic!("no organize action in {offered:#?}")); + assert_eq!(action["title"], "lucisv: organize imports (removes 0, sorts 2)"); + let edits = action["edit"]["changes"][&top_uri].as_array().expect("one file's edits"); + assert_eq!(edits.len(), 1, "{edits:#?}"); + assert_eq!(edits[0]["newText"], " import a_pkg::*;\n import b_pkg::*;"); + + // 3. Asking for quick fixes alone does not compute it. + let quick = messages.iter().find(|m| m["id"] == 3).expect("codeAction response")["result"] + .as_array() + .expect("an array") + .clone(); + assert!( + !quick.iter().any(|a| a["kind"] == "source.organizeImports"), + "the `only` filter is honoured: {quick:#?}" + ); + + // 4. The command applies the same edit... + let ran = messages.iter().find(|m| m["id"] == 4).expect("executeCommand response"); + assert!(ran["error"].is_null(), "{ran:#?}"); + + // 5. ...and refuses elsewhere with a sentence rather than silence. + let refused = messages.iter().find(|m| m["id"] == 5).expect("executeCommand response"); + let said = refused["error"]["message"].as_str().unwrap_or_default(); + assert!(said.contains("no import run to organize"), "{refused:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_linter/src/context.rs b/crates/vlog_linter/src/context.rs index 10734fa..6d07537 100644 --- a/crates/vlog_linter/src/context.rs +++ b/crates/vlog_linter/src/context.rs @@ -7,7 +7,7 @@ use vlog_parser::ast::SourceFile; use vlog_parser::span::TextRange; use vlog_parser::token::{Comment, Token, TokenKind}; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex}; -use vlog_semantic::{analyze, Semantics}; +use vlog_semantic::{analyze, Exports, PackageExports, Semantics}; use crate::options::RuleOptions; use crate::signals::Signals; @@ -158,6 +158,34 @@ pub trait MentionOracle: Sync { fn module_interface(&self, _name: &str) -> Option { None } + + /// Every name the package `package` exports, re-exports included — or + /// [`Exports::Unknown`] when the project holds no such package and + /// [`Exports::Ambiguous`] when it holds two. + /// + /// The third closed question a rule may ask about other files, added by + /// TODO §52.2 for `unused-import`. It is deliberately the *same* + /// question `vlog_refactor`'s organize-imports engine asks its workspace + /// index — [`vlog_semantic::PackageExports`] — so the rule that squiggles + /// an unused import and the refactoring that deletes it cannot come to + /// disagree about what a package exports. A front end with no such table + /// answers `Unknown` to everything, which leaves the rule silent. + fn package_exports(&self, _package: &str) -> Exports { + Exports::Unknown + } +} + +/// The project's package table as [`vlog_semantic`] wants to read it — one +/// [`MentionOracle`], asked through the trait the judgement takes. +pub(crate) struct OracleExports<'a>(pub(crate) Option<&'a dyn MentionOracle>); + +impl PackageExports for OracleExports<'_> { + fn exports(&self, package: &str) -> Exports { + match self.0 { + Some(oracle) => oracle.package_exports(package), + None => Exports::Unknown, + } + } } /// The names a module or interface declares that an instantiation may write. @@ -384,6 +412,16 @@ impl<'a> LintContext<'a> { self.oracle?.module_interface(name) } + /// The project's package table, as the shared import judgement reads it. + /// + /// A run with no oracle answers [`Exports::Unknown`] to every package, + /// which makes `vlog_semantic::import_usage` refuse rather than guess — + /// so `unused-import` is silent in a single-file run exactly as + /// `unused-signal` is. + pub fn package_exports(&self) -> impl PackageExports + '_ { + OracleExports(self.oracle) + } + /// Whether this run can see other files at all. pub fn has_oracle(&self) -> bool { self.oracle.is_some() diff --git a/crates/vlog_linter/src/interfaces.rs b/crates/vlog_linter/src/interfaces.rs index da03d6f..2c23d39 100644 --- a/crates/vlog_linter/src/interfaces.rs +++ b/crates/vlog_linter/src/interfaces.rs @@ -1,4 +1,5 @@ -//! What each module in one file declares that an instantiation may name. +//! What one file declares that a project census has to know: each module's +//! connectable surface, and each package's exported names. //! //! The language server answers [`MentionOracle::module_interface`] from its //! workspace index, which already records every module's ports and parameters. @@ -10,11 +11,43 @@ //! whole is reported as **unknowable** rather than as a short list, because a //! short list is what turns a legal connection into an accusation. +use std::path::Path; + use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile}; +use vlog_semantic::{SymbolKind, WorkspaceIndex}; use crate::context::ModuleInterface; use crate::visit::walk_items; +/// Every package one file declares, with the names it exports — `None` for a +/// package this file alone cannot answer for. +/// +/// The CLI's half of [`crate::MentionOracle::package_exports`], on the same +/// terms [`module_interfaces`] is the CLI's half of `module_interface`: the +/// language server reads the answer off its workspace index, and a run with +/// no index reads it off a **one-file** index of the very same kind, so the +/// two cannot come to disagree about what a package exports. +/// +/// A package writing `export q::*;` answers `None`: which names that lets +/// through is a question only a whole-project index can settle, and a short +/// list is what would turn a used import into an accusation. +pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option>)> { + let index = WorkspaceIndex::build([(path.to_path_buf(), src)]); + index + .units_of(SymbolKind::Package) + .map(|(name, _)| name.to_string()) + .collect::>() + .into_iter() + .map(|name| { + let answer = index + .reexported_packages(&name) + .is_empty() + .then(|| index.members_of(&name).map(|(member, _)| member.to_string()).collect()); + (name, answer) + }) + .collect() +} + /// Every module, interface and program the file declares, with what it /// exposes. `None` for a unit whose header cannot be read whole. /// diff --git a/crates/vlog_linter/src/lib.rs b/crates/vlog_linter/src/lib.rs index 6ffef5c..329d6bf 100644 --- a/crates/vlog_linter/src/lib.rs +++ b/crates/vlog_linter/src/lib.rs @@ -44,7 +44,7 @@ mod waiver_file; use std::path::PathBuf; pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource}; -pub use interfaces::module_interfaces; +pub use interfaces::{module_interfaces, package_exports}; pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions}; pub use registry::{ all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule, @@ -57,6 +57,9 @@ pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation}; /// crate alone. One harvest for the whole workspace — see /// `docs/features/semantic-lints-on/README.md`. pub use vlog_semantic::words; +/// The package table a [`MentionOracle`] answers `package_exports` with, +/// re-exported so an implementor names one crate rather than two. +pub use vlog_semantic::Exports; pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES}; pub use waiver::UNUSED_WAIVER; pub use waiver_file::{ExternalWaivers, UnusedReport, WaiverUse}; diff --git a/crates/vlog_linter/src/registry.rs b/crates/vlog_linter/src/registry.rs index 3efcb99..4798ebf 100644 --- a/crates/vlog_linter/src/registry.rs +++ b/crates/vlog_linter/src/registry.rs @@ -146,6 +146,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::unknown_parameter::UnknownParameter, &rules::unknown_port::UnknownPort, &rules::unpacked_dimensions_range_ordering::UnpackedDimensionsRangeOrdering, + &rules::unused_import::UnusedImport, &rules::unused_signal::UnusedSignal, &rules::unused_waiver::UnusedWaiver, &rules::uvm_macro_semicolon::UvmMacroSemicolon, diff --git a/crates/vlog_linter/src/rules/mod.rs b/crates/vlog_linter/src/rules/mod.rs index 3417e33..ebeb4bc 100644 --- a/crates/vlog_linter/src/rules/mod.rs +++ b/crates/vlog_linter/src/rules/mod.rs @@ -74,6 +74,7 @@ pub mod undriven_net; pub mod unknown_parameter; pub mod unknown_port; pub mod unpacked_dimensions_range_ordering; +pub mod unused_import; pub mod unused_signal; pub mod unused_waiver; pub mod uvm_macro_semicolon; diff --git a/crates/vlog_linter/src/rules/unused_import.rs b/crates/vlog_linter/src/rules/unused_import.rs new file mode 100644 index 0000000..9971a11 --- /dev/null +++ b/crates/vlog_linter/src/rules/unused_import.rs @@ -0,0 +1,228 @@ +//! `unused-import` — an `import p::*;` nothing in its scope reaches through. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::{Applicability, Fix, Violation}; + +/// See [`Rule::doc`]. +pub struct UnusedImport; + +const NAME: &str = "unused-import"; + +impl Rule for UnusedImport { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "delete an import nothing uses" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "`import p::*;` at the top of a module, a package or a class is the \ + cheapest line in the file to leave behind: it survives every rename \ + and every deletion of the code that needed it, and it goes on \ + pulling a whole package's names into the scope, where they shadow \ + nothing and collide with everything. This rule reports the ones \ + nothing reaches through, and `lucisv: organize imports` is the same \ + judgement applied as an edit — one computation, so the squiggle and \ + the lightbulb can never disagree.\n\n\ + **Used** means some reference in the scope, or in a scope nested \ + inside it, could have got its name through that import: the name is \ + not declared locally in between, the import's path admits it \ + (`p::*` admits everything, `p::x` admits `x`), and `p` really \ + exports it — including through a `export q::*;` re-export chain. A \ + **qualified** `p::y` is not a use: it resolves inside `p` whether \ + the import is written or not.\n\n\ + What the rule deliberately **refuses to judge**, saying nothing at \ + all rather than guessing: a package the project does not hold or \ + holds twice; a scope containing a macro call or a conditional \ + directive, because a name may live in text lucisv never expanded; \ + and a class whose base class is declared in another file, because an \ + inherited member could be the use. It is silent for a file it cannot \ + see the project around — one file, a stdin buffer — for the same \ + reason `unused-signal` is: there is nothing there to ask.\n\n\ + The fix deletes the whole `import` item. An import carrying a \ + comment is reported without one: the comment would have to go with \ + the line, and lucisv never drops a comment." + } + + fn default_on(&self) -> bool { + // Off, and off *with* a project too — hence no `needs_workspace` + // here, which would have switched it on wherever an oracle exists. + // An unused import is a tidiness finding, not a correctness one, and + // a whole existing tree lighting up on the day lucisv learns to see + // it is not a default anybody asked for. Silence in a single-file run + // needs no switch: with no project there is no package table, every + // scope refuses, and the rule reports nothing. + false + } + + fn fix(&self) -> Option { + Some(Applicability::Safe) + } + + fn check(&self, ctx: &LintContext) -> Vec { + let exports = ctx.package_exports(); + let semantics = ctx.semantics(); + let source = ctx.source(); + vlog_semantic::unused_imports(ctx.file(), semantics, ctx.tokens(), &exports) + .into_iter() + .map(|found| { + let violation = Violation::new(NAME, found.message(), found.span); + match deletion(source, found.span) { + Some(range) => violation.with_fix(Fix::safe(vec![(range, String::new())])), + None => violation, + } + }) + .collect() + } +} + +/// The bytes a fix deletes: the whole line the `import` sits on, its final +/// newline included. +/// +/// `None` when the line holds anything else — another item, or a comment. +/// A comment is never dropped (CLAUDE.md invariant 3) and a second item is +/// not this finding's to delete, so the finding ships without a fix and the +/// user decides. +fn deletion( + source: &str, + span: vlog_parser::span::TextRange, +) -> Option { + let start = source + .get(..span.start as usize) + .and_then(|head| head.rfind('\n')) + .map_or(0, |n| n as u32 + 1); + let end = match source.get(span.end as usize..).and_then(|tail| tail.find('\n')) { + Some(n) => span.end + n as u32 + 1, + None => source.len() as u32, + }; + let before = source.get(start as usize..span.start as usize)?; + let after = source.get(span.end as usize..end as usize)?; + let clean = before.chars().all(char::is_whitespace) && after.chars().all(char::is_whitespace); + clean.then(|| vlog_parser::span::TextRange::new(start, end)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Exports, MentionOracle}; + + /// A project holding exactly these packages. + struct Project(&'static [(&'static str, &'static [&'static str])]); + + impl MentionOracle for Project { + fn mentioned_elsewhere(&self, _name: &str) -> bool { + false + } + + fn package_exports(&self, package: &str) -> Exports { + match self.0.iter().find(|(name, _)| *name == package) { + Some((_, names)) => { + Exports::Known(names.iter().map(|n| (*n).to_string()).collect()) + } + None => Exports::Unknown, + } + } + } + + const PROJECT: Project = Project(&[("a_pkg", &["a_t", "A_W"]), ("b_pkg", &["b_t"])]); + + fn messages(src: &str) -> Vec { + UnusedImport + .check(&LintContext::new(src, None).with_oracle(&PROJECT)) + .into_iter() + .map(|v| v.message) + .collect() + } + + /// The buffer with every fix applied, back to front. + fn fixed(src: &str) -> String { + let mut out = src.to_string(); + let violations = UnusedImport.check(&LintContext::new(src, None).with_oracle(&PROJECT)); + let mut edits: Vec<_> = violations + .iter() + .filter_map(|v| v.fix.as_ref()) + .flat_map(|f| f.edits.clone()) + .collect(); + edits.sort_by_key(|(range, _)| range.start); + for (range, text) in edits.iter().rev() { + out.replace_range(range.start as usize..range.end as usize, text); + } + out + } + + #[test] + fn an_import_nothing_uses_is_reported_and_fixed() { + let src = "module m;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendmodule\n"; + assert_eq!( + messages(src), + vec!["`a_pkg::*` is imported but nothing in this scope uses it".to_string()] + ); + assert_eq!(fixed(src), "module m;\n import b_pkg::*;\n b_t q;\nendmodule\n"); + } + + #[test] + fn an_import_the_scope_reaches_through_is_not_reported() { + let src = "module m;\n import a_pkg::*;\n a_t x;\nendmodule\n"; + assert!(messages(src).is_empty(), "{:?}", messages(src)); + } + + #[test] + fn a_qualified_use_does_not_count() { + let src = "module m;\n import a_pkg::*;\n a_pkg::a_t x;\nendmodule\n"; + assert_eq!(messages(src).len(), 1, "a `::` path resolves without the import"); + } + + #[test] + fn a_shadowing_declaration_does_not_count() { + let src = "module m;\n import a_pkg::*;\n typedef bit a_t;\n a_t x;\nendmodule\n"; + assert_eq!(messages(src).len(), 1); + } + + #[test] + fn a_nested_scope_s_use_counts() { + let src = + "module m;\n import a_pkg::*;\n initial begin\n int w = A_W;\n end\nendmodule\n"; + assert!(messages(src).is_empty(), "{:?}", messages(src)); + } + + #[test] + fn a_macro_call_silences_the_scope() { + let src = "module m;\n import a_pkg::*;\n `MY_CHECK(x)\nendmodule\n"; + assert!(messages(src).is_empty(), "a refusal is not an accusation"); + } + + #[test] + fn an_unknown_package_silences_the_scope() { + let src = "module m;\n import nowhere_pkg::*;\n wire a;\nendmodule\n"; + assert!(messages(src).is_empty(), "{:?}", messages(src)); + } + + #[test] + fn a_run_with_no_project_says_nothing() { + let src = "module m;\n import a_pkg::*;\n wire a;\nendmodule\n"; + let found = UnusedImport.check(&LintContext::new(src, None)); + assert!(found.is_empty(), "no oracle, no accusation"); + } + + #[test] + fn an_import_carrying_a_comment_is_reported_without_a_fix() { + let src = "module m;\n import a_pkg::*; // why?\n wire a;\nendmodule\n"; + let found = UnusedImport.check(&LintContext::new(src, None).with_oracle(&PROJECT)); + assert_eq!(found.len(), 1); + assert!(found[0].fix.is_none(), "a fix here would delete the comment"); + } + + #[test] + fn a_package_scope_is_judged_like_a_module() { + let src = "package w_pkg;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendpackage\n"; + assert_eq!(messages(src).len(), 1); + } +} diff --git a/crates/vlog_refactor/src/check.rs b/crates/vlog_refactor/src/check.rs index d5ed3a1..45495ba 100644 --- a/crates/vlog_refactor/src/check.rs +++ b/crates/vlog_refactor/src/check.rs @@ -1256,6 +1256,79 @@ mod tests { assert_eq!(verify_splice(&mut scope, &edits, "m", "adding port `rst`"), Ok(())); } + // ------------------------------------------------------------------ + // organize imports: the resolution check as its second net (§52.1) + // ------------------------------------------------------------------ + // + // The engine refuses to *judge* an import it cannot be sure about; this + // is what catches a judgement that was wrong anyway. Both pairs below are + // lexically perfect deletions of a whole `import` line — the token stream + // loses exactly the pieces the edit deletes and nothing else — so only the + // resolution half can tell them apart. + + /// A package and a module importing it, as two files. + fn imported() -> Vec<(PathBuf, String)> { + vec![ + ( + PathBuf::from("/rtl/a_pkg.sv"), + "package a_pkg;\n typedef int a_t;\nendpackage\n".into(), + ), + ( + PathBuf::from("/rtl/m.sv"), + "module m;\n import a_pkg::*;\n a_t sig;\nendmodule\n".into(), + ), + ] + } + + /// The deletion of `m.sv`'s whole `import` line, newline included. + const IMPORT_LINE: &str = " import a_pkg::*;\n"; + + fn import_deletion(text: &str) -> Vec<(usize, Vec)> { + let start = text.find(IMPORT_LINE).expect("import") as u32; + let end = start + IMPORT_LINE.len() as u32; + vec![( + 1usize, + vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }], + )] + } + + #[test] + fn removing_an_import_a_reference_needs_is_rejected() { + // The attack: an honest-looking edit that deletes exactly one import + // line, where `a_t` resolved through it. Nothing lexical objects — + // and afterwards `a_t` names nothing at all. + let files = imported(); + let mut scope = Scope::build(&files); + let text = files[1].1.clone(); + let outcome = + verify_splice(&mut scope, &import_deletion(&text), "", "organizing the imports"); + let message = outcome.expect_err("a needed import is a refusal"); + assert!(message.contains("would change what `a_t` means"), "{message}"); + } + + #[test] + fn removing_an_import_nothing_needs_verifies() { + // The same deletion, of an import the body does not reach through: + // `a_t` is declared here, so every name resolves where it did. + let files = vec![ + files_entry("/rtl/a_pkg.sv", "package a_pkg;\n typedef int a_t;\nendpackage\n"), + files_entry( + "/rtl/m.sv", + "module m;\n import a_pkg::*;\n typedef bit a_t;\n a_t sig;\nendmodule\n", + ), + ]; + let mut scope = Scope::build(&files); + let text = files[1].1.clone(); + assert_eq!( + verify_splice(&mut scope, &import_deletion(&text), "", "organizing the imports"), + Ok(()) + ); + } + + fn files_entry(path: &str, text: &str) -> (PathBuf, String) { + (PathBuf::from(path), text.to_string()) + } + #[test] fn a_rename_that_edited_the_declaration_but_not_its_uses_is_rejected() { // The whole point of the resolution check: the tokens are perfect, the diff --git a/crates/vlog_refactor/src/imports.rs b/crates/vlog_refactor/src/imports.rs new file mode 100644 index 0000000..9101edd --- /dev/null +++ b/crates/vlog_refactor/src/imports.rs @@ -0,0 +1,467 @@ +//! Organize imports: drop what nothing uses, merge exact duplicates, sort the +//! run at the scope's top. +//! +//! The judgement — *which* imports anything uses — is not here. It is +//! [`vlog_semantic::import_usage`], because the lint rule that squiggles the +//! same lines has to ask exactly the same question and a second implementation +//! would eventually answer differently. What is here is the **editing**: which +//! lines one `import` item occupies, which of them form the contiguous run at +//! the top of a module, package, class or compilation unit, what order they +//! belong in, and the refusals that come from the text rather than from the +//! symbol table. +//! +//! Every import item is treated as the **block of whole lines** it occupies, +//! its own comments included, and the run is rewritten by writing those blocks +//! back in a new order. So a comment travels with the line it was written on, +//! byte for byte, and the splice verifier's piece comparison — which counts +//! every comment on both sides of the edit — is what proves it did +//! (`check::verify_splice`, CLAUDE.md invariant 3). An import carrying a +//! comment is never *deleted*: the comment would have nowhere to go, and +//! `never_dropped` would refuse the edit whole. +//! +//! See `docs/features/organize-imports/README.md`. + +use std::path::{Path, PathBuf}; + +use vlog_parser::ast::{ClassDecl, Item, ItemKind, Module, SourceFile}; +use vlog_parser::span::TextRange; +use vlog_parser::token::Comment; +use vlog_parser::{parse_source_tolerant, tokenize, ParseDiagnostic}; +use vlog_semantic::{analyze, import_scopes, import_usage, ImportScope, Semantics}; + +use crate::rename::{display, Scope}; +use crate::{check, RefactorEdit, TextEdit}; + +/// Sort the `import` run at the top of the scope the cursor is in, delete the +/// imports nothing there uses, and drop exact duplicates. +/// +/// The scope is the innermost module, interface, package, class or +/// compilation unit covering `offset`. Nothing outside the cursor's own file +/// is edited: an `import` binds names in the scope that wrote it and nowhere +/// else. +pub fn organize_imports( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result { + Ok(organize(files, file, offset)?.0) +} + +/// [`organize_imports`], plus what its code action's title promises: how many +/// imports it removes and how many it writes back in order. +pub fn organize_counts( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result<(RefactorEdit, usize, usize), String> { + organize(files, file, offset) +} + +/// The lightbulb's text, written here so every front end says the same thing. +pub fn organize_title(removed: usize, sorted: usize) -> String { + format!("lucisv: organize imports (removes {removed}, sorts {sorted})") +} + +/// Every `import` item in a file that nothing in its scope uses, with the +/// sentence saying so. +/// +/// The census half of the engine: no edit, no verification, one answer per +/// unused item. A scope the judgement refuses contributes nothing. +pub fn unused_imports(files: &[(PathBuf, String)], file: &Path) -> Vec<(TextRange, String)> { + let scope = Scope::build(files); + let Some(text) = scope.index_of(file).and_then(|i| scope.text(i)) else { return Vec::new() }; + let (tree, diagnostics) = parse_source_tolerant(text); + if !diagnostics.is_empty() { + return Vec::new(); + } + let Ok(tokens) = tokenize(text) else { return Vec::new() }; + let semantics = analyze(&tree, text); + vlog_semantic::unused_imports(&tree, &semantics, &tokens, scope.index()) + .into_iter() + .map(|found| (found.span, found.message())) + .collect() +} + +/// Every package the scope at `offset` imports, or nothing when there is no +/// import run to organize there. +/// +/// The **cheap gate**, and the fan-out namer with it: one parse of one file, +/// no workspace, no I/O — the same bargain `port_action_modules` strikes, and +/// for the same reason (a `textDocument/codeAction` arrives on every cursor +/// move). Empty exactly where [`organize_imports`] would find nothing to do +/// for want of a scope; a caller reads the named packages' files and hands +/// them, and nothing else, to the engine. +pub fn imported_packages(text: &str, offset: u32) -> Vec { + let (tree, diagnostics) = parse_source_tolerant(text); + if !diagnostics.is_empty() { + return Vec::new(); + } + let Some(items) = container_at(&tree, offset) else { return Vec::new() }; + let imports: Vec<&Item> = items.iter().filter(|item| is_import(item)).collect(); + if imports.is_empty() || !at_the_top(text, items, offset) { + return Vec::new(); + } + let mut out: Vec = Vec::new(); + for item in imports { + let ItemKind::Import(paths) = &item.kind else { continue }; + for path in paths { + if !out.contains(&path.pkg.text) { + out.push(path.pkg.text.clone()); + } + } + } + out +} + +/// Whether the cursor is somewhere the action belongs: in the scope's header +/// — everything before its first item — or on one of its import items' lines. +fn at_the_top(text: &str, items: &[Item], offset: u32) -> bool { + let Some(first) = items.first() else { return false }; + if offset < block(text, first).map_or(first.span.start, |block| block.start) { + return true; + } + items.iter().filter(|item| is_import(item)).any(|item| { + block(text, item).is_some_and(|block| block.start <= offset && offset <= block.end) + }) +} + +fn is_import(item: &Item) -> bool { + matches!(item.kind, ItemKind::Import(_)) +} + +// ---------------------------------------------------------------------- +// the plan +// ---------------------------------------------------------------------- + +fn organize( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, +) -> Result<(RefactorEdit, usize, usize), String> { + let mut scope = Scope::build(files); + 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)?; + let semantics = analyze(&tree, text); + let Ok(tokens) = tokenize(text) else { return Err(not_in_scope(file)) }; + + let here = scope_at(&tree, &semantics, offset)?; + let verdicts = import_usage(&semantics, &tokens, here.scope, scope.index())?; + let mut blocks = Blocks::read(text, here.items, &verdicts)?; + let (edits, warnings, removed, sorted) = blocks.plan(text)?; + if edits.is_empty() { + return Err(match warnings.first() { + Some(sentence) => sentence.clone(), + None => "these imports are already sorted, and every one of them is used.".to_string(), + }); + } + + let what = "organizing the imports"; + let plan = vec![(i, edits)]; + check::verify_splice(&mut scope, &plan, "", what)?; + let Some((_, edits)) = plan.into_iter().next() else { return Err(not_in_scope(file)) }; + let edit = RefactorEdit { edits: vec![(file.to_path_buf(), edits)], warnings }; + Ok((edit, removed, sorted)) +} + +/// The innermost scope covering the cursor that may write `import` items. +fn scope_at<'t>( + tree: &'t SourceFile, + semantics: &Semantics, + offset: u32, +) -> Result, String> { + import_scopes(tree, semantics) + .into_iter() + .rfind(|here| here.span.contains(offset) || here.span.end == offset) + .ok_or_else(|| "there is no scope at this position to organize imports in.".to_string()) +} + +/// The items of the innermost module, package or class covering `offset`, or +/// the file's own — the tree-only twin of [`scope_at`], for the cheap gate. +fn container_at(tree: &SourceFile, offset: u32) -> Option<&[Item]> { + let mut found: &[Item] = &tree.items; + let mut items: &[Item] = &tree.items; + loop { + let inner = items.iter().find_map(|item| { + if !item.span.contains(offset) { + return None; + } + match &item.kind { + ItemKind::Module(m) => Some(nested(m)), + ItemKind::Package { items, .. } => Some(items.as_slice()), + ItemKind::Class(c) => Some(class_items(c)), + _ => None, + } + }); + match inner { + Some(inner) => { + found = inner; + items = inner; + } + None => return Some(found), + } + } +} + +fn nested(module: &Module) -> &[Item] { + &module.items +} + +fn class_items(class: &ClassDecl) -> &[Item] { + &class.items +} + +// ---------------------------------------------------------------------- +// blocks +// ---------------------------------------------------------------------- + +/// One `import` item as the whole lines it occupies, with everything the plan +/// has to know about it. +struct Block { + /// The lines the item and its own comments cover, the final newline + /// excluded. + range: TextRange, + /// Sort key: package name, `*` before a named item, then the item name. + key: (String, u8, String), + /// The paths it writes, normalized — what makes two items duplicates. + paths: Vec<(String, Option)>, + /// Whether any path of it could supply a name something uses. + used: bool, + /// Whether it carries a comment, which is what makes it undeletable. + commented: bool, + /// The item as written, for a sentence. + written: String, +} + +/// The import items of one scope, in source order, with the run at the top +/// marked off. +struct Blocks { + blocks: Vec, + /// How many of `blocks`, from the front, form the contiguous run at the + /// scope's top. + run: usize, +} + +impl Blocks { + /// Read one scope's import items, or say why they cannot be read. + fn read( + text: &str, + items: &[Item], + verdicts: &[vlog_semantic::ImportUse], + ) -> Result { + let mut blocks = Vec::new(); + for item in items { + let ItemKind::Import(paths) = &item.kind else { continue }; + let Some(range) = block(text, item) else { + return Err(shared_line(text, item.span.start)); + }; + let mut used = false; + let mut keys = Vec::new(); + let mut normalized = Vec::new(); + for path in paths { + let Some(verdict) = verdicts.iter().find(|v| v.name_span == path.pkg.span) else { + return Err(LOST.to_string()); + }; + used |= verdict.used; + let item_name = verdict.item.clone(); + keys.push(( + verdict.package.clone(), + u8::from(item_name.is_some()), + item_name.clone().unwrap_or_default(), + )); + normalized.push((verdict.package.clone(), item_name)); + } + let Some(key) = keys.into_iter().min() else { continue }; + blocks.push(Block { + range, + key, + paths: normalized, + used, + commented: !item.meta.leading.is_empty() || item.meta.trailing.is_some(), + written: text + .get(item.span.start as usize..item.span.end as usize) + .unwrap_or("") + .to_string(), + }); + } + let run = run_length(text, items, &blocks); + Ok(Blocks { blocks, run }) + } + + /// The edits, the sentences about what was left alone, and the two counts + /// a title promises. + fn plan(&mut self, text: &str) -> Result<(Vec, Vec, usize, usize), String> { + let mut warnings = Vec::new(); + let mut keep: Vec = Vec::with_capacity(self.blocks.len()); + let mut seen: Vec<&[(String, Option)]> = Vec::new(); + for block in &self.blocks { + let duplicate = seen.contains(&block.paths.as_slice()); + seen.push(&block.paths); + let drop = !block.used || duplicate; + if drop && block.commented { + warnings.push(commented(&block.written)); + } + keep.push(!drop || block.commented); + } + + let mut edits = Vec::new(); + let mut removed = 0usize; + let mut sorted = 0usize; + // The run is one replacement: its surviving blocks, in order, written + // back as the lines they were. + let (head, tail) = self.blocks.split_at(self.run); + let mut written: Vec<&Block> = + head.iter().zip(&keep).filter(|(_, k)| **k).map(|(b, _)| b).collect(); + written.sort_by(|a, b| a.key.cmp(&b.key)); + if let (Some(first), Some(last)) = (head.first(), head.last()) { + // Nothing left of the run means its last newline goes too, or the + // deletion would leave a blank line where the imports were. + let end = match written.is_empty() { + true => (last.range.end as usize + 1).min(text.len()) as u32, + false => last.range.end, + }; + let range = TextRange::new(first.range.start, end); + let new_text = written + .iter() + .map(|block| { + text.get(block.range.start as usize..block.range.end as usize).unwrap_or("") + }) + .collect::>() + .join("\n"); + let old = text.get(range.start as usize..range.end as usize).unwrap_or(""); + if new_text != old { + // The two counts are what the run's own edit does, so a title + // never promises a sort that was already true. + removed += head.len() - written.len(); + sorted = written.len(); + edits.push(TextEdit { range, new_text }); + } + } + // Everything after the run is deleted where it is, one whole line at + // a time, or left alone. + for (block, keep) in tail.iter().zip(keep.get(self.run..).unwrap_or(&[])) { + if *keep { + continue; + } + removed += 1; + let end = (block.range.end as usize + 1).min(text.len()) as u32; + edits.push(TextEdit { + range: TextRange::new(block.range.start, end), + new_text: String::new(), + }); + } + edits.sort_by_key(|edit| (edit.range.start, edit.range.end)); + Ok((edits, warnings, removed, sorted)) + } +} + +/// How many of a scope's import items form the **contiguous run at its top**: +/// the leading items, all of them imports, each on the line after the one +/// before it. +/// +/// A blank line between two imports ends the run rather than being swallowed: +/// a blank line is a grouping the author wrote, and an "organize" that erased +/// it would be reformatting rather than organizing. +fn run_length(text: &str, items: &[Item], blocks: &[Block]) -> usize { + let mut run = 0usize; + for (n, item) in items.iter().enumerate() { + if !is_import(item) || n != run { + break; + } + let Some(block) = blocks.get(run) else { break }; + if let Some(previous) = run.checked_sub(1).and_then(|p| blocks.get(p)) { + let between = text.get(previous.range.end as usize..block.range.start as usize); + if between != Some("\n") { + break; + } + } + run += 1; + } + run +} + +/// The whole lines one item occupies, its own comments included — or `None` +/// when the item shares a line with something else, which is the one layout +/// this refactoring will not rearrange. +fn block(text: &str, item: &Item) -> Option { + let mut spans: Vec = item.meta.leading.iter().map(|c: &Comment| c.span).collect(); + spans.extend(item.meta.before_sep.iter().map(|c| c.span)); + if let Some(comment) = &item.meta.trailing { + spans.push(comment.span); + } + spans.push(item.span); + spans.sort_by_key(|span| (span.start, span.end)); + let first = spans.first()?.start; + let last = spans.iter().map(|span| span.end).max()?; + let start = line_start(text, first); + let end = line_end(text, last); + + // Everything in the block that is not the item's own code or one of its + // own comments must be whitespace: anything else is another item's, and + // moving this block would move that too. + let mut cursor = start; + for span in &spans { + if span.start < cursor { + continue; + } + if !blank(text, cursor, span.start) { + return None; + } + cursor = cursor.max(span.end); + } + blank(text, cursor, end).then(|| TextRange::new(start, end)) +} + +fn blank(text: &str, from: u32, to: u32) -> bool { + text.get(from as usize..to as usize).is_some_and(|gap| gap.chars().all(char::is_whitespace)) +} + +fn line_start(text: &str, at: u32) -> u32 { + text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |n| n as u32 + 1) +} + +fn line_end(text: &str, at: u32) -> u32 { + match text.get(at as usize..).and_then(|tail| tail.find('\n')) { + Some(n) => at + n as u32, + None => text.len() as u32, + } +} + +// ---------------------------------------------------------------------- +// sentences +// ---------------------------------------------------------------------- + +const LOST: &str = "lucisv lost track of one of the imports it was reading, so it made no edits."; + +fn not_in_scope(file: &Path) -> String { + format!("{} is not one of the files lucisv was given.", display(file)) +} + +fn shared_line(text: &str, at: u32) -> String { + let line = text.get(..at as usize).map_or(0, |head| head.matches('\n').count()) + 1; + format!( + "the import on line {line} shares its line with something else; lucisv organizes imports written one per line, so it made no edits." + ) +} + +fn commented(written: &str) -> String { + format!( + "`{}` is unused, but it carries a comment lucisv would have to delete with it; delete the comment first and lucisv will remove the line.", + written.trim_end_matches(';') + ) +} + +/// A file that does not parse is a file whose imports lucisv misread, and a +/// misread import list is one it would delete lines out of. +fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> { + match diagnostics.first() { + None => Ok(()), + Some(problem) => Err(format!( + "{} does not parse ({} at line {}), so lucisv will not organize its imports.", + display(file), + problem.message, + problem.line + )), + } +} diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 6cfb2b5..01c91f4 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -28,12 +28,16 @@ //! spans instead of edits — see `docs/features/references-nav/README.md`. mod check; +mod imports; mod instantiate; mod ports; mod references; mod rename; mod scope; +pub use imports::{ + imported_packages, organize_counts, organize_imports, organize_title, unused_imports, +}; pub use references::find_references; pub use instantiate::{ diff --git a/crates/vlog_refactor/tests/corpus.rs b/crates/vlog_refactor/tests/corpus.rs index c337b60..7f1450a 100644 --- a/crates/vlog_refactor/tests/corpus.rs +++ b/crates/vlog_refactor/tests/corpus.rs @@ -653,3 +653,146 @@ fn edited(text: &str, edits: &[vlog_refactor::TextEdit]) -> String { } copy } + +// ---------------------------------------------------------------------- +// TODO §52 — organize imports +// ---------------------------------------------------------------------- + +/// The census the plan asks for: every scope in the corpus writing two or +/// more `import` items, organized in a copy, with the counts reported. +/// +/// Four properties per organized scope, and none of them a percentage. The +/// result **parses** (no diagnostic the original did not have). It +/// **formats**, and formatting it twice does not move it. Nothing in the file +/// stops resolving — the count of references that resolve to *nothing at all* +/// may not grow, which is the census-sized shadow of the resolution identity +/// `verify_splice` already proved inside the engine. And organizing the result +/// again finds nothing to do, which is idempotency. +/// +/// A refusal is not a failure: it is the answer for a scope lucisv cannot +/// judge, and the reasons are counted and printed so the ratio is visible. +#[test] +fn every_scope_with_two_imports_in_the_corpus_organizes_or_refuses() { + let Some(files) = corpus() else { return }; + let sources = read(&files); + assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog"); + let config = vlog_formatter::Config::default(); + + let mut scopes = 0usize; + let mut organized = 0usize; + let mut removed_total = 0usize; + let mut sorted_total = 0usize; + let mut refusals: Vec<(&'static str, usize)> = Vec::new(); + let started = Instant::now(); + for (path, text) in &sources { + for offset in import_run_offsets(text) { + scopes += 1; + match vlog_refactor::organize_counts(&sources, path, offset) { + Err(said) => { + let reason = refusal_kind(&said); + match refusals.iter_mut().find(|(held, _)| *held == reason) { + Some((_, count)) => *count += 1, + None => refusals.push((reason, 1)), + } + } + Ok((edit, removed, sorted)) => { + organized += 1; + removed_total += removed; + sorted_total += sorted; + let copy = edited(text, edit.edits_for(path)); + assert_ne!( + ©, + text, + "an organize that changed nothing in {}", + path.display() + ); + let before = vlog_parser::parse_source_tolerant(text).1.len(); + let after = vlog_parser::parse_source_tolerant(©).1.len(); + assert!(after <= before, "{} stopped parsing", path.display()); + assert!( + unresolved(©) <= unresolved(text), + "{} lost a resolution", + path.display() + ); + if let Ok(once) = vlog_formatter::format_source(text, &config) { + let _ = once; + let once = + vlog_formatter::format_source(©, &config).unwrap_or_else(|e| { + panic!( + "the formatter refuses the organize of {}: {e}", + path.display() + ) + }); + let twice = vlog_formatter::format_source(&once, &config) + .expect("formats a second time"); + assert_eq!( + once, + twice, + "formatting {}'s organize diverges", + path.display() + ); + } + // Idempotency: the same cursor, over the edited copy. + let mut again = sources.clone(); + if let Some(entry) = again.iter_mut().find(|(p, _)| p == path) { + entry.1 = copy.clone(); + } + let repeat = vlog_refactor::organize_imports(&again, path, offset); + assert!(repeat.is_err(), "{} organizes twice: {repeat:?}", path.display()); + } + } + } + } + refusals.sort_by_key(|(reason, _)| *reason); + println!( + "corpus organize-imports: {scopes} scopes with 2+ imports, {organized} organized \ + ({removed_total} imports removed, {sorted_total} sorted) in {:.2}s\n refused: {refusals:?}", + started.elapsed().as_secs_f64() + ); + assert_eq!( + scopes, + organized + refusals.iter().map(|(_, n)| n).sum::(), + "every scope is either organized or refused" + ); +} + +/// How many of a file's references resolve to nothing at all. +fn unresolved(text: &str) -> usize { + let semantics = vlog_semantic::analyze(&vlog_parser::parse_source_tolerant(text).0, text); + semantics + .references() + .iter() + .filter(|r| matches!(r.resolution, vlog_semantic::Resolution::NotFound)) + .count() +} + +/// One offset per scope of the file that writes two or more `import` items: +/// the first import's package name. +fn import_run_offsets(text: &str) -> Vec { + let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text); + if !diagnostics.is_empty() { + return Vec::new(); + } + let semantics = vlog_semantic::analyze(&tree, text); + vlog_semantic::import_scopes(&tree, &semantics) + .into_iter() + .filter_map(|here| { + let scope = semantics.scope(here.scope)?; + (scope.imports.len() >= 2).then(|| scope.imports.first().map(|i| i.name_span.start))? + }) + .collect() +} + +/// Which refusal a sentence is, for the census's histogram. +fn refusal_kind(said: &str) -> &'static str { + const KINDS: [(&str, &str); 7] = [ + ("does not preprocess", "macro or directive"), + ("nothing lucisv can see declares", "unknown package"), + ("more than once", "package declared twice"), + ("declared in another file", "base class elsewhere"), + ("does not parse", "parse error"), + ("one per line", "two imports on a line"), + ("already sorted", "nothing to do"), + ]; + KINDS.iter().find(|(needle, _)| said.contains(needle)).map_or("other", |(_, kind)| *kind) +} diff --git a/crates/vlog_refactor/tests/imports.rs b/crates/vlog_refactor/tests/imports.rs new file mode 100644 index 0000000..e3c4322 --- /dev/null +++ b/crates/vlog_refactor/tests/imports.rs @@ -0,0 +1,445 @@ +//! Behavior tests for `organize_imports` and `unused_imports`: what the +//! organize writes, what it keeps, what it refuses, and the attack pair that +//! proves the verifier is the second net. +//! +//! Every test states the whole workspace and asserts on the *applied* text, +//! because that is what the user ends up with. A refusal is asserted on its +//! sentence, since that sentence is the entire answer the editor shows. + +use std::path::PathBuf; + +use vlog_refactor::{organize_counts, organize_imports, unused_imports, RefactorEdit}; + +/// A workspace: `(path, text)` pairs, the shape the engine takes. +fn files(pairs: &[(&str, &str)]) -> Vec<(PathBuf, String)> { + pairs.iter().map(|(path, text)| (PathBuf::from(*path), text.to_string())).collect() +} + +fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 +} + +/// One file's text with the refactoring applied, the way a client applies a +/// `WorkspaceEdit`: back to front, so every range still means what it said. +fn applied(files: &[(PathBuf, String)], edit: &RefactorEdit, path: &str) -> String { + let path = PathBuf::from(path); + let mut text = files + .iter() + .find(|(p, _)| *p == path) + .map(|(_, text)| text.clone()) + .expect("a file in the workspace"); + for change in edit.edits_for(&path).iter().rev() { + text.replace_range( + change.range.start as usize..change.range.end as usize, + &change.new_text, + ); + } + text +} + +/// Two packages every test can import from. +const A_PKG: &str = "package a_pkg;\n typedef int a_t;\n parameter int A_W = 4;\nendpackage\n"; +const B_PKG: &str = "package b_pkg;\n typedef int b_t;\n parameter int B_W = 8;\nendpackage\n"; + +/// The workspace, the organize at `needle`, and the cursor's file afterwards. +fn organize(top: &str, needle: &str) -> Result<(RefactorEdit, String), String> { + organize_in( + &[("/rtl/a_pkg.sv", A_PKG), ("/rtl/b_pkg.sv", B_PKG), ("/rtl/top.sv", top)], + top, + needle, + ) +} + +/// The same, over a workspace the test states in full. +fn organize_in( + pairs: &[(&str, &str)], + top: &str, + needle: &str, +) -> Result<(RefactorEdit, String), String> { + let workspace = files(pairs); + let edit = organize_imports(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, needle))?; + let text = applied(&workspace, &edit, "/rtl/top.sv"); + Ok((edit, text)) +} + +/// What the refusal at this cursor says. +fn refusal(top: &str, needle: &str) -> String { + organize(top, needle).expect_err("a refusal") +} + +/// Every unused import of one file, as `(text, sentence)`. +fn unused(top: &str) -> Vec<(String, String)> { + let workspace = + files(&[("/rtl/a_pkg.sv", A_PKG), ("/rtl/b_pkg.sv", B_PKG), ("/rtl/top.sv", top)]); + unused_imports(&workspace, &PathBuf::from("/rtl/top.sv")) + .into_iter() + .map(|(span, message)| (top[span.start as usize..span.end as usize].to_string(), message)) + .collect() +} + +// ---------------------------------------------------------------------- +// what it removes +// ---------------------------------------------------------------------- + +#[test] +fn an_import_nothing_uses_is_deleted_with_its_line() { + let top = "module m;\n import a_pkg::*;\n import b_pkg::*;\n b_t x;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert_eq!(text, "module m;\n import b_pkg::*;\n b_t x;\nendmodule\n", "{text}"); +} + +#[test] +fn a_used_wildcard_and_a_used_item_both_stay() { + let top = + "module m;\n import b_pkg::*;\n import a_pkg::a_t;\n a_t p;\n b_t q;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert!(text.contains("import a_pkg::a_t;") && text.contains("import b_pkg::*;"), "{text}"); + assert_eq!(text.lines().nth(1), Some(" import a_pkg::a_t;"), "sorted by package: {text}"); +} + +#[test] +fn an_item_import_whose_name_is_never_written_goes() { + let top = "module m;\n import a_pkg::a_t;\n import a_pkg::A_W;\n a_t x;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert_eq!(text, "module m;\n import a_pkg::a_t;\n a_t x;\nendmodule\n", "{text}"); +} + +#[test] +fn a_name_declared_locally_does_not_use_the_import() { + // `a_t` is a local typedef here, so the import supplies nothing. + let top = "module m;\n import a_pkg::*;\n typedef bit a_t;\n a_t x;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert_eq!(text, "module m;\n typedef bit a_t;\n a_t x;\nendmodule\n", "{text}"); +} + +#[test] +fn a_qualified_use_does_not_keep_the_import() { + let top = "module m;\n import a_pkg::*;\n a_pkg::a_t x;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + // The whole run goes, and so does its newline: no blank line is left + // where the imports were. + assert_eq!(text, "module m;\n a_pkg::a_t x;\nendmodule\n", "{text}"); +} + +#[test] +fn a_nested_block_keeps_the_outer_import() { + // Only the `initial` block names `A_W`, and only it names `b_t`. + let top = "module m;\n import b_pkg::*;\n import a_pkg::*;\n initial begin\n b_t v;\n int w = A_W;\n end\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert!(text.contains("import a_pkg::*;") && text.contains("import b_pkg::*;"), "{text}"); + assert_eq!(text.lines().nth(1), Some(" import a_pkg::*;"), "sorted only: {text}"); +} + +#[test] +fn a_nested_class_keeps_the_package_s_import() { + // The class's own scope writes no import; the name arrives through the + // package's, so organizing the package must keep it. + let top = "package w_pkg;\n import b_pkg::*;\n import a_pkg::*;\n class c;\n a_t handle;\n b_t other;\n endclass\nendpackage\n"; + let (_, text) = organize(top, "package w_pkg").expect("organized"); + assert_eq!(text.matches("import").count(), 2, "both imports stay: {text}"); +} + +#[test] +fn a_name_shadowed_inside_a_nested_scope_still_uses_the_outer_import() { + // `a_t` is declared in the block, so *that* use is not the import's — but + // the module body's own `a_t` is. + let top = "module m;\n import a_pkg::*;\n import b_pkg::*;\n a_t outer;\n initial begin\n int a_t;\n a_t = 1;\n end\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert!(text.contains("import a_pkg::*;"), "{text}"); + assert!(!text.contains("b_pkg"), "nothing names b_pkg: {text}"); +} + +#[test] +fn an_exact_duplicate_keeps_the_first() { + let top = "module m;\n import a_pkg::*;\n import a_pkg::*;\n a_t x;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert_eq!(text.matches("import a_pkg::*;").count(), 1, "{text}"); +} + +// ---------------------------------------------------------------------- +// order +// ---------------------------------------------------------------------- + +#[test] +fn the_run_is_sorted_by_package_then_item_with_the_wildcard_first() { + let top = "module m;\n import b_pkg::b_t;\n import a_pkg::A_W;\n import b_pkg::*;\n import a_pkg::a_t;\n a_t p;\n b_t q;\n int w = A_W;\n int v = B_W;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + let run: Vec<&str> = text.lines().skip(1).take(4).collect(); + assert_eq!( + run, + vec![ + " import a_pkg::A_W;", + " import a_pkg::a_t;", + " import b_pkg::*;", + " import b_pkg::b_t;", + ], + "{text}" + ); +} + +#[test] +fn organizing_twice_changes_nothing_the_second_time() { + let top = "module m;\n import b_pkg::*;\n import a_pkg::*;\n a_t p;\n b_t q;\nendmodule\n"; + let (_, once) = organize(top, "module m").expect("organized"); + let message = organize(&once, "module m").expect_err("a second pass has nothing to do"); + assert!(message.contains("already sorted"), "{message}"); +} + +// ---------------------------------------------------------------------- +// comments +// ---------------------------------------------------------------------- + +#[test] +fn a_comment_travels_with_the_import_it_sits_on() { + let top = "module m;\n // the b one\n import b_pkg::*;\n import a_pkg::*; // the a one\n a_t p;\n b_t q;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert_eq!( + text, + "module m;\n import a_pkg::*; // the a one\n // the b one\n import b_pkg::*;\n a_t p;\n b_t q;\nendmodule\n", + "{text}" + ); +} + +#[test] +fn an_unused_import_with_a_comment_is_kept_and_reported() { + let top = "module m;\n import a_pkg::*; // why?\n import b_pkg::*;\n b_t q;\nendmodule\n"; + let message = refusal(top, "module m"); + assert!(message.contains("delete the comment first"), "{message}"); +} + +#[test] +fn a_commented_unused_import_beside_a_real_change_is_left_with_a_warning() { + let top = "module m;\n import b_pkg::*;\n import a_pkg::*; // why?\n b_t q;\nendmodule\n"; + let (edit, text) = organize(top, "module m").expect("organized"); + assert!(text.contains("import a_pkg::*; // why?"), "the comment survives: {text}"); + assert!( + edit.warnings.iter().any(|w| w.contains("delete the comment first")), + "{:?}", + edit.warnings + ); +} + +// ---------------------------------------------------------------------- +// refusals +// ---------------------------------------------------------------------- + +#[test] +fn an_unknown_package_refuses() { + let top = "module m;\n import nowhere_pkg::*;\n import a_pkg::*;\n a_t x;\nendmodule\n"; + let message = refusal(top, "module m"); + assert!(message.contains("nothing lucisv can see declares"), "{message}"); +} + +#[test] +fn a_package_declared_twice_refuses() { + let top = "module m;\n import a_pkg::*;\n import b_pkg::*;\n a_t x;\nendmodule\n"; + let workspace = files(&[ + ("/rtl/a_pkg.sv", A_PKG), + ("/rtl/a_pkg_copy.sv", A_PKG), + ("/rtl/b_pkg.sv", B_PKG), + ("/rtl/top.sv", top), + ]); + let message = organize_imports(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, "module m")) + .expect_err("two declarations are a refusal"); + assert!(message.contains("more than once"), "{message}"); +} + +#[test] +fn a_macro_call_in_the_scope_refuses() { + let top = "module m;\n import a_pkg::*;\n import b_pkg::*;\n `MY_CHECK(a_t)\nendmodule\n"; + let message = refusal(top, "module m"); + assert!(message.contains("does not preprocess"), "{message}"); +} + +#[test] +fn a_conditional_directive_in_the_scope_refuses() { + let top = "module m;\n import a_pkg::*;\n import b_pkg::*;\n`ifdef FOO\n b_t q;\n`endif\nendmodule\n"; + let message = refusal(top, "module m"); + assert!(message.contains("does not preprocess"), "{message}"); +} + +#[test] +fn a_class_with_a_base_in_another_file_refuses() { + let top = "package w_pkg;\n import a_pkg::*;\n import b_pkg::*;\n class c extends uvm_object;\n endclass\nendpackage\n"; + let message = refusal(top, "package w_pkg"); + assert!(message.contains("declared in another file"), "{message}"); +} + +#[test] +fn a_file_that_does_not_parse_refuses() { + let top = "module m;\n import a_pkg::*;\n import b_pkg::*;\n always_comb begin\nendmodule\n"; + let message = refusal(top, "module m"); + assert!(message.contains("does not parse"), "{message}"); +} + +#[test] +fn two_imports_on_one_line_refuse() { + let top = "module m;\n import a_pkg::*; import b_pkg::*;\n b_t q;\nendmodule\n"; + let message = refusal(top, "module m"); + assert!(message.contains("one per line"), "{message}"); +} + +#[test] +fn a_cursor_where_there_is_nothing_to_organize_refuses() { + let top = "module m;\n wire a;\nendmodule\n"; + let message = refusal(top, "wire a"); + assert!(message.contains("already sorted"), "{message}"); +} + +// ---------------------------------------------------------------------- +// the run's edges +// ---------------------------------------------------------------------- + +#[test] +fn a_blank_line_ends_the_run_and_is_not_swallowed() { + let top = + "module m;\n import b_pkg::*;\n\n import a_pkg::*;\n a_t p;\n b_t q;\nendmodule\n"; + let message = refusal(top, "module m"); + assert!(message.contains("already sorted"), "the run is one import: {message}"); +} + +#[test] +fn an_import_below_the_run_is_still_deleted_when_nothing_uses_it() { + let top = "module m;\n import b_pkg::*;\n wire w;\n import a_pkg::*;\n b_t q;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert_eq!(text, "module m;\n import b_pkg::*;\n wire w;\n b_t q;\nendmodule\n", "{text}"); +} + +// ---------------------------------------------------------------------- +// scopes +// ---------------------------------------------------------------------- + +#[test] +fn the_cursor_picks_the_innermost_scope() { + let top = "import a_pkg::*;\nmodule m;\n import b_pkg::*;\n import a_pkg::*;\n b_t q;\nendmodule\n"; + let (_, text) = organize(top, "b_t q").expect("organized"); + assert!(text.starts_with("import a_pkg::*;\n"), "the unit import is untouched: {text}"); + assert_eq!(text.matches("import a_pkg::*;").count(), 1, "the module's copy went: {text}"); +} + +#[test] +fn a_package_declared_in_the_same_file_is_answered_by_the_binder() { + // `local_pkg` is not in the index's units under any other file, and the + // judgement never asks the project about it: the binder's own tables say + // whether it exports `l_t`. + let top = "package local_pkg;\n typedef int l_t;\nendpackage\nmodule m;\n import local_pkg::*;\n import b_pkg::*;\n l_t x;\nendmodule\n"; + let (_, text) = organize(top, "module m").expect("organized"); + assert!(text.contains("import local_pkg::*;"), "{text}"); + assert!(!text.contains("b_pkg"), "nothing names b_pkg: {text}"); +} + +#[test] +fn a_package_scope_organizes_like_a_module() { + let top = + "package w_pkg;\n import b_pkg::*;\n import a_pkg::*;\n a_t p;\n b_t q;\nendpackage\n"; + let (_, text) = organize(top, "package w_pkg").expect("organized"); + assert_eq!(text.lines().nth(1), Some(" import a_pkg::*;"), "{text}"); +} + +#[test] +fn a_re_exported_name_keeps_the_import_that_reaches_it() { + // `c_pkg` declares nothing of its own and re-exports `a_pkg`'s names; the + // import of `c_pkg` is what `a_t` arrives through, so it stays. + let c_pkg = "package c_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n"; + let top = "module m;\n import b_pkg::*;\n import c_pkg::*;\n a_t p;\nendmodule\n"; + let (_, text) = organize_in( + &[ + ("/rtl/a_pkg.sv", A_PKG), + ("/rtl/b_pkg.sv", B_PKG), + ("/rtl/c_pkg.sv", c_pkg), + ("/rtl/top.sv", top), + ], + top, + "module m", + ) + .expect("organized"); + assert_eq!(text, "module m;\n import c_pkg::*;\n a_t p;\nendmodule\n", "{text}"); +} + +// ---------------------------------------------------------------------- +// the census +// ---------------------------------------------------------------------- + +#[test] +fn the_census_names_every_unused_import_in_the_file() { + let top = "module m;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendmodule\n"; + let found = unused(top); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].0, "import a_pkg::*;"); + assert!(found[0].1.contains("nothing in this scope uses it"), "{}", found[0].1); +} + +#[test] +fn the_census_says_nothing_about_a_scope_it_refuses_to_judge() { + let top = "module m;\n import a_pkg::*;\n `MY_CHECK(x)\nendmodule\n"; + assert!(unused(top).is_empty(), "a refusal is not an accusation"); +} + +// ---------------------------------------------------------------------- +// counts +// ---------------------------------------------------------------------- + +#[test] +fn the_counts_are_what_a_title_promises() { + let top = "module m;\n import b_pkg::*;\n import a_pkg::*;\n import a_pkg::*;\n a_t p;\n b_t q;\nendmodule\n"; + let workspace = + files(&[("/rtl/a_pkg.sv", A_PKG), ("/rtl/b_pkg.sv", B_PKG), ("/rtl/top.sv", top)]); + let (_, removed, sorted) = + organize_counts(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, "module m")) + .expect("organized"); + assert_eq!((removed, sorted), (1, 2)); +} + +// ---------------------------------------------------------------------- +// an import a same-file export re-exports through (§52's QA, HIGH) +// ---------------------------------------------------------------------- + +/// IEEE 1800 §26.6: a package may only export what it imported or declared, +/// so `export a_pkg::*;` is backed by the `import a_pkg::*;` above it and the +/// import is *used* — deleting it would leave an export nothing backs. +#[test] +fn an_import_a_same_file_export_re_exports_through_is_kept() { + let top = "package c_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n"; + let result = organize(top, "package c_pkg"); + assert!( + result.is_err(), + "nothing to organize: the one import is used by the export, got {result:?}" + ); + let workspace = files(&[("/rtl/a_pkg.sv", A_PKG), ("/rtl/top.sv", top)]); + assert!( + unused_imports(&workspace, &PathBuf::from("/rtl/top.sv")).is_empty(), + "the rule agrees" + ); +} + +#[test] +fn an_item_export_backs_only_the_import_of_that_item() { + // `export a_pkg::a_t;` is backed by `import a_pkg::a_t;` and by + // `import a_pkg::*;` alike; an import of a different package is not. + let top = "package c_pkg;\n import b_pkg::*;\n import a_pkg::a_t;\n export a_pkg::a_t;\nendpackage\n"; + let (edit, text) = organize(top, "package c_pkg").expect("organized"); + assert_eq!(edit.warnings.len(), 0, "{:?}", edit.warnings); + assert_eq!( + text, "package c_pkg;\n import a_pkg::a_t;\n export a_pkg::a_t;\nendpackage\n", + "{text}" + ); +} + +#[test] +fn a_star_star_export_backs_every_import() { + let top = + "package c_pkg;\n import b_pkg::*;\n import a_pkg::*;\n export *::*;\nendpackage\n"; + let (_, text) = organize(top, "package c_pkg").expect("sorted, nothing removed"); + assert_eq!( + text, + "package c_pkg;\n import a_pkg::*;\n import b_pkg::*;\n export *::*;\nendpackage\n", + "{text}" + ); +} + +#[test] +fn a_dpi_export_backs_no_import() { + let top = "package c_pkg;\n import a_pkg::*;\n function void f(); endfunction\n export \"DPI-C\" function f;\nendpackage\n"; + let (_, text) = organize(top, "package c_pkg").expect("the unused import goes"); + assert!(!text.contains("import a_pkg"), "{text}"); +} diff --git a/crates/vlog_semantic/src/imports.rs b/crates/vlog_semantic/src/imports.rs new file mode 100644 index 0000000..1549148 --- /dev/null +++ b/crates/vlog_semantic/src/imports.rs @@ -0,0 +1,618 @@ +//! Which of a scope's `import`s anything actually uses. +//! +//! One question, asked by two callers: `vlog_refactor`'s organize-imports +//! engine, which deletes what nothing uses, and `vlog_linter`'s +//! `unused-import` rule, which squiggles it. They must agree to the letter — +//! a lightbulb that offers to delete a line the rule does not flag, or the +//! other way round, is lucisv disagreeing with itself — so the judgement +//! lives here, beside the resolution rules it mirrors, and neither caller +//! writes a second copy of it. +//! +//! **What "used" means.** An import written in scope `S` is used when some +//! reference in `S`, or in a scope nested inside `S`, could have got its name +//! *through that import*: the name is not declared locally between the +//! reference and `S`, the import's own path admits the name (`p::*` admits +//! everything, `p::x` admits `x`), and `p` really exports it — read from the +//! binder's own tables when this file declares `p`, and from the project's +//! member table (§48's re-exports included) when it does not. A **qualified** +//! use `p::y` is not one: the name after a `::` or a `.` is looked up inside +//! whatever precedes it, never on the lexical chain the imports sit on, so it +//! would resolve identically with the import gone. +//! +//! The judgement is deliberately a **superset** of the truth. Where two +//! imports could each supply one name, both are called used; where a +//! reference's target is one this crate resolves without consulting imports +//! at all (an instantiated module's name, say), it still counts as a use if +//! the package happens to export that name. Being wrong in that direction +//! keeps an import; being wrong in the other direction deletes a line the +//! code needs, which is the one outcome nothing here may produce. +//! +//! **And where it refuses.** [`import_usage`] answers `Err` — never "unused" +//! — for a package the project cannot name, a package it names twice, a scope +//! carrying a macro call or a conditional directive (a name may live in text +//! lucisv never read), and a class whose base is declared in another file (an +//! inherited member could be the use). See +//! `docs/features/organize-imports/README.md`. + +use vlog_parser::ast::{ImportPath, Item, ItemKind, SourceFile}; +use vlog_parser::span::TextRange; +use vlog_parser::token::{Token, TokenKind}; + +use crate::model::{ScopeId, ScopeKind, SymbolKind}; +use crate::{Semantics, WorkspaceIndex}; + +/// What a project knows about the names one package exports. +/// +/// The smallest question the judgement needs, and the *whole* of what it asks +/// about other files — which is what lets a lint rule reading a project index +/// and a refactoring reading a file set give the same answer. A front end with +/// no project at all answers [`Exports::Unknown`] to everything, which makes +/// [`import_usage`] refuse rather than guess. +pub trait PackageExports { + /// Every name `package` exports, re-exports included. + fn exports(&self, package: &str) -> Exports; +} + +/// A project's answer about one package. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Exports { + /// Exactly one package of this name is indexed; these are its names. + Known(Vec), + /// Nothing the project can see declares a package of this name. + Unknown, + /// The project declares the name more than once. Which one an import + /// means is not lucisv's to guess. + Ambiguous, +} + +impl Exports { + /// Whether the package is known to export `name`. + fn holds(&self, name: &str) -> bool { + match self { + Exports::Known(names) => names.iter().any(|held| held == name), + _ => false, + } + } +} + +impl PackageExports for WorkspaceIndex { + /// The index's own member table for the package, which is + /// [`WorkspaceIndex::members_of_chain`] — the same walk a `p::x` lookup + /// takes, so a name the resolution would find through a re-export is a + /// name this reports as exported. + fn exports(&self, package: &str) -> Exports { + let [def] = self.units(package) else { + return match self.units(package).is_empty() { + true => Exports::Unknown, + false => Exports::Ambiguous, + }; + }; + if def.kind != SymbolKind::Package { + return Exports::Unknown; + } + Exports::Known(self.members_of_chain(package).into_iter().map(|(n, _)| n.into()).collect()) + } +} + +/// One `import` written in a scope, and whether anything uses it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ImportUse { + /// The package named before `::`. + pub package: String, + /// The imported name; `None` for a `::*` wildcard. + pub item: Option, + /// Byte range of the package name as written — the + /// [`Import`](crate::Import) this verdict is about, and the way a caller + /// finds the `import` item it belongs to. + pub name_span: TextRange, + /// True when some reference in the scope, or in one nested inside it, + /// could have reached its declaration through this import. + pub used: bool, +} + +/// Judge every `import` written in `scope`, or say why the question cannot be +/// answered honestly. +/// +/// `tokens` is the file's token stream — the same text `sem` was built from. +/// It is what tells a qualified `p::y` from a bare `y` and what finds the +/// compiler directives the judgement refuses to reason around. +pub fn import_usage( + sem: &Semantics, + tokens: &[Token], + scope: ScopeId, + exports: &dyn PackageExports, +) -> Result, String> { + let Some(here) = sem.scope(scope) else { + return Err("lucisv lost track of the scope whose imports it was reading.".to_string()); + }; + if here.imports.is_empty() { + return Ok(Vec::new()); + } + directives_clear(tokens, here.span)?; + bases_declared_here(sem, here.span)?; + + let mut verdicts: Vec<(ImportUse, Exports)> = Vec::new(); + for import in &here.imports { + let known = exports.exports(&import.package); + // A package this *file* declares is answered by the binder's own + // tables below, so the project's opinion of it is not needed — but a + // package nothing here declares has no second answer. + if import.scope.is_none() { + match known { + Exports::Unknown => return Err(unknown(&import.package)), + Exports::Ambiguous => return Err(ambiguous(&import.package)), + Exports::Known(_) => {} + } + } + verdicts.push(( + ImportUse { + package: import.package.clone(), + item: import.item.clone(), + name_span: import.name_span, + used: false, + }, + known, + )); + } + + exports_use(tokens, here.span, &mut verdicts); + let skipped = import_spans(sem); + for reference in sem.references() { + if !covers(here.span, reference.name_span) { + continue; + } + if skipped.contains(&reference.name_span) || qualified(tokens, reference.name_span) { + continue; + } + mark(sem, scope, &reference.scope, &reference.name, &mut verdicts); + } + Ok(verdicts.into_iter().map(|(verdict, _)| verdict).collect()) +} + +/// One scope a file may write `import` items in — a module, an interface, a +/// package, a class, or the compilation unit — with the items written +/// directly in it. +/// +/// The walk both callers need: the refactoring organizes the run at one such +/// scope's top, and the lint rule reports the unused imports of every one of +/// them. Outermost first, so a caller looking for the *innermost* scope +/// covering a cursor takes the last match. +#[derive(Debug, Clone, Copy)] +pub struct ImportScope<'t> { + /// The scope the items bind into. + pub scope: ScopeId, + /// The items written directly in it. + pub items: &'t [Item], + /// Byte range of the whole construct (the file, for the unit scope). + pub span: TextRange, +} + +/// Every scope of a file that may write `import` items, outermost first. +pub fn import_scopes<'t>(tree: &'t SourceFile, sem: &Semantics) -> Vec> { + let mut out = + vec![ImportScope { scope: sem.file_scope(), items: &tree.items, span: sem.file_span() }]; + nested_scopes(&tree.items, sem, &mut out); + out +} + +fn nested_scopes<'t>(items: &'t [Item], sem: &Semantics, out: &mut Vec>) { + for item in items { + let (name_span, inner) = match &item.kind { + ItemKind::Module(m) => (m.name_span, &m.items), + ItemKind::Package { name_span, items, .. } => (*name_span, items), + ItemKind::Class(c) => (c.name_span, &c.items), + _ => continue, + }; + // The scope is found through the *declaration* the binder made for + // this very name, so an AST node and a `ScopeId` can never be paired + // by a span comparison that happens to agree. + let scope = sem + .symbol_at(name_span.start) + .and_then(|id| sem.symbol(id)) + .and_then(|symbol| symbol.child_scope); + if let Some(scope) = scope { + out.push(ImportScope { scope, items: inner, span: item.span }); + } + nested_scopes(inner, sem, out); + } +} + +/// One `import` item whose every path is unused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UnusedImport { + /// Byte range of the whole `import … ;` item, attributes included. + pub span: TextRange, + /// The paths it writes, as written: `p::*`, `p::x`. + pub paths: Vec, +} + +impl UnusedImport { + /// The one sentence every front end says about this finding — the lint + /// rule's message and the engine census's alike, written once so the two + /// cannot come to word it differently. + pub fn message(&self) -> String { + format!("{} is imported but nothing in this scope uses it", self.phrase()) + } + + /// The paths as one phrase for a message: `` `p::*` `` / `` `p::x` and + /// `q::*` ``. + pub fn phrase(&self) -> String { + let quoted: Vec = self.paths.iter().map(|path| format!("`{path}`")).collect(); + match quoted.split_last() { + Some((last, [])) => last.clone(), + Some((last, head)) => format!("{} and {last}", head.join(", ")), + None => String::new(), + } + } +} + +/// Every `import` item of a file that nothing in its scope uses, in source +/// order. +/// +/// A scope [`import_usage`] refuses to judge contributes nothing: a refusal +/// is "lucisv does not know", and reporting an import it does not know about +/// would be the accusation this whole module exists to avoid. +pub fn unused_imports( + tree: &SourceFile, + sem: &Semantics, + tokens: &[Token], + exports: &dyn PackageExports, +) -> Vec { + let mut out: Vec = Vec::new(); + for here in import_scopes(tree, sem) { + let Ok(verdicts) = import_usage(sem, tokens, here.scope, exports) else { continue }; + for item in here.items { + let ItemKind::Import(paths) = &item.kind else { continue }; + let judged: Vec<&ImportUse> = paths + .iter() + .filter_map(|path| verdicts.iter().find(|v| v.name_span == path.pkg.span)) + .collect(); + // An item whose paths the verdicts do not all cover is one this + // walk lost track of; nothing is claimed about it. + if judged.len() != paths.len() || judged.iter().any(|verdict| verdict.used) { + continue; + } + out.push(UnusedImport { + span: item.span, + paths: paths.iter().map(ImportPath::text).collect(), + }); + } + } + out.sort_by_key(|found| (found.span.start, found.span.end)); + out +} + +/// Mark every import of `scope` that could have supplied `name` to a +/// reference written in `from`. +/// +/// The walk is [`crate::resolve`]'s `lexical`, stopped at `scope`: a scope's +/// own declarations are searched before its imports, a hit there shadows +/// everything further out, and only the imports of `scope` itself are the +/// ones this function is judging. +fn mark( + sem: &Semantics, + scope: ScopeId, + from: &ScopeId, + name: &str, + verdicts: &mut [(ImportUse, Exports)], +) { + let mut current = Some(*from); + while let Some(id) = current { + let Some(here) = sem.scope(id) else { return }; + if here.lookup_local(name).is_some() { + return; + } + if id == scope { + break; + } + current = here.parent; + } + if current.is_none() { + // `from` is not nested in `scope` after all — nothing to mark. + return; + } + let Some(here) = sem.scope(scope) else { return }; + for (import, (verdict, known)) in here.imports.iter().zip(verdicts.iter_mut()) { + if verdict.used || !import.supplies(name) { + continue; + } + // A package this file declares is answered by the binder, exactly as + // `resolve::lexical` answers it; one it does not is the project's. + verdict.used = match import.scope { + Some(pkg) => sem.scope(pkg).is_some_and(|pkg| pkg.lookup_local(name).is_some()), + None => known.holds(name), + }; + } +} + +/// Marks used every import an `export` written in `span` re-exports through. +/// +/// `export p::x;` is legal only over an `import p::x` or `import p::*` in +/// the same package (IEEE 1800 §26.6: a package may only export what it +/// imported or declared), and `export *::*;` re-exports every import — so +/// deleting the import would leave an export nothing backs. The export's own +/// halves are references that `qualified` and `import_spans` both skip, which +/// is why this is read off the tokens before the reference walk (§52's QA). +fn exports_use(tokens: &[Token], span: TextRange, verdicts: &mut [(ImportUse, Exports)]) { + let mut i = 0; + while i < tokens.len() { + let t = &tokens[i]; + i += 1; + if !t.is_kw("export") || !covers(span, t.span) { + continue; + } + // `export "DPI-C" …` is a DPI export: its second token is a string, + // never a `pkg :: item` triple, so the loop below does not fire. + let mut j = i; + while let (Some(pkg), Some(sep), Some(item)) = + (tokens.get(j), tokens.get(j + 1), tokens.get(j + 2)) + { + if !sep.is_sym("::") { + break; + } + for (verdict, _) in verdicts.iter_mut() { + let package = pkg.text == "*" || verdict.package == pkg.text; + let name = + item.text == "*" || verdict.item.as_deref().is_none_or(|own| own == item.text); + if package && name { + verdict.used = true; + } + } + j += 3; + if tokens.get(j).is_some_and(|c| c.is_sym(",")) { + j += 1; + } else { + break; + } + } + } +} + +/// Every byte range an `import`'s own package name occupies, in any scope. +/// +/// `import p::x;` records `p` as a use like any other, and counting it as one +/// would make every import supply its own package name to itself. +fn import_spans(sem: &Semantics) -> Vec { + let mut out: Vec = + sem.scopes().iter().flat_map(|scope| scope.imports.iter().map(|i| i.name_span)).collect(); + out.sort_by_key(|span| (span.start, span.end)); + out +} + +/// Whether the name at `span` is the tail of a `::` or `.` path — a member of +/// whatever precedes it, looked up there and never on the lexical chain. +/// +/// An **empty** span is never one. A reference the binder could not point at +/// its own bytes (a `pkg :: mod` instantiation name, an end label) has no +/// token to stand before, and answering `true` for it would drop a use — the +/// one direction this module may not err in. +fn qualified(tokens: &[Token], span: TextRange) -> bool { + if span.is_empty() { + return false; + } + let at = tokens.partition_point(|token| token.span.start < span.start); + let Some(before) = at.checked_sub(1).and_then(|n| tokens.get(n)) else { return false }; + before.kind == TokenKind::Symbol && (before.text == "::" || before.text == ".") +} + +/// No macro call and no conditional directive inside `span`. +/// +/// A `` `MY_CHECK(sig) `` is text lucisv did not read: the name it passes may +/// be the only use of an import, and deleting the import on the strength of +/// what the parser saw would break the file. The handful of directives that +/// can introduce no name at all are the exception, because refusing over a +/// `` `timescale `` would be refusing over nothing. +/// +/// The lexer splits the two apart already: a *known* preprocessor directive +/// is a [`TokenKind::Directive`] running to the end of its line, and a macro +/// **call** is an ordinary identifier whose first byte is a backtick. +fn directives_clear(tokens: &[Token], span: TextRange) -> Result<(), String> { + for token in tokens { + if !covers(span, token.span) { + continue; + } + let refuse = match token.kind { + TokenKind::Directive => !nameless(&token.text), + TokenKind::Ident => token.text.starts_with('`'), + _ => false, + }; + if !refuse { + continue; + } + return Err(format!( + "`{}` is a macro or a conditional directive, and lucisv does not preprocess — a name this scope needs may live in text it never read, so it judged no import here.", + first_line(&token.text) + )); + } + Ok(()) +} + +/// The compiler directives that cannot bring a name into a scope, and so are +/// not a reason to refuse. Everything else — a macro call, `` `include ``, +/// `` `ifdef `` and its family, `` `define `` — is. +fn nameless(text: &str) -> bool { + const HARMLESS: [&str; 11] = [ + "timescale", + "default_nettype", + "resetall", + "celldefine", + "endcelldefine", + "unconnected_drive", + "nounconnected_drive", + "line", + "begin_keywords", + "end_keywords", + "pragma", + ]; + let word = text.trim_start_matches('`').split(|c: char| !c.is_ascii_alphanumeric() && c != '_'); + word.take(1).any(|word| HARMLESS.contains(&word)) +} + +/// A directive's first line, for a refusal that has to fit in a sentence. +fn first_line(text: &str) -> &str { + text.lines().next().unwrap_or(text).trim_end() +} + +/// Every class inside `span` extends a class **this file declares**. +/// +/// A base class in another file supplies members this crate cannot list, and +/// any one of them could be the name an import was written for. The check is +/// the whole span rather than the scope alone: a class nested in the package +/// being organized inherits the package's imports, so its base is as much a +/// reason to refuse as the scope's own would be. +fn bases_declared_here(sem: &Semantics, span: TextRange) -> Result<(), String> { + for scope in sem.scopes() { + if scope.kind != ScopeKind::Class || !covers(span, scope.span) { + continue; + } + let Some(base) = scope.extends() else { continue }; + let last = base.rsplit("::").next().unwrap_or(base); + let declared = sem + .symbols_named(last) + .filter_map(|id| sem.symbol(id)) + .any(|symbol| symbol.kind == SymbolKind::Class); + if !declared { + return Err(format!( + "`{base}` is declared in another file, and a member it inherits could be what an import here is for; lucisv judged no import in this scope." + )); + } + } + Ok(()) +} + +/// Whether `outer` covers `inner` entirely. +fn covers(outer: TextRange, inner: TextRange) -> bool { + outer.start <= inner.start && inner.end <= outer.end +} + +fn unknown(package: &str) -> String { + format!( + "nothing lucisv can see declares the package `{package}`, so it cannot tell which of these imports are used." + ) +} + +fn ambiguous(package: &str) -> String { + format!( + "the project declares a package called `{package}` more than once, so lucisv cannot tell which one these imports mean." + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::{parse_source_tolerant, tokenize}; + + /// A project that says every package exports exactly these names. + struct Project(&'static [(&'static str, &'static [&'static str])]); + + impl PackageExports for Project { + fn exports(&self, package: &str) -> Exports { + match self.0.iter().find(|(name, _)| *name == package) { + Some((_, names)) => { + Exports::Known(names.iter().map(|n| (*n).to_string()).collect()) + } + None => Exports::Unknown, + } + } + } + + /// The verdicts for the innermost scope covering `at`. + fn usage(src: &str, at: &str, project: Project) -> Result, String> { + let semantics = crate::analyze(&parse_source_tolerant(src).0, src); + let tokens = tokenize(src).expect("lexes"); + let offset = src.find(at).expect("anchor") as u32; + let scope = innermost(&semantics, offset); + import_usage(&semantics, &tokens, scope, &project) + .map(|uses| uses.into_iter().map(|u| (u.package.clone(), u.used)).collect()) + } + + /// The innermost import-carrying scope covering an offset. + fn innermost(sem: &Semantics, offset: u32) -> ScopeId { + let mut best = ScopeId(0); + for (i, scope) in sem.scopes().iter().enumerate() { + let container = matches!( + scope.kind, + ScopeKind::Module | ScopeKind::Package | ScopeKind::Class | ScopeKind::File + ); + if container && scope.span.contains(offset) { + best = ScopeId(i as u32); + } + } + best + } + + const PKG: Project = Project(&[("p", &["x", "y"]), ("q", &["z"])]); + + #[test] + fn a_bare_name_the_package_exports_uses_the_wildcard() { + let src = "module m;\n import p::*;\n x u1 ();\nendmodule\n"; + assert_eq!(usage(src, "module m", PKG), Ok(vec![("p".to_string(), true)])); + } + + #[test] + fn an_import_nothing_names_is_unused() { + let src = "module m;\n import p::*;\n wire a;\nendmodule\n"; + assert_eq!(usage(src, "module m", PKG), Ok(vec![("p".to_string(), false)])); + } + + #[test] + fn a_qualified_use_does_not_use_the_import() { + let src = "module m;\n import p::*;\n localparam int W = p::x;\nendmodule\n"; + assert_eq!(usage(src, "module m", PKG), Ok(vec![("p".to_string(), false)])); + } + + #[test] + fn a_locally_declared_name_shadows_the_import() { + let src = "module m;\n import p::*;\n logic x;\n assign x = 1;\nendmodule\n"; + assert_eq!(usage(src, "module m", PKG), Ok(vec![("p".to_string(), false)])); + } + + #[test] + fn an_item_import_is_used_only_by_its_own_name() { + let src = "module m;\n import p::x;\n import p::y;\n assign w = y;\nendmodule\n"; + let verdicts = usage(src, "module m", PKG).expect("judged"); + assert_eq!(verdicts, vec![("p".to_string(), false), ("p".to_string(), true)]); + } + + #[test] + fn a_nested_scope_uses_the_outer_scope_s_import() { + let src = + "module m;\n import p::*;\n initial begin\n $display(y);\n end\nendmodule\n"; + assert_eq!(usage(src, "module m", PKG), Ok(vec![("p".to_string(), true)])); + } + + #[test] + fn a_macro_call_refuses_the_whole_scope() { + let src = "module m;\n import p::*;\n `MY_CHECK(a)\nendmodule\n"; + let message = usage(src, "module m", PKG).expect_err("a macro is a refusal"); + assert!(message.contains("does not preprocess"), "{message}"); + } + + #[test] + fn a_timescale_is_not_a_reason_to_refuse() { + let src = "package p;\n `timescale 1ns / 1ps\n import q::*;\n int a;\nendpackage\n"; + assert_eq!(usage(src, "package p", PKG), Ok(vec![("q".to_string(), false)])); + } + + #[test] + fn an_unknown_package_refuses() { + let src = "module m;\n import missing::*;\nendmodule\n"; + let message = usage(src, "module m", PKG).expect_err("an unknown package is a refusal"); + assert!(message.contains("nothing lucisv can see declares"), "{message}"); + } + + #[test] + fn a_class_extending_another_file_refuses() { + let src = "package w;\n import p::*;\n class c extends base;\n endclass\nendpackage\n"; + let message = usage(src, "package w", PKG).expect_err("an outside base is a refusal"); + assert!(message.contains("declared in another file"), "{message}"); + } + + #[test] + fn a_package_this_file_declares_is_answered_by_the_binder() { + // `Project` has never heard of `local_pkg`, and the file declares it — + // so the binder's own tables settle both imports without a refusal. + let src = "package local_pkg;\n typedef int t;\nendpackage\nmodule m;\n import local_pkg::*;\n t a;\nendmodule\n"; + assert_eq!(usage(src, "module m", PKG), Ok(vec![("local_pkg".to_string(), true)])); + } +} diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index f41caae..89ee346 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -19,6 +19,7 @@ mod bind; pub mod classes; mod facts; +pub mod imports; pub mod instantiations; mod model; mod resolve; @@ -26,6 +27,10 @@ pub mod words; mod workspace; pub use facts::{record_path, FACTS_FORMAT}; +pub use imports::{ + import_scopes, import_usage, unused_imports, Exports, ImportScope, ImportUse, PackageExports, + UnusedImport, +}; pub use model::{ DocumentSymbol, Duplicate, Import, MemberSite, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Surface, Symbol, SymbolId, SymbolKind, diff --git a/crates/vlog_semantic/src/workspace/index.rs b/crates/vlog_semantic/src/workspace/index.rs index 81e3a94..4372f70 100644 --- a/crates/vlog_semantic/src/workspace/index.rs +++ b/crates/vlog_semantic/src/workspace/index.rs @@ -190,6 +190,25 @@ impl WorkspaceIndex { self.reexports.get(unit).map_or(&[], Vec::as_slice) } + /// The packages `unit` re-exports names from, each named once. + /// + /// The public half of [`WorkspaceIndex::reexports`], and the one question + /// a caller assembling a *file set* has to ask: a refactoring that judges + /// which of a file's imports are used must hold every file that can + /// supply a name through `import p::*`, and `p` re-exporting from `q` + /// makes `q`'s file one of them. Empty for every unit that re-exports + /// nothing, which is all but a handful in any workspace. See + /// `docs/features/organize-imports/README.md`. + pub fn reexported_packages(&self, unit: &str) -> Vec<&str> { + let mut out: Vec<&str> = Vec::new(); + for edge in self.reexports(unit) { + if !out.contains(&edge.package.as_str()) { + out.push(edge.package.as_str()); + } + } + out + } + /// The **declared type** of one member of one unit, as the next unit name /// to look in — the hop that walks a chain `pkt_t::hdr::addr` across /// files, and the one a `MemberSite::Unit` path is folded by. diff --git a/docs/features/organize-imports/README.md b/docs/features/organize-imports/README.md new file mode 100644 index 0000000..5c99521 --- /dev/null +++ b/docs/features/organize-imports/README.md @@ -0,0 +1,775 @@ +# organize-imports + +TODO §52 — the third of the §8 refactoring backlog. One judgement, three +faces: an engine function, a lint rule, and a code action under LSP's own +`source.organizeImports` kind. + +## Goal + +`import pkg::*;` / `import pkg::item;` accumulate at the top of a module, a +package, a class or a compilation unit and never leave. They survive the +rename that took away the only name they supplied and the deletion of the code +that needed them, and each one goes on pulling a whole package's names into the +scope. **Organizing** them does what Pylance's does: remove the imports nothing +uses, merge exact duplicates, and sort the contiguous run at the scope's top — +package name, then item, `*` first within one package — keeping every comment +attached to the line it was written on. + +The same computation is a lint rule, `unused-import` (Style, default off, safe +fix = the removal), so the editor squiggles exactly what the action would +delete. That is the round's central constraint: **one judgement, in one place** +(`vlog_semantic::import_usage`), read by both. A lightbulb offering to delete a +line the rule does not flag, or a rule flagging a line the lightbulb keeps, is +lucisv disagreeing with itself. + +Whole-edit-or-nothing, through the ports engine's existing splice verifier +(`vlog_refactor::check::verify_splice`): an `Ok` is safe to apply, an `Err` is +a sentence for the user and no edits at all. + +## API as built + +```rust +// crates/vlog_semantic/src/lib.rs — the judgement, shared by both callers +pub trait PackageExports { fn exports(&self, package: &str) -> Exports; } +pub enum Exports { Known(Vec), Unknown, Ambiguous } +pub struct ImportUse { package, item, name_span, used } +pub struct ImportScope<'t> { scope: ScopeId, items: &'t [Item], span: TextRange } +pub struct UnusedImport { span: TextRange, paths: Vec } // + .message(), .phrase() + +pub fn import_usage(sem: &Semantics, tokens: &[Token], scope: ScopeId, + exports: &dyn PackageExports) -> Result, String>; +pub fn import_scopes<'t>(tree: &'t SourceFile, sem: &Semantics) -> Vec>; +pub fn unused_imports(tree: &SourceFile, sem: &Semantics, tokens: &[Token], + exports: &dyn PackageExports) -> Vec; +impl PackageExports for WorkspaceIndex { .. } + +// new on the index, for a caller that has to assemble a *file set* +pub fn WorkspaceIndex::reexported_packages(&self, unit: &str) -> Vec<&str>; + +// crates/vlog_refactor/src/lib.rs — the editing +pub fn organize_imports(files: &[(PathBuf, String)], file: &Path, offset: u32) + -> Result; +pub fn organize_counts(files, file, offset) -> Result<(RefactorEdit, usize, usize), String>; +pub fn organize_title(removed: usize, sorted: usize) -> String; +pub fn unused_imports(files: &[(PathBuf, String)], file: &Path) -> Vec<(TextRange, String)>; +pub fn imported_packages(text: &str, offset: u32) -> Vec; // the cheap gate + +// crates/vlog_linter/src/lib.rs — the oracle's third closed question +trait MentionOracle { fn package_exports(&self, package: &str) -> Exports { Exports::Unknown } } +pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option>)>; +impl LintContext { pub fn package_exports(&self) -> impl PackageExports + '_ } + +// crates/lucisv_server/src/imports.rs +pub const ORGANIZE_IMPORTS: &str = "lucisv.organizeImports"; // [uri, position] +pub fn kind() -> CodeActionKind; // CodeActionKind::SOURCE_ORGANIZE_IMPORTS +pub fn code_actions / offers / resolve / execute / commands +``` + +`files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence +convention are M2's, unchanged. + +## What "used" means, exactly as implemented + +An import written in scope `S` is **used** when some reference in `S`, or in a +scope nested inside `S`, could have got its name through that import. The walk +is `resolve::lexical`'s own, stopped at `S`: + +1. From the scope the reference is *written* in, outward. At each scope, its + own declarations first: a `lookup_local` hit **shadows** — the reference is + not the import's, and the walk stops there. +2. On reaching `S`, every import of `S` whose path admits the name + (`Import::supplies`: `p::*` admits everything, `p::x` admits `x`) is asked + whether `p` really exports it: + - `p` declared **in this file** → the binder's own tables + (`Import::scope`, then `Scope::lookup_local` in the package's scope) — + which is literally what `resolve::lexical` consults; + - `p` declared **elsewhere** → the project's member table, which for the + `WorkspaceIndex` implementation is `members_of_chain`: the unit's own + members, its `extends` hops, and the packages it **re-exports** from + (§48). That is the same walk a `p::x` lookup takes, so a name resolution + would find through a re-export chain is a name this reports as exported. +3. Every import that could have supplied it is marked used. Where two imports + could each supply one name, **both** are kept. + +Two references never count as uses: + +* **A qualified tail.** The name after a `::` or a `.` is looked up inside + whatever precedes it, never on the lexical chain the imports sit on, so + `p::y` resolves identically with the import gone. The test is the token + before the name — `Symbol("::")` or `Symbol(".")` — which is the whole of it. +* **An import's own package name.** `import p::*;` records `p` as an ordinary + use, and counting it would make every import supply its own name to itself. + Every `Import::name_span` in the file is skipped by identity. + +The judgement is deliberately a **superset** of the truth. A reference whose +target `vlog_semantic` resolves *without* consulting imports at all — an +instantiated module's name, a modport port — still counts as a use when the +package happens to export that name. Being wrong in that direction keeps an +import; being wrong in the other direction deletes a line the code needs, which +is the one outcome nothing here may produce. + +## Refusals — where it will not judge at all + +`import_usage` answers `Err(sentence)`, never "unused", in each of these. The +rule reports **nothing** for such a scope; the action refuses with the +sentence. + +| Situation | Sentence (abridged) | +| --- | --- | +| `p` not in the project | ``nothing lucisv can see declares the package `p`, so it cannot tell which of these imports are used.`` | +| `p` declared twice | ``the project declares a package called `p` more than once, so lucisv cannot tell which one these imports mean.`` | +| A macro call or a conditional directive anywhere in `S` or a nested scope | ``` `` `include "x.svh"` `` is a macro or a conditional directive, and lucisv does not preprocess — a name this scope needs may live in text it never read, so it judged no import here.``` | +| A class in `S` whose base is declared in another file | ``` `uvm_object` is declared in another file, and a member it inherits could be what an import here is for; lucisv judged no import in this scope.``` | +| The file has a parse diagnostic | ``m.sv does not parse (… at line N), so lucisv will not organize its imports.`` | + +The macro rule is the lexer's own split: a known preprocessor directive is a +`TokenKind::Directive`, a macro **call** is an identifier whose first byte is a +backtick, and both refuse. The exception is a short list of directives that can +introduce no name at all — `timescale`, `default_nettype`, `resetall`, +`celldefine`, `endcelldefine`, `unconnected_drive`, `nounconnected_drive`, +`line`, `begin_keywords`, `end_keywords`, `pragma` — because refusing over a +`` `timescale `` would be refusing over nothing. + +Two more refusals belong to the **editing** half rather than the judgement: + +| Situation | Sentence (abridged) | +| --- | --- | +| Two imports share a line | ``the import on line N shares its line with something else; lucisv organizes imports written one per line, so it made no edits.`` | +| Nothing to do | ``these imports are already sorted, and every one of them is used.`` | + +## The edit + +Every import item is treated as the **block of whole lines** it occupies, its +own comments included, and the run is rewritten by writing those blocks back in +a new order — never by regenerating the text. So a comment travels with the +line it was written on, byte for byte. + +* **The run** is the maximal prefix of the scope's items that are all `import` + items, each on the line after the one before it. A **blank line ends the + run**: a blank line is a grouping the author wrote, and an "organize" that + erased it would be reformatting rather than organizing. +* **The run is one replacement**: its surviving blocks, sorted by + `(package, item is Some, item)` — so `import p::*;` sorts before + `import p::x;` — with a **stable** sort, which is what makes a second pass + the identity. +* **Exact duplicates keep the first.** Two items writing the same + `(package, item)` list are one; the later copy goes, unless it carries a + comment. +* **Imports below the run** that nothing uses are deleted where they are, one + whole line at a time (the trailing newline included). +* **A run nothing survives** takes its last newline with it, so a scope whose + every import went is left with no blank line where they were. +* **An import carrying a comment is never deleted.** The comment would have + nowhere to go, and `check::never_dropped` would refuse the whole edit + anyway. + +### Deviation from the plan, and why + +The plan says a commented unused import should "refuse with a sentence: *delete +the comment first*". As shipped, that sentence is a **warning** on an otherwise +successful organize, and the refusal only when there is nothing else to do — +which the "nothing to change" path produces anyway, so the user sees the +sentence exactly where the plan wanted it. Refusing the whole action for one +commented line would have made the action unavailable for any file whose first +import carries a `// dep packages` banner, which is most of them. The lint rule +takes the same line: it **reports** the finding and ships it **without a fix**, +because the fix would delete the comment. + +## The verifier is the second net + +`organize_imports` hands its edits to `check::verify_splice` with an empty +`watch_name` — an `import` binds names in the scope that wrote it and nowhere +else, so only the edited file can change meaning, and `contains_word` answers +`false` for an empty needle, which watches exactly that file and no other. + +The check that matters here is **resolution identity**: every declaration and +every reference whose name span does not overlap an edit must resolve to the +same place before and after. Deleting an import a reference needed turns that +reference from `External(a_pkg's a_t)` into nothing, and the verifier refuses. +The attack pair is pinned in `check.rs`: + +* `removing_an_import_a_reference_needs_is_rejected` — a lexically perfect + deletion of one whole `import` line where the body's `a_t` resolved through + it. Nothing lexical objects; the resolution half says *"organizing the + imports would change what `a_t` means in m.sv"*. +* `removing_an_import_nothing_needs_verifies` — the same deletion where `a_t` + is declared locally, which must pass, so the refusal above is a discriminator + and not a blanket. + +The verifier cannot see a wrong removal of an **unindexed** package's import — +before and after, the reference is unresolved either way — which is exactly why +"unknown package" is a refusal in the judgement rather than a guess. + +## Assumptions + +* An `import` item occupies whole lines of its own. One that shares a line with + another item is refused rather than rearranged. +* A scope's comment attachment is the parser's: `Meta::leading`, + `Meta::trailing` and `Meta::before_sep` of the `import` item are its own, and + everything else on the block's lines must be whitespace (checked, and a + refusal when it is not). +* **Module *header* imports** (`module m import p::*; (...)`) are read for the + judgement — they are in `Scope::imports` like any other — but are never + deleted and never sorted. They are not `Item`s, so they have no line of their + own to move; leaving them alone is safe and is what ships. +* Imports inside a generate block or a function body bind into a scope + `import_scopes` does not walk, so they are neither organized nor reported. +* The lint rule's silence in single-file mode is not a switch: with no oracle + the package table answers `Unknown` for everything, every scope refuses, and + the rule reports nothing. + +## Handshakes + +* **`vlog_semantic` → `vlog_refactor`, `vlog_linter`** (new). `import_usage`, + `import_scopes`, `unused_imports`, `PackageExports`/`Exports`, `ImportUse`, + `ImportScope`, `UnusedImport`. Additive; nothing existing changed. +* **`vlog_semantic::WorkspaceIndex`** (new method). + `reexported_packages(unit) -> Vec<&str>` — the public half of the existing + `pub(super) reexports`, for a caller assembling a file set. Additive. +* **`vlog_linter::MentionOracle`** (new default method). + `package_exports(&self, package: &str) -> Exports`, defaulting to + `Exports::Unknown`. Every existing implementor keeps compiling and every + existing rule is unaffected. Implemented by `lucisv_server`'s + `IndexMentions` (off the workspace index) and by `lucisv`'s `Elsewhere` (off + a per-file one-file index, `vlog_linter::package_exports`). +* **`lucisv` CLI census** (widened). `Census` gained a `packages` table, built + only when `unused-import` is enabled (`reads_packages`), and the census is + now built for that rule as well as for the `needs_workspace` ones. A package + the run declares twice, or one writing any `export q::*;`, answers + "cannot say" — a whole-project index is what settles a re-export chain, and a + short list is what would turn a used import into an accusation. +* **`lucisv_server`** — one new module (`imports.rs`), the oracle method on + `IndexMentions`, one new code-action kind + (`source.organizeImports`) in `capabilities`, one new command in + `commands()`, one new branch in `ports::execute`, and two in + `server/dispatch.rs` (the `codeAction` fan-out and the `codeAction/resolve` + split, which routes by the action's `kind`). +* **`editors/vscode/package.json`** — the `lucisv.lint.rules.*` block + regenerated by `cargo run -p vlog_linter --example vscode_lint_settings`. + +## Status / TODO + +- [x] 52.1 engine: used/unused, sort, dedup, refusals +- [x] 52.2 `unused-import` rule + safe fix + toggle +- [x] 52.3 code action (`source.organizeImports`, lazy) + command +- [x] docs; §8 line annotated; README/site rows (lead — see below) +- [x] Gates (guarded); byte-identity vs 0.46.0; corpus census +- [ ] QA + +## Gate numbers (2026-09-05, all guarded) + +| Gate | Result | +| --- | --- | +| `cargo fmt -p` (the five touched crates) | clean | +| `cargo clippy --all-targets` | clean, no new `#[allow]` | +| `cargo test --workspace` | **4 016 passed, 0 failed, 44 ignored** (baseline 3 951) | +| `tools/corpus_check.sh` | **814/820 (99.3%)**, the same six; verification-error: none; crash: none | +| `format --stdout` vs `lucisv-0.46.0` over 860 corpus files | **0 differing** | +| `cargo build --release -p lucisv -p lucisv_server` | ok | +| `node editors/vscode/smoke.js target/release/lucisv-server` | OK (20 messages) | +| the vscode toggle drift test | green (`package.json` regenerated) | + +No guard kill at any point. + +## Measurements + +### Corpus census (`cargo test -p vlog_refactor --test corpus`) + +860 files; **40 scopes** write two or more imports. + +| Outcome | Count | +| --- | --- | +| organized | 1 (1 import removed, 0 sorted) | +| refused: macro or directive | 32 | +| refused: nothing to do | 5 | +| refused: unknown package | 2 | + +Every organized result parses, formats, converges under a second format, loses +no resolution (`Resolution::NotFound` never grows), and organizes to nothing +the second time. 51 s over the whole corpus. + +**The finding is the refusal ratio.** Four in five scopes with two or more +imports carry a macro call or a `` `include `` somewhere inside them, and lucisv +does not preprocess. That is the honest answer, not a gap to close by loosening +the rule. + +### The rule over the corpus (`lucisv check --select unused-import corpus`) + +**2 findings, both substantiated by hand:** + +* `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_subreg_arb.sv:30` — + `import prim_mubi_pkg::*;`. Every one of the file's ~60 uses of that package + is written fully qualified (`prim_mubi_pkg::mubi4_or_hi`, + `prim_mubi_pkg::MuBi4True`, …). The import really is dead. +* `corpus/common_cells/test/clk_int_div_tb.sv:21` — `import stream_test::*;`. + `stream_test` exports one name, `stream_driver`, and the file's only use of + it is `stream_test::stream_driver #(...)` on line 56, qualified. Dead. + +(One corpus file, `riscv_core_setting.tpl.sv`, does not lex — a pre-existing +template file, unrelated.) + +### OpenTitan UVM env packages (read-only; organized into scratch copies) + +All 34 of `hw/ip/*/dv/env/*_pkg.sv` copied to the scratch directory and +organized against the whole of `hw/` (4 013 files) as the workspace. + +| Outcome | Count | +| --- | --- | +| refused: `` `include "uvm_macros.svh" `` | 30 | +| refused: `` `include "dv_macros.svh" `` | 1 | +| refused: `` `include "aes_ral_extension.svh" `` | 1 | +| refused: `` `ifdef USE_1_RMI_INTF `` | 1 | +| organized | 0 | +| **"unused" claims made** | **0** | + +Zero claims, therefore zero unsubstantiated claims. Every UVM env package in +OpenTitan `` `include ``s its macro library into the package scope, and text +lucisv never read is text a name can live in — so the judgement refuses, which +is the answer the plan asked for. `git -C opentitan status --porcelain` shows +only the three files that were already modified. + +## Work log + +**2026-09-05 — dev (§52).** + +* **Where the judgement lives.** The plan has the rule "reading the same engine + function through the project-facts oracle", but `vlog_linter` does not depend + on `vlog_refactor` and a rule holds one file, not a file set — so the engine + function is not reachable from it. The judgement went into + **`vlog_semantic::imports`** instead, which both crates already depend on, + behind a one-method `PackageExports` trait: `WorkspaceIndex` implements it + for the refactoring, and the linter's `MentionOracle` answers it for the + rule. One implementation, two front ends, no new crate edge. Named here + because it is a deviation from the plan's wording, not from its intent. +* **Telling a qualified use from a lexical one.** `Reference` carries no target + kind, and `Resolution::ExternalCandidate`'s `paths` cannot distinguish an + import path `p::x` from the path `unit_member` records for a written `p::x`. + The discriminator that works is the **token before the name**: `::` or `.` + means a member lookup, which never consults imports. Skipping the *head* of a + `::` path was considered and rejected — `pkg::t'(x)` and `cls::CONST` record + their head as `Target::Unit`, which *does* consult imports, so skipping heads + would lose real uses. +* **The macro token.** A macro call is not a `TokenKind::Directive`; the lexer + gives it `Ident` with a leading backtick (`` `uvm_info(...) ``). Found by a + failing test, fixed in `directives_clear`, which now checks both. +* **`sorted` counts only what the run's own edit rewrites**, so a title never + promises a sort that was already true. (Found by the corpus census reporting + `sorted=2` for a scope whose run was untouched.) +* **The CLI census** was widened rather than left silent: a rule that can only + ever fire from the language server is not really shipped. The per-file + package table is read off a **one-file `WorkspaceIndex`**, which is the very + code the server's answer comes from, so the two cannot drift; a package with + any re-export edge answers "cannot say", because only a whole-project index + settles a chain. +* **The server's file set** is the buffer plus the transitive closure of + (packages imported at the cursor) → (every file declaring one) → (packages + those re-export from). *Every* declaration of a name, not the first, so the + "declared twice" refusal fires where the index can see it. Narrowing without + the re-export hop was rejected outright: a missing re-export source would + make a used import look unused, and the verifier cannot catch that (both + sides of the edit would be computed in the same narrow world). +* **Commented unused imports** ship as a warning plus no fix rather than as a + whole-action refusal — see "Deviation from the plan" above. + +### Files touched + +Expected by the plan: `crates/vlog_refactor/src/imports.rs` (new), +`crates/vlog_refactor/src/lib.rs`, `crates/vlog_refactor/src/check.rs` (the +attack pair), `crates/vlog_refactor/tests/imports.rs` (new), +`crates/vlog_refactor/tests/corpus.rs`, +`crates/vlog_linter/src/rules/unused_import.rs` (new), +`crates/vlog_linter/src/rules/mod.rs`, `crates/vlog_linter/src/registry.rs`, +`crates/vlog_linter/src/context.rs`, `crates/vlog_linter/src/lib.rs`, +`crates/lucisv_server/src/imports.rs` (new), +`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/src/ports.rs`, +`crates/lucisv_server/src/server/dispatch.rs`, +`crates/lucisv_server/src/lint.rs` (the oracle method), +`crates/lucisv_server/tests/e2e.rs`, +`editors/vscode/package.json`, `TODO.md`. + +**Outside the plan's expected set**, each named because the plan did not +anticipate it: + +* `crates/vlog_semantic/src/imports.rs` (new) and + `crates/vlog_semantic/src/lib.rs` — the shared judgement (see the work log's + first entry). +* `crates/vlog_semantic/src/workspace/index.rs` — `reexported_packages`, so + the server can close the file set over re-export edges. +* `crates/vlog_linter/src/interfaces.rs` — `package_exports(path, src)`, the + CLI's per-file package table, beside the module-interface one it already + holds for exactly the same reason. +* `crates/lucisv/src/lint.rs` — the CLI census's `packages` table and the + oracle method on `Elsewhere`. + +### 2026-09-05 — lead, at review (rework of QA's HIGH) + +An `export p::x;` / `export p::*;` / `export *::*;` written in the same +scope now marks the import it re-exports through as used +(`vlog_semantic::imports::exports_use`, read off the tokens before the +reference walk, because the export's halves are references that +`qualified` and `import_spans` both skip). IEEE 1800 §26.6: a package may +only export what it imported or declared, so deleting the import left an +export nothing backs — the two corpus files with this idiom escaped only +through an unrelated `` `include `` refusal. Pinned by four tests in +`tests/imports.rs`: the `*` export keeps the import (organize has nothing +to do; `unused_imports` agrees), an item export backs the item import and +the `*` import but not another package's, `*::*` backs every import, and a +DPI export backs none. QA's LOW (the opentitan table's 33-of-34) is a +documentation count: the 34th file declares no imports. + +## Docs to apply at merge (lead) + +**`docs/site/` — language-tools row.** Add beside the port refactorings: + +> **Organize imports** — remove the `import pkg::*;` lines nothing uses, merge +> exact duplicates and sort the run at the top of a module, package or class. +> Filed under `source.organizeImports`, so an editor's organize-on-save runs +> it. Refuses rather than guesses wherever a macro, a conditional directive, an +> unknown package or a base class in another file could hide a use. + +**`README.md` — the rule table** (hand-maintained; the generated +`rules_markdown()` already carries the rule). One row, in the `style` block: + +> | `unused-import` † | style | safe | no `import` nothing in the scope reaches through (off by default) | + +The `†` is the README's own mark for a rule that needs to see the project; +`unused-import` needs one for the same reason `unused-signal` does, though — +unlike those — it stays **off** even when there is one. + +**`docs/topo.md`** — three new edges to record: + +* `vlog_semantic ──▶ vlog_refactor` and `vlog_semantic ──▶ vlog_linter`: + `import_usage` / `import_scopes` / `unused_imports` / `PackageExports`. +* `vlog_linter ◀──▶ lucisv`, `lucisv_server`: `MentionOracle::package_exports` + (a new default method, so no existing implementor broke). +* `vlog_semantic::WorkspaceIndex::reexported_packages` — new public read, used + by `lucisv_server::imports` only. + +**`TODO.md` §8** — the line for organize-imports is annotated in place (done by +this lane); §52's own checkboxes are ticked except the QA line. + +## QA log + +**Verdict: REWORK — one HIGH finding** (an import backing a same-file +`export` can be deleted, corrupting the file per IEEE 1800 §26.6; see below). +Everything else verified PASS: gates reproduced exactly, the "used" matrix +holds under 29 independent attacks, the verifier's deletion attack pair is +sound, refusals match spec, the rule and CLI census are honest (including the +sibling-file and declared-twice/re-export silence cases), and the opentitan +sweep reproduces with one LOW documentation discrepancy (see below). + +**2026-09-05 — QA (§52).** + +Read `crates/vlog_semantic/src/imports.rs`, `crates/vlog_refactor/src/imports.rs` ++ `check.rs`'s attack pair, `crates/vlog_linter/src/rules/unused_import.rs` + +`interfaces.rs` + `context.rs` + `registry.rs`, `crates/lucisv/src/lint.rs`'s +census widening, `crates/lucisv_server/src/imports.rs` + `main.rs` + `ports.rs` ++ `server/dispatch.rs`, `editors/vscode/package.json`, and every existing test +(`vlog_semantic/src/imports.rs` unit tests, `vlog_refactor/tests/imports.rs`, +`vlog_linter/src/rules/unused_import.rs` unit tests, +`lucisv_server/src/imports.rs` unit tests, `lucisv_server/tests/e2e.rs`'s +organize-imports test, `vlog_refactor/tests/corpus.rs`'s §52 census). Built +`cargo build --release -p lucisv -p lucisv_server` (already current). Added 29 +temporary attack tests to a scratch `vlog_refactor/tests/qa_attack_imports.rs` +and a scratch `vlog_refactor/tests/qa_opentitan_imports.rs` (read-only against +`/Users/guoliangchen/repo/opentitan`); both removed before filing this log — +the tree's file set is unchanged apart from this entry and TODO.md. + +**Gates reproduced independently, all guarded:** + +| Gate | Result | +| --- | --- | +| `cargo fmt -p` (the five touched crates) | clean | +| `cargo clippy --workspace --all-targets` | clean, 0 warnings | +| `cargo test --workspace` | **4 045 passed, 0 failed, 44 ignored** (4 016 dev baseline + 29 of mine, all new tests green) | +| `tools/corpus_check.sh corpus` | **814/820 (99.3%)**, same six parse errors, verification-error: none, crash: none | +| `format --stdout` vs `~/.cache/lucisv-baselines/lucisv-0.46.0` over 860 files | **0 differing** | +| `node editors/vscode/smoke.js` | OK (20 messages) | +| vscode toggle drift test | part of `cargo test --workspace`, green | + +All dev numbers reproduced exactly. + +**The "used" matrix — 29 attack tests, all confirmed correct** (via +`organize_imports`/`unused_imports` over scratch workspaces): cast `t'(x)`, +class handle before `new()`, function call, task call, enum variant, a +parameter in a bit range `[W-1:0]`, a generate-block reference, an +always-block reference, a nested class method, a constraint block, a +covergroup, an assertion property, a default argument value, a type-parameter +argument `#(.T(t))`, an escaped identifier, a compilation-unit import, a +class-body import, a module-header import (judged, never moved — confirmed +the body's own unused import is still removed alongside it), an import inside +a generate block (neither organized nor reported, confirmed by both the +engine and the census), a hierarchical tail `u_x.sig` (confirmed it does +**not** save the import — the head is local), a string literal and a comment +(both confirmed **not** uses — the comment case doubly confirmed unused by +the census), a name shadowed only in a sibling nested block (outer use still +needs the import), two wildcard imports of the same name (both marked used; +confirmed the verifier **refuses** the sort when it would flip which import +`resolve::lexical` resolves the name through first — a second, sort-induced +class of protection beyond the plan's deletion-only attack pair, and correct: +CLAUDE.md invariant 1 wants a refusal here, not a silent reorder), and +`import p::x` where `p` does not export `x` (reported as **unused** rather +than a distinct refusal — a legitimate reading of the plan's open choice, +and safe either way since such an import cannot be legally used). + +**The verifier attack pair** (`removing_an_import_a_reference_needs_is_rejected`, +`removing_an_import_nothing_needs_verifies`) read and correct: the discriminator +is genuinely the resolution-identity check, confirmed by tracing +`check::verify_splice`'s `watched_files` — `contains_word(_, "")` is `false` +(`rename/warnings.rs:479`), so an empty `watch_name` watches only the edited +file, matching the README's claim that an import's meaning never crosses a +file boundary. + +**Refusals** — the 11 nameless directives, two-imports-one-line, parse +diagnostics, unknown/twice-declared packages: all match existing passing +tests; independently confirmed `` `timescale `` etc. do not refuse. + +**The rule and the CLI census** — corpus findings (2, both substantiated by +grep, matching the dev's report exactly): `prim_subreg_arb.sv:30` and +`clk_int_div_tb.sv:21`. `--fix` on a scratch copy deletes the line and +reformats cleanly. Editor toggle present in `package.json`, drift test green. +Confirmed silent in stdin/single-file mode. Confirmed silent (no false +positive) when the run does not include the package's file: `lucisv check +--select unused-import top.sv` with `a_pkg.sv` present on disk but **not** +passed on the command line reports nothing; the same run including both files +correctly flags the genuinely-unused import. Confirmed silent (Ambiguous) when +a package is declared twice across the run's files, and when a package +re-exports (`export q::*;`) — the CLI's `package_exports` answers `None` per +`interfaces.rs`'s own logic, verified by reading `reexported_packages`'s +syntactic (not resolution-gated) computation. + +**Opentitan (read-only), independently reproduced.** `hw/ip/*/dv/env/*_pkg.sv` +— the plan's literal one-level glob — is **34** files, not 32/33; confirmed +by `ls`. Ran `organize_imports` on each, cursor inside the package body, +against the whole of `hw/` (3 979 files) as the workspace: + +| Outcome | Count | +| --- | --- | +| refused: `` `include "uvm_macros.svh" `` | 30 | +| refused: `` `include "dv_macros.svh" `` | 1 | +| refused: `` `include "aes_ral_extension.svh" `` | 1 | +| refused: `` `ifdef USE_1_RMI_INTF `` | 1 | +| no imports at all — trivially "already sorted" | 1 (`spi_host_env_cfg_pkg.sv`) | +| organized | 0 | +| **"unused" claims made** | **0** | + +The first four rows match the dev's report exactly. **LOW finding:** the +dev's table (30+1+1+1 = 33) omits `spi_host_env_cfg_pkg.sv`, which declares no +imports at all and so is neither a refusal nor an organize — the table should +read 34 total, not 33, with a row (or footnote) for the no-imports case. No +functional impact: this file makes zero claims either way. +`git -C opentitan status --porcelain` after the sweep shows only the three +pre-existing modified files. Cheap-gate timing: `imported_packages` on a real +4 149-byte UVM package averaged **0.20 ms/call** over 50 calls — stays off +the hot path as designed. + +### HIGH — an import backing a same-file `export` is deleted, corrupting the file + +**Reproduction.** The dev's own idiom (used in +`tests/imports.rs::a_re_exported_name_keeps_the_import_that_reaches_it`, and +real in the corpus — see below): + +```systemverilog +package c_pkg; + import a_pkg::*; + export a_pkg::*; +endpackage +``` + +Cursor in `c_pkg`'s scope, nothing else in `c_pkg` ever references a name of +`a_pkg` lexically. `organize_imports` returns `Ok`, deleting the `import` +line: + +```systemverilog +package c_pkg; + export a_pkg::*; +endpackage +``` + +Reproduced end-to-end through the shipped CLI: +`lucisv check --select unused-import --fix` on exactly this file deletes the +import and leaves the bare `export` behind. + +**Why this is corruption, not a stylistic choice.** IEEE 1800-2017 §26.6 +requires that a name (or `*`) named in an `export` declaration already be +**imported or declared** in the exporting package's own scope — a bare +`export a_pkg::*;` with no preceding `import a_pkg::*;` (or declaration of +`a_pkg`'s names) in the same package is not legal per the LRM. lucisv's own +model does not enforce this — `docs/features/package-reexports/README.md` +says so explicitly: *"A re-export edge is untyped. Nothing checks that ... +the exporting package imports it (§26.6 requires ... this, and lucisv is not +an elaborator)."* That is a reasonable simplification for §48 (a read-only +feature), but §52 is the first feature that **writes**, and it exploits +exactly this gap: deleting the import does not change how `a_pkg` itself +resolves in the `export` statement (a package name resolves through the +global unit table, not through the local import), so `check::verify_splice`'s +resolution-identity check — which is the *only* net organize-imports relies +on beyond the "used" judgment — sees no difference and passes the edit. + +**Root cause.** `import_usage`'s "used" judgment (`imports.rs`'s `mark`, +walking `sem.references()`) never treats an `export` item's package/item +names as a use of the corresponding `import`; per the plan's own definition +("some reference in S ... resolves to a member of p **through that +import**"), an `export` is not "a reference" in this sense at all, so this is +a gap in the plan's definition, not a coding slip inside an otherwise-correct +implementation of it. + +**Blast radius confirmed real, not synthetic.** Two corpus files use exactly +this idiom — `corpus/ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv` +(`export ibex_mem_intf_pkg::*;`) and +`corpus/ibex/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv` +(`export dv_base_reg_pkg::csr_field_t, dv_base_reg_pkg::decode_csr_or_field;`). +Both currently escape the bug only because they **also** carry +`` `include "uvm_macros.svh" `` in the same scope, which refuses the whole +scope for an unrelated reason — the corpus census's "1 organized" result is a +different, unrelated file. A re-export package with no macros or includes at +all (plausible, and not a contrived shape) would hit this silently, and +`unused-import --fix` hits it too, independent of any macro at all, whenever +the "used" judgment is ever reached for such a scope. + +**Severity: HIGH.** Violates CLAUDE.md invariant 1 ("never corrupt code") +under the "wrong removal" framing this QA pass was scoped to attack; the +verifier — organize-imports' only safety net beyond the judgment itself — +structurally cannot see it, by the same design note §48 already recorded. + +**Suggested direction (not prescriptive — QA does not redesign):** either (a) +`import_usage`'s `mark` should count a same-file `export`'s package/item +names as a use of a same-package-and-name `import` (cheapest, keeps the +"never lose a use" superset property), or (b) `bases_declared_here`-style +refusal extended to any scope containing an `export` of a package this file +also imports, whose exported names are not independently verified used +elsewhere — refusing is always safe per this codebase's own stated bias. + +**2026-09-05 — QA re-attack of the rework.** + +Read `crates/vlog_semantic/src/imports.rs`'s `exports_use` (and its call site +at `import_usage`'s line 158, before the reference walk) against the lead's +work-log entry, and the four new tests appended to +`crates/vlog_refactor/tests/imports.rs`. Rebuilt +`cargo build --release -p lucisv -p lucisv_server` (current). Added a +temporary scratch `crates/vlog_refactor/tests/qa_attack_reexports.rs` (21 +tests) and `crates/vlog_refactor/tests/qa_corpus_reexports.rs` (4 tests, +read-only against `corpus/`); both removed before filing this entry — the +tree's file set is unchanged apart from this entry. + +**Gates reproduced, all guarded:** + +| Gate | Result | +| --- | --- | +| `cargo test -p vlog_semantic -p vlog_refactor -p vlog_linter` | **all green** — `vlog_linter` 647+14, `vlog_refactor` 103+54+9(corpus)+32+35(imports)+53+70 = the full existing suite, plus my 21+4 temporary attack tests, 0 failed; `vlog_semantic` 36 unit + the full integration suite (workspace.rs 87, reexports.rs 14, member_access.rs 40, …), 0 failed | +| `cargo clippy --all-targets` | clean on every production and existing-test file; two trivial warnings (dead helper, elidable lifetime) confined to my own since-deleted scratch files | + +No guard kill at any point. + +**The shape table — every export/import shape in the plan's attack list, +through `organize_imports`/`unused_imports` (all PASS unless noted):** + +| Shape | Outcome | +| --- | --- | +| `import p::x;` + `export p::x;` | kept | +| `import p::*;` + `export p::x;` | kept | +| `import q::*;` only (unrelated to the export's `p`) | judged normally: reported **unused** (correctly not saved by an unrelated export) | +| `import p::y;` + `export p::*;` | kept | +| three imports + `export *::*;` | all three kept, sort still applies (verified with the run deliberately out of order so "already sorted" doesn't mask it) | +| `export a::*, b::x;` with `import a::*;` + `import b::x;` | both halves of the list back their own import | +| `export p::*;` written **before** `import p::*;` in the same package | kept — order does not matter, confirming the README's claim | +| DPI `export "DPI-C" function f;` | backs nothing; the otherwise-unused `import a_pkg::*;` is correctly reported/removed | +| DPI `export "DPI-C" f_c = function f;` | same — backs nothing | +| `export` text inside a `//` comment | not seen (comments are detached from the token stream — `TokenKind::Keyword` never fires there); import correctly still reported unused | +| `export` text inside a string literal (`$display("export a_pkg::*;")`) | not seen (`TokenKind::String`, not `Keyword`); import correctly still reported unused | +| `export ;` (garbage after the keyword) | no panic — the `(pkg, sep, item)` triple pattern just fails to match and the loop breaks | +| package that both directly uses a name **and** exports it | kept once; no double-marking issue (`used` is a bool) | +| `export *::*;` + an import of a **package that exports nothing at all** | **kept** — over-keeping, the codebase's own stated safe direction | +| package this file both imports and re-exports, sorting run present + comments on both imports | sorted correctly, both comments survive byte-for-byte, export line untouched | + +**Scope boundary (`covers(span, t.span)`) — the two cases the plan called out +by name:** + +* *Sibling scope:* a module's own `import a_pkg::*;` is **not** backed by an + unrelated package `c_pkg`'s `export a_pkg::*;` written elsewhere in the same + file — confirmed the module's import is still reported unused. Correct: + sibling top-level scopes' spans don't overlap, so `covers` correctly + excludes it. +* *Nested-inside scope (LOW, informational):* an **illegal** `export` written + inside a class nested inside the exporting package (the parser accepts it — + a class body is parsed by the same item loop as any other scope, per + `crates/vlog_parser/src/parser/class.rs`'s own doc comment — even though + IEEE 1800 §26.6 only permits `export` directly in a package) *does* leak + upward: `exports_use` is called once per scope with that scope's own + `here.span`, and `covers` is a pure byte-range containment test, so a + class's export token — physically inside the package's textual span — is + seen when judging the **package's** imports too, and marks the package's + otherwise-unused import as used. Confirmed by direct test: the import + survives when it otherwise wouldn't. **This is over-keeping, the same safe + direction as the `*::*` + empty-package case above** — it can only cause + lucisv to keep a line that, by a stricter reading, it need not have, never + to delete one a real export needs, so it does not violate CLAUDE.md + invariant 1. Filed as LOW / informational, not a blocker: illegal SV that + the tool does not otherwise validate (§48's own README already disclaims + `export`/`import` legality checking), and the outcome is on the safe side + of the invariant. + +**Corpus (§4), read-only.** `` `include ``-only stripping reproduces the +*existing* corpus census's masking exactly (both files still refuse, now on +their *next* honest reason instead of the `include`: `ibex_mem_intf_agent_pkg.sv` +refuses "unknown package `uvm_pkg`" — `uvm_pkg` is a vendored UVM library +never checked into this corpus, confirmed absent by `grep -rl "^package +uvm_pkg"`; `csr_utils_pkg.sv` refuses on a genuine `` `uvm_info(...) `` macro +**call** in its own body, unrelated to any `` `include ``). Pushing further — +stubbing a one-line `uvm_pkg` package and stripping every backtick line, not +just `` `include `` ones — got `ibex_mem_intf_agent_pkg.sv` all the way to an +actual organize: **`import ibex_mem_intf_pkg::*;` survives** (3 other, +genuinely-unused imports removed, 1 sorted) — direct, real-corpus, +end-to-end confirmation of the fix. The same crude stripping broke +`csr_utils_pkg.sv`'s parse (a multi-line construct straddling a removed +line), so that file's end-to-end run could not be completed; its export shape +(`export dv_base_reg_pkg::csr_field_t, dv_base_reg_pkg::decode_csr_or_field;`, +an item-list export) is exactly the `export a::*, b::x;` shape already +confirmed correct above, so this is a tooling limit of my crude line-strip, +not an open question about the fix. No functional impact either way; filed +as informational. + +**Neutering (§5).** Not executed as a live mutation — reasoning from the code +instead, per the task's own stated alternative. Line 158 of +`crates/vlog_semantic/src/imports.rs` +(`exports_use(tokens, here.span, &mut verdicts);`) is the *only* production +call site that can set `verdict.used = true` from an `export`; nothing else +in `import_usage` inspects `export` tokens at all. Removing that call (or +stubbing `exports_use` to a no-op) would make all three of +`an_import_a_same_file_export_re_exports_through_is_kept`, +`an_item_export_backs_only_the_import_of_that_item` and +`a_star_star_export_backs_every_import` fail (each asserts an outcome that +requires an import to be judged used *only* through the export), while +`a_dpi_export_backs_no_import` would keep passing unchanged (a DPI export +was never marked as backing anything, with or without the fix) — three of +the four tests are load-bearing for this exact fix, one is a control that +correctly does not depend on it. + +**Verdict: PASS.** No HIGH or MEDIUM findings. Two LOW/informational notes +recorded above (the nested-illegal-class scope leak, both directions of which +are safe by construction; and a corpus-reproduction limit of my own +stripping, not of the fix). The HIGH from the prior QA pass — an import +backing a same-file `export` being deleted, corrupting the file per IEEE 1800 +§26.6 — is fixed: every shape in the attack list keeps the import an `export` +needs, the scope boundary the fix claims (`covers(span, t.span)`) holds for +the case that matters (siblings), and the one case where it over-reaches +(an illegal nested export) only ever over-keeps, never under-keeps. + +## Review + +**2026-09-05 — lead.** Accepted after one rework; ships in 0.47.0 with §53. +Putting the judgement in `vlog_semantic` so the refactoring and the rule +read one implementation was the right deviation, and the "used" rule is +deliberately a superset — over-keeping is the safe direction for a +refactoring whose only failure mode is deleting code. That it refuses 33 +of 33 opentitan UVM packages is honest: every one carries a +`` `include "uvm_macros.svh" `` and lucisv does not preprocess, so a name +the scope needs may live in text it never read. QA's HIGH was a real +wrong removal — an `export p::*` is legal only over an import of `p`, and +the judgement had no notion of it — and the fix reads the exports off the +tokens before the reference walk, pinned four ways and re-attacked across +every export shape. The re-attack's LOW (an illegal export nested in a +class leaks upward and over-keeps) is the safe direction and is left as +recorded. The macro/`` `include `` refusal is what decides the feature's +usefulness on verification code; it stays, and is the honest limit of a +tool that does not preprocess. diff --git a/docs/site/dist/pagefind/fragment/en_1a2f59a.pf_fragment b/docs/site/dist/pagefind/fragment/en_1a2f59a.pf_fragment new file mode 100644 index 0000000..37d0f04 Binary files /dev/null and b/docs/site/dist/pagefind/fragment/en_1a2f59a.pf_fragment differ diff --git a/docs/site/dist/pagefind/fragment/en_a668f18.pf_fragment b/docs/site/dist/pagefind/fragment/en_a668f18.pf_fragment deleted file mode 100644 index 89dbce6..0000000 Binary files a/docs/site/dist/pagefind/fragment/en_a668f18.pf_fragment and /dev/null differ diff --git a/docs/site/dist/pagefind/fragment/en_ad63758.pf_fragment b/docs/site/dist/pagefind/fragment/en_ad63758.pf_fragment deleted file mode 100644 index e95e568..0000000 Binary files a/docs/site/dist/pagefind/fragment/en_ad63758.pf_fragment and /dev/null differ diff --git a/docs/site/dist/pagefind/fragment/en_c6caac5.pf_fragment b/docs/site/dist/pagefind/fragment/en_c6caac5.pf_fragment new file mode 100644 index 0000000..aa38385 Binary files /dev/null and b/docs/site/dist/pagefind/fragment/en_c6caac5.pf_fragment differ diff --git a/docs/site/dist/pagefind/index/en_1d5c371.pf_index b/docs/site/dist/pagefind/index/en_1d5c371.pf_index new file mode 100644 index 0000000..57c3999 Binary files /dev/null and b/docs/site/dist/pagefind/index/en_1d5c371.pf_index differ diff --git a/docs/site/dist/pagefind/index/en_30d4d48.pf_index b/docs/site/dist/pagefind/index/en_30d4d48.pf_index new file mode 100644 index 0000000..dce40b9 Binary files /dev/null and b/docs/site/dist/pagefind/index/en_30d4d48.pf_index differ diff --git a/docs/site/dist/pagefind/index/en_3f6ad46.pf_index b/docs/site/dist/pagefind/index/en_3f6ad46.pf_index deleted file mode 100644 index b55be1d..0000000 Binary files a/docs/site/dist/pagefind/index/en_3f6ad46.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/index/en_9adb19f.pf_index b/docs/site/dist/pagefind/index/en_9adb19f.pf_index deleted file mode 100644 index a1c02bb..0000000 Binary files a/docs/site/dist/pagefind/index/en_9adb19f.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/pagefind-entry.json b/docs/site/dist/pagefind/pagefind-entry.json index d832603..3f66f9e 100644 --- a/docs/site/dist/pagefind/pagefind-entry.json +++ b/docs/site/dist/pagefind/pagefind-entry.json @@ -1 +1 @@ -{"version":"1.5.2","languages":{"en":{"hash":"en_bd6347a7d0","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file +{"version":"1.5.2","languages":{"en":{"hash":"en_fc49ef3316","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file diff --git a/docs/site/dist/pagefind/pagefind.en_bd6347a7d0.pf_meta b/docs/site/dist/pagefind/pagefind.en_bd6347a7d0.pf_meta deleted file mode 100644 index 0ff21c4..0000000 Binary files a/docs/site/dist/pagefind/pagefind.en_bd6347a7d0.pf_meta and /dev/null differ diff --git a/docs/site/dist/pagefind/pagefind.en_fc49ef3316.pf_meta b/docs/site/dist/pagefind/pagefind.en_fc49ef3316.pf_meta new file mode 100644 index 0000000..3d7305b Binary files /dev/null and b/docs/site/dist/pagefind/pagefind.en_fc49ef3316.pf_meta differ diff --git a/docs/site/dist/reference/language-tools/index.html b/docs/site/dist/reference/language-tools/index.html index 3e0e270..66451a5 100644 --- a/docs/site/dist/reference/language-tools/index.html +++ b/docs/site/dist/reference/language-tools/index.html @@ -292,6 +292,11 @@ index scope when the defining module lives outside the default folder scope.

Adds, removes, and propagates module ports; expands a .* wildcard into the named connections it stands for (a port with no same-named signal in scope becomes .p() and is named in a warning) — lucisv.expandWildcard; converts a Verilog-2001 header to ANSI, each body declaration merged into the port it described (IEEE 1800 §23.2.2.2) with its comments carried along — lucisv.convertToAnsi +Organize imports +code action (source.organizeImports) / command +Removes the import pkg::*; lines nothing in the scope reaches through, merges exact duplicates and sorts the run at the top of a module, package or class; refuses rather than guesses wherever a macro, a conditional directive, an unknown package or a base class in another file could hide a use — lucisv.organizeImports + + Instantiate module inline completion / lucisv.instantiate Builds an instance from an indexed module interface, including in clients without ghost text @@ -342,4 +347,4 @@ index scope when the defining module lives outside the default folder scope.

The server handles didOpen, incremental didChange, didSave, didClose, watched-file changes, configuration changes, cancellation, shutdown, and exit. It dynamically registers file watchers, emits work-done progress while building large indexes, coalesces code-lens refreshes, and promotes open-buffer overlays into the workspace without waiting for disk writes.

- \ No newline at end of file + \ No newline at end of file diff --git a/docs/site/dist/reference/rules/index.html b/docs/site/dist/reference/rules/index.html index 996be54..97ccc5f 100644 --- a/docs/site/dist/reference/rules/index.html +++ b/docs/site/dist/reference/rules/index.html @@ -70,7 +70,7 @@ })();

Lint rules

73 rules indexed

+

Lint rules

74 rules indexed

Every rule is in one of three severity classes. error is code that would very likely fail to compile, elaborate or synthesize; warning is code that compiles and very likely does not mean what it says; style is code that is correct and reads badly. The class is the word in the CLI diagnostic line (FILE:LINE:COL: warning: …), the severity field of --output-format json, and the colour of the editor’s squiggle — and it is accepted wherever a rule name is, so --ignore style and --select error both work.

Every error-class rule is held to one discipline: it goes silent whenever the run cannot answer — a file that did not fully parse, a module the project does not hold or holds twice, a name a macro produces, a fragment written to be `included. A wrong accusation in that class is worse than a hundred missed ones.

This page is hand-written prose. The generated truth is lucisv check --rules-doc, which prints every rule with its class, default, fix and rationale straight from the registry — and every option a rule takes, with its kind and default.

@@ -454,6 +454,13 @@ Remove ineffective suppressions +unused-import +style +off +safe +Remove an import nothing in the scope reaches through + + void-cast warning on @@ -634,6 +641,8 @@

Reports internal nets or variables with no use. Ports, intentionally unused names, and names mentioned anywhere in raw tokens are excluded — and, over a project, any name another file writes down, since cross-file hierarchy can establish uses a single-file analysis cannot see. That is why the rule runs by default over a directory and stays off for one file.

Reports malformed, unknown, or ineffective waiver comments when their target rule is enabled. A waiver for a disabled rule is not judged.

+ +

An import pkg::*; or import pkg::item; that no reference in its scope — or in a scope nested in it — reaches a name through. “Reaches through” is the binder’s own lookup: the name is not declared closer than the import, and the package exports it (same-file packages by the binder’s tables, others by the workspace index, re-exports included). A qualified use pkg::y does not use the import; an export pkg::… in the same package does (a package may only re-export what it imported, IEEE 1800 §26.6). Off by default, and silent without a project: the rule needs the index to know what a package exports, and it refuses to judge — reporting nothing — where a macro call, a conditional directive, an unknown or twice-declared package, or a base class in another file could hide a use. The safe fix deletes the import line; the Organize imports code action does the same and also merges duplicates and sorts the run.

Reports reg in .sv and .svh files and recommends logic. Verilog .v/.vh files and unnamed stdin are exempt; wire remains valid and is never flagged.

diff --git a/docs/site/src/content/docs/reference/language-tools.md b/docs/site/src/content/docs/reference/language-tools.md index bdaa0f2..b962971 100644 --- a/docs/site/src/content/docs/reference/language-tools.md +++ b/docs/site/src/content/docs/reference/language-tools.md @@ -69,6 +69,7 @@ index scope when the defining module lives outside the default folder scope. | Prepare rename | `textDocument/prepareRename` | Verifies the target and returns its editable range | | Rename | `textDocument/rename` | Renames local or workspace-resolved symbols | | Port actions | code actions / commands | Adds, removes, and propagates module ports; expands a `.*` wildcard into the named connections it stands for (a port with no same-named signal in scope becomes `.p()` and is named in a warning) — `lucisv.expandWildcard`; converts a Verilog-2001 header to ANSI, each body declaration merged into the port it described (IEEE 1800 §23.2.2.2) with its comments carried along — `lucisv.convertToAnsi` | +| Organize imports | code action (`source.organizeImports`) / command | Removes the `import pkg::*;` lines nothing in the scope reaches through, merges exact duplicates and sorts the run at the top of a module, package or class; refuses rather than guesses wherever a macro, a conditional directive, an unknown package or a base class in another file could hide a use — `lucisv.organizeImports` | | Instantiate module | inline completion / `lucisv.instantiate` | Builds an instance from an indexed module interface, including in clients without ghost text | | Apply workspace edit | `workspace/applyEdit` | Delivers multi-file refactor changes to the client | | Show definition | `window/showDocument` | Opens a generated or resolved target after an action | diff --git a/docs/site/src/content/docs/reference/rules.md b/docs/site/src/content/docs/reference/rules.md index d11a2d8..85f1342 100644 --- a/docs/site/src/content/docs/reference/rules.md +++ b/docs/site/src/content/docs/reference/rules.md @@ -3,7 +3,7 @@ title: Lint rules description: Complete reference for every lucisv lint rule, its severity, default, fix, and rationale. --- -73 rules indexed +74 rules indexed Every rule is in one of three **severity** classes. `error` is code that would very likely fail to compile, elaborate or synthesize; `warning` is code that compiles and very likely does not mean what it says; `style` is code that is correct and reads badly. The class is the word in the CLI diagnostic line (`FILE:LINE:COL: warning: …`), the `severity` field of `--output-format json`, and the colour of the editor's squiggle — and it is accepted wherever a rule name is, so `--ignore style` and `--select error` both work. @@ -77,6 +77,7 @@ A rule marked **on (project)** runs by default only where lucisv can see th | [`unknown-port`](#unknown-port) | error | on (project) | — | Connect only ports the module declares | | [`unused-signal`](#unused-signal) | warning | on (project) | — | Detect unreferenced internal signals | | [`unused-waiver`](#unused-waiver) | style | on | — | Remove ineffective suppressions | +| [`unused-import`](#unused-import) | style | off | safe | Remove an `import` nothing in the scope reaches through | | [`void-cast`](#void-cast) | warning | on | — | Cast to `void` only what a call returns | | [`wire-reg-mixup`](#wire-reg-mixup) | error | on | — | Prefer `logic` to `reg` in SystemVerilog | | [`create-object-name-match`](#create-object-name-match) | warning | on | — | Name a `type_id::create` after its handle | @@ -163,6 +164,10 @@ Reports internal nets or variables with no use. Ports, intentionally unused name Reports malformed, unknown, or ineffective waiver comments when their target rule is enabled. A waiver for a disabled rule is not judged. +## unused-import + +An `import pkg::*;` or `import pkg::item;` that no reference in its scope — or in a scope nested in it — reaches a name through. "Reaches through" is the binder's own lookup: the name is not declared closer than the import, and the package exports it (same-file packages by the binder's tables, others by the workspace index, re-exports included). A qualified use `pkg::y` does not use the import; an `export pkg::…` in the same package does (a package may only re-export what it imported, IEEE 1800 §26.6). **Off by default, and silent without a project**: the rule needs the index to know what a package exports, and it refuses to judge — reporting nothing — where a macro call, a conditional directive, an unknown or twice-declared package, or a base class in another file could hide a use. The safe fix deletes the `import` line; the `Organize imports` code action does the same and also merges duplicates and sorts the run. + ## wire-reg-mixup Reports `reg` in `.sv` and `.svh` files and recommends `logic`. Verilog `.v`/`.vh` files and unnamed stdin are exempt; `wire` remains valid and is never flagged. diff --git a/docs/topo.md b/docs/topo.md index 5b86e2e..5cb118d 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -122,6 +122,9 @@ what a change on the pointed-to side must not silently break. | `vlog_linter ──▶ lucisv_core` | depends | `walk::is_excluded`, the `--exclude` matcher, reused for a waiver file's `--location` so one pattern language serves the whole tool (waiver-files, §39, 2026-09-04). `lucisv_core` still depends on nothing, so no cycle. | | `vlog_linter ──▶ vlog_formatter` **(dev-only)** | depends (tests) | The `.lint` fix harness asserts a lint fix never produces text `format_source` refuses. **The library dependency list is still `vlog_parser` + `vlog_semantic` + std** — `cargo tree -p vlog_linter -e normal` is the pinned check. Do not promote this to a normal dep; the fence filter deliberately lives in the front ends instead (see shared-fence-filter, §2.4). | | `vlog_refactor ──▶ vlog_formatter` **(dev-only)** | depends (tests) | expand-wildcard (§50, 2026-09-05): the acceptance tests format and converge what an expansion writes. No production edge. | +| `vlog_refactor ──▶ vlog_semantic` (organize-imports) | depends | `imports::{import_usage, import_scopes, unused_imports, PackageExports, Exports}` — the one "is this import used" judgement, shared with the linter (§52, 2026-09-05). | +| `vlog_linter ──▶ vlog_semantic` (organize-imports) | depends | the same `imports::*` judgement behind the `unused-import` rule; `MentionOracle::package_exports` is a new default method, so no implementor broke (§52). | +| `lucisv_server ──▶ vlog_semantic` (organize-imports) | depends | `WorkspaceIndex::reexported_packages`, read by `lucisv_server::imports` to close the file set over re-exports (§52). | | `vlog_refactor ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant` + diagnostics, `LineIndex`, `TextRange`, the port/instantiation/module AST shapes, `token::is_keyword` (new-name validity), `defines` via the index. Every edit span originates in a parsed node — no textual search-and-replace. | | `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). | | `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache), `atomic::write_atomic` (formatter and lint-fix replacement). (`walk::is_excluded` is `pub` but currently has no consumer outside the crate.) | diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 929552d..82a0344 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -1235,6 +1235,18 @@ "order": 90, "markdownDescription": "**style** — declare an unpacked dimension in increasing order, `[0:N-1]`. On by default." }, + "lucisv.lint.rules.unused-import": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: Off by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 91, + "markdownDescription": "**style** — delete an import nothing uses. Off by default." + }, "lucisv.lint.rules.unused-waiver": { "type": "string", "enum": ["default", "on", "off"], @@ -1244,7 +1256,7 @@ "Never run this rule." ], "default": "default", - "order": 91, + "order": 92, "markdownDescription": "**style** — remove waivers that no longer suppress anything. On by default." }, "lucisv.lint.rules.v2001-generate-begin": { @@ -1256,7 +1268,7 @@ "Never run this rule." ], "default": "default", - "order": 92, + "order": 93, "markdownDescription": "**style** — do not write a bare `begin` block inside a generate region. On by default." } }