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
// 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<String>), 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<String> } // + .message(), .phrase()
pub fn import_usage(sem: &Semantics, tokens: &[Token], scope: ScopeId,
exports: &dyn PackageExports) -> Result<Vec<ImportUse>, String>;
pub fn import_scopes<'t>(tree: &'t SourceFile, sem: &Semantics) -> Vec<ImportScope<'t>>;
pub fn unused_imports(tree: &SourceFile, sem: &Semantics, tokens: &[Token],
exports: &dyn PackageExports) -> Vec<UnusedImport>;
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<RefactorEdit, String>;
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<String>; // 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<Vec<String>>)>;
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:
- From the scope the reference is written in, outward. At each scope, its
own declarations first: a
lookup_localhit shadows — the reference is not the import's, and the walk stops there. - On reaching
S, every import ofSwhose path admits the name (Import::supplies:p::*admits everything,p::xadmitsx) is asked whetherpreally exports it:pdeclared in this file → the binder's own tables (Import::scope, thenScope::lookup_localin the package's scope) — which is literally whatresolve::lexicalconsults;pdeclared elsewhere → the project's member table, which for theWorkspaceIndeximplementation ismembers_of_chain: the unit's own members, itsextendshops, and the packages it re-exports from (§48). That is the same walk ap::xlookup takes, so a name resolution would find through a re-export chain is a name this reports as exported.
- 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, sop::yresolves identically with the import gone. The test is the token before the name —Symbol("::")orSymbol(".")— which is the whole of it. - An import's own package name.
import p::*;recordspas an ordinary use, and counting it would make every import supply its own name to itself. EveryImport::name_spanin 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
importitems, 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)— soimport p::*;sorts beforeimport 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_droppedwould 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 wholeimportline where the body'sa_tresolved through it. Nothing lexical objects; the resolution half says "organizing the imports would change whata_tmeans in m.sv".removing_an_import_nothing_needs_verifies— the same deletion wherea_tis declared locally, which must pass, so the refusal above is a discriminator and not a blanket.
Since take 5 §P1c (2026-09-07) the offer no longer runs this net; the
resolve does. A lazy client's lightbulb is answered by
vlog_refactor::organize_offer{,_in}, which runs the same planner (so the
"removes N, sorts M" count is the one the click will carry) and stops before
verify_splice; codeAction/resolve and lucisv.organizeImports recompute
through organize_imports, which verifies over the identical file set before
any edit leaves the engine. The offer is therefore optimistic in exactly one
way — a plan the verifier would refuse is shown and then refused on the
click with the sentence — which is the contract every other lazy offer
already had (docs/features/lazy-code-action/README.md: "the offer may be
optimistic; the resolve is exact"). No edit reaches an editor unverified.
QA (perf5-p1, P1c) could not construct a plan the verifier refuses that the
planner accepts, so the attack pair below is the pin.
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
importitem 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::trailingandMeta::before_sepof theimportitem 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 inScope::importslike any other — but are never deleted and never sorted. They are notItems, 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_scopesdoes 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
Unknownfor 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 existingpub(super) reexports, for a caller assembling a file set. Additive.vlog_linter::MentionOracle(new default method).package_exports(&self, package: &str) -> Exports, defaulting toExports::Unknown. Every existing implementor keeps compiling and every existing rule is unaffected. Implemented bylucisv_server'sIndexMentions(off the workspace index) and bylucisv'sElsewhere(off a per-file one-file index,vlog_linter::package_exports).lucisvCLI census (widened).Censusgained apackagestable, built only whenunused-importis enabled (reads_packages), and the census is now built for that rule as well as for theneeds_workspaceones. A package the run declares twice, or one writing anyexport 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 onIndexMentions, one new code-action kind (source.organizeImports) incapabilities, one new command incommands(), one new branch inports::execute, and two inserver/dispatch.rs(thecodeActionfan-out and thecodeAction/resolvesplit, which routes by the action'skind).editors/vscode/package.json— thelucisv.lint.rules.*block regenerated bycargo run -p vlog_linter --example vscode_lint_settings.
Status / TODO
- 52.1 engine: used/unused, sort, dedup, refusals
- 52.2
unused-importrule + safe fix + toggle - 52.3 code action (
source.organizeImports, lazy) + command - docs; §8 line annotated; README/site rows (lead — see below)
- 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_testexports one name,stream_driver, and the file's only use of it isstream_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 `includes 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_linterdoes not depend onvlog_refactorand a rule holds one file, not a file set — so the engine function is not reachable from it. The judgement went intovlog_semantic::importsinstead, which both crates already depend on, behind a one-methodPackageExportstrait:WorkspaceIndeximplements it for the refactoring, and the linter'sMentionOracleanswers 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.
Referencecarries no target kind, andResolution::ExternalCandidate'spathscannot distinguish an import pathp::xfrom the pathunit_memberrecords for a writtenp::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)andcls::CONSTrecord their head asTarget::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 itIdentwith a leading backtick (`uvm_info(...)). Found by a failing test, fixed indirectives_clear, which now checks both. sortedcounts only what the run's own edit rewrites, so a title never promises a sort that was already true. (Found by the corpus census reportingsorted=2for 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) andcrates/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'spackagestable and the oracle method onElsewhere.
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 undersource.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 | noimportnothing 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_refactorandvlog_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 bylucisv_server::importsonly.
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.rsserver/dispatch.rs,editors/vscode/package.json, and every existing test (vlog_semantic/src/imports.rsunit tests,vlog_refactor/tests/imports.rs,vlog_linter/src/rules/unused_import.rsunit tests,lucisv_server/src/imports.rsunit tests,lucisv_server/tests/e2e.rs's organize-imports test,vlog_refactor/tests/corpus.rs's §52 census). Builtcargo build --release -p lucisv -p lucisv_server(already current). Added 29 temporary attack tests to a scratchvlog_refactor/tests/qa_attack_imports.rsand a scratchvlog_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):
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:
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 packagec_pkg'sexport 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, socoverscorrectly excludes it. - Nested-inside scope (LOW, informational): an illegal
exportwritten 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, percrates/vlog_parser/src/parser/class.rs's own doc comment — even though IEEE 1800 §26.6 only permitsexportdirectly in a package) does leak upward:exports_useis called once per scope with that scope's ownhere.span, andcoversis 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 disclaimsexport/importlegality 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.