Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94b0711efb | ||
|
|
449b874798 | ||
|
|
4d342367b9 | ||
|
|
a5ca0c9b10 | ||
|
|
acf20f7e62 | ||
|
|
e6eaf53c35 | ||
|
|
ce2f7190ed | ||
|
|
aa479cf701 | ||
|
|
d9ed2c447a |
No files matched your search
@@ -4,6 +4,102 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.48.2 — 2026-09-06
|
||||
|
||||
### The 0.48.0 packages, rebuilt from the right commit
|
||||
|
||||
- **0.48.0's packages were built one commit early** — a release-chain
|
||||
slip tagged the version commit before the feature commit landed, and
|
||||
the tag was moved after the build had started — so its extension lacks
|
||||
the DUT-centred hierarchy view its notes describe. **0.48.1 never
|
||||
built**: its tag caught a concurrent lane's half-written verifier
|
||||
edits. 0.48.2 is the 0.48.0 tree, packaged from the commit that has
|
||||
the view. Nothing else changed.
|
||||
|
||||
## 0.48.0 — 2026-09-06
|
||||
|
||||
### A DUT-centred hierarchy view
|
||||
|
||||
- **Star a module as DUT** from the hierarchy pane's row menu (or the
|
||||
`lucisv.hierarchy.starDut` command, or a checked-in
|
||||
`lucisv.hierarchy.duts` setting, whose entries show locked). Each DUT
|
||||
gets two collapsible sections: the DUT with its instance subtree, the
|
||||
DUT at the very top, and the DUT's parents — an upward tree from the
|
||||
DUT through every module that instantiates it, transitively, which is
|
||||
where the DV bench lands. One section holds every other module: those
|
||||
in no DUT's subtree or ancestor chain, re-rooted where their only
|
||||
parents are DUT ancestors, so a monitor beside the DUT under the same
|
||||
bench stays visible. One DUT → three sections; two → five. A module
|
||||
both below one DUT and above another appears in both DUT sections.
|
||||
With nothing starred the pane is exactly as before. Client-only, over
|
||||
the hierarchy snapshot the server already sends.
|
||||
|
||||
## 0.47.0 — 2026-09-06
|
||||
|
||||
### Organize imports, extract module
|
||||
|
||||
- **Organize imports.** 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; `source.organizeImports`, so an
|
||||
editor's organize-on-save runs it, and `lucisv.organizeImports`. "Used"
|
||||
is the binder's own lookup, read as a superset — over-keeping is the
|
||||
safe direction — and an `export pkg::…` in the same package counts as a
|
||||
use of its import (IEEE 1800 §26.6). It refuses rather than guesses
|
||||
wherever a macro call, a conditional directive, an unknown or
|
||||
twice-declared package, or a base class in another file could hide a
|
||||
use, which is why every opentitan UVM package (all carrying
|
||||
`` `include "uvm_macros.svh" ``) is refused. The same judgement is the
|
||||
new `unused-import` rule (Style, off by default, safe fix).
|
||||
- **Extract module.** Select whole module items and give a name: the
|
||||
items become a new module with ports inferred from dataflow across the
|
||||
selection (read only → `input`, written → `output`, written on both
|
||||
sides → refused), parameters passed through, used imports copied, and
|
||||
the selection replaced by an instantiation rendered from the new
|
||||
module's own text. Written to a new file when the client can create
|
||||
one, below the source module otherwise. Forty-three refusal sentences
|
||||
for what lucisv cannot judge (a routine argument, a hierarchical path
|
||||
crossing the boundary, an interface-typed name, a `typedef` of the
|
||||
source module, …). `refactor.extract` code action, `lucisv.extractModule`,
|
||||
and a name prompt in the VS Code extension. Inline module follows in a
|
||||
later release.
|
||||
- **The verifier's never-dropped ledger follows a move.** For the bytes
|
||||
an extraction moves, a comment or attribute deleted inside the moved
|
||||
region must land exactly once in the file the move names; a deletion
|
||||
outside the region stays an ordinary deletion that must be written
|
||||
back in its own file. Opt-in per edit, four equations, twelve attack
|
||||
pairs through the production entry, re-attacked by QA.
|
||||
|
||||
## 0.46.0 — 2026-09-05
|
||||
|
||||
### Two refactorings: expand `.*`, convert ports to ANSI
|
||||
|
||||
- **Expand `.*`.** A wildcard connection is written out as the named
|
||||
connections it stands for, in the module's declaration order, through
|
||||
the port engine's splice and verifier. The wildcard rule is read
|
||||
strictly (IEEE 1800 §23.3.2.4): a same-named net, variable or port
|
||||
binds; a parameter, genvar, type or instance does not, and that port
|
||||
becomes `.p()` with a warning naming it. Refused inside a `bind`
|
||||
directive, on a positional list, on two `.*`, or when a file does not
|
||||
parse. Code action `lucisv: expand .* (N connections)` and command
|
||||
`lucisv.expandWildcard`.
|
||||
- **Convert ports to ANSI.** A Verilog-2001 header with body
|
||||
declarations becomes an ANSI header (`output b; reg [7:0] b;` →
|
||||
`output reg [7:0] b`, every merge of §23.2.2.2), the absorbed
|
||||
declarations deleted and their comments carried onto the ports. The
|
||||
edit inserts around each header name so nothing that referenced the
|
||||
port moves; twenty-three shapes are refused with a sentence rather
|
||||
than guessed (port expressions, disagreeing ranges, initialisers,
|
||||
directives, a comment that would have to move into a one-line list).
|
||||
Code action `lucisv: convert ports to ANSI (N ports)` and command
|
||||
`lucisv.convertToAnsi`.
|
||||
- **The refactoring verifier's comment rule is stricter, and covers
|
||||
attributes.** Every comment and every `(* … *)` attribute a file had it
|
||||
still has, by exact text and count; a piece a deletion covers is
|
||||
written back exactly as many times as it was deleted, and an edit may
|
||||
not duplicate one nothing touched — which also catches a comment
|
||||
rewritten, truncated or duplicated. Ships with masked-corruption
|
||||
attack tests, re-attacked by QA.
|
||||
|
||||
## 0.45.0 — 2026-09-05
|
||||
|
||||
### Cross-file semantics: type spans, re-exports, hierarchical tails
|
||||
|
||||
Generated
+9
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -265,19 +265,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.45.0"
|
||||
version = "0.48.2"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -710,8 +710,54 @@ section only tracks the milestones.
|
||||
- [x] **M14 `macro-expansion`** — single-step macro expansion on hover
|
||||
(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.
|
||||
- [ ] Backlog (~~extract module~~, inline, ~~`.*` expansion~~, ~~ANSI
|
||||
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
|
||||
action and `lucisv.expandWildcard`. It leaves one thing behind, added to
|
||||
this backlog: **a `.*` written in a `bind` directive**, which binds in the
|
||||
target's scope rather than the one it is written in — elaboration, not
|
||||
lexical lookup, and 57 of OpenTitan's 66 wildcard sites.
|
||||
**Non-ANSI → ANSI conversion shipped 2026-09-05 (§51,
|
||||
`docs/features/ansi-conversion/README.md`)**: a Verilog-2001 header rewritten
|
||||
the modern way, each port declaration merged with the net or variable
|
||||
declaration that completes it per IEEE 1800 §23.2.2.2, with a code action and
|
||||
`lucisv.convertToAnsi`. It leaves two things behind, added to this backlog:
|
||||
**an `interface`'s non-ANSI header**, which needs the `modport`s that name
|
||||
the same ports read first; and **an attribute instance on an absorbed
|
||||
declaration** (`(* keep *) input a;`), which the conversion refuses rather
|
||||
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.
|
||||
**Extract module shipped 2026-09-05 (§53.1,
|
||||
`docs/features/extract-inline-module/README.md`)**: a selection of whole
|
||||
module items becomes a module of its own, with ports and parameters inferred
|
||||
from the dataflow across the boundary, the `import`s it needs carried across,
|
||||
and the instantiation that replaces it rendered from the new module's own
|
||||
text — into a file beside its own where the editor can create one, below the
|
||||
module it came from where it cannot. `refactor.extract` plus
|
||||
`lucisv.extractModule`, whose name comes from an input box the VS Code
|
||||
extension puts in front of it. **Inline module (§53.2) is not started**, so
|
||||
the backlog line above keeps it. Extract leaves four things behind, added to
|
||||
this backlog: **a task or function used on both sides** of the selection,
|
||||
which would have to move or be duplicated; **a hierarchical reference**
|
||||
crossing the boundary, which no port can carry; **an `initial`/`final`
|
||||
block**, whose meaning is when it runs; and **an unpacked-array or
|
||||
interface-typed name** crossing, which the port renderer will not write.
|
||||
|
||||
## 9. LSP 3.18 protocol audit (2026-08-26)
|
||||
|
||||
@@ -4594,8 +4640,10 @@ lead, a release every two or three sections:
|
||||
0.44.0 → §47 `DataType` spans, retire `scan.rs` (topo 2) → §48 package
|
||||
re-exports (topo 16) → §49 cross-file instance-member tail in rename
|
||||
(topo 23) → 0.45.0 → §50 `.*` expansion → §51 non-ANSI → ANSI ports →
|
||||
0.46.0 → §52 organize imports → §53 extract / inline module → 0.47.0 →
|
||||
§54 coverage gaps L3/L6/L10 → 0.48.0. Sections after §46 are planned when
|
||||
0.46.0 → §52 organize imports → §53.1 extract module → 0.47.0 →
|
||||
**§56 DUT-centred hierarchy view (owner request 2026-09-06) → 0.48.0** →
|
||||
§53.2 inline module (its own lane; 53.1 consumed the round, as planned)
|
||||
→ §54 coverage gaps L3/L6/L10 → 0.49.0. Sections after §46 are planned when
|
||||
reached.
|
||||
|
||||
## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22
|
||||
@@ -4985,12 +5033,12 @@ declines a wildcard site).
|
||||
under `hw/ip` and expand ten of them into scratch copies, each result
|
||||
formatting cleanly and parsing with the same instance count.
|
||||
|
||||
- [ ] 50.1 `expand_wildcard` engine + refusals
|
||||
- [ ] 50.2 code action (lazy) + command
|
||||
- [ ] docs: feature README; README/site rows (lead applies); §8 line
|
||||
- [x] 50.1 `expand_wildcard` engine + refusals
|
||||
- [x] 50.2 code action (lazy) + command
|
||||
- [x] docs: feature README; README/site rows (lead applies); §8 line
|
||||
annotated
|
||||
- [ ] Gates (guarded); byte-identity vs 0.45.0
|
||||
- [ ] QA: the LRM rule attacked (kinds, scopes, generate, parameters);
|
||||
- [x] Gates (guarded); byte-identity vs 0.45.0
|
||||
- [x] QA: the LRM rule attacked (kinds, scopes, generate, parameters);
|
||||
refusals; ten opentitan sites in scratch copies
|
||||
|
||||
## 51. Non-ANSI → ANSI port conversion (planned 2026-09-05) — the second §8 refactoring
|
||||
@@ -5044,10 +5092,355 @@ parses" verifier is the safety net; this is the whole-header version.
|
||||
non-ANSI modules under `hw/vendor` and ten conversions into scratch
|
||||
copies.
|
||||
|
||||
- [ ] 51.1 `convert_to_ansi` engine + refusals
|
||||
- [ ] 51.2 code action (lazy) + command
|
||||
- [ ] docs: feature README; README/site rows (lead applies); §8 line
|
||||
- [x] 51.1 `convert_to_ansi` engine + refusals — `ports/ansi.rs` (the planner)
|
||||
plus `ports/merge.rs` (IEEE 1800 §23.2.2.2), 23 refusals, each a sentence
|
||||
- [x] 51.2 code action (lazy) + command — the fourth `port_actions` offer, so
|
||||
both offer paths get it; `lucisv.convertToAnsi` is the fifth command
|
||||
- [x] docs: feature README; README/site rows (lead applies); §8 line
|
||||
annotated
|
||||
- [ ] Gates (guarded); byte-identity vs 0.45.0; the corpus conversion census
|
||||
- [ ] QA: every §23.2.2.2 merge rule attacked; comments; refusals; the
|
||||
corpus census re-derived; opentitan scratch conversions
|
||||
- [x] Gates (guarded); byte-identity vs 0.45.0; the corpus conversion census
|
||||
— **zero non-ANSI headers in corpus/ and in all of OpenTitan**, so the
|
||||
acceptance material is real ANSI headers made non-ANSI and converted
|
||||
back: 5 in the shipped suite, 290 verified under `hw/ip`
|
||||
- [x] QA: every §23.2.2.2 merge rule attacked; comments; refusals; the
|
||||
corpus census re-derived; opentitan scratch conversions — verdict
|
||||
REWORK, two findings in `docs/features/ansi-conversion/README.md`'s
|
||||
QA log (V-1: `comments_kept` forgives a duplicated *untouched*
|
||||
comment, no attack test; V-2: an attribute on an absorbed
|
||||
declaration is silently dropped)
|
||||
|
||||
## 52. Organize imports (planned 2026-09-05) — the third §8 refactoring
|
||||
|
||||
One lane after 0.46.0, §36's protocol. Feature README:
|
||||
`docs/features/organize-imports/README.md`. Ships in 0.47.0 with §53.
|
||||
|
||||
`import pkg::*;` / `import pkg::item;` items accumulate at the top of a
|
||||
module, package, class or compilation unit. "Organize" 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. The same computation is a
|
||||
lint rule, `unused-import` (Style, default off; safe fix = the removal),
|
||||
so the editor squiggles what the action would delete.
|
||||
|
||||
- **What "used" means (the whole risk).** An import `p::*` in scope S is
|
||||
used when some reference in S or a scope nested in S resolves to a
|
||||
member of `p` *through that import* — i.e. the name is not declared
|
||||
locally between the reference and S, and `p` exports it (same-file
|
||||
package: the binder's own tables; cross-file: the index's member table
|
||||
for `p`, including §48's re-exports). `p::x` is used when `x` is
|
||||
referenced that way. A qualified use `p::y` does NOT use the import.
|
||||
**Refuse to judge — never remove — when `p` is unknown to the index
|
||||
(not indexed, or in an unindexed scope), when `p` is declared twice,
|
||||
when S or any nested scope contains a macro call or a conditional
|
||||
directive (a name may live in text lucisv did not read), when S is a
|
||||
class with a base class outside the file (an inherited member could be
|
||||
the use), or when the file has a parse diagnostic.** The verifier's
|
||||
resolution check is the second net: after the edit every reference in
|
||||
the file must resolve to what it resolved to before (that is what the
|
||||
ports engine's `verify_splice` already asserts — reuse it).
|
||||
- **Engine** (`vlog_refactor`, new `imports.rs` + `imports/` if it grows):
|
||||
`organize_imports(files, file, offset) -> Result<RefactorEdit, String>`
|
||||
for the scope at the cursor (the innermost module/package/class/unit),
|
||||
and `unused_imports(files, file) -> Vec<(TextRange, reason)>` for the
|
||||
rule. Edits: deletions of whole `import` items (with their line) and
|
||||
one replacement for the sorted run; an import that carries a comment
|
||||
is never deleted (refuse with a sentence: "delete the comment first")
|
||||
and is sorted with its comment attached (the `pieces` rule of §51's
|
||||
verifier). Exact duplicates keep the first.
|
||||
- **Rule** `unused-import` in `vlog_linter` (Style, default off; option
|
||||
none), reading the same engine function through the project-facts
|
||||
oracle the semantic rules use (`ctx.mentioned_elsewhere`-style —
|
||||
whatever gives the index's member table; if the linter cannot reach it
|
||||
in single-file mode, the rule is silent there, as `unused-signal` is).
|
||||
Safe fix: delete the item. Docs row + toggle regenerated.
|
||||
- **Server:** code action `lucisv: organize imports (removes N, sorts M)`
|
||||
on a cursor in an import run or the scope header (lazy per §37.1),
|
||||
`source.organizeImports` kind so editors' organize-on-save wires it;
|
||||
command `lucisv.organizeImports [uri, position]`.
|
||||
- Tests: engine — used/unused for `*` and item forms, same-file and
|
||||
cross-file packages, a re-export chain (§48), a name shadowed locally
|
||||
(import unused), a nested class using the outer scope's import (used),
|
||||
duplicates, sort order with mixed `*`/items, comments on imports (kept,
|
||||
moved with their line, deletion refused), every refusal; the verifier's
|
||||
resolution check catches a wrong removal (an attack pair: remove an
|
||||
import a reference needs → must be refused); idempotency; corpus census
|
||||
over every scope with ≥ 2 imports: organize in a scratch copy, result
|
||||
parses/formats/converges, resolution counts unchanged, counts of
|
||||
removed/sorted/refused reported. Rule — true positives, near-misses,
|
||||
the census over the corpus with counts. Server — offer/resolve, the
|
||||
`source.organizeImports` kind honoured on `codeAction` with `only`,
|
||||
the command; opentitan read-only: UVM env packages (`hw/ip/*/dv/env/*_pkg.sv`)
|
||||
organized into scratch copies, counts, and every "unused" claim
|
||||
checked by grep for the package's members in the file.
|
||||
|
||||
- [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.
|
||||
|
||||
- [x] 53.1 extract: dataflow ports, parameters, imports, the new file,
|
||||
refusals, action + command + extension input box
|
||||
- [ ] 53.2 inline: substitution, prefixing, refusals, action + command
|
||||
— **unstarted**; §53.1 alone took the round
|
||||
- [ ] the extract → inline round trip pinned — blocked on 53.2
|
||||
- [x] docs; §8 line annotated (extract only); site rows (lead — see the
|
||||
feature README's "Docs to apply at merge")
|
||||
- [x] Gates (guarded); byte-identity vs 0.46.0; corpus scratch checks
|
||||
- [x] 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
|
||||
|
||||
## 54. Coverage gaps L3, L6, L10 (planned 2026-09-06) — the owner's "do all three"
|
||||
|
||||
One lane after 0.47.0, §36's protocol. Feature README:
|
||||
`docs/features/coverage-gaps-l/README.md`. Ships in 0.48.0. Every item is
|
||||
a grammar arm with its formatter twin, the snapshot + idempotency suite,
|
||||
strict/tolerant parity, and the byte-identity gates; none of these shapes
|
||||
occur in the corpus or opentitan (say so per item with the grep), so the
|
||||
acceptance is hand-written cases plus the fuzzers.
|
||||
|
||||
### 54.1 L6 — the language shapes
|
||||
|
||||
- `->>` non-blocking event trigger (`->> e;`, `->> #5 e;`, `->> @(posedge clk) e;`).
|
||||
- Stream operator `with [range]` (`{<< {a with [0:3]}}`, `[i+:4]`, `[i-:4]`).
|
||||
- Cast bases other than a name or system call: a parenthesised width
|
||||
`(W+1)'(x)`, a sized literal `4'(x)`, a type with dims `logic [3:0]'(x)`
|
||||
— the LRM's `casting_type` (§6.24.1).
|
||||
- Drive strength on a net declaration: `wire (strong0, weak1) w = a;`,
|
||||
`wire (supply0, supply1) [7:0] v;` — `DataDecl` gains the strength the way
|
||||
`ContAssign` already carries one (`parse_opt_drive_strength` exists).
|
||||
- `let` at statement position (a `let` declared inside a sequential block
|
||||
/ procedural scope, IEEE 1800 §11.13).
|
||||
- `#(min:typ:max)` clocking skew: `default input #(1:2:3) output #(2:3:4);`
|
||||
and per-signal skews.
|
||||
Each: parser arm, AST field with comment slots where a gap opens (the
|
||||
comment-slots gap fuzzer's zero-failure bar), formatter arm, cases file,
|
||||
strict/tolerant parity, `size_pins` unmoved.
|
||||
|
||||
### 54.2 L3 — `randsequence` bodies
|
||||
|
||||
`randsequence (main) main : first second; first : { $display("a"); };
|
||||
second : third | fourth := 2; …; endsequence` — a production grammar (IEEE
|
||||
1800 §18.17): productions with optional return types and arguments,
|
||||
weighted alternatives `:=`, `rand join`, `repeat`, `if`/`case`, code
|
||||
blocks, `break`/`return`. Today an opaque `Verbatim` leaf? Check
|
||||
(`grep -rn randsequence crates/vlog_parser/src`). Ruling: model the
|
||||
production list and alternatives as real nodes (a `RandSequence` statement
|
||||
with `Production { name, ret_type, args, alternatives: Vec<Alternative {
|
||||
weight, items }> }`, items being production references or a code block
|
||||
parsed as a statement block); the formatter prints one production per
|
||||
line, alternatives aligned after `:` / `|`; comment slots per production.
|
||||
Zero corpus occurrences — a pure-LRM feature; the LRM's own examples are
|
||||
the cases.
|
||||
|
||||
### 54.3 L10 — cosmetics
|
||||
|
||||
- An enum body one-lined when short: `typedef enum {A, B, C} e_t;` stays on
|
||||
one line when it fits the width and has no comments — today it always
|
||||
breaks? Confirm with a case; make the group breakable the way a port list
|
||||
is (`Doc::Group`), so long bodies still break one per line. **Byte
|
||||
identity WILL change** for corpus files with short enums: measure the
|
||||
count, list them, and the lead rules at review whether the change is
|
||||
wanted (the corpus has ibex/opentitan enums — likely dozens of files).
|
||||
- `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin ``
|
||||
column: macro statements between `_begin`/`_end` are plain macro items
|
||||
with no block for the formatter to see; a targeted rule — a macro
|
||||
statement whose name matches `uvm_object_utils_begin`/`uvm_component_utils_begin`
|
||||
opens an indent level closed by `uvm_object_utils_end`/`uvm_component_utils_end`
|
||||
— in the item/statement sequence printer, gated on exactly those names.
|
||||
Byte identity changes for UVM files that already indent them — measure
|
||||
and list.
|
||||
Both cosmetics are **off by default behind a config key** if the corpus
|
||||
count is large: `[format] enum-one-line = true|false`, `[format]
|
||||
uvm-utils-indent = true|false`, default false, so 0.48.0 changes no
|
||||
byte for anyone who does not opt in; the lead decides the defaults at
|
||||
review from the counts.
|
||||
|
||||
- [ ] 54.1 the six L6 shapes, each with cases + parity + fuzzers
|
||||
- [ ] 54.2 `randsequence` as real nodes
|
||||
- [ ] 54.3 the two cosmetics behind config keys, corpus impact measured
|
||||
- [ ] docs; coverage_gaps L3/L6/L10 struck; README/site config keys (lead)
|
||||
- [ ] Gates (guarded); byte-identity vs 0.47.0 (0 differing with the keys
|
||||
off); opentitan sweep unchanged
|
||||
- [ ] QA: every shape with comments in every gap; the fuzzers; the keys on
|
||||
over the corpus in a scratch copy (idempotent, comments kept)
|
||||
|
||||
## 56. DUT-centred hierarchy view (owner request 2026-09-06)
|
||||
|
||||
The next lane after 0.47.0 ships — ahead of §53.2 and §54, at the owner's
|
||||
request. One lane, §36's protocol; dev Opus 5, QA Sonnet 5. Feature README:
|
||||
`docs/features/dut-hierarchy/README.md`. Ships in 0.48.0.
|
||||
|
||||
**What the owner asked for, verbatim in substance.** A design holds many
|
||||
modules and one (or a few) is the DUT — the module that matters most. It
|
||||
usually has DV above it (a testbench that instantiates it). The hierarchy
|
||||
pane should let the user right-click any module and **star it as DUT**.
|
||||
With one DUT starred the pane shows three sections: **the DUT with its
|
||||
children** (its instance subtree, the DUT at the very top), **the DUT's
|
||||
parents** (every module that instantiates it, transitively — typically the
|
||||
DV — as a tree explored upward from the DUT), and **all other modules**
|
||||
(everything that is neither below nor above any DUT), each section
|
||||
collapsible. Two DUTs starred → five sections: DUT1 + children, DUT1
|
||||
parents, DUT2 + children, DUT2 parents, all other modules. Unstar from the
|
||||
same menu.
|
||||
|
||||
**Where it lives.** Entirely in the extension over the existing flat
|
||||
snapshot (`lucisv/moduleHierarchy`: `files`, `modules`, `instances`;
|
||||
`hierarchyModel.js::buildHierarchy` already builds the forward tree and
|
||||
chooses roots) — the server changes nothing. The reverse map (module →
|
||||
instantiating modules, via each instance's owning module) is one pass over
|
||||
the same snapshot in the model. DUT choices persist per workspace in
|
||||
`workspaceState` (a list of module names, in the order starred), the way
|
||||
the existing bookmark does (`hierarchyView.js` `BOOKMARK_KEY`).
|
||||
|
||||
- **Model** (`hierarchyModel.js`): `sections(model, duts)` returning, in
|
||||
order, for each starred DUT `{ kind: 'dut', name, root }` (the DUT's
|
||||
forward subtree, exactly the node the plain view would show for it) and
|
||||
`{ kind: 'parents', name, root }` (an upward tree: the DUT as the root,
|
||||
each child a module that instantiates the parent node — with the
|
||||
instance name that does it — recursing up until a module nothing
|
||||
instantiates; cycles cut with a visited set), then
|
||||
`{ kind: 'others', roots }` = today's roots minus every module that is in
|
||||
any DUT's subtree or ancestor chain (a module both below DUT1 and above
|
||||
DUT2 appears in both DUT sections and not in others). A starred name the
|
||||
snapshot no longer holds (renamed/deleted) keeps its section with an
|
||||
empty "not in the index" row rather than vanishing silently.
|
||||
- **View** (`hierarchyView.js`): section nodes as collapsible tree items
|
||||
with icons (`debug-start`-style for a DUT, an upward arrow for parents,
|
||||
a folder for others), the DUT section expanded by default, others
|
||||
collapsed; DUT rows carry a `contextValue` so the menu shows
|
||||
"Unstar DUT" on a starred module and "Star as DUT" on any other; the
|
||||
existing search, reveal-on-open and bookmark behaviour work inside every
|
||||
section; when no DUT is starred the pane looks exactly as today (pin it
|
||||
— the snapshot-to-tree output byte-identical to the current tests).
|
||||
- **Commands + menus** (`package.json`): `lucisv.hierarchy.starDut`,
|
||||
`lucisv.hierarchy.unstarDut`, `lucisv.hierarchy.clearDuts`; `view/item/context`
|
||||
entries gated on `viewItem`; a `view/title` "Clear DUTs". Also a setting
|
||||
`lucisv.hierarchy.duts` (string array) as the second way to set them
|
||||
(a checked-in `.vscode/settings.json` for a team) — the union with the
|
||||
starred list, the setting's entries shown with a lock icon and not
|
||||
unstar-able from the menu (say so in a tooltip).
|
||||
- **Tests** (`node --test editors/vscode/*_test.js`, the existing model
|
||||
tests' harness): sections for zero, one and two DUTs on a fixture with a
|
||||
DV bench above a DUT above three leaves plus two unrelated modules; a
|
||||
module both below one DUT and above another; a cycle (`a` instantiates
|
||||
`b` instantiates `a`) in the parents walk; a starred name absent from the
|
||||
snapshot; the others section excludes exactly the right set; the plain
|
||||
view unchanged with no DUT; persistence round trip through a fake
|
||||
`workspaceState`; the setting union and lock; the menu `when` clauses.
|
||||
Manual: a checklist entry in `docs/manual-acceptance.md` (star aes in
|
||||
opentitan → three sections; star aes and hmac → five; unstar).
|
||||
- Docs: the extension README's hierarchy section, the site's editors page
|
||||
(lead applies), the feature README.
|
||||
|
||||
- [x] 56.1 model: reverse map, `sections()`, others-exclusion, cycle cut
|
||||
- [x] 56.2 view: section nodes, icons, context values, persistence,
|
||||
setting union
|
||||
- [x] 56.3 commands, menus, package.json, tests, acceptance checklist row
|
||||
- [ ] docs (lead applies README/site)
|
||||
- [x] Gates: `node --test editors/vscode/*_test.js`; vsix smoke; the plain
|
||||
view pinned unchanged
|
||||
- [x] QA: every section shape attacked on the fixture and on opentitan
|
||||
(real snapshot, read-only); persistence; the setting; menus
|
||||
+61
-10
@@ -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<String, Option<vlog_linter::ModuleInterface>>,
|
||||
/// 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<String, Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
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<String>, Vec<(String, Option<vlog_linter::ModuleInterface>)>);
|
||||
fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census {
|
||||
type PerFile = (
|
||||
Vec<String>,
|
||||
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
|
||||
Vec<(String, Option<Vec<String>>)>,
|
||||
);
|
||||
let per_file: Vec<PerFile> = 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<String, u32> = HashMap::new();
|
||||
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
|
||||
for (words, declared) in per_file {
|
||||
let mut exported: HashMap<String, Option<Vec<String>>> = 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<vlog_linter::ModuleInterface> {
|
||||
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<vlog_linter::ModuleInterface> {
|
||||
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() {
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Extract a selection into a module of its own, on the wire:
|
||||
//! `textDocument/codeAction` under LSP's own `refactor.extract`, and
|
||||
//! `workspace/executeCommand` for the editors that have no lightbulb.
|
||||
//!
|
||||
//! Protocol only. The edit is `vlog_refactor::extract_module`; this module
|
||||
//! decides which files that engine is handed, turns its answer into a
|
||||
//! `WorkspaceEdit`, and turns its refusal into a request error.
|
||||
//!
|
||||
//! **The action carries a command, not an edit** — which is what makes it the
|
||||
//! laziest of the lot rather than merely a lazy one. Extracting needs a *name*
|
||||
//! for the new module, and LSP has no prompt: a code action can carry an
|
||||
//! `edit`, a `command`, or both, and only a command can be intercepted by a
|
||||
//! client that wants to ask the user something first. So the offer is one
|
||||
//! parse of one buffer (`vlog_refactor::extract_site`) plus a `Command` naming
|
||||
//! [`EXTRACT_MODULE`] and the default name `M_extracted`; the VS Code
|
||||
//! extension registers a client-side command of the same name that shows an
|
||||
//! input box and calls the server's with what the user typed, and every other
|
||||
//! client runs the command as sent and gets the default. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
//!
|
||||
//! **The new file.** A module extracted into a file of its own is a
|
||||
//! `CreateFile` resource operation, which only a client that advertises
|
||||
//! `workspace.workspaceEdit.documentChanges` *and* `resourceOperations`
|
||||
//! containing `create` can apply. That capability is read at `initialize`
|
||||
//! ([`crate::server::ClientAbilities::create_files`]) and is the whole of the
|
||||
//! choice between the two homes: a client that can create files gets `N.sv`
|
||||
//! beside `M`'s file, and every other client gets `N` written below `M` in the
|
||||
//! file it came from. The engine says which happened in its warnings.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use lsp_types::{
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, Command, CreateFile, DocumentChangeOperation,
|
||||
DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier, Range, ResourceOp,
|
||||
TextDocumentEdit, TextEdit, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{Home, RefactorEdit};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// Extract a selection into a module: `[uri, range, name]`.
|
||||
pub const EXTRACT_MODULE: &str = "lucisv.extractModule";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![EXTRACT_MODULE.to_string()]
|
||||
}
|
||||
|
||||
/// The kind LSP reserves for an extraction, which is what an editor's
|
||||
/// "Refactor…" menu asks for by name.
|
||||
pub fn kind() -> CodeActionKind {
|
||||
CodeActionKind::REFACTOR_EXTRACT
|
||||
}
|
||||
|
||||
/// The action for a selection, carrying the command that will ask for a name.
|
||||
///
|
||||
/// One parse of the buffer and nothing else: the engine's cheap gate answers
|
||||
/// "there is nothing here" for almost every selection, and where it does find
|
||||
/// something the offer is a `Command`, so no workspace is read until the user
|
||||
/// has picked the action *and* named the module.
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
if doc.path.is_none() {
|
||||
// An `untitled:` buffer has no directory to put `N.sv` beside and no
|
||||
// path for the engine's file set; nothing is offered rather than
|
||||
// offered and refused.
|
||||
return Vec::new();
|
||||
}
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range).unwrap_or(Value::Null),
|
||||
Value::String(site.default_name.clone()),
|
||||
];
|
||||
let title = vlog_refactor::extract_title();
|
||||
vec![CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: title.clone(),
|
||||
kind: Some(kind()),
|
||||
command: Some(Command {
|
||||
title,
|
||||
command: EXTRACT_MODULE.to_string(),
|
||||
arguments: Some(arguments),
|
||||
}),
|
||||
..Default::default()
|
||||
})]
|
||||
}
|
||||
|
||||
/// Run `lucisv.extractModule`, or say why it cannot run.
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
arguments: &[Value],
|
||||
create_files: bool,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let uri: Uri = argument(arguments, 0, "a document URI")?;
|
||||
let range: Range = argument(arguments, 1, "a range")?;
|
||||
let name: String = argument(arguments, 2, "a name for the new module")?;
|
||||
let doc = ws
|
||||
.document(&uri)
|
||||
.ok_or_else(|| "lucisv can only extract from an open file.".to_string())?;
|
||||
let path = doc
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?;
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine looks up every module the selection instantiates and every
|
||||
// package it imports, so the file set is those units' own fan-out — plus
|
||||
// the new name's, so a workspace that already declares it is a workspace
|
||||
// the engine can refuse over.
|
||||
let mut units = site.units;
|
||||
units.push(name.clone());
|
||||
let files = ws.module_sources(&path, &units);
|
||||
let home = match create_files {
|
||||
true => Home::NewFile,
|
||||
false => Home::SameFile,
|
||||
};
|
||||
let refactoring = vlog_refactor::extract_module(&files, &path, start, end, &name, home)?;
|
||||
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
/// A whole extraction as a `WorkspaceEdit`.
|
||||
///
|
||||
/// `documentChanges` rather than `changes` whenever a file is created: a
|
||||
/// creation is a resource operation, and the two shapes cannot be mixed in one
|
||||
/// edit. An extraction that creates nothing goes through the ordinary
|
||||
/// `changes` map, which every client understands.
|
||||
pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<WorkspaceEdit, String> {
|
||||
if refactoring.created.is_empty() {
|
||||
return crate::ports::workspace_edit(ws, refactoring);
|
||||
}
|
||||
let mut operations: Vec<DocumentChangeOperation> = Vec::new();
|
||||
for path in &refactoring.created {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
operations.push(DocumentChangeOperation::Op(ResourceOp::Create(CreateFile {
|
||||
uri,
|
||||
options: None,
|
||||
annotation_id: None,
|
||||
})));
|
||||
}
|
||||
for (path, edits) in &refactoring.edits {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
// A file the edit creates has no text yet, and the one insertion into
|
||||
// it is at 0:0 — which is what `Positions` over an empty text says.
|
||||
let created = refactoring.created.iter().any(|created| created == path);
|
||||
let text = match created {
|
||||
true => String::new(),
|
||||
false => ws.text_of(path).ok_or_else(|| unaddressable(path))?,
|
||||
};
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
operations.push(DocumentChangeOperation::Edit(TextDocumentEdit {
|
||||
text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
|
||||
edits: edits
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
OneOf::Left(TextEdit {
|
||||
range: positions.range(edit.range),
|
||||
new_text: edit.new_text.clone(),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
}));
|
||||
}
|
||||
Ok(WorkspaceEdit {
|
||||
document_changes: Some(DocumentChanges::Operations(operations)),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn argument<T: serde::de::DeserializeOwned>(
|
||||
arguments: &[Value],
|
||||
n: usize,
|
||||
what: &str,
|
||||
) -> Result<T, String> {
|
||||
arguments
|
||||
.get(n)
|
||||
.and_then(|value| serde_json::from_value(value.clone()).ok())
|
||||
.ok_or_else(|| format!("{EXTRACT_MODULE} wants {what} as argument {}.", n + 1))
|
||||
}
|
||||
|
||||
fn unaddressable(path: &std::path::Path) -> String {
|
||||
format!("lucisv could not address {} as a document; no edits were made.", path.display())
|
||||
}
|
||||
|
||||
const NOTHING: &str = "there is nothing to extract at this selection.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use lsp_types::Position;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// 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_extract_{}_{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 TOP: &str = "\
|
||||
module top (
|
||||
input logic [7:0] a,
|
||||
input logic [7:0] b,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] s;
|
||||
assign s = a + b;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn opened(tree: &Tree) -> (Workspace, Uri) {
|
||||
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 range of `assign s = a + b;`, as the client speaks it.
|
||||
fn selection() -> Range {
|
||||
Range {
|
||||
start: Position { line: 6, character: 2 },
|
||||
end: Position { line: 6, character: 19 },
|
||||
}
|
||||
}
|
||||
|
||||
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
|
||||
actions
|
||||
.into_iter()
|
||||
.filter_map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => Some(action),
|
||||
CodeActionOrCommand::Command(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name() {
|
||||
let tree = Tree::new("offer");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let actions = only(code_actions(&ws, &uri, selection()));
|
||||
let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") };
|
||||
assert_eq!(action.title, "lucisv: extract selection into module…");
|
||||
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_EXTRACT));
|
||||
assert!(action.edit.is_none(), "the offer reads no workspace");
|
||||
let command = action.command.as_ref().expect("a command");
|
||||
assert_eq!(command.command, EXTRACT_MODULE);
|
||||
let arguments = command.arguments.as_ref().expect("arguments");
|
||||
assert_eq!(arguments.len(), 3);
|
||||
assert_eq!(arguments[2], Value::String("top_extracted".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_covers_no_whole_item_is_offered_nothing() {
|
||||
let tree = Tree::new("nothing");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let half = Range {
|
||||
start: Position { line: 6, character: 2 },
|
||||
end: Position { line: 6, character: 8 },
|
||||
};
|
||||
assert!(code_actions(&ws, &uri, half).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_creates_the_new_file_for_a_client_that_can() {
|
||||
let tree = Tree::new("create");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(selection()).expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments, true).expect("extracts");
|
||||
assert!(warnings.iter().any(|w| w.contains("sum.sv")), "{warnings:?}");
|
||||
let Some(DocumentChanges::Operations(ops)) = edit.document_changes else {
|
||||
panic!("a creating edit speaks documentChanges: {edit:?}")
|
||||
};
|
||||
let creates = ops
|
||||
.iter()
|
||||
.filter(|op| matches!(op, DocumentChangeOperation::Op(ResourceOp::Create(_))))
|
||||
.count();
|
||||
assert_eq!(creates, 1, "one file is created: {ops:?}");
|
||||
assert_eq!(ops.len(), 3, "the creation plus one edit per file: {ops:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot() {
|
||||
let tree = Tree::new("same");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(selection()).expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments, false).expect("extracts");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.contains("did not say it can create files")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(edit.document_changes.is_none(), "no resource operation is needed");
|
||||
let changes = edit.changes.as_ref().expect("changes");
|
||||
assert_eq!(changes.len(), 1, "one file is touched");
|
||||
assert_eq!(changes.get(&uri).expect("this file").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_says_why_when_there_is_nothing_to_extract() {
|
||||
let tree = Tree::new("refuse");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Range {
|
||||
start: Position { line: 0, character: 0 },
|
||||
end: Position { line: 0, character: 3 },
|
||||
})
|
||||
.expect("range"),
|
||||
Value::String("sum".to_string()),
|
||||
];
|
||||
assert_eq!(execute(&ws, &arguments, true), Err(NOTHING.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_wants_all_three_of_its_arguments() {
|
||||
let tree = Tree::new("arguments");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let short = vec![serde_json::to_value(&uri).expect("uri")];
|
||||
let message = execute(&ws, &short, true).expect_err("a refusal");
|
||||
assert!(message.contains("argument 2"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_asking_only_for_refactor_extract_is_answered() {
|
||||
let filter = [CodeActionKind::REFACTOR_EXTRACT];
|
||||
assert!(crate::code_action::wanted(Some(&filter), &kind()));
|
||||
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
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<CodeActionOrCommand> {
|
||||
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<CodeActionOrCommand> {
|
||||
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<CodeAction, String> {
|
||||
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>), 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<String> = packages.to_vec();
|
||||
let mut seen: Vec<String> = 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<String> =
|
||||
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<TextEdit> {
|
||||
action
|
||||
.edit
|
||||
.as_ref()
|
||||
.expect("an edit")
|
||||
.changes
|
||||
.as_ref()
|
||||
.expect("changes")
|
||||
.get(uri)
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
|
||||
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<String> = 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();
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -13,11 +13,13 @@ mod convert;
|
||||
mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod extract;
|
||||
mod file_ops;
|
||||
mod folding;
|
||||
mod format;
|
||||
mod hierarchy;
|
||||
mod hover;
|
||||
mod imports;
|
||||
mod includes;
|
||||
mod index_cache;
|
||||
mod inlay;
|
||||
@@ -59,11 +61,12 @@ use lsp_types::{
|
||||
DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions,
|
||||
FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
|
||||
InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind,
|
||||
RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions,
|
||||
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
|
||||
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
|
||||
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
|
||||
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
RenameOptions, ResourceOperationKind, SaveOptions, SelectionRangeProviderCapability,
|
||||
SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
|
||||
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
|
||||
TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions,
|
||||
WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
};
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
@@ -127,6 +130,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
code_action_resolve: code_action_resolve_support(¶ms),
|
||||
create_files: create_files_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -260,6 +264,8 @@ fn capabilities() -> ServerCapabilities {
|
||||
CodeActionKind::QUICKFIX,
|
||||
CodeActionKind::new(code_action::FIX_ALL),
|
||||
CodeActionKind::new(ports::REFACTOR_PORTS),
|
||||
imports::kind(),
|
||||
extract::kind(),
|
||||
]),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
// The quick fixes are complete when they are offered; the port
|
||||
@@ -397,10 +403,12 @@ 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<String> {
|
||||
let mut commands = ports::commands();
|
||||
commands.extend(imports::commands());
|
||||
commands.extend(extract::commands());
|
||||
commands.extend(instantiate::commands());
|
||||
commands.extend(lens::commands());
|
||||
commands
|
||||
@@ -523,6 +531,32 @@ fn code_action_resolve_support(params: &InitializeParams) -> bool {
|
||||
.is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit"))
|
||||
}
|
||||
|
||||
/// Whether the client can apply a `WorkspaceEdit` that **creates a file** —
|
||||
/// `workspace.workspaceEdit.documentChanges` *and* a `resourceOperations`
|
||||
/// list containing `create`.
|
||||
///
|
||||
/// Both halves, because a creation is a resource operation and a resource
|
||||
/// operation can only be sent inside `documentChanges`: a client with one and
|
||||
/// not the other cannot apply the edit at all. A client that says nothing gets
|
||||
/// the extracted module written below the one it came from, in the file it
|
||||
/// came from, which needs no capability of any kind
|
||||
/// (`docs/features/extract-inline-module/README.md`).
|
||||
fn create_files_support(params: &InitializeParams) -> bool {
|
||||
let Some(edits) = params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.workspace_edit.as_ref())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let creates = edits
|
||||
.resource_operations
|
||||
.as_ref()
|
||||
.is_some_and(|kinds| kinds.contains(&ResourceOperationKind::Create));
|
||||
edits.document_changes.unwrap_or(false) && creates
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
@@ -1179,6 +1213,51 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_files_support_needs_both_halves_of_the_capability() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, ResourceOperationKind, WorkspaceClientCapabilities,
|
||||
WorkspaceEditClientCapabilities,
|
||||
};
|
||||
assert!(
|
||||
!create_files_support(&InitializeParams::default()),
|
||||
"silence means the module goes below the one it came from"
|
||||
);
|
||||
|
||||
let saying = |document_changes: Option<bool>, ops: Option<&[ResourceOperationKind]>| {
|
||||
InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities {
|
||||
workspace_edit: Some(WorkspaceEditClientCapabilities {
|
||||
document_changes,
|
||||
resource_operations: ops.map(<[_]>::to_vec),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let create = [ResourceOperationKind::Create];
|
||||
let rename = [ResourceOperationKind::Rename];
|
||||
assert!(create_files_support(&saying(Some(true), Some(&create))), "what VS Code sends");
|
||||
assert!(
|
||||
!create_files_support(&saying(Some(true), Some(&rename))),
|
||||
"a client that can rename but not create cannot apply the creation"
|
||||
);
|
||||
assert!(
|
||||
!create_files_support(&saying(Some(true), None)),
|
||||
"no resource operations at all is no creation"
|
||||
);
|
||||
assert!(
|
||||
!create_files_support(&saying(None, Some(&create))),
|
||||
"a resource operation can only be sent inside `documentChanges`"
|
||||
);
|
||||
assert!(!create_files_support(&saying(Some(false), Some(&create))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The port refactorings on the wire: `textDocument/codeAction` for the two
|
||||
//! that need no typing, and `workspace/executeCommand` for all three.
|
||||
//! The port refactorings on the wire: `textDocument/codeAction` for the four
|
||||
//! that need no typing, and `workspace/executeCommand` for all five.
|
||||
//!
|
||||
//! Protocol only. Every edit is computed by `vlog_refactor` over the same file
|
||||
//! set the workspace index was built from; this module turns the result into a
|
||||
@@ -8,9 +8,10 @@
|
||||
//!
|
||||
//! **Why commands as well as code actions.** Adding a port needs a
|
||||
//! declaration typed by the user, and a code action carries no input — so
|
||||
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`
|
||||
//! and `lucisv.propagatePorts` take a position and exist for the same reason a
|
||||
//! Vim user has no lightbulb: a command works everywhere a keybinding does.
|
||||
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`,
|
||||
//! `lucisv.propagatePorts`, `lucisv.expandWildcard` and `lucisv.convertToAnsi`
|
||||
//! take a position and exist for the same reason a Vim user has no lightbulb:
|
||||
//! a command works everywhere a keybinding does.
|
||||
//! See `docs/features/refactor-ports/README.md`.
|
||||
//!
|
||||
//! **Two shapes of code action.** A client that can resolve is *offered*
|
||||
@@ -48,10 +49,20 @@ pub const ADD_PORT: &str = "lucisv.addPort";
|
||||
pub const REMOVE_PORT: &str = "lucisv.removePort";
|
||||
/// Connect an instantiation's missing ports: `[uri, position]`.
|
||||
pub const PROPAGATE_PORTS: &str = "lucisv.propagatePorts";
|
||||
/// Write out the `.*` at a position: `[uri, position]`.
|
||||
pub const EXPAND_WILDCARD: &str = "lucisv.expandWildcard";
|
||||
/// Rewrite the non-ANSI header at a position ANSI-style: `[uri, position]`.
|
||||
pub const CONVERT_TO_ANSI: &str = "lucisv.convertToAnsi";
|
||||
|
||||
/// Every command this server executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![ADD_PORT.to_string(), REMOVE_PORT.to_string(), PROPAGATE_PORTS.to_string()]
|
||||
vec![
|
||||
ADD_PORT.to_string(),
|
||||
REMOVE_PORT.to_string(),
|
||||
PROPAGATE_PORTS.to_string(),
|
||||
EXPAND_WILDCARD.to_string(),
|
||||
CONVERT_TO_ANSI.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The port actions available at a position, each carrying its own computed
|
||||
@@ -243,12 +254,21 @@ fn key(title: &str) -> &str {
|
||||
|
||||
/// An offered title with the workspace's own instantiation count in it,
|
||||
/// replacing the one the offer's one or two files could see.
|
||||
///
|
||||
/// Only a title whose count *is* an instantiation census is recounted:
|
||||
/// `lucisv: expand .* (3 connections)` counts the connections one wildcard
|
||||
/// becomes, which the offer's own two files already know exactly and no index
|
||||
/// lookup could improve (`vlog_refactor::is_sites_phrase`).
|
||||
fn counted(ws: &Workspace, title: String, modules: &[String]) -> String {
|
||||
let Some(head) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")) else {
|
||||
let Some((head, phrase)) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" ("))
|
||||
else {
|
||||
return title;
|
||||
};
|
||||
if !vlog_refactor::is_sites_phrase(phrase) {
|
||||
return title;
|
||||
}
|
||||
let sites = modules.iter().map(|name| instances_of(ws, name)).sum();
|
||||
format!("{} ({})", head.0, vlog_refactor::sites_phrase(sites))
|
||||
format!("{head} ({})", vlog_refactor::sites_phrase(sites))
|
||||
}
|
||||
|
||||
/// Every instance of `name` the index has seen. An edge is one written
|
||||
@@ -267,7 +287,7 @@ fn declared_twice(ws: &Workspace, name: &str) -> bool {
|
||||
ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1
|
||||
}
|
||||
|
||||
/// Run one of the three commands, or say why it cannot run.
|
||||
/// Run one of the five commands, or say why it cannot run.
|
||||
///
|
||||
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
|
||||
/// it reaches the editor is `server.rs`'s business: it is pushed as a
|
||||
@@ -313,10 +333,23 @@ pub fn execute(
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::propagate_ports(&sources, &path, offset)?
|
||||
}
|
||||
EXPAND_WILDCARD => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, EXPAND_WILDCARD)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::expand_wildcard(&sources, &path, offset)?
|
||||
}
|
||||
CONVERT_TO_ANSI => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, CONVERT_TO_ANSI)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::convert_to_ansi(&sources, &path, offset)?
|
||||
}
|
||||
// The instantiation skeleton is not a port refactoring and computes
|
||||
// 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()))
|
||||
}
|
||||
@@ -1336,8 +1369,144 @@ mod tests {
|
||||
assert!(message.contains("position"), "{message}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the `.*` expansion (TODO §50)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A workspace whose `top.sv` instantiates `sub` with a wildcard.
|
||||
fn wildcard(tree: &Tree) -> (Workspace, Uri, &'static str) {
|
||||
const TEXT: &str =
|
||||
"module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TEXT);
|
||||
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(), TEXT.to_string());
|
||||
(ws, uri, TEXT)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_wildcard_takes_a_position() {
|
||||
let tree = Tree::new("expand");
|
||||
let (ws, uri, text) = wildcard(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 2, character: 24 }).expect("position"),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, EXPAND_WILDCARD, &arguments).expect("expands");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let edits = edits_for(&edit, &uri);
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0].new_text, ".rst(rst)");
|
||||
// The range is the `.*` itself, in the client's own coordinates.
|
||||
assert_eq!(edits[0].range.start.character, 24);
|
||||
assert_eq!(edits[0].range.end.character, 26);
|
||||
assert_eq!(&text[text.find(".*").expect("the wildcard")..][..2], ".*");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_wildcard_refuses_where_there_is_no_wildcard() {
|
||||
let tree = Tree::new("expand_none");
|
||||
let (ws, top_uri, _) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&top_uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 2, character: 6 }).expect("position"),
|
||||
];
|
||||
let message = execute(&ws, EXPAND_WILDCARD, &arguments).expect_err("no wildcard");
|
||||
assert!(message.contains("writes no `.*` to expand"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
|
||||
let tree = Tree::new("expand_action");
|
||||
let (ws, uri, text) = wildcard(&tree);
|
||||
let offset = text.find(".*").expect("the wildcard") as u32;
|
||||
|
||||
let lazy = offered(&ws, &uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
|
||||
// The count is the connections the wildcard becomes, and the index's
|
||||
// instantiation census must not overwrite it.
|
||||
assert_eq!(menu(&lazy)[0].0, "lucisv: expand .* (1 connection)");
|
||||
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
|
||||
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(resolved.title, "lucisv: expand .* (1 connection)");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
|
||||
assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, ".rst(rst)");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the non-ANSI → ANSI conversion (TODO §51)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A workspace whose `legacy.sv` writes a Verilog-2001 header.
|
||||
const LEGACY: &str =
|
||||
"module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
|
||||
fn legacy(tree: &Tree) -> (Workspace, Uri) {
|
||||
let path = tree.write("legacy.sv", LEGACY);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), LEGACY.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_ansi_takes_a_position() {
|
||||
let tree = Tree::new("ansi");
|
||||
let (ws, uri) = legacy(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
// The module's own name — inside the header, and nowhere near a
|
||||
// port declaration.
|
||||
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
|
||||
];
|
||||
// Two insertions — the ANSI prefixes — and three deletions: `input a;`,
|
||||
// `output [7:0] b;` and the `reg [7:0] b;` that completed it.
|
||||
let (edit, warnings) = execute(&ws, CONVERT_TO_ANSI, &arguments).expect("converts");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let edits = edits_for(&edit, &uri);
|
||||
let written: Vec<&str> = edits.iter().map(|e| e.new_text.as_str()).collect();
|
||||
assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_ansi_refuses_an_ansi_header() {
|
||||
let tree = Tree::new("ansi_none");
|
||||
let (ws, top_uri, _) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&top_uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
|
||||
];
|
||||
let message = execute(&ws, CONVERT_TO_ANSI, &arguments).expect_err("nothing to convert");
|
||||
assert!(message.contains("declares no ports"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ansi_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
|
||||
let tree = Tree::new("ansi_action");
|
||||
let (ws, uri) = legacy(&tree);
|
||||
// The cursor on the module's name: in the header, on no port.
|
||||
let offset = LEGACY.find("legacy (").expect("the name") as u32;
|
||||
|
||||
let lazy = offered(&ws, &uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
|
||||
assert_eq!(menu(&lazy)[0].0, "lucisv: convert ports to ANSI (2 ports)");
|
||||
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
|
||||
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(resolved.title, "lucisv: convert ports to ANSI (2 ports)");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
|
||||
assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, "input ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_list_is_what_the_server_advertises() {
|
||||
assert_eq!(commands(), vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS]);
|
||||
assert_eq!(
|
||||
commands(),
|
||||
vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS, EXPAND_WILDCARD, CONVERT_TO_ANSI]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -44,9 +44,9 @@ use serde_json::Value;
|
||||
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,
|
||||
code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy,
|
||||
hover, imports, includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename,
|
||||
selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
impl Server {
|
||||
@@ -268,13 +268,38 @@ 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),
|
||||
});
|
||||
}
|
||||
// Extracting a selection into a module of its own. This one
|
||||
// answers for the *range*, not the cursor, and carries a
|
||||
// command rather than an edit — it needs a name for the new
|
||||
// module, and only a command can be intercepted by a client
|
||||
// that wants to ask the user for one.
|
||||
if code_action::wanted(only.as_deref(), &extract::kind()) {
|
||||
actions.extend(extract::code_actions(&self.workspace, &uri, p.range));
|
||||
}
|
||||
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)),
|
||||
}
|
||||
@@ -343,6 +368,22 @@ impl Server {
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
};
|
||||
}
|
||||
// Extracting takes the client's own capability with it: only
|
||||
// a client that can apply a `CreateFile` gets the new module
|
||||
// in a file of its own.
|
||||
if p.command == extract::EXTRACT_MODULE {
|
||||
return match extract::execute(
|
||||
&self.workspace,
|
||||
&p.arguments,
|
||||
self.abilities.create_files,
|
||||
) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
self.deliver(&p.command, edit)
|
||||
}
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
};
|
||||
}
|
||||
match ports::execute(&self.workspace, &p.command, &p.arguments) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
|
||||
@@ -111,6 +111,13 @@ pub struct ClientAbilities {
|
||||
/// which is what every client got before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
pub code_action_resolve: bool,
|
||||
/// Whether the client can apply a `WorkspaceEdit` that creates a file —
|
||||
/// `workspace.workspaceEdit.documentChanges` plus a `resourceOperations`
|
||||
/// list containing `create`. Only then does an extracted module get a
|
||||
/// file of its own; a client that said nothing gets it written below the
|
||||
/// module it came from
|
||||
/// (`docs/features/extract-inline-module/README.md`).
|
||||
pub create_files: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
|
||||
@@ -1587,6 +1587,223 @@ fn a_client_that_resolves_is_offered_the_port_action_without_its_edit() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A top whose instantiation of `sub` connects one port and wildcards the
|
||||
/// rest. Line 2, character 24 is the `.*`.
|
||||
const WILDCARD_TOP: &str =
|
||||
"module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
|
||||
const LEGACY_TOP: &str =
|
||||
"module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn the_ansi_conversion_is_offered_resolved_and_commanded_over_the_wire() {
|
||||
// TODO §51 on the wire: the action is offered with the cursor on the
|
||||
// module's own name — anywhere in a non-ANSI header — with the port count
|
||||
// in its title, the resolve hands back the insertions and deletions, and
|
||||
// the command answers with the same edit for a client with no lightbulb.
|
||||
let dir = temp_dir("ansi");
|
||||
let legacy = dir.join("legacy.sv");
|
||||
std::fs::write(&legacy, LEGACY_TOP).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", legacy.display());
|
||||
|
||||
let boot = |id: u32| {
|
||||
[
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(LEGACY_TOP).expect("json")
|
||||
)),
|
||||
]
|
||||
.concat()
|
||||
};
|
||||
|
||||
let session = [
|
||||
boot(1),
|
||||
// The cursor on the module's name, which is in the header and on no port.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":9}},"end":{{"line":0,"character":9}}}},"context":{{"diagnostics":[]}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"lucisv.convertToAnsi","arguments":["{uri}",{{"line":0,"character":9}}]}}}}"#
|
||||
)),
|
||||
// ...and a position inside the body is refused with the engine's sentence.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.convertToAnsi","arguments":["{uri}",{{"line":7,"character":9}}]}}}}"#
|
||||
)),
|
||||
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 command is advertised beside the other four.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let commands = initialize["result"]["capabilities"]["executeCommandProvider"]["commands"]
|
||||
.as_array()
|
||||
.expect("the commands are listed");
|
||||
assert!(commands.iter().any(|c| c == "lucisv.convertToAnsi"), "{commands:#?}");
|
||||
|
||||
// 2. The offer names the conversion and its port count, with no edit.
|
||||
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
|
||||
let offered = actions["result"].as_array().expect("an array of actions");
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
|
||||
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: convert ports to ANSI (2 ports)");
|
||||
assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}");
|
||||
|
||||
// 3. The command answers with the two insertions and the three deletions:
|
||||
// `b`'s port declaration and the `reg` that completed it both go.
|
||||
let converted = messages.iter().find(|m| m["id"] == 3).expect("executeCommand response");
|
||||
let edits = converted["result"]["changes"][&uri].as_array().expect("edits");
|
||||
let written: Vec<&str> = edits.iter().map(|e| e["newText"].as_str().unwrap_or("?")).collect();
|
||||
assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}");
|
||||
assert_eq!(edits[0]["range"]["start"]["line"], 1, "the first port's own line");
|
||||
assert_eq!(edits[0]["range"]["start"], edits[0]["range"]["end"], "an insertion, not a rewrite");
|
||||
|
||||
// 4. ...and a refusal is `RequestFailed` with the engine's own sentence.
|
||||
let refused = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
|
||||
assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed");
|
||||
assert!(
|
||||
refused["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("no module declaration at this position")),
|
||||
"{refused:#?}"
|
||||
);
|
||||
|
||||
// 5. Handing the offered action back resolves it to that same edit.
|
||||
let resolve = [
|
||||
boot(1),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#,
|
||||
serde_json::to_string(action).expect("json")
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&resolve);
|
||||
let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response");
|
||||
let edits = resolved["result"]["edit"]["changes"][&uri]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no edit in {resolved:#?}"));
|
||||
assert_eq!(edits[0]["newText"], "input ");
|
||||
assert_eq!(resolved["result"]["title"], "lucisv: convert ports to ANSI (2 ports)");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wildcard_expansion_is_offered_resolved_and_commanded_over_the_wire() {
|
||||
// TODO §50 on the wire: the action is offered lazily at the `.*` with the
|
||||
// count of connections it becomes (not the instantiation census the other
|
||||
// port titles carry), the resolve hands back the edit, and the command
|
||||
// answers with the same edit for a client with no lightbulb.
|
||||
let dir = temp_dir("wildcard");
|
||||
let sub = dir.join("sub.sv");
|
||||
std::fs::write(&sub, PORTS_SUB).expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
std::fs::write(&top, WILDCARD_TOP).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let top_uri = format!("file://{}", top.display());
|
||||
|
||||
let boot = |id: u32| {
|
||||
[
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(WILDCARD_TOP).expect("json")
|
||||
)),
|
||||
]
|
||||
.concat()
|
||||
};
|
||||
|
||||
let session = [
|
||||
boot(1),
|
||||
// The cursor on the `.*` itself.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":24}},"end":{{"line":2,"character":24}}}},"context":{{"diagnostics":[]}}}}}}"#
|
||||
)),
|
||||
// ...and the command, which needs no lightbulb at all.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"lucisv.expandWildcard","arguments":["{top_uri}",{{"line":2,"character":24}}]}}}}"#
|
||||
)),
|
||||
// ...and a position with no `.*` is refused with the engine's sentence.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.expandWildcard","arguments":["{top_uri}",{{"line":1,"character":4}}]}}}}"#
|
||||
)),
|
||||
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 command is advertised beside the other three.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let commands = initialize["result"]["capabilities"]["executeCommandProvider"]["commands"]
|
||||
.as_array()
|
||||
.expect("the commands are listed");
|
||||
assert!(commands.iter().any(|c| c == "lucisv.expandWildcard"), "{commands:#?}");
|
||||
|
||||
// 2. The offer names the wildcard and its connection count, with no edit.
|
||||
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
|
||||
let offered = actions["result"].as_array().expect("an array of actions");
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
|
||||
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: expand .* (1 connection)");
|
||||
assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}");
|
||||
|
||||
// 3. The command answers with the edit that replaces the `.*`.
|
||||
let expanded = messages.iter().find(|m| m["id"] == 3).expect("executeCommand response");
|
||||
let edits = expanded["result"]["changes"][&top_uri].as_array().expect("edits");
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0]["newText"], ".rst(rst)");
|
||||
assert_eq!(edits[0]["range"]["start"]["line"], 2);
|
||||
assert_eq!(edits[0]["range"]["start"]["character"], 24, "the `.*` itself is replaced");
|
||||
assert_eq!(edits[0]["range"]["end"]["character"], 26);
|
||||
|
||||
// 4. ...and a refusal is `RequestFailed` with the engine's own sentence.
|
||||
let refused = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
|
||||
assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed");
|
||||
assert!(
|
||||
refused["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("no module instantiation at this position")),
|
||||
"{refused:#?}"
|
||||
);
|
||||
|
||||
// 5. Handing the offered action back resolves it to that same edit.
|
||||
let resolve = [
|
||||
boot(1),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#,
|
||||
serde_json::to_string(action).expect("json")
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&resolve);
|
||||
let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response");
|
||||
let edits = resolved["result"]["edit"]["changes"][&top_uri]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no edit in {resolved:#?}"));
|
||||
assert_eq!(edits[0]["newText"], ".rst(rst)");
|
||||
assert_eq!(resolved["result"]["title"], "lucisv: expand .* (1 connection)");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The module hinting pair: a definition worth a skeleton, and a top that is
|
||||
/// half-way through instantiating it.
|
||||
const HINT_SUB: &str = "module hint_sub #(\n parameter int WIDTH = 8\n) (\n input logic clk,\n input logic [WIDTH-1:0] data,\n output logic ready\n);\nendmodule\n";
|
||||
@@ -8312,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);
|
||||
}
|
||||
@@ -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<ModuleInterface> {
|
||||
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()
|
||||
|
||||
@@ -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<Vec<String>>)> {
|
||||
let index = WorkspaceIndex::build([(path.to_path_buf(), src)]);
|
||||
index
|
||||
.units_of(SymbolKind::Package)
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.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.
|
||||
///
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Applicability> {
|
||||
Some(Applicability::Safe)
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
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<vlog_parser::span::TextRange> {
|
||||
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<String> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,11 @@ description = "Refactorings for Verilog/SystemVerilog, computed from resolved re
|
||||
[dependencies]
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Tests only, the same arrangement `vlog_linter` uses: the `.*` expansion's
|
||||
# acceptance test asserts that what the refactoring writes is something the
|
||||
# formatter accepts and leaves alone the second time. The library still
|
||||
# depends on vlog_parser + vlog_semantic alone
|
||||
# (`cargo tree -p vlog_refactor -e normal`).
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
@@ -0,0 +1,888 @@
|
||||
//! The lexical half of the splice contract: the pieces a file is made of, the
|
||||
//! comparison that says an edit wrote exactly what it promised, and the ledger
|
||||
//! of the pieces that are never dropped.
|
||||
//!
|
||||
//! [`super::verify_splice`] and [`super::verify_move`] are the callers, and the
|
||||
//! difference between them lives here: a splice balances every never-dropped
|
||||
//! piece inside one file, while a move is allowed to carry the pieces of one
|
||||
//! region into the file that receives them — [`Transit`] is that allowance and
|
||||
//! the whole of it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
use crate::rename::display;
|
||||
use crate::TextEdit;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// lexical splice
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// One lexical piece of a file, in source order: a code token, or a comment.
|
||||
/// Comments are pieces of their own rather than trivia hanging off a token,
|
||||
/// because an insertion can legitimately move which token a comment attaches
|
||||
/// to without moving the comment itself.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum Piece {
|
||||
Code(TokenKind, String),
|
||||
Comment(String),
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
/// How the piece is named in a refusal.
|
||||
fn describe(&self) -> String {
|
||||
match self {
|
||||
Piece::Code(_, text) => format!("the token `{text}`"),
|
||||
Piece::Comment(text) => format!("the comment `{text}`"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every piece of a file with the bytes it occupies, in source order.
|
||||
fn pieces(text: &str) -> Option<Vec<(TextRange, Piece)>> {
|
||||
let tokens = tokenize(text).ok()?;
|
||||
let mut out: Vec<(TextRange, Piece)> = Vec::new();
|
||||
for token in &tokens {
|
||||
for comment in &token.leading {
|
||||
out.push((comment.span, Piece::Comment(comment.text.clone())));
|
||||
}
|
||||
if token.kind != TokenKind::Eof {
|
||||
out.push((token.span, Piece::Code(token.kind, token.text.clone())));
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push((comment.span, Piece::Comment(comment.text.clone())));
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// One file's three streams of pieces: what it had, what it has, and what the
|
||||
/// edits themselves spell.
|
||||
pub(super) struct Split {
|
||||
old: Vec<(TextRange, Piece)>,
|
||||
new: Vec<(TextRange, Piece)>,
|
||||
written: Vec<Vec<(TextRange, Piece)>>,
|
||||
}
|
||||
|
||||
impl Split {
|
||||
/// Lex all three, or say which one lucisv could not read.
|
||||
pub(super) fn read(
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<Split, String> {
|
||||
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
|
||||
return Err(format!(
|
||||
"{} would no longer lex after {what}; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
};
|
||||
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
|
||||
for edit in edits {
|
||||
let Some(pieces) = pieces(&edit.new_text) else {
|
||||
return Err(format!(
|
||||
"{what} would write text that does not lex; no edits were made."
|
||||
));
|
||||
};
|
||||
written.push(pieces);
|
||||
}
|
||||
Ok(Split { old, new, written })
|
||||
}
|
||||
|
||||
/// The edited file must lex to the original's pieces with the edits' own
|
||||
/// pieces written in where the edits are — and to nothing else.
|
||||
pub(super) fn positions_match(
|
||||
&self,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let clone = |pieces: &[(TextRange, Piece)]| -> Vec<Piece> {
|
||||
pieces
|
||||
.iter()
|
||||
.map(|(_, piece)| match piece {
|
||||
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
|
||||
Piece::Comment(text) => Piece::Comment(text.clone()),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut expected: Vec<Piece> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
for (span, piece) in &self.old {
|
||||
while let (Some(edit), Some(pieces)) = (edits.get(next), self.written.get(next)) {
|
||||
if edit.range.start > span.start {
|
||||
break;
|
||||
}
|
||||
expected.extend(clone(pieces));
|
||||
next += 1;
|
||||
}
|
||||
if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span)) {
|
||||
continue;
|
||||
}
|
||||
expected.push(piece.clone());
|
||||
}
|
||||
while let Some(pieces) = self.written.get(next) {
|
||||
expected.extend(clone(pieces));
|
||||
next += 1;
|
||||
}
|
||||
|
||||
let actual = clone(&self.new);
|
||||
for (n, expected) in expected.iter().enumerate() {
|
||||
match actual.get(n) {
|
||||
Some(actual) if actual == expected => {}
|
||||
Some(actual) => {
|
||||
return Err(format!(
|
||||
"{what} would write {} where {} belongs in {}; no edits were made.",
|
||||
actual.describe(),
|
||||
expected.describe(),
|
||||
display(path)
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"{what} would lose {} in {}; no edits were made.",
|
||||
expected.describe(),
|
||||
display(path)
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
if actual.len() > expected.len() {
|
||||
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
|
||||
return Err(format!(
|
||||
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-file contract: the never-dropped ledger, checked on the spot, and
|
||||
/// then the positional comparison. The order is the one that gives the most
|
||||
/// useful sentence — a dropped comment is said as a dropped comment rather
|
||||
/// than as a piece that went missing from position 47.
|
||||
pub(super) fn pieces_match(
|
||||
split: &Split,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let ledger = Ledger::of(split, edits, TextRange::empty(0));
|
||||
ledger.check(&display(path), what, &Tally::new())?;
|
||||
split.positions_match(edits, path, what)
|
||||
}
|
||||
|
||||
/// The range the move takes text out of file `i`, if it names that file at all:
|
||||
/// a source's own region, or the empty range that says "this one only
|
||||
/// receives". A file the move does not name has none, and keeps the per-file
|
||||
/// contract.
|
||||
pub(super) fn region_of(moving: &[(usize, TextRange)], i: usize) -> Option<TextRange> {
|
||||
moving.iter().find(|(file, _)| *file == i).map(|(_, region)| *region)
|
||||
}
|
||||
|
||||
/// Whether a piece sits inside the bytes a move takes out of its file. An
|
||||
/// empty region holds nothing: a destination has no region, and a piece that
|
||||
/// only *overlaps* a region is one the move did not wholly carry, so it is an
|
||||
/// ordinary deletion and has to be written back where it was.
|
||||
fn within(region: TextRange, span: TextRange) -> bool {
|
||||
!region.is_empty() && region.start <= span.start && span.end <= region.end
|
||||
}
|
||||
|
||||
/// The pieces an edit may never lose, gain or duplicate: a **comment**
|
||||
/// (CLAUDE.md invariant 3) and an **attribute instance** `(* ... *)`.
|
||||
///
|
||||
/// The piece comparison above cannot see either on its own. A piece inside a
|
||||
/// deleted range disappears from *both* sides of it — from `expected`, because
|
||||
/// pieces inside an edit are skipped, and from `actual`, because it is really
|
||||
/// gone — so a dropped comment, or a dropped `(* keep *)`, would pass
|
||||
/// unnoticed. An attribute is a code token rather than trivia, but a deletion
|
||||
/// hides it exactly the way it hides a comment, and losing one changes what a
|
||||
/// synthesizer does; so both are counted here, by exact text.
|
||||
///
|
||||
/// Three equations, over every text that appears on any side. `had` and `has`
|
||||
/// are the file's counts before and after, `gone` counts the old pieces a
|
||||
/// non-empty edit range covers, `wrote` counts the pieces lexed out of the
|
||||
/// edits' own inserted text, and `out` counts the pieces of `gone` that a move
|
||||
/// carried out of this file — zero for every file that is not the source of
|
||||
/// one, which is every file but an extraction's.
|
||||
///
|
||||
/// 1. **`has + out >= had`** — nothing is ever lost. This is the whole of
|
||||
/// invariant 3 and the only half the rule this replaced had; a file may end
|
||||
/// up short only by exactly what left through its own moved region.
|
||||
/// 2. **`wrote <= gone - out + in`**, unless the text is one a refactoring
|
||||
/// [`generated`] itself — a piece is written back *where it was deleted*,
|
||||
/// and nowhere else. This refuses a planner that takes the comment on
|
||||
/// `input a, b;` and writes it onto *both* ports (one really did, on the
|
||||
/// way — see the work log), and equally one that duplicates the text of a
|
||||
/// comment it never touched. `in` is the transit a **destination** of a
|
||||
/// move may receive and is zero everywhere else, so a deletion outside the
|
||||
/// moved region has to be written back in its own file as it always did.
|
||||
/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the
|
||||
/// edits say, transit out counted as gone and transit in as wrote. An
|
||||
/// application that grew a second copy of a comment the edits write once is
|
||||
/// masked corruption the first two equations would forgive.
|
||||
///
|
||||
/// Where each piece now *sits* is the piece comparison's business, not this
|
||||
/// one's; between them a moved comment is verified as exactly as a stationary
|
||||
/// one.
|
||||
///
|
||||
/// **A ledger is one file's**, always. [`pieces_match`] checks it with no
|
||||
/// transit at all, which is the contract every refactoring that stays inside
|
||||
/// one file has always had. [`super::verify_move`] gives the source of a move its
|
||||
/// region — so the comment carried out of `M.sv` is `out` rather than lost —
|
||||
/// and the destination the allowance to receive it, and then [`Transit`] holds
|
||||
/// the two halves to each other. See
|
||||
/// `docs/features/extract-inline-module/README.md` for the attack pairs.
|
||||
#[derive(Default)]
|
||||
struct Ledger {
|
||||
/// The pieces the file had before the edits.
|
||||
before: Tally,
|
||||
/// The pieces it has after them.
|
||||
after: Tally,
|
||||
/// The old pieces a non-empty edit range covers.
|
||||
deleted: Tally,
|
||||
/// Of those, the ones inside the region a move takes out of this file.
|
||||
out: Tally,
|
||||
/// The pieces the edits' own inserted text spells.
|
||||
writes: Tally,
|
||||
}
|
||||
|
||||
impl Ledger {
|
||||
/// Count one file's streams. `region` is the bytes a move carries out of
|
||||
/// it — empty for every file that keeps the per-file contract, and for a
|
||||
/// file that only receives.
|
||||
fn of(split: &Split, edits: &[TextEdit], region: TextRange) -> Ledger {
|
||||
let covered = |span: TextRange| {
|
||||
edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span))
|
||||
};
|
||||
let mut out = Ledger::default();
|
||||
tally_into(&mut out.before, split.old.iter().map(|(_, piece)| piece));
|
||||
tally_into(&mut out.after, split.new.iter().map(|(_, piece)| piece));
|
||||
tally_into(
|
||||
&mut out.deleted,
|
||||
split.old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece),
|
||||
);
|
||||
tally_into(
|
||||
&mut out.out,
|
||||
split
|
||||
.old
|
||||
.iter()
|
||||
.filter(|(span, _)| covered(*span) && within(region, *span))
|
||||
.map(|(_, piece)| piece),
|
||||
);
|
||||
tally_into(&mut out.writes, split.written.iter().flatten().map(|(_, piece)| piece));
|
||||
out
|
||||
}
|
||||
|
||||
/// The three equations, for this one file. `where_` names it, already
|
||||
/// quoted for a sentence; `receives` is the transit it may be handed by
|
||||
/// the rest of the move, and is empty for every file that is not a
|
||||
/// destination of one.
|
||||
fn check(&self, where_: &str, what: &str, receives: &Tally) -> Result<(), String> {
|
||||
let mut texts: Vec<&Kept> =
|
||||
self.before.keys().chain(self.after.keys()).chain(self.writes.keys()).collect();
|
||||
texts.sort_unstable();
|
||||
texts.dedup();
|
||||
let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0);
|
||||
// `out` is a subset of `deleted`, so the subtraction cannot go under —
|
||||
// saturating rather than plain because an arithmetic panic is not a
|
||||
// refusal, and this is a safety net.
|
||||
let ordinary = |key: &Kept| count(&self.deleted, key).saturating_sub(count(&self.out, key));
|
||||
|
||||
// Three passes rather than three tests in one pass, so that the
|
||||
// sentence the user reads is the worst thing wrong with the edit
|
||||
// rather than whichever text sorted first.
|
||||
if let Some(Kept(noun, text)) = texts
|
||||
.iter()
|
||||
.find(|key| count(&self.after, key) + count(&self.out, key) < count(&self.before, key))
|
||||
{
|
||||
return Err(format!(
|
||||
"{what} would delete the {noun} `{text}` in {where_}; {noun}s are never dropped, so nothing was edited."
|
||||
));
|
||||
}
|
||||
if let Some(key) = texts.iter().find(|key| {
|
||||
count(&self.writes, key) > ordinary(key) + count(receives, key) && !generated(&key.1)
|
||||
}) {
|
||||
let Kept(noun, text) = key;
|
||||
let (gone, wrote) = (ordinary(key), count(&self.writes, key));
|
||||
let deletes = match gone {
|
||||
0 => "without deleting it".to_string(),
|
||||
gone => format!("where it deletes it {}", times(gone)),
|
||||
};
|
||||
return Err(format!(
|
||||
"{what} would write the {noun} `{text}` {} in {where_} {deletes}; {noun}s are never duplicated, so nothing was edited.",
|
||||
times(wrote)
|
||||
));
|
||||
}
|
||||
// `deleted` is a subset of `before`, so the subtraction cannot go
|
||||
// under — saturating rather than plain because an arithmetic panic is
|
||||
// not a refusal, and this is a safety net.
|
||||
let accounted = |key: &Kept| {
|
||||
count(&self.before, key).saturating_sub(count(&self.deleted, key))
|
||||
+ count(&self.writes, key)
|
||||
};
|
||||
if let Some(key) = texts.iter().find(|key| count(&self.after, key) != accounted(key)) {
|
||||
let Kept(noun, text) = key;
|
||||
return Err(format!(
|
||||
"{what} would leave the {noun} `{text}` in {where_} {}, where its edits account for it {}; nothing was edited.",
|
||||
times(count(&self.after, key)),
|
||||
times(accounted(key))
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many more of a piece this file's edits write than they delete —
|
||||
/// what a destination of a move has to have received.
|
||||
fn gained(&self, key: &Kept) -> i64 {
|
||||
let count = |tally: &Tally| tally.get(key).copied().unwrap_or(0) as i64;
|
||||
count(&self.writes) - count(&self.deleted)
|
||||
}
|
||||
}
|
||||
|
||||
/// The files a move names, and the never-dropped pieces travelling between
|
||||
/// them: a **source** loses the pieces inside its own region, and a
|
||||
/// **destination** — a file the move names with an empty range — is the only
|
||||
/// place they may land.
|
||||
///
|
||||
/// This is the whole of the widening [`super::verify_move`] exists for, and
|
||||
/// the whole of what it is allowed to forgive: the allowance is bound to the
|
||||
/// bytes that move, so a piece deleted anywhere else in one of these files is
|
||||
/// an ordinary deletion its own ledger holds it to.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Transit {
|
||||
files: Vec<Moved>,
|
||||
}
|
||||
|
||||
/// One file of a move: what a refusal calls it, whether it receives rather
|
||||
/// than sends, and its own ledger.
|
||||
struct Moved {
|
||||
where_: String,
|
||||
receives: bool,
|
||||
ledger: Ledger,
|
||||
}
|
||||
|
||||
impl Transit {
|
||||
/// Take one file's counts, with the region the move carries text out of.
|
||||
pub(super) fn add(
|
||||
&mut self,
|
||||
where_: &str,
|
||||
region: TextRange,
|
||||
split: &Split,
|
||||
edits: &[TextEdit],
|
||||
) {
|
||||
self.files.push(Moved {
|
||||
where_: where_.to_string(),
|
||||
receives: region.is_empty(),
|
||||
ledger: Ledger::of(split, edits, region),
|
||||
});
|
||||
}
|
||||
|
||||
/// The three equations per file — the destinations, and only they, holding
|
||||
/// the transit as their allowance — and then rule 4 over the move whole.
|
||||
pub(super) fn check(&self, what: &str) -> Result<(), String> {
|
||||
let mut sent = Tally::new();
|
||||
for file in &self.files {
|
||||
for (key, n) in &file.ledger.out {
|
||||
*sent.entry(key.clone()).or_insert(0) += n;
|
||||
}
|
||||
}
|
||||
let nothing = Tally::new();
|
||||
for file in &self.files {
|
||||
let receives = match file.receives {
|
||||
true => &sent,
|
||||
false => ¬hing,
|
||||
};
|
||||
file.ledger.check(&file.where_, what, receives)?;
|
||||
}
|
||||
self.lands(&sent, what)
|
||||
}
|
||||
|
||||
/// Rule 4: what left a region has to land, exactly once in total, in the
|
||||
/// files the move named as destinations. Rule 2 lets each destination
|
||||
/// receive the transit; this is what says the move as a whole received it
|
||||
/// once — two destinations that each write the comment are two comments.
|
||||
fn lands(&self, sent: &Tally, what: &str) -> Result<(), String> {
|
||||
let names = |receives: bool| -> Vec<String> {
|
||||
self.files.iter().filter(|f| f.receives == receives).map(|f| f.where_.clone()).collect()
|
||||
};
|
||||
let mut texts: Vec<&Kept> = sent.keys().collect();
|
||||
texts.sort_unstable();
|
||||
for key in texts {
|
||||
let out = sent.get(key).copied().unwrap_or(0);
|
||||
let landed: i64 =
|
||||
self.files.iter().filter(|f| f.receives).map(|f| f.ledger.gained(key)).sum();
|
||||
if landed == out as i64 {
|
||||
continue;
|
||||
}
|
||||
let Kept(noun, text) = key;
|
||||
let rule = match landed < out as i64 {
|
||||
true => format!("{noun}s are never dropped"),
|
||||
false => format!("{noun}s are never duplicated"),
|
||||
};
|
||||
let (sources, destinations) = (names(false), names(true));
|
||||
let landing = match landed > 0 {
|
||||
true => format!("{} into {}", times(landed as usize), and_list(&destinations)),
|
||||
false => "nowhere".to_string(),
|
||||
};
|
||||
return Err(format!(
|
||||
"{what} would move the {noun} `{text}` out of {} {} and write it back {landing}; {rule}, so nothing was edited.",
|
||||
and_list(&sources),
|
||||
times(out)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One never-dropped piece, keyed for counting: the noun a refusal calls it by
|
||||
/// (`comment` or `attribute`) and its exact text.
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct Kept(&'static str, String);
|
||||
|
||||
type Tally = HashMap<Kept, usize>;
|
||||
|
||||
/// How many of each never-dropped piece a stream of pieces holds. Every other
|
||||
/// piece is a code token the comparison above already pins position by
|
||||
/// position, so it is not counted here.
|
||||
fn tally_into<'p>(out: &mut Tally, pieces: impl Iterator<Item = &'p Piece>) {
|
||||
for piece in pieces {
|
||||
let key = match piece {
|
||||
Piece::Comment(text) => Kept("comment", text.clone()),
|
||||
Piece::Code(TokenKind::Attribute, text) => Kept("attribute", text.clone()),
|
||||
Piece::Code(..) => continue,
|
||||
};
|
||||
*out.entry(key).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// The comments a refactoring writes itself rather than moves, which it may
|
||||
/// therefore write however many times it needs and even where the file already
|
||||
/// has one. `add_port` and `propagate_ports` both leave
|
||||
/// `/* TODO: connect */` at a connection they cannot name a signal for, and a
|
||||
/// module gains its ports one at a time — so the second addition to a file
|
||||
/// finds the first one's placeholder already sitting there. Everything else a
|
||||
/// refactoring writes has to be a piece it is deleting somewhere else.
|
||||
fn generated(text: &str) -> bool {
|
||||
text == "/* TODO: connect */"
|
||||
}
|
||||
|
||||
/// A count, in prose, so a refusal reads like a sentence.
|
||||
fn times(n: usize) -> String {
|
||||
match n {
|
||||
0 => "never".to_string(),
|
||||
1 => "once".to_string(),
|
||||
2 => "twice".to_string(),
|
||||
n => format!("{n} times"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two byte ranges share a byte. Empty ranges — the insertions —
|
||||
/// overlap nothing: they replace no text, so they delete nothing.
|
||||
pub(super) fn overlaps(a: TextRange, b: TextRange) -> bool {
|
||||
a.start < b.end && b.start < a.end
|
||||
}
|
||||
|
||||
/// A list of file names as a sentence reads them: `a.sv`, `a.sv` and `b.sv`,
|
||||
/// `a.sv`, `b.sv` and `c.sv`.
|
||||
fn and_list(names: &[String]) -> String {
|
||||
let quoted: Vec<String> = names.iter().map(|name| format!("`{name}`")).collect();
|
||||
match quoted.split_last() {
|
||||
None => "no files".to_string(),
|
||||
Some((last, [])) => last.clone(),
|
||||
Some((last, head)) => format!("{} and {last}", head.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use crate::apply;
|
||||
|
||||
/// The per-file splice contract, over texts — one lex plus the production
|
||||
/// [`super::pieces_match`], so every attack below asks the real question.
|
||||
fn pieces_match(
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let split = Split::read(before, after, edits, path, what)?;
|
||||
super::pieces_match(&split, edits, path, what)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the splice verifier, and the attacks on it
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A module whose port list is one per line, with a comment on each port —
|
||||
/// the shape every one of the attacks below tries to damage.
|
||||
const PORTS: &str =
|
||||
"module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n";
|
||||
|
||||
/// The edit `add_port` produces for `PORTS`: a `,` before the last port's
|
||||
/// comment and the new port after it.
|
||||
fn add_edits() -> Vec<TextEdit> {
|
||||
let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32;
|
||||
let after_comment = PORTS.find("*/").expect("comment") as u32 + 2;
|
||||
vec![
|
||||
TextEdit { range: TextRange::empty(end), new_text: ",".into() },
|
||||
TextEdit {
|
||||
range: TextRange::empty(after_comment),
|
||||
new_text: "\n input logic [7:0] cfg".into(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn splice_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_splice_the_engine_actually_produces_verifies() {
|
||||
let honest = apply(PORTS, &add_edits());
|
||||
assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass");
|
||||
assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() {
|
||||
// The hazard the two-edit shape exists to avoid: a `,` after `//` is a
|
||||
// `,` nobody will ever see.
|
||||
let corrupted = PORTS
|
||||
.replace("// the clock", "// the clock,")
|
||||
.replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg");
|
||||
assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_landed_at_the_wrong_place_is_rejected() {
|
||||
// The same tokens, spliced one port earlier: every piece is accounted
|
||||
// for, but not in the order the edits promised.
|
||||
let corrupted = apply(PORTS, &add_edits())
|
||||
.replace("input clk,", "input clk, input logic [7:0] cfg,")
|
||||
.replace(",\n input logic [7:0] cfg\n)", "\n)");
|
||||
assert!(splice_attack(&corrupted).is_err(), "position is part of the promise");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_also_dropped_a_comment_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace(" // a", "");
|
||||
let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;");
|
||||
assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_wrote_more_than_it_promised_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;");
|
||||
assert!(splice_attack(&corrupted).is_err(), "an invented declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_landed_inside_a_string_is_rejected() {
|
||||
let text = "module m;\n initial $display(\"hello\");\nendmodule\n";
|
||||
let at = text.find("hello").expect("string") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
|
||||
let corrupted = apply(text, &edits);
|
||||
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
|
||||
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_would_swallow_a_comment_is_refused() {
|
||||
// The one rule the piece comparison cannot see on its own: a comment
|
||||
// inside a deleted range disappears from *both* sides.
|
||||
let start = PORTS.find("input rst").expect("rst") as u32;
|
||||
let end = PORTS.find("*/").expect("comment") as u32 + 2;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(PORTS, &edits);
|
||||
let outcome =
|
||||
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
|
||||
let message = outcome.expect_err("a deleted comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_whose_result_does_not_lex_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops");
|
||||
assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4)
|
||||
// ------------------------------------------------------------------
|
||||
//
|
||||
// 2026-09-05: `comments_kept` replaced "no deletion may cover a comment",
|
||||
// so that `ports::ansi` can move a body declaration's comment onto the
|
||||
// ANSI port that declaration becomes. Every attack below is a crafted
|
||||
// (input, corrupted output) pair the relaxation could plausibly forgive.
|
||||
|
||||
/// A Verilog-2001 header whose two declarations each carry a comment —
|
||||
/// the shape the ANSI conversion has to move a comment out of.
|
||||
const MOVED: &str =
|
||||
"module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n";
|
||||
|
||||
/// The edits `convert_to_ansi` really produces for `MOVED`.
|
||||
fn move_edits() -> Vec<TextEdit> {
|
||||
let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())];
|
||||
let at = MOVED.find("module m").expect("header") as u32;
|
||||
let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at)
|
||||
.expect("the conversion the attacks corrupt");
|
||||
edit.edits.into_iter().next().expect("one file").1
|
||||
}
|
||||
|
||||
fn move_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(
|
||||
MOVED,
|
||||
corrupted,
|
||||
&move_edits(),
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_moved_comments_the_engine_actually_writes_verify() {
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
assert_eq!(move_attack(&honest), Ok(()), "the real output must pass");
|
||||
assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}");
|
||||
assert!(honest.contains("input a, // the note"), "{honest}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() {
|
||||
// The exact hole the character budget exists for: one of the two
|
||||
// `// the note`s is dropped, and a search for its text still finds
|
||||
// the other one.
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1);
|
||||
let message = move_attack(&corrupted).expect_err("one comment short is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() {
|
||||
// Same character count, different text: the budget alone would
|
||||
// forgive this one, and the per-comment search does not.
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1);
|
||||
let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_shortened_a_comment_is_rejected() {
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1);
|
||||
let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_left_the_comment_where_it_was_is_rejected() {
|
||||
// The deletion really deleted, but the comment was written back into
|
||||
// the *body* rather than into the header: every comment is still
|
||||
// there, and the piece order is not what the edits promised.
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
let corrupted = honest
|
||||
.replace("input a, // the note", "input a,")
|
||||
.replace("endmodule", "// the note\nendmodule");
|
||||
// `never_dropped` passes this one: every count is equal on both sides
|
||||
// (the comment really was deleted and really was written back once).
|
||||
// The *piece comparison* is the guard, because where a comment lands
|
||||
// is bound to where the edits put it — which is also the answer to
|
||||
// "a comment deleted here and written back somewhere unrelated".
|
||||
let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal");
|
||||
assert!(message.contains("where the comment `// the note` belongs"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() {
|
||||
// The bug this half of the rule was added for, reproduced as the edits
|
||||
// that caused it: one declaration declares two ports, and its comment
|
||||
// is written onto *both*. Nothing is dropped, and the piece comparison
|
||||
// cannot object — it checks the edits against themselves, and the
|
||||
// duplicate is in the edits. Only counting the file's comments sees it.
|
||||
const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n";
|
||||
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
|
||||
let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3);
|
||||
let edits = vec![
|
||||
TextEdit { range: TextRange::empty(a), new_text: "input ".into() },
|
||||
TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() },
|
||||
TextEdit { range: TextRange::empty(b), new_text: "input ".into() },
|
||||
TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() },
|
||||
TextEdit {
|
||||
range: TextRange::new(at(" input a,"), at("endmodule")),
|
||||
new_text: String::new(),
|
||||
},
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a doubled comment is a refusal");
|
||||
assert!(message.contains("would write the comment"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() {
|
||||
// The old rule's own case, restated: no edit writes the comment, so
|
||||
// the relaxation must not reach it.
|
||||
let start = MOVED.find("input a;").expect("a") as u32;
|
||||
let end = MOVED.find("\n output").expect("output") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(MOVED, &edits);
|
||||
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a deleted comment nothing writes back is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 2026-09-05 rework: the duplication half, the equation, and attributes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() {
|
||||
// QA's V-1 pair. Nothing deletes — or even overlaps — the body's own
|
||||
// `// shared`, and two pure insertions each write it again. Every
|
||||
// count only grows, so "before is a subset of after" forgives it, and
|
||||
// the piece comparison cannot object because the duplicates are in the
|
||||
// edits. Only `wrote <= gone` sees it.
|
||||
const SHARED: &str =
|
||||
"module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n";
|
||||
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
|
||||
let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4);
|
||||
let edits = vec![
|
||||
TextEdit { range: TextRange::empty(a), new_text: " // shared".into() },
|
||||
TextEdit { range: TextRange::empty(b), new_text: " // shared".into() },
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a duplicated comment is a refusal");
|
||||
assert!(message.contains("comments are never duplicated"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() {
|
||||
// The whitelist, and the whole of it. `add_port` and
|
||||
// `propagate_ports` write `/* TODO: connect */` themselves, and a
|
||||
// module gains its ports one at a time — so the second addition to a
|
||||
// file finds the first one's placeholder already sitting there and
|
||||
// writes another. `wrote > gone` with nothing deleted, and legitimate.
|
||||
let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n";
|
||||
let at = source.find("))").expect("list") as u32 + 1;
|
||||
let edits = vec![TextEdit {
|
||||
range: TextRange::empty(at),
|
||||
new_text: ", .b(/* TODO: connect */)".into(),
|
||||
}];
|
||||
let spliced = apply(source, &edits);
|
||||
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
|
||||
let outcome =
|
||||
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
|
||||
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() {
|
||||
// Masked corruption of the third kind: the edits are honest — they
|
||||
// delete both `// the note`s and write both back — and the *applied*
|
||||
// text carries a third. Neither "nothing is lost" nor "written back
|
||||
// where it was deleted" can see that; only the equation can.
|
||||
let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule");
|
||||
let message = move_attack(&corrupted).expect_err("an invented copy is a refusal");
|
||||
assert!(message.contains("where its edits account for it"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() {
|
||||
// A `//` is only a comment where the lexer says it is. Written back
|
||||
// inside a string literal, or swallowed into the comment next to it,
|
||||
// the text is present in the file and absent from its pieces — which
|
||||
// is exactly the substring search this rule refuses to be.
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
let in_string = honest
|
||||
.replacen(" // the note", "", 1)
|
||||
.replace("endmodule", " initial $display(\"// the note\");\nendmodule");
|
||||
let message = move_attack(&in_string).expect_err("a string is not a comment");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
|
||||
let nested = honest
|
||||
.replacen(" // the note", "", 1)
|
||||
.replace("// the note", "// the note // the note");
|
||||
let message = move_attack(&nested).expect_err("one comment is not two");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
/// A body declaration carrying an attribute instance. `Item.span` covers
|
||||
/// the `(* keep *)`, so a deletion hides it from *both* sides of the piece
|
||||
/// comparison exactly the way it hides a comment — QA's finding V-2.
|
||||
const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n";
|
||||
|
||||
/// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus
|
||||
/// whatever `written` says) before the header name, and the whole body
|
||||
/// declaration gone.
|
||||
fn attribute_edits(written: &str) -> Vec<TextEdit> {
|
||||
let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32;
|
||||
vec![
|
||||
TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() },
|
||||
TextEdit {
|
||||
range: TextRange::new(at(" (* keep *)"), at("endmodule")),
|
||||
new_text: String::new(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
|
||||
let corrupted = apply(ATTRIBUTED, edits);
|
||||
pieces_match(
|
||||
ATTRIBUTED,
|
||||
&corrupted,
|
||||
edits,
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_swallows_an_attribute_is_rejected() {
|
||||
// The planner refuses this one first (`ports::ansi::attributes_clear`,
|
||||
// pinned in `tests/ansi.rs`); this is the verifier saying so a second
|
||||
// time, from the edits alone, for whatever writes them next.
|
||||
let message = attribute_attack(&attribute_edits("input "))
|
||||
.expect_err("a dropped attribute is a refusal");
|
||||
assert!(message.contains("attributes are never dropped"), "{message}");
|
||||
assert!(message.contains("`(* keep *)`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_moves_an_attribute_verifies() {
|
||||
// What the refusal above is protecting: an edit that really does carry
|
||||
// the attribute over is not what this rule is for.
|
||||
let edits = attribute_edits("(* keep *) input ");
|
||||
assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute");
|
||||
assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_rewrote_an_attribute_is_rejected() {
|
||||
// `(* keep *)` and `(* keep=1 *)` are not the same instruction to a
|
||||
// synthesizer, and an attribute is matched by exact text.
|
||||
let message = attribute_attack(&attribute_edits("(* keep=1 *) input "))
|
||||
.expect_err("a rewritten attribute is a refusal");
|
||||
assert!(message.contains("attributes are never dropped"), "{message}");
|
||||
}
|
||||
}
|
||||
@@ -10,13 +10,15 @@
|
||||
//! [`verify`] is the *rename* contract: the token stream may not change shape
|
||||
//! at all. [`verify_splice`] is the same contract for a refactoring that
|
||||
//! deliberately writes or deletes text (the port ones): the token stream may
|
||||
//! change only by exactly the pieces the edits spell, no comment may be
|
||||
//! deleted, no file may gain a parse error, and every name *outside* the
|
||||
//! edited ranges must still resolve to exactly what it did.
|
||||
//! change only by exactly the pieces the edits spell, no comment and no
|
||||
//! attribute may be deleted, no file may gain a parse error, and every name
|
||||
//! *outside* the edited ranges must still resolve to exactly what it did.
|
||||
//!
|
||||
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
|
||||
//! contract, kept separately, so the formatter's safety net does not widen.
|
||||
|
||||
mod ledger;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -31,6 +33,8 @@ use vlog_semantic::{
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
use crate::{apply, Shift, TextEdit};
|
||||
|
||||
use ledger::{overlaps, pieces_match, region_of, Split, Transit};
|
||||
|
||||
/// Check the whole edit, or refuse it whole.
|
||||
pub(crate) fn verify(
|
||||
scope: &mut Scope,
|
||||
@@ -63,7 +67,7 @@ pub(crate) fn verify(
|
||||
// cannot see them. A file that spells *either* is watched, which is what
|
||||
// catches a third file whose existing `new_name` reference the rename
|
||||
// would make ambiguous without touching a byte of it.
|
||||
let watched = watched_files(scope, edits, old_name, new_name);
|
||||
let watched = watched_files(scope, edits, &[old_name, new_name]);
|
||||
for &i in &watched {
|
||||
if scope.analysis(i).is_none() {
|
||||
return Err(ABANDONED.to_string());
|
||||
@@ -120,9 +124,11 @@ pub(crate) fn verify(
|
||||
/// in at the edits' positions and nothing else moved. An edit that landed
|
||||
/// in a string, split a token or wrote a `,` into a line comment cannot
|
||||
/// survive it.
|
||||
/// 2. **Comments are never dropped** (CLAUDE.md invariant 3): no deletion may
|
||||
/// cover a comment. A port or connection with a comment on it is refused,
|
||||
/// not silently un-commented.
|
||||
/// 2. **Comments and attributes are never dropped** (CLAUDE.md invariant 3):
|
||||
/// every comment and every `(* ... *)` the file had it still has, and no
|
||||
/// more. A deletion may cover one only when the edits write it back — which
|
||||
/// is how the ANSI conversion moves a body declaration's comment onto the
|
||||
/// port it becomes; see [`ledger::Ledger`].
|
||||
/// 3. **The file still parses**: a touched file may not gain a parse
|
||||
/// diagnostic it did not have.
|
||||
/// 4. **Resolution identity outside the edits.** Every declaration and every
|
||||
@@ -135,6 +141,54 @@ pub(crate) fn verify_splice(
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
watch_name: &str,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
verify_move(scope, edits, &[watch_name], what, &[])
|
||||
}
|
||||
|
||||
/// [`verify_splice`], for a refactoring that **moves text from one file into
|
||||
/// another** — which is what extracting a module into its own file is.
|
||||
///
|
||||
/// Everything is the same except the accounting of the pieces that are never
|
||||
/// dropped. Per file, "a comment this edit deletes must be one this edit
|
||||
/// writes back" is exactly right for every refactoring that stays inside one
|
||||
/// file, and exactly wrong for a move: the comment is deleted in `M.sv` and
|
||||
/// written in `N.sv`, so neither file balances on its own.
|
||||
///
|
||||
/// **The widening is bound to the bytes that move, not to the files.**
|
||||
/// `moving` names every file the move touches: a **source**, with the byte
|
||||
/// range the move takes its text out of (the selection), and a
|
||||
/// **destination** — a file that only receives — with an empty range. Per file
|
||||
/// `f` and per never-dropped text `t`, where `before`/`after` are the file's
|
||||
/// own counts, `gone` the old pieces a non-empty edit range covers, `wrote` the
|
||||
/// pieces the edits' own text spells, and `out` the pieces of `gone` that sit
|
||||
/// **inside** `f`'s region — the ones in transit:
|
||||
///
|
||||
/// 1. `after_f + out_f >= before_f` — nothing is lost. A file may end up short
|
||||
/// only by exactly what left through its own region.
|
||||
/// 2. `wrote_f <= (gone_f - out_f) + in_f`, unless the text is one a
|
||||
/// refactoring generated itself (`ledger::generated`) — nothing is duplicated. `in_f` is the whole
|
||||
/// transit (`Σ out`) for a destination and zero for everyone else, so a
|
||||
/// deletion *outside* the region is an ordinary deletion that has to be
|
||||
/// written back in its own file exactly as before.
|
||||
/// 3. `after_f == before_f - gone_f + wrote_f` — the applied text says exactly
|
||||
/// what the edits say, transit out counted as gone and transit in as wrote.
|
||||
/// 4. `Σ over destinations of (wrote - gone) == Σ over sources of out` — the
|
||||
/// transit lands, exactly once, in the files the move named.
|
||||
///
|
||||
/// A file `moving` does not name keeps the per-file contract untouched, so a
|
||||
/// piece in transit to a file the move never named is refused twice over: by
|
||||
/// that file's own rule 2, and by rule 4. See
|
||||
/// `docs/features/extract-inline-module/README.md` for the attack pairs.
|
||||
///
|
||||
/// `watched` are the names whose meaning the refactoring changes (the module
|
||||
/// whose ports moved; both module names, for an extraction), which is what
|
||||
/// widens the resolution check beyond the edited files.
|
||||
pub(crate) fn verify_move(
|
||||
scope: &mut Scope,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
watched_names: &[&str],
|
||||
what: &str,
|
||||
moving: &[(usize, TextRange)],
|
||||
) -> Result<(), String> {
|
||||
let abandoned = format!("lucisv could not verify {what}, so it made no edits.");
|
||||
let edited: Vec<(PathBuf, String)> = edits
|
||||
@@ -148,9 +202,19 @@ pub(crate) fn verify_splice(
|
||||
return Err(abandoned);
|
||||
}
|
||||
|
||||
let mut transit = Transit::default();
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(abandoned) };
|
||||
pieces_match(before, text, edits, path, what)?;
|
||||
let split = Split::read(before, text, edits, path, what)?;
|
||||
match region_of(moving, *i) {
|
||||
// A file the move names balances against the pieces in transit
|
||||
// rather than on its own; its positional comparison is unchanged.
|
||||
Some(region) => {
|
||||
transit.add(&display(path), region, &split, edits);
|
||||
split.positions_match(edits, path, what)?;
|
||||
}
|
||||
None => pieces_match(&split, edits, path, what)?,
|
||||
}
|
||||
// A tolerant parse of a file that was already broken still reports its
|
||||
// old diagnostics, so the bar is "no *new* one", not "none".
|
||||
let (before_count, after_count) =
|
||||
@@ -162,10 +226,11 @@ pub(crate) fn verify_splice(
|
||||
));
|
||||
}
|
||||
}
|
||||
transit.check(what)?;
|
||||
|
||||
let shifts = Shifts::new(scope, edits, "");
|
||||
let excluded = Excluded::new(scope, edits);
|
||||
let watched = watched_files(scope, edits, watch_name, watch_name);
|
||||
let watched = watched_files(scope, edits, watched_names);
|
||||
for &i in &watched {
|
||||
if scope.analysis(i).is_none() {
|
||||
return Err(abandoned);
|
||||
@@ -259,19 +324,14 @@ impl Excluded {
|
||||
/// is a sound *superset* of "has a token spelling the name" — a token spells
|
||||
/// its name literally, so it is always found — and it errs by watching a few
|
||||
/// files whose only mention is in a comment.
|
||||
fn watched_files(
|
||||
scope: &Scope,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
old_name: &str,
|
||||
new_name: &str,
|
||||
) -> Vec<usize> {
|
||||
fn watched_files(scope: &Scope, edits: &[(usize, Vec<TextEdit>)], names: &[&str]) -> Vec<usize> {
|
||||
let mut watched: Vec<usize> = edits.iter().map(|(i, _)| *i).collect();
|
||||
for i in 0..scope.len() {
|
||||
let Some(text) = scope.text(i) else { continue };
|
||||
if watched.contains(&i) {
|
||||
continue;
|
||||
}
|
||||
if contains_word(text, old_name) || contains_word(text, new_name) {
|
||||
if names.iter().any(|name| contains_word(text, name)) {
|
||||
watched.push(i);
|
||||
}
|
||||
}
|
||||
@@ -342,148 +402,6 @@ fn tokens_match(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// lexical splice
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// One lexical piece of a file, in source order: a code token, or a comment.
|
||||
/// Comments are pieces of their own rather than trivia hanging off a token,
|
||||
/// because an insertion can legitimately move which token a comment attaches
|
||||
/// to without moving the comment itself.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Piece {
|
||||
Code(TokenKind, String),
|
||||
Comment(String),
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
/// How the piece is named in a refusal.
|
||||
fn describe(&self) -> String {
|
||||
match self {
|
||||
Piece::Code(_, text) => format!("the token `{text}`"),
|
||||
Piece::Comment(text) => format!("the comment `{text}`"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every piece of a file with the bytes it occupies, in source order.
|
||||
fn pieces(text: &str) -> Option<Vec<(TextRange, Piece)>> {
|
||||
let tokens = tokenize(text).ok()?;
|
||||
let mut out: Vec<(TextRange, Piece)> = Vec::new();
|
||||
for token in &tokens {
|
||||
for comment in &token.leading {
|
||||
out.push((comment.span, Piece::Comment(comment.text.clone())));
|
||||
}
|
||||
if token.kind != TokenKind::Eof {
|
||||
out.push((token.span, Piece::Code(token.kind, token.text.clone())));
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push((comment.span, Piece::Comment(comment.text.clone())));
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The edited file must lex to the original's pieces with the edits' own
|
||||
/// pieces written in where the edits are — and to nothing else.
|
||||
fn pieces_match(
|
||||
before: &str,
|
||||
after: &str,
|
||||
edits: &[TextEdit],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
|
||||
return Err(format!(
|
||||
"{} would no longer lex after {what}; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
};
|
||||
// Invariant 3, checked here rather than trusted to the planner: a deletion
|
||||
// that covers a comment would delete it from both sides of this comparison
|
||||
// and pass, so it is refused outright.
|
||||
for (span, piece) in &old {
|
||||
let deleted = edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span));
|
||||
if deleted && matches!(piece, Piece::Comment(_)) {
|
||||
return Err(format!(
|
||||
"{what} would delete {} in {}; comments are never dropped, so nothing was edited.",
|
||||
piece.describe(),
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut expected: Vec<Piece> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
|
||||
for edit in edits {
|
||||
let Some(pieces) = pieces(&edit.new_text) else {
|
||||
return Err(format!("{what} would write text that does not lex; no edits were made."));
|
||||
};
|
||||
written.push(pieces);
|
||||
}
|
||||
for (span, piece) in old {
|
||||
while let (Some(edit), Some(pieces)) = (edits.get(next), written.get(next)) {
|
||||
if edit.range.start > span.start {
|
||||
break;
|
||||
}
|
||||
expected.extend(pieces.iter().map(|(_, piece)| match piece {
|
||||
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
|
||||
Piece::Comment(text) => Piece::Comment(text.clone()),
|
||||
}));
|
||||
next += 1;
|
||||
}
|
||||
if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, span)) {
|
||||
continue;
|
||||
}
|
||||
expected.push(piece);
|
||||
}
|
||||
while let Some(pieces) = written.get(next) {
|
||||
expected.extend(pieces.iter().map(|(_, piece)| match piece {
|
||||
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
|
||||
Piece::Comment(text) => Piece::Comment(text.clone()),
|
||||
}));
|
||||
next += 1;
|
||||
}
|
||||
|
||||
let actual: Vec<Piece> = new.into_iter().map(|(_, piece)| piece).collect();
|
||||
for (n, expected) in expected.iter().enumerate() {
|
||||
match actual.get(n) {
|
||||
Some(actual) if actual == expected => {}
|
||||
Some(actual) => {
|
||||
return Err(format!(
|
||||
"{what} would write {} where {} belongs in {}; no edits were made.",
|
||||
actual.describe(),
|
||||
expected.describe(),
|
||||
display(path)
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"{what} would lose {} in {}; no edits were made.",
|
||||
expected.describe(),
|
||||
display(path)
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
if actual.len() > expected.len() {
|
||||
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
|
||||
return Err(format!(
|
||||
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether two byte ranges share a byte. Empty ranges — the insertions —
|
||||
/// overlap nothing: they replace no text, so they delete nothing.
|
||||
fn overlaps(a: TextRange, b: TextRange) -> bool {
|
||||
a.start < b.end && b.start < a.end
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// resolution identity
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -720,108 +638,6 @@ mod tests {
|
||||
assert!(attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the splice verifier, and the attacks on it
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A module whose port list is one per line, with a comment on each port —
|
||||
/// the shape every one of the attacks below tries to damage.
|
||||
const PORTS: &str =
|
||||
"module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n";
|
||||
|
||||
/// The edit `add_port` produces for `PORTS`: a `,` before the last port's
|
||||
/// comment and the new port after it.
|
||||
fn add_edits() -> Vec<TextEdit> {
|
||||
let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32;
|
||||
let after_comment = PORTS.find("*/").expect("comment") as u32 + 2;
|
||||
vec![
|
||||
TextEdit { range: TextRange::empty(end), new_text: ",".into() },
|
||||
TextEdit {
|
||||
range: TextRange::empty(after_comment),
|
||||
new_text: "\n input logic [7:0] cfg".into(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn splice_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_splice_the_engine_actually_produces_verifies() {
|
||||
let honest = apply(PORTS, &add_edits());
|
||||
assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass");
|
||||
assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() {
|
||||
// The hazard the two-edit shape exists to avoid: a `,` after `//` is a
|
||||
// `,` nobody will ever see.
|
||||
let corrupted = PORTS
|
||||
.replace("// the clock", "// the clock,")
|
||||
.replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg");
|
||||
assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_landed_at_the_wrong_place_is_rejected() {
|
||||
// The same tokens, spliced one port earlier: every piece is accounted
|
||||
// for, but not in the order the edits promised.
|
||||
let corrupted = apply(PORTS, &add_edits())
|
||||
.replace("input clk,", "input clk, input logic [7:0] cfg,")
|
||||
.replace(",\n input logic [7:0] cfg\n)", "\n)");
|
||||
assert!(splice_attack(&corrupted).is_err(), "position is part of the promise");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_also_dropped_a_comment_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace(" // a", "");
|
||||
assert!(splice_attack(&corrupted).is_err(), "comments are never dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;");
|
||||
assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_wrote_more_than_it_promised_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;");
|
||||
assert!(splice_attack(&corrupted).is_err(), "an invented declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_landed_inside_a_string_is_rejected() {
|
||||
let text = "module m;\n initial $display(\"hello\");\nendmodule\n";
|
||||
let at = text.find("hello").expect("string") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
|
||||
let corrupted = apply(text, &edits);
|
||||
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
|
||||
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_would_swallow_a_comment_is_refused() {
|
||||
// The one rule the piece comparison cannot see on its own: a comment
|
||||
// inside a deleted range disappears from *both* sides.
|
||||
let start = PORTS.find("input rst").expect("rst") as u32;
|
||||
let end = PORTS.find("*/").expect("comment") as u32 + 2;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(PORTS, &edits);
|
||||
let outcome =
|
||||
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
|
||||
let message = outcome.expect_err("a deleted comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_whose_result_does_not_lex_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops");
|
||||
assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_captures_a_name_outside_the_edit_is_rejected() {
|
||||
// The resolution half: the module already has a net called `cfg`, and
|
||||
@@ -865,6 +681,330 @@ 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<TextEdit>)> {
|
||||
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())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the moved-piece rule, and the attacks on it (CLAUDE.md invariant 4)
|
||||
// ------------------------------------------------------------------
|
||||
//
|
||||
// 2026-09-05: `verify_move` lets a piece that is never dropped travel out
|
||||
// of the region an extraction moves and into the file that receives it — a
|
||||
// comment deleted in `m.sv` and written in `sum.sv` balances across the
|
||||
// move and in neither file alone.
|
||||
//
|
||||
// 2026-09-06 rework (QA's finding V1): the allowance is bound to the
|
||||
// **region**, not to the files, and every attack below goes through the
|
||||
// production entry point — a real `Scope`, the raw `TextEdit`s and
|
||||
// `verify_move` itself, positional comparison and all. The pair in
|
||||
// `a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance` is
|
||||
// the one the file-scoped pool forgave, and no ledger-only helper could
|
||||
// have seen it.
|
||||
|
||||
/// A module with a comment and an attribute inside the region an
|
||||
/// extraction moves — the two pieces the ledger is the only guard for.
|
||||
const EXTRACT: &str = "module m (\n input logic a,\n input logic b,\n output logic q\n);\n logic s;\n (* keep *) assign s = a & b; // the and\n assign q = s | 1'b0;\nendmodule\n";
|
||||
|
||||
const MOVED_WHAT: &str = "extracting `sum` out of `m`";
|
||||
|
||||
/// One extraction, as the verifier is told about it: the edits per file,
|
||||
/// and the bytes the move carries out of `m.sv`.
|
||||
struct Plan {
|
||||
m: Vec<TextEdit>,
|
||||
n: Vec<TextEdit>,
|
||||
region: TextRange,
|
||||
}
|
||||
|
||||
/// The edits the extraction really makes for `source`: one replacement in
|
||||
/// `m.sv`, one insertion into an empty `sum.sv`.
|
||||
fn extraction(source: &str) -> Plan {
|
||||
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
|
||||
let start = source.find("(* keep *)").expect("attribute") as u32;
|
||||
let end = source.find("// the and").expect("comment") as u32 + 10;
|
||||
let edit = crate::extract_module(
|
||||
&files,
|
||||
Path::new("/rtl/m.sv"),
|
||||
start,
|
||||
end,
|
||||
"sum",
|
||||
crate::Home::NewFile,
|
||||
)
|
||||
.expect("the extraction the attacks corrupt");
|
||||
let m = edit.edits_for(&PathBuf::from("/rtl/m.sv")).to_vec();
|
||||
let n = edit.edits_for(&PathBuf::from("/rtl/sum.sv")).to_vec();
|
||||
let region = m.first().expect("the replacement").range;
|
||||
Plan { m, n, region }
|
||||
}
|
||||
|
||||
/// Verify a plan the way the engine does: a real `Scope` over the two
|
||||
/// files, the raw edits, and the production `verify_move`. `moves` is what
|
||||
/// the engine passes — `m.sv` as the source of the region and `sum.sv` as
|
||||
/// the file that receives — or nothing at all, for the opt-in test.
|
||||
fn verified(source: &str, plan: &Plan, moves: bool) -> Result<(), String> {
|
||||
let files = vec![
|
||||
(PathBuf::from("/rtl/m.sv"), source.to_string()),
|
||||
(PathBuf::from("/rtl/sum.sv"), String::new()),
|
||||
];
|
||||
let mut scope = Scope::build(&files);
|
||||
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (m, n) = (at("/rtl/m.sv"), at("/rtl/sum.sv"));
|
||||
let edits = vec![(m, plan.m.clone()), (n, plan.n.clone())];
|
||||
let moving = match moves {
|
||||
true => vec![(m, plan.region), (n, TextRange::empty(0))],
|
||||
false => Vec::new(),
|
||||
};
|
||||
verify_move(&mut scope, &edits, &["m", "sum"], MOVED_WHAT, &moving)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_move_the_engine_actually_produces_verifies() {
|
||||
let plan = extraction(EXTRACT);
|
||||
assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "the real output must pass");
|
||||
let (m, n) = (apply(EXTRACT, &plan.m), apply("", &plan.n));
|
||||
// The comment *and* the attribute travel, which is the whole of what
|
||||
// the allowance is for.
|
||||
assert!(n.contains("// the and") && n.contains("(* keep *)"), "{n}");
|
||||
assert!(!m.contains("// the and") && !m.contains("(* keep *)"), "{m}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_deleted_outside_the_region_is_not_one_the_move_may_balance() {
|
||||
// QA's V1 pair, and the reason the allowance is bound to the region
|
||||
// rather than to the files. `m.sv` holds the same comment twice: one
|
||||
// inside the region, one on a line the extraction never touches. The
|
||||
// corrupted plan deletes *both* and writes the comment into `sum.sv`
|
||||
// twice — so a pool kept over the two files balanced two in against
|
||||
// two out and forgave it, while `m.sv` alone lost a comment nothing
|
||||
// ever moved.
|
||||
let source = EXTRACT.replace("assign q = s | 1'b0;", "assign q = s | 1'b0; // the and");
|
||||
let mut plan = extraction(&source);
|
||||
let stray = source.rfind("// the and").expect("the untouched copy") as u32;
|
||||
plan.m.push(TextEdit {
|
||||
range: TextRange::new(stray - 1, stray + 10),
|
||||
new_text: String::new(),
|
||||
});
|
||||
for edit in &mut plan.n {
|
||||
edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and");
|
||||
}
|
||||
// Each file is honest about its own edits — this is not a positional
|
||||
// failure — and the counts over the pair really do balance: two copies
|
||||
// before, two after. Only the region says which of them moved.
|
||||
let (m, n) = (apply(&source, &plan.m), apply("", &plan.n));
|
||||
assert_eq!(source.matches("// the and").count(), 2, "two copies to begin with");
|
||||
assert_eq!(
|
||||
m.matches("// the and").count() + n.matches("// the and").count(),
|
||||
2,
|
||||
"and two after, which is what a pool kept over the files forgave"
|
||||
);
|
||||
let message = verified(&source, &plan, true).expect_err("a lost copy is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
assert!(message.contains("m.sv"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_that_lands_twice_in_the_new_file_is_rejected() {
|
||||
// The corruption in the *edits* rather than in the application: the
|
||||
// new file's text carries the comment twice where the region held it
|
||||
// once. The transit is an allowance for one.
|
||||
let mut plan = extraction(EXTRACT);
|
||||
for edit in &mut plan.n {
|
||||
edit.new_text = edit.new_text.replace("// the and", "// the and\n // the and");
|
||||
}
|
||||
let message = verified(EXTRACT, &plan, true).expect_err("a duplicate is a refusal");
|
||||
assert!(message.contains("never duplicated"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_left_behind_as_well_as_moved_is_rejected() {
|
||||
// Deleted once, written twice — once where it belongs and once back
|
||||
// into the file it came from, above the instantiation.
|
||||
let mut plan = extraction(EXTRACT);
|
||||
for edit in &mut plan.m {
|
||||
edit.new_text = format!("// the and\n {}", edit.new_text);
|
||||
}
|
||||
let message = verified(EXTRACT, &plan, true).expect_err("a duplicate is a refusal");
|
||||
assert!(message.contains("never duplicated"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_the_move_carries_that_lands_nowhere_is_rejected() {
|
||||
// The whole hazard of the allowance: the comment leaves `m.sv`
|
||||
// legitimately, and the corrupted `sum.sv` simply never writes it.
|
||||
// Per file, both halves look innocent.
|
||||
let mut plan = extraction(EXTRACT);
|
||||
for edit in &mut plan.n {
|
||||
edit.new_text = edit.new_text.replace(" // the and", "");
|
||||
}
|
||||
let message = verified(EXTRACT, &plan, true).expect_err("a lost comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
assert!(message.contains("write it back nowhere"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_the_move_carries_that_lands_nowhere_is_rejected() {
|
||||
let mut plan = extraction(EXTRACT);
|
||||
for edit in &mut plan.n {
|
||||
edit.new_text = edit.new_text.replace("(* keep *) ", "");
|
||||
}
|
||||
let message = verified(EXTRACT, &plan, true).expect_err("a lost attribute is a refusal");
|
||||
assert!(message.contains("attributes are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_the_new_file_invents_with_nothing_in_transit_is_rejected() {
|
||||
// Nothing deleted it anywhere, and the transit is the only allowance a
|
||||
// destination has.
|
||||
let mut plan = extraction(EXTRACT);
|
||||
for edit in &mut plan.n {
|
||||
edit.new_text = edit.new_text.replace("endmodule", " // invented\nendmodule");
|
||||
}
|
||||
let message = verified(EXTRACT, &plan, true).expect_err("an invented comment is a refusal");
|
||||
assert!(message.contains("never duplicated"), "{message}");
|
||||
assert!(message.contains("// invented"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_placeholder_the_new_file_writes_is_not_a_duplicate() {
|
||||
// The whitelist is untouched by the rework: `/* TODO: connect */` is
|
||||
// text a refactoring writes itself, not a piece it moves.
|
||||
let mut plan = extraction(EXTRACT);
|
||||
for edit in &mut plan.n {
|
||||
edit.new_text = edit.new_text.replace("endmodule", " /* TODO: connect */\nendmodule");
|
||||
}
|
||||
assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "the whitelist still whitelists");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_in_transit_to_a_file_the_move_did_not_name_is_rejected() {
|
||||
// The move names `m.sv` and `sum.sv`; the plan writes the new module
|
||||
// into a third file instead. That file never asked for an allowance,
|
||||
// so it keeps the per-file contract and the comment it writes is one
|
||||
// it never deleted.
|
||||
let plan = extraction(EXTRACT);
|
||||
let files = vec![
|
||||
(PathBuf::from("/rtl/m.sv"), EXTRACT.to_string()),
|
||||
(PathBuf::from("/rtl/other.sv"), String::new()),
|
||||
(PathBuf::from("/rtl/sum.sv"), String::new()),
|
||||
];
|
||||
let mut scope = Scope::build(&files);
|
||||
let at = |name: &str| scope.index_of(Path::new(name)).expect(name);
|
||||
let (m, other, sum) = (at("/rtl/m.sv"), at("/rtl/other.sv"), at("/rtl/sum.sv"));
|
||||
let edits = vec![(m, plan.m.clone()), (other, plan.n.clone())];
|
||||
let moving = vec![(m, plan.region), (sum, TextRange::empty(0))];
|
||||
let message = verify_move(&mut scope, &edits, &["m", "sum"], MOVED_WHAT, &moving)
|
||||
.expect_err("a file the move did not name is not a destination");
|
||||
assert!(message.contains("never duplicated"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_wider_than_the_region_is_an_ordinary_deletion() {
|
||||
// The old fifth attack, through the production entry: a deletion
|
||||
// widened past the selection swallows `// the rest`, which was never
|
||||
// the extraction's to move and which nothing writes back. Only the
|
||||
// pieces *inside* the region are in transit.
|
||||
let source = EXTRACT.replace("assign q = s | 1'b0;", "assign q = s | 1'b0; // the rest");
|
||||
let mut plan = extraction(&source);
|
||||
let end = source.find("// the rest").expect("comment") as u32 + 11;
|
||||
plan.m[0].range = TextRange::new(plan.m[0].range.start, end);
|
||||
let message = verified(&source, &plan, true).expect_err("a swallowed comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
assert!(message.contains("// the rest"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_that_does_not_cover_what_the_edits_delete_is_rejected() {
|
||||
// The planner lying about its own region is the same corruption seen
|
||||
// from the other side: it says the move takes only the `assign`, and
|
||||
// its edit deletes the trailing comment too.
|
||||
let mut plan = extraction(EXTRACT);
|
||||
let comment = EXTRACT.find("// the and").expect("comment") as u32;
|
||||
plan.region = TextRange::new(plan.region.start, comment);
|
||||
let message = verified(EXTRACT, &plan, true).expect_err("a lied-about region is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_widening_is_opt_in_and_a_refactoring_that_asked_for_none_still_gets_none() {
|
||||
// The same honest extraction, verified with an *empty* `moving` list:
|
||||
// the per-file contract refuses it, which is what says nothing else in
|
||||
// this crate lost a guard when `verify_move` gained one.
|
||||
let plan = extraction(EXTRACT);
|
||||
let message = verified(EXTRACT, &plan, false)
|
||||
.expect_err("without `moving`, a cross-file move is a dropped piece");
|
||||
assert!(message.contains("are never dropped"), "{message}");
|
||||
assert_eq!(verified(EXTRACT, &plan, true), Ok(()), "and with it, the same plan verifies");
|
||||
}
|
||||
|
||||
#[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
|
||||
@@ -0,0 +1,469 @@
|
||||
//! Which names cross the selection's boundary, and what the new module's
|
||||
//! header is therefore made of.
|
||||
//!
|
||||
//! `flow` says what is *done* to each name on each side; this says what each
|
||||
//! crossing name **becomes** — a port, a parameter, a copied `import`, or a
|
||||
//! refusal. Three closures run here, and they are one closure really: the
|
||||
//! signals the selection reads and drives, the parameters they and their own
|
||||
//! types depend on, and the imports the whole of that needs to resolve.
|
||||
//!
|
||||
//! The last of the three is the subtle one. What the new module has to be able
|
||||
//! to resolve is not "the names the selection writes down" but that *plus the
|
||||
//! type names of its own header* — a port declared `input logic [N-1:0] a`
|
||||
//! names `N` even though no statement in the selection does, and a port typed
|
||||
//! `word_t` needs whatever import supplied it. Both were found by the corpus
|
||||
//! and opentitan trials rather than by reasoning; see the feature README's
|
||||
//! work log.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{ItemKind, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind};
|
||||
|
||||
use crate::rename::display;
|
||||
|
||||
use super::flow;
|
||||
use super::region::Region;
|
||||
use super::render::{self, Param, Port};
|
||||
use super::{count, escaped, header_names, inside, inside_module, lost_name};
|
||||
use super::{outside_module, outside_module_member};
|
||||
use super::{slice, unmovable};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the boundary
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Everything that crosses the selection's boundary, classified.
|
||||
pub(super) struct Crossing {
|
||||
pub(super) ports: Vec<Port>,
|
||||
pub(super) params: Vec<Param>,
|
||||
pub(super) imports: Vec<String>,
|
||||
}
|
||||
|
||||
impl Crossing {
|
||||
pub(super) fn read(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
flow: &flow::Flow,
|
||||
packages: &[(String, TextRange)],
|
||||
new_file: bool,
|
||||
) -> Result<Crossing, String> {
|
||||
let mut ports: Vec<(TextRange, Port)> = Vec::new();
|
||||
let mut params: Vec<(TextRange, Param)> = Vec::new();
|
||||
let module = region.module_name().to_string();
|
||||
let mut wanted: Vec<String> = Vec::new();
|
||||
// Names a `package` of this file declares. `N` reaches one the way
|
||||
// `M` does — through a qualified spelling, or through an import of
|
||||
// that package which the new module is given a copy of.
|
||||
let mut from_package: Vec<(String, String)> = Vec::new();
|
||||
|
||||
for (n, symbol) in semantics.symbols().iter().enumerate() {
|
||||
let sides = flow.sides(SymbolId(n as u32));
|
||||
let declared_inside = inside(region, symbol.name_span);
|
||||
if declared_inside {
|
||||
if sides.used_outside() {
|
||||
return Err(escaped(&symbol.name));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !sides.used_inside() {
|
||||
continue;
|
||||
}
|
||||
// A module, an interface and a package are visible from every
|
||||
// file of the design, so one declared beside `M` is one `N` can
|
||||
// reach too — they never become ports and never refuse.
|
||||
if matches!(
|
||||
symbol.kind,
|
||||
SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if !inside_module(region, symbol.name_span) {
|
||||
// Not a port: a name the module itself does not declare is
|
||||
// one the new module reaches the way `M` did, or one `visible`
|
||||
// below refuses because a file of its own would not see it.
|
||||
if let Some(package) = package_of(packages, symbol.name_span) {
|
||||
from_package.push((package.to_string(), symbol.name.clone()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match symbol.kind {
|
||||
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var => {
|
||||
let dir = direction(&symbol.name, sides)?;
|
||||
let Some(site) = render::site_of(region.module, &symbol.name) else {
|
||||
return Err(lost_name(&symbol.name));
|
||||
};
|
||||
let port = render::port(text, &module, &symbol.name, &site, dir)?;
|
||||
ports.push((symbol.name_span, port));
|
||||
}
|
||||
SymbolKind::Param | SymbolKind::LocalParam => wanted.push(symbol.name.clone()),
|
||||
kind => return Err(unmovable(&symbol.name, &module, kind)),
|
||||
}
|
||||
}
|
||||
|
||||
// A **port's own type** may name a parameter — `input logic [N-1:0] a`
|
||||
// — and that parameter crosses the boundary as squarely as one the
|
||||
// selection reads, or the new module's header names nothing. So does
|
||||
// a parameter's type, and a parameter's default; the three are one
|
||||
// closure, run below until nothing new is wanted.
|
||||
let declared = declarations(semantics, region);
|
||||
for (_, port) in &ports {
|
||||
for word in &port.names {
|
||||
depends(&declared, &module, &port.name, word, &mut wanted)?;
|
||||
}
|
||||
}
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while let Some(name) = wanted.pop() {
|
||||
if seen.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
let Some(site) = render::site_of(region.module, &name) else {
|
||||
return Err(lost_name(&name));
|
||||
};
|
||||
let param = render::param(text, &module, &name, &site)?;
|
||||
for word in ¶m.names {
|
||||
depends(&declared, &module, &name, word, &mut wanted)?;
|
||||
}
|
||||
let span = span_of(semantics, region, &name);
|
||||
params.push((span, param));
|
||||
seen.push(name);
|
||||
}
|
||||
|
||||
ports.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
params.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
let needed = needed(text, semantics, flow, &ports, ¶ms);
|
||||
visible(text, semantics, region, packages, &needed, &module, new_file)?;
|
||||
let imports = imports(semantics, region, packages, &needed);
|
||||
reachable(text, &needed, &from_package, &imports)?;
|
||||
Ok(Crossing {
|
||||
ports: ports.into_iter().map(|(_, port)| port).collect(),
|
||||
params: params.into_iter().map(|(_, param)| param).collect(),
|
||||
imports,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn warnings(
|
||||
&self,
|
||||
new_name: &str,
|
||||
created: &Option<PathBuf>,
|
||||
file: &Path,
|
||||
) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
out.push(match created {
|
||||
Some(path) => format!(
|
||||
"`{new_name}` was written to a new file, `{}`.",
|
||||
display(path)
|
||||
),
|
||||
None => format!(
|
||||
"`{new_name}` was written below its neighbour in `{}`: this editor did not say it can create files, so lucisv did not make one.",
|
||||
display(file)
|
||||
),
|
||||
});
|
||||
out.push(format!(
|
||||
"lucisv gave `{new_name}` {} and {} from the names the selection reads and drives; check the directions before you rely on them.",
|
||||
count(self.ports.len(), "port"),
|
||||
count(self.params.len(), "parameter"),
|
||||
));
|
||||
if !self.imports.is_empty() {
|
||||
out.push(format!(
|
||||
"`{new_name}` imports {}, which the selection needed.",
|
||||
self.imports.iter().map(|path| format!("`{path}`")).collect::<Vec<_>>().join(", ")
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction one crossing signal's port gets, or the sentence saying why
|
||||
/// lucisv will not decide.
|
||||
fn direction(name: &str, sides: flow::Sides) -> Result<&'static str, String> {
|
||||
if sides.inside_unknown {
|
||||
return Err(format!(
|
||||
"the selection passes `{name}` to a task or function, and only that routine's declaration says whether it is an argument in or out; lucisv will not guess a port direction from it."
|
||||
));
|
||||
}
|
||||
if !sides.inside_write {
|
||||
return Ok("input");
|
||||
}
|
||||
if sides.outside_write {
|
||||
return Err(format!("`{name}` is driven on both sides of the selection."));
|
||||
}
|
||||
if sides.outside_unknown {
|
||||
return Err(format!(
|
||||
"the selection drives `{name}`, and something outside it passes the same name to a task or function, which may drive it too; lucisv will not make it an output over that."
|
||||
));
|
||||
}
|
||||
Ok("output")
|
||||
}
|
||||
|
||||
/// One identifier written in a header lucisv is about to move: a parameter it
|
||||
/// has to carry across too, a keyword or a package name it can ignore, or a
|
||||
/// declaration of `M`'s that a header in another module could not name.
|
||||
fn depends(
|
||||
declared: &HashMap<&str, SymbolKind>,
|
||||
module: &str,
|
||||
owner: &str,
|
||||
word: &str,
|
||||
wanted: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
match declared.get(word) {
|
||||
// A keyword (`logic`, `int`), a system function, or a name that comes
|
||||
// from somewhere `visible` and `reachable` judge on their own terms.
|
||||
None => Ok(()),
|
||||
Some(SymbolKind::Param | SymbolKind::LocalParam) => {
|
||||
wanted.push(word.to_string());
|
||||
Ok(())
|
||||
}
|
||||
Some(_) => Err(header_names(module, owner, word)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name the module's own scope declares, with its kind — what a
|
||||
/// parameter default is checked against.
|
||||
fn declarations<'s>(semantics: &'s Semantics, region: &Region<'_>) -> HashMap<&'s str, SymbolKind> {
|
||||
semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|symbol| inside_module(region, symbol.name_span))
|
||||
.map(|symbol| (symbol.name.as_str(), symbol.kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the module declares `name`, for ordering a header the way the source
|
||||
/// orders its declarations.
|
||||
fn span_of(semantics: &Semantics, region: &Region<'_>, name: &str) -> TextRange {
|
||||
semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.find(|symbol| symbol.name == name && inside_module(region, symbol.name_span))
|
||||
.map_or(TextRange::empty(0), |symbol| symbol.name_span)
|
||||
}
|
||||
|
||||
/// Every name the new module has to be able to resolve for itself: the names
|
||||
/// the selection writes down, plus the type names its own header will carry.
|
||||
///
|
||||
/// A header type is matched by the *text* the declaration wrote — the port's
|
||||
/// prefix is that text — so a `word_t` in a port list is the same reference the
|
||||
/// import judgement asks about, and not a second reading of it.
|
||||
fn needed<'s>(
|
||||
text: &str,
|
||||
semantics: &'s Semantics,
|
||||
flow: &flow::Flow,
|
||||
ports: &[(TextRange, Port)],
|
||||
params: &[(TextRange, Param)],
|
||||
) -> Vec<&'s vlog_semantic::Reference> {
|
||||
let mut out: Vec<&vlog_semantic::Reference> =
|
||||
flow.inside.iter().filter_map(|n| semantics.references().get(*n)).collect();
|
||||
let header: Vec<&str> = ports
|
||||
.iter()
|
||||
.map(|(_, port)| port.prefix.as_str())
|
||||
.chain(params.iter().map(|(_, param)| param.prefix.as_str()))
|
||||
.collect();
|
||||
for reference in semantics.references() {
|
||||
let written = slice(text, reference.name_span);
|
||||
if written.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if header.iter().any(|prefix| prefix.split_whitespace().any(|word| word == written)) {
|
||||
out.push(reference);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `import` paths the new module gets: the ones written in `M` that one of
|
||||
/// the names it needs could have come through.
|
||||
fn imports(
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
packages: &[(String, TextRange)],
|
||||
needed: &[&vlog_semantic::Reference],
|
||||
) -> Vec<String> {
|
||||
let Some(scope) = semantics
|
||||
.symbol_at(region.module.name_span.start)
|
||||
.and_then(|id| semantics.symbol(id))
|
||||
.and_then(|symbol| symbol.child_scope)
|
||||
.and_then(|id| semantics.scope(id))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for import in &scope.imports {
|
||||
let path = import.path();
|
||||
if out.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
if needed.iter().any(|r| supplied_by(semantics, packages, import, r)) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a use of a name could have come through an import of `package`.
|
||||
///
|
||||
/// Two shapes, because the binder answers them differently. A package
|
||||
/// **another file** declares leaves an [`Resolution::ExternalCandidate`] whose
|
||||
/// `paths` name it; a package **this file** declares is resolved on the spot,
|
||||
/// and what says so is that the declaration sits inside that package's own
|
||||
/// item span.
|
||||
fn supplied_by(
|
||||
semantics: &Semantics,
|
||||
packages: &[(String, TextRange)],
|
||||
import: &vlog_semantic::Import,
|
||||
reference: &vlog_semantic::Reference,
|
||||
) -> bool {
|
||||
if !import.supplies(&reference.name) {
|
||||
return false;
|
||||
}
|
||||
let package = import.package.as_str();
|
||||
match &reference.resolution {
|
||||
// The binder writes the import paths it walked into `paths`, in the
|
||||
// spelling the source wrote them (`p::*`, `p::w_t`) — so the question
|
||||
// is whether this very import is one of them, not whether some path
|
||||
// happens to end in the name.
|
||||
Resolution::ExternalCandidate { paths, .. }
|
||||
| Resolution::InheritedCandidate { paths, .. } => {
|
||||
paths.iter().any(|path| *path == import.path())
|
||||
}
|
||||
Resolution::Resolved(symbol) => semantics
|
||||
.symbol(*symbol)
|
||||
.and_then(|symbol| package_of(packages, symbol.name_span))
|
||||
.is_some_and(|declared_in| declared_in == package),
|
||||
Resolution::NotFound => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name the new module needs has to be one a file of its own can see: a
|
||||
/// declaration of `M`'s own (which becomes a port or a parameter), a unit of
|
||||
/// the design (a module, an interface, a package), or a member of a package.
|
||||
///
|
||||
/// What this refuses is the rest — a `typedef`, a `localparam` or a class
|
||||
/// written at the **file scope** of `M`'s file, which is a compilation-unit
|
||||
/// declaration and reaches exactly the files that were compiled with it. It
|
||||
/// runs over the names the new module writes down *and* the type names of its
|
||||
/// own header, so a port typed with a file-scope `typedef` is refused as
|
||||
/// squarely as a body reference to one.
|
||||
fn visible(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
packages: &[(String, TextRange)],
|
||||
needed: &[&vlog_semantic::Reference],
|
||||
module: &str,
|
||||
new_file: bool,
|
||||
) -> Result<(), String> {
|
||||
if !new_file {
|
||||
return Ok(());
|
||||
}
|
||||
for reference in needed {
|
||||
let Resolution::Resolved(id) = reference.resolution else { continue };
|
||||
let Some(symbol) = semantics.symbol(id) else { continue };
|
||||
if inside_module(region, symbol.name_span) {
|
||||
continue;
|
||||
}
|
||||
if package_of(packages, symbol.name_span).is_some() {
|
||||
continue;
|
||||
}
|
||||
if matches!(symbol.kind, SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package) {
|
||||
continue;
|
||||
}
|
||||
// A field of a struct and a signal of an interface each have a
|
||||
// declaration of their own, and naming it is not what the user needs
|
||||
// to read: what crosses the boundary is `s` or `bus`, and `f` is a
|
||||
// name of *its* type. So the head goes first when there is one.
|
||||
return Err(match access_head(text, reference.name_span) {
|
||||
Some(head) => outside_module_member(head, &symbol.name, module),
|
||||
None => outside_module(&symbol.name, module),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The head of a member access, if the reference is one: `s` in `s.f`, `bus`
|
||||
/// in `bus.data`, and `u` in `u.v.w`.
|
||||
///
|
||||
/// Read from the text rather than from the tree because that is where the
|
||||
/// question is cheap and exact: a reference's own span is the field, and what
|
||||
/// precedes it — a `.` and an identifier — is the thing the field belongs to.
|
||||
fn access_head(text: &str, span: TextRange) -> Option<&str> {
|
||||
let (mut at, mut head) = dotted_word_before(text, span.start as usize)?;
|
||||
while let Some((start, word)) = dotted_word_before(text, at) {
|
||||
at = start;
|
||||
head = word;
|
||||
}
|
||||
Some(head)
|
||||
}
|
||||
|
||||
/// The identifier written immediately before `at` and a `.`, with where it
|
||||
/// starts: `("s", …)` for `s.` and nothing at all for anything else.
|
||||
fn dotted_word_before(text: &str, at: usize) -> Option<(usize, &str)> {
|
||||
let rest = text.get(..at)?.trim_end().strip_suffix('.')?.trim_end();
|
||||
let start = rest
|
||||
.char_indices()
|
||||
.rev()
|
||||
.take_while(|(_, c)| c.is_alphanumeric() || *c == '_' || *c == '$')
|
||||
.last()
|
||||
.map(|(i, _)| i)?;
|
||||
let word = rest.get(start..)?;
|
||||
match word.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
true => None,
|
||||
false => Some((start, word)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A name a `package` of this file declares reaches the new module only if the
|
||||
/// new module can spell it: either every use writes the package out
|
||||
/// (`w_pkg::word_t`), or `M` imports it and lucisv copied that import across.
|
||||
fn reachable(
|
||||
text: &str,
|
||||
needed: &[&vlog_semantic::Reference],
|
||||
from_package: &[(String, String)],
|
||||
imports: &[String],
|
||||
) -> Result<(), String> {
|
||||
for (package, name) in from_package {
|
||||
let unqualified = needed
|
||||
.iter()
|
||||
.filter(|reference| reference.name == *name)
|
||||
.any(|reference| !qualified(text, reference.name_span));
|
||||
if !unqualified {
|
||||
continue;
|
||||
}
|
||||
let imported = imports
|
||||
.iter()
|
||||
.any(|path| path == &format!("{package}::*") || path == &format!("{package}::{name}"));
|
||||
if !imported {
|
||||
return Err(format!(
|
||||
"the selection uses `{name}`, which `{package}` declares, without writing `{package}::` in front of it and without an `import` lucisv could carry across; write the package out, or import it where the new module can see it."
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a name is written with its package in front of it: `w_pkg::word_t`.
|
||||
fn qualified(text: &str, span: TextRange) -> bool {
|
||||
text.get(..span.start as usize).is_some_and(|head| head.trim_end().ends_with("::"))
|
||||
}
|
||||
|
||||
/// The `package` of this file whose body holds `span`, if any.
|
||||
fn package_of(packages: &[(String, TextRange)], span: TextRange) -> Option<&str> {
|
||||
packages
|
||||
.iter()
|
||||
.find(|(_, at)| at.start <= span.start && span.end <= at.end)
|
||||
.map(|(name, _)| name.as_str())
|
||||
}
|
||||
|
||||
/// Every `package` this file declares, with the bytes it occupies.
|
||||
pub(super) fn packages(tree: &SourceFile) -> Vec<(String, TextRange)> {
|
||||
tree.items
|
||||
.iter()
|
||||
.filter_map(|item| match &item.kind {
|
||||
ItemKind::Package { name, .. } => Some((name.clone(), item.span)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,664 @@
|
||||
//! Which names cross the selection's boundary, and in which direction.
|
||||
//!
|
||||
//! The whole of "what ports does the new module need" is here, and it is one
|
||||
//! question asked of two tables: `vlog_semantic`'s references say *which
|
||||
//! declaration* each name in the module means, and the tree says whether each
|
||||
//! use of it is a **write** or a **read**. A name declared outside the
|
||||
//! selection and used inside it becomes a port — `input` when the selection
|
||||
//! only reads it, `output` when the selection writes it.
|
||||
//!
|
||||
//! **A name is written by the selection when, and only when, it is:** the
|
||||
//! left-hand side of a continuous assignment; the left-hand side of a
|
||||
//! blocking or non-blocking assignment (or of a `for` initialiser or step, or
|
||||
//! the target of a `++`/`--`) anywhere inside an `always` block; the target of
|
||||
//! a `force`, a `release` or a `deassign`; the target of a `-> ev`; the
|
||||
//! declarator's own initialiser; or connected to an `output` or `inout` port
|
||||
//! of an instantiated module — which is a fact only that module's own
|
||||
//! declaration holds, so it is looked up through the workspace index and the
|
||||
//! extraction is **refused** when the index cannot answer. Everything else is
|
||||
//! a read. Two positions are neither, and both refuse rather than guess: an
|
||||
//! argument of a task or function call, whose direction only the routine's
|
||||
//! prototype knows, and a positional or `.*` connection, which names no port
|
||||
//! at all.
|
||||
//!
|
||||
//! Nothing here edits. It answers, or it refuses with a sentence.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vlog_parser::ast::{
|
||||
Connections, Expr, ExprKind, ForStep, Instantiation, Item, ItemKind, ListElem, Stmt, StmtKind,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Reference, Resolution, Semantics, Surface, SymbolId, SymbolKind};
|
||||
|
||||
use crate::instantiate::{instantiation_plan, module_definition};
|
||||
use crate::rename::Scope;
|
||||
|
||||
use super::region::Region;
|
||||
|
||||
/// What one use of a name is.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Use {
|
||||
Read,
|
||||
Write,
|
||||
/// A position whose direction lucisv cannot know: a call argument, a
|
||||
/// connection to a port it could not read.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Everything done to one declaration, on each side of the boundary.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub(super) struct Sides {
|
||||
pub(super) inside_read: bool,
|
||||
pub(super) inside_write: bool,
|
||||
pub(super) inside_unknown: bool,
|
||||
pub(super) outside_read: bool,
|
||||
pub(super) outside_write: bool,
|
||||
pub(super) outside_unknown: bool,
|
||||
}
|
||||
|
||||
impl Sides {
|
||||
pub(super) fn used_inside(&self) -> bool {
|
||||
self.inside_read || self.inside_write || self.inside_unknown
|
||||
}
|
||||
|
||||
pub(super) fn used_outside(&self) -> bool {
|
||||
self.outside_read || self.outside_write || self.outside_unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// The boundary table: what each declaration the module holds has done to it
|
||||
/// on each side of the selection, and which of the module's own references sit
|
||||
/// inside it.
|
||||
pub(super) struct Flow {
|
||||
sides: HashMap<SymbolId, Sides>,
|
||||
/// The references written inside the region, in source order.
|
||||
pub(super) inside: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Flow {
|
||||
pub(super) fn sides(&self, symbol: SymbolId) -> Sides {
|
||||
self.sides.get(&symbol).copied().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify every use of every name in the module, on both sides of the
|
||||
/// selection.
|
||||
pub(super) fn read(
|
||||
scope: &Scope<'_>,
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
) -> Result<Flow, String> {
|
||||
let mut marks = Marks::default();
|
||||
marks.items(scope, region, ®ion.module.items)?;
|
||||
|
||||
// Every reference in the file, placed on its side of the boundary and
|
||||
// given the direction the tree marked its span with.
|
||||
let mut sides: HashMap<SymbolId, Sides> = HashMap::new();
|
||||
let mut inside = Vec::new();
|
||||
for (n, reference) in semantics.references().iter().enumerate() {
|
||||
let span = reference.name_span;
|
||||
let within = region.span.start <= span.start && span.end <= region.span.end;
|
||||
if within {
|
||||
inside.push(n);
|
||||
}
|
||||
let Resolution::Resolved(symbol) = reference.resolution else { continue };
|
||||
let use_ = marks.use_of(span);
|
||||
let entry = sides.entry(symbol).or_default();
|
||||
match (within, use_) {
|
||||
(true, Use::Read) => entry.inside_read = true,
|
||||
(true, Use::Write) => entry.inside_write = true,
|
||||
(true, Use::Unknown) => entry.inside_unknown = true,
|
||||
(false, Use::Read) => entry.outside_read = true,
|
||||
(false, Use::Write) => entry.outside_write = true,
|
||||
(false, Use::Unknown) => entry.outside_unknown = true,
|
||||
}
|
||||
}
|
||||
// A declarator's own initialiser writes the declaration rather than
|
||||
// referring to it, so it is not in the reference table at all.
|
||||
for (span, within) in marks.initialised.drain(..) {
|
||||
let Some(symbol) = semantics.symbol_at(span.start) else { continue };
|
||||
let entry = sides.entry(symbol).or_default();
|
||||
match within {
|
||||
true => entry.inside_write = true,
|
||||
false => entry.outside_write = true,
|
||||
}
|
||||
}
|
||||
let _ = text;
|
||||
Ok(Flow { sides, inside })
|
||||
}
|
||||
|
||||
/// Whether any reference inside the region is a **hierarchical** one whose
|
||||
/// head instance the region does not itself declare — `u_x.sig` reaching out
|
||||
/// of the selection, which lucisv will not move across a module boundary.
|
||||
///
|
||||
/// The §49 surface is what says a tail is hierarchical at all
|
||||
/// ([`Surface::Hierarchical`] is recorded exactly when the head resolved to an
|
||||
/// instance); the head is then the nearest reference before it that resolved
|
||||
/// to an [`SymbolKind::Instance`] with nothing but the dots of the path
|
||||
/// between them.
|
||||
pub(super) fn hierarchical_escape(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
region: &Region<'_>,
|
||||
) -> Option<String> {
|
||||
let refs = semantics.references();
|
||||
for reference in refs {
|
||||
let span = reference.name_span;
|
||||
if span.start < region.span.start || region.span.end < span.end {
|
||||
continue;
|
||||
}
|
||||
let Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } =
|
||||
&reference.resolution
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
match head_of(text, semantics, refs, reference) {
|
||||
// The instance the path starts at moves with the selection, so
|
||||
// the path is not crossing anything. It is the *declaration* that
|
||||
// has to move, not the mention of it.
|
||||
Some(head) if declared_inside(semantics, region, head) => continue,
|
||||
Some(head) => return Some(format!("{}.{}", head.name, reference.name)),
|
||||
None => return Some(format!("\u{2026}.{}", reference.name)),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The instance a hierarchical tail hangs off: the nearest earlier reference
|
||||
/// that resolved to an instance, with only a dotted path between the two.
|
||||
fn head_of<'r>(
|
||||
text: &str,
|
||||
semantics: &Semantics,
|
||||
refs: &'r [Reference],
|
||||
tail: &Reference,
|
||||
) -> Option<&'r Reference> {
|
||||
let mut best: Option<&Reference> = None;
|
||||
for candidate in refs {
|
||||
if candidate.name_span.end > tail.name_span.start {
|
||||
continue;
|
||||
}
|
||||
let is_instance = candidate
|
||||
.resolved()
|
||||
.and_then(|id| semantics.symbol(id))
|
||||
.is_some_and(|symbol| symbol.kind == SymbolKind::Instance);
|
||||
if !is_instance {
|
||||
continue;
|
||||
}
|
||||
if best.is_none_or(|found| candidate.name_span.end > found.name_span.end) {
|
||||
best = Some(candidate);
|
||||
}
|
||||
}
|
||||
let head = best?;
|
||||
let between = text.get(head.name_span.end as usize..tail.name_span.start as usize)?;
|
||||
// A dotted path, index selects included: `u_a.u_b`, `u_q[0].sig`.
|
||||
let dotted = between
|
||||
.chars()
|
||||
.all(|c| c == '.' || c == '[' || c == ']' || c == ':' || c.is_alphanumeric() || c == '_');
|
||||
dotted.then_some(head)
|
||||
}
|
||||
|
||||
fn inside(region: &Region<'_>, span: TextRange) -> bool {
|
||||
region.span.start <= span.start && span.end <= region.span.end
|
||||
}
|
||||
|
||||
/// Whether the declaration a reference names is written inside the region.
|
||||
fn declared_inside(semantics: &Semantics, region: &Region<'_>, reference: &Reference) -> bool {
|
||||
reference
|
||||
.resolved()
|
||||
.and_then(|id| semantics.symbol(id))
|
||||
.is_some_and(|symbol| inside(region, symbol.name_span))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// marking the tree
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Where the tree says a name is written, and where it says lucisv cannot
|
||||
/// know. Both are sets of *name spans*, which is what lets the reference table
|
||||
/// be read straight off them.
|
||||
#[derive(Default)]
|
||||
struct Marks {
|
||||
writes: Vec<TextRange>,
|
||||
unknown: Vec<TextRange>,
|
||||
/// `(declared name's span, inside the region)` for every declarator whose
|
||||
/// own initialiser drives it.
|
||||
initialised: Vec<(TextRange, bool)>,
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
fn use_of(&self, span: TextRange) -> Use {
|
||||
if self.unknown.iter().any(|marked| covers(*marked, span)) {
|
||||
return Use::Unknown;
|
||||
}
|
||||
match self.writes.contains(&span) {
|
||||
true => Use::Write,
|
||||
false => Use::Read,
|
||||
}
|
||||
}
|
||||
|
||||
fn items(
|
||||
&mut self,
|
||||
scope: &Scope<'_>,
|
||||
region: &Region<'_>,
|
||||
items: &[Item],
|
||||
) -> Result<(), String> {
|
||||
for item in items {
|
||||
self.item(scope, region, item)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn item(&mut self, scope: &Scope<'_>, region: &Region<'_>, item: &Item) -> Result<(), String> {
|
||||
match &item.kind {
|
||||
ItemKind::DataDecl(decl) => {
|
||||
for declarator in &decl.declarators {
|
||||
if declarator.init.is_some() {
|
||||
self.initialised
|
||||
.push((declarator.name_span, inside(region, declarator.name_span)));
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::ContAssign(assign) => {
|
||||
for pair in &assign.assigns {
|
||||
self.write(&pair.lhs);
|
||||
}
|
||||
}
|
||||
ItemKind::Always { stmt, .. } => self.body(stmt),
|
||||
ItemKind::Initial(stmt) | ItemKind::Final(stmt) => self.body(stmt),
|
||||
ItemKind::Function(decl) => {
|
||||
for stmt in &decl.stmts {
|
||||
self.body(stmt);
|
||||
}
|
||||
}
|
||||
ItemKind::Task(decl) => {
|
||||
for stmt in &decl.stmts {
|
||||
self.body(stmt);
|
||||
}
|
||||
}
|
||||
ItemKind::Instantiation(inst) => self.instantiation(scope, region, inst)?,
|
||||
ItemKind::GateInstantiation(gates) => {
|
||||
for instance in &gates.instances {
|
||||
for arg in &instance.args {
|
||||
self.unknown.push(arg.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => self.items(scope, region, items)?,
|
||||
ItemKind::GenBlock(block) => self.items(scope, region, &block.items)?,
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
self.items(scope, region, &gen_if.then.items)?;
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
vlog_parser::ast::GenElse::If(_, nested) => {
|
||||
self.items(scope, region, &nested.then.items)?;
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
vlog_parser::ast::GenElse::Block(block) => {
|
||||
self.items(scope, region, &block.items)?;
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => self.items(scope, region, &gen_for.body.items)?,
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
self.items(scope, region, &case_item.body.items)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every write inside one procedural block, at any statement depth.
|
||||
fn body(&mut self, stmt: &Stmt) {
|
||||
walk(stmt, &mut |stmt| match &stmt.kind {
|
||||
StmtKind::Assign { lhs, .. } | StmtKind::ForceRelease { lhs, .. } => self.write(lhs),
|
||||
StmtKind::EventTrigger(expr) => self.write(expr),
|
||||
StmtKind::For { init, step, .. } => {
|
||||
for entry in init {
|
||||
self.write(&entry.assign.lhs);
|
||||
}
|
||||
for entry in step {
|
||||
match entry {
|
||||
ForStep::Assign(assign) => self.write(&assign.lhs),
|
||||
ForStep::Expr(expr) => match increment_target(expr) {
|
||||
Some(target) => self.write(target),
|
||||
None => self.unknown.push(expr.span),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
// `x++;` is a write; every other expression statement is a call,
|
||||
// whose arguments may be `output` arguments.
|
||||
StmtKind::ExprStmt(expr) => match increment_target(expr) {
|
||||
Some(target) => self.write(target),
|
||||
None => self.unknown.push(expr.span),
|
||||
},
|
||||
_ => {}
|
||||
});
|
||||
// A call written anywhere in the block — in a condition, on the
|
||||
// right-hand side of an assignment — passes arguments whose direction
|
||||
// only the routine's own prototype knows.
|
||||
walk(stmt, &mut |stmt| stmt_exprs(stmt, &mut |expr| self.calls(expr)));
|
||||
}
|
||||
|
||||
/// An instantiation's connections, whose direction the instantiated
|
||||
/// module's declaration holds.
|
||||
fn instantiation(
|
||||
&mut self,
|
||||
scope: &Scope<'_>,
|
||||
region: &Region<'_>,
|
||||
inst: &Instantiation,
|
||||
) -> Result<(), String> {
|
||||
let touches = inst.instances.iter().any(|instance| inside(region, instance.name_span));
|
||||
for instance in &inst.instances {
|
||||
match &instance.conns {
|
||||
Connections::Ordered(conns) => {
|
||||
if touches {
|
||||
return Err(positional(&inst.module, &instance.name));
|
||||
}
|
||||
for conn in conns {
|
||||
self.unknown.push(match conn {
|
||||
ListElem::Ok(conn) => conn.span,
|
||||
ListElem::Error(raw) => raw.span,
|
||||
});
|
||||
}
|
||||
}
|
||||
Connections::Named(conns) => {
|
||||
let ports = match touches {
|
||||
true => Some(ports_of(scope, &inst.module)?),
|
||||
false => None,
|
||||
};
|
||||
for conn in conns {
|
||||
let conn = match conn {
|
||||
ListElem::Ok(conn) => conn,
|
||||
ListElem::Error(raw) => {
|
||||
if touches {
|
||||
return Err(unreadable(&inst.module, &instance.name));
|
||||
}
|
||||
self.unknown.push(raw.span);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(ports) = ports.as_deref() else {
|
||||
self.unknown.push(conn.span);
|
||||
continue;
|
||||
};
|
||||
if conn.name == "*" {
|
||||
return Err(wildcard(&inst.module, &instance.name));
|
||||
}
|
||||
// `.p` with no expression connects the same-named
|
||||
// signal, whose own name is not written down here;
|
||||
// the connection's port name is the signal's name.
|
||||
let Some(port) = ports.iter().find(|(name, _)| *name == conn.name) else {
|
||||
return Err(no_such_port(&inst.module, &conn.name));
|
||||
};
|
||||
let Some(expr) = &conn.expr else {
|
||||
return Err(implicit(&inst.module, &instance.name, &conn.name));
|
||||
};
|
||||
match port.1.as_str() {
|
||||
"output" | "inout" => self.write(expr),
|
||||
"input" => {}
|
||||
_ => return Err(no_direction(&inst.module, &conn.name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every argument of every call in an expression, marked unknown.
|
||||
fn calls(&mut self, expr: &Expr) {
|
||||
walk_expr(expr, &mut |expr| {
|
||||
if let ExprKind::Call { args, .. } = &expr.kind {
|
||||
for arg in args {
|
||||
self.unknown.push(arg.span);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Records every name an assignment's left-hand side writes.
|
||||
fn write(&mut self, lhs: &Expr) {
|
||||
lvalue_targets(lhs, &mut self.writes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `outer` covers `inner` entirely.
|
||||
fn covers(outer: TextRange, inner: TextRange) -> bool {
|
||||
outer.start <= inner.start && inner.end <= outer.end
|
||||
}
|
||||
|
||||
/// The names one left-hand side writes. `a.b[3] = x` writes `a`, which is
|
||||
/// what resolves.
|
||||
fn lvalue_targets(expr: &Expr, out: &mut Vec<TextRange>) {
|
||||
match &expr.kind {
|
||||
ExprKind::Ident(_) => out.push(expr.span),
|
||||
ExprKind::Paren { inner, .. } => lvalue_targets(inner, out),
|
||||
ExprKind::Cast { expr, .. } => lvalue_targets(expr, out),
|
||||
ExprKind::Index { base, .. } | ExprKind::Range { base, .. } => lvalue_targets(base, out),
|
||||
ExprKind::Member { base, .. } => lvalue_targets(base, out),
|
||||
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
|
||||
for item in items {
|
||||
lvalue_targets(&item.expr, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The target of `x++` / `x--` / `++x`, which is a write dressed as an
|
||||
/// expression.
|
||||
fn increment_target(expr: &Expr) -> Option<&Expr> {
|
||||
match &expr.kind {
|
||||
ExprKind::Postfix { expr, op, .. } | ExprKind::Unary { expr, op, .. }
|
||||
if op == "++" || op == "--" =>
|
||||
{
|
||||
Some(expr)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ports of an instantiated module: name and direction, read from the
|
||||
/// file the workspace index says declares it.
|
||||
fn ports_of(scope: &Scope<'_>, module: &str) -> Result<Vec<(String, String)>, String> {
|
||||
let path =
|
||||
module_definition(scope.index(), module).map_err(|_| unknown_module(module))?.to_path_buf();
|
||||
let Some(text) = scope.index_of(&path).and_then(|i| scope.text(i)) else {
|
||||
return Err(unknown_module(module));
|
||||
};
|
||||
let plan = instantiation_plan(module, text, None).map_err(|_| unknown_module(module))?;
|
||||
Ok(plan.ports.into_iter().map(|port| (port.name, port.dir)).collect())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// walks
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn walk(stmt: &Stmt, f: &mut dyn FnMut(&Stmt)) {
|
||||
f(stmt);
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
|
||||
for stmt in stmts {
|
||||
walk(stmt, f);
|
||||
}
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
walk(then, f);
|
||||
if let Some(els) = els {
|
||||
walk(els, f);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for item in items {
|
||||
walk(&item.stmt, f);
|
||||
}
|
||||
}
|
||||
StmtKind::Labeled { stmt, .. } => walk(stmt, f),
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => walk(body, f),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
walk(inner, f)
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
if let Some(then) = then {
|
||||
walk(then, f);
|
||||
}
|
||||
if let Some(els) = els {
|
||||
walk(els, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The expressions one statement writes directly — not its children's.
|
||||
fn stmt_exprs(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Assign { lhs, rhs, .. } => {
|
||||
f(lhs);
|
||||
f(rhs);
|
||||
}
|
||||
StmtKind::If { cond, .. } | StmtKind::While { cond, .. } | StmtKind::Wait { cond, .. } => {
|
||||
f(cond)
|
||||
}
|
||||
StmtKind::DoWhile { cond, .. } => f(cond),
|
||||
StmtKind::Case { expr, items, .. } => {
|
||||
f(expr);
|
||||
for item in items {
|
||||
for label in &item.labels {
|
||||
f(&label.expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Repeat { count, .. } => f(count),
|
||||
StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => f(expr),
|
||||
StmtKind::ForceRelease { lhs, rhs, .. } => {
|
||||
f(lhs);
|
||||
if let Some(rhs) = rhs {
|
||||
f(rhs);
|
||||
}
|
||||
}
|
||||
StmtKind::For { init, cond, step, .. } => {
|
||||
for entry in init {
|
||||
f(&entry.assign.rhs);
|
||||
}
|
||||
if let Some(cond) = cond {
|
||||
f(cond);
|
||||
}
|
||||
for entry in step {
|
||||
match entry {
|
||||
ForStep::Assign(assign) => f(&assign.rhs),
|
||||
ForStep::Expr(expr) => f(expr),
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Return { expr: Some(expr), .. } => f(expr),
|
||||
StmtKind::Assert { cond, .. } => f(cond),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_expr(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
|
||||
f(expr);
|
||||
match &expr.kind {
|
||||
ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => walk_expr(expr, f),
|
||||
ExprKind::Binary { lhs, rhs, .. } => {
|
||||
walk_expr(lhs, f);
|
||||
walk_expr(rhs, f);
|
||||
}
|
||||
ExprKind::Ternary { cond, then, els, .. } => {
|
||||
walk_expr(cond, f);
|
||||
walk_expr(then, f);
|
||||
walk_expr(els, f);
|
||||
}
|
||||
ExprKind::Call { callee, args, .. } => {
|
||||
walk_expr(callee, f);
|
||||
for arg in args {
|
||||
walk_expr(&arg.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Index { base, index, .. } => {
|
||||
walk_expr(base, f);
|
||||
walk_expr(index, f);
|
||||
}
|
||||
ExprKind::Range { base, msb, lsb, .. } => {
|
||||
walk_expr(base, f);
|
||||
walk_expr(msb, f);
|
||||
walk_expr(lsb, f);
|
||||
}
|
||||
ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => walk_expr(base, f),
|
||||
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
|
||||
for item in items {
|
||||
walk_expr(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Repl { count, inner, .. } => {
|
||||
walk_expr(count, f);
|
||||
for item in inner {
|
||||
walk_expr(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Paren { inner, .. } => walk_expr(inner, f),
|
||||
ExprKind::Cast { expr, .. } => walk_expr(expr, f),
|
||||
ExprKind::New(inner) => walk_expr(inner, f),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sentences
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn positional(module: &str, instance: &str) -> String {
|
||||
format!(
|
||||
"`{instance}` connects `{module}` by position, so lucisv cannot tell which of its connections are outputs; convert it to named connections first."
|
||||
)
|
||||
}
|
||||
|
||||
fn wildcard(module: &str, instance: &str) -> String {
|
||||
format!(
|
||||
"`{instance}` connects `{module}` with `.*`, which names no signals; expand the `.*` first (lucisv offers that as its own refactoring)."
|
||||
)
|
||||
}
|
||||
|
||||
fn implicit(module: &str, instance: &str, port: &str) -> String {
|
||||
format!(
|
||||
"`{instance}` connects `{module}`'s `{port}` implicitly (`.{port}`), which names no expression for lucisv to move; write the signal out first."
|
||||
)
|
||||
}
|
||||
|
||||
fn unreadable(module: &str, instance: &str) -> String {
|
||||
format!(
|
||||
"lucisv could not read one of `{instance}`'s connections to `{module}`, so it cannot tell what the selection drives."
|
||||
)
|
||||
}
|
||||
|
||||
fn unknown_module(module: &str) -> String {
|
||||
format!(
|
||||
"the selection instantiates `{module}`, and lucisv has no single indexed declaration of it, so it cannot tell which of its connections are outputs."
|
||||
)
|
||||
}
|
||||
|
||||
fn no_such_port(module: &str, port: &str) -> String {
|
||||
format!(
|
||||
"the selection connects `.{port}`, which `{module}`'s declaration does not name, so lucisv cannot tell whether it is driven."
|
||||
)
|
||||
}
|
||||
|
||||
fn no_direction(module: &str, port: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{port}` without a direction, so lucisv cannot tell whether the selection drives it."
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
//! Extract a selection of whole module items into a module of its own.
|
||||
//!
|
||||
//! The user selects one or more contiguous items of a module `M` — an
|
||||
//! `always` block, an `assign`, an instantiation, a declaration, a generate
|
||||
//! construct — and names the module `N` they want them in. lucisv works out
|
||||
//! `N`'s ports from the dataflow across the selection's boundary, writes `N`
|
||||
//! into a file of its own beside `M`'s (or below `M`, for a client that cannot
|
||||
//! create files), and replaces the selection with an instantiation of `N`
|
||||
//! **rendered from `N`'s own text**, so the skeleton and the module can never
|
||||
//! disagree about what `N`'s ports are.
|
||||
//!
|
||||
//! Three files, one question each:
|
||||
//!
|
||||
//! * `region` — *what does the selection cover?* The module, the run of whole
|
||||
//! items, and the item kinds lucisv will not carry into another module.
|
||||
//! * `flow` — *which names cross the boundary, and in which direction?* The
|
||||
//! dataflow rule, and the two positions it refuses to guess at.
|
||||
//! * `render` — *what does lucisv write?* A port's type as its declaration
|
||||
//! spells it, the new module, and the instantiation.
|
||||
//!
|
||||
//! This file is the plan: the entry points, the classification of each
|
||||
//! crossing name into a port, a parameter or a refusal, the edits, and the
|
||||
//! verification. Everything is one [`check::verify_move`] over the whole edit,
|
||||
//! which for a new file is the ordinary splice contract plus one deliberate
|
||||
//! widening: the comments the selection carries are deleted in `M`'s file and
|
||||
//! written in `N`'s, so the never-dropped ledger is kept over the pair rather
|
||||
//! than over each file alone. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
|
||||
mod boundary;
|
||||
mod flow;
|
||||
mod region;
|
||||
mod render;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, SourceFile};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{analyze, SymbolKind};
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
use boundary::Crossing;
|
||||
use region::Region;
|
||||
|
||||
/// Where the extracted module is written.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Home {
|
||||
/// A file `N.sv` beside `M`'s own — what a client that advertises
|
||||
/// `workspace.workspaceEdit.documentChanges` with `CreateFile` support
|
||||
/// gets, because only such a client can apply the creation.
|
||||
NewFile,
|
||||
/// Below `M`, in `M`'s own file — the fallback for every other client,
|
||||
/// and for a caller that asked for it.
|
||||
SameFile,
|
||||
}
|
||||
|
||||
/// What the cheap gate found: the selection is in a module, and these are the
|
||||
/// units whose files the engine needs read.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ExtractSite {
|
||||
/// The module the selection is written in.
|
||||
pub module: String,
|
||||
/// The name the action proposes when the caller has none: `M_extracted`.
|
||||
pub default_name: String,
|
||||
/// Every unit whose declaration the engine will look up: the module
|
||||
/// itself, the modules the selection instantiates, and the packages the
|
||||
/// module imports.
|
||||
pub units: Vec<String>,
|
||||
}
|
||||
|
||||
/// Whether a selection is one lucisv could extract, and what it would need to
|
||||
/// read to try.
|
||||
///
|
||||
/// **The cheap gate**: one parse of one buffer, no workspace and no I/O — the
|
||||
/// bargain `port_action_modules` and `imported_packages` strike, and for the
|
||||
/// same reason (a `textDocument/codeAction` arrives on every cursor move).
|
||||
/// Empty exactly where [`extract_module`] would refuse for want of a module or
|
||||
/// a whole item to move.
|
||||
pub fn extract_site(text: &str, start: u32, end: u32) -> Option<ExtractSite> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?;
|
||||
let module = region.module_name().to_string();
|
||||
let mut units = vec![module.clone()];
|
||||
for item in ®ion.items {
|
||||
collect_instantiated(item, &mut units);
|
||||
}
|
||||
for import in ®ion.module.imports {
|
||||
for path in &import.paths {
|
||||
push(&mut units, path.pkg.text.clone());
|
||||
}
|
||||
}
|
||||
for item in ®ion.module.items {
|
||||
if let ItemKind::Import(paths) = &item.kind {
|
||||
for path in paths {
|
||||
push(&mut units, path.pkg.text.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(ExtractSite { default_name: format!("{module}_extracted"), module, units })
|
||||
}
|
||||
|
||||
/// The lightbulb's text, written here so every front end says the same thing.
|
||||
pub fn extract_title() -> String {
|
||||
"lucisv: extract selection into module…".to_string()
|
||||
}
|
||||
|
||||
/// Extract the items `[start, end)` covers out of the module that holds them,
|
||||
/// into a module called `new_name`.
|
||||
pub fn extract_module(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
start: u32,
|
||||
end: u32,
|
||||
new_name: &str,
|
||||
home: Home,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
plain_identifier(new_name)?;
|
||||
// The new file joins the in-scope set as an *empty* file, so that every
|
||||
// question below — the index, the analysis, the verification — is asked
|
||||
// about it exactly the way it is asked about a file that was always there.
|
||||
let mut sources: Vec<(PathBuf, String)> = files.to_vec();
|
||||
let created = match home {
|
||||
Home::SameFile => None,
|
||||
Home::NewFile => {
|
||||
let path = beside(file, new_name);
|
||||
match sources.iter().find(|(held, _)| *held == path) {
|
||||
Some((_, text)) if !text.trim().is_empty() => return Err(occupied(&path)),
|
||||
Some(_) => {}
|
||||
None => sources.push((path.clone(), String::new())),
|
||||
}
|
||||
Some(path)
|
||||
}
|
||||
};
|
||||
let plan = Extraction::plan(&sources, file, start, end, new_name, created.clone())?;
|
||||
Ok(RefactorEdit {
|
||||
edits: plan.edits,
|
||||
warnings: plan.warnings,
|
||||
created: created.into_iter().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// What the extraction produced, before it is dressed as a [`RefactorEdit`].
|
||||
struct Extraction {
|
||||
edits: Vec<(PathBuf, Vec<TextEdit>)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Extraction {
|
||||
fn plan(
|
||||
sources: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
start: u32,
|
||||
end: u32,
|
||||
new_name: &str,
|
||||
created: Option<PathBuf>,
|
||||
) -> Result<Extraction, String> {
|
||||
let mut scope = Scope::build(sources);
|
||||
let Some(here) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(here) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
if let Some(problem) = diagnostics.first() {
|
||||
return Err(format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not extract from it.",
|
||||
display(file),
|
||||
problem.message,
|
||||
problem.line
|
||||
));
|
||||
}
|
||||
let region = Region::read(&tree, text, TextRange::new(start, end))?;
|
||||
let module = region.module_name().to_string();
|
||||
declared_once(&scope, &module)?;
|
||||
undeclared(&scope, new_name)?;
|
||||
if new_name == module {
|
||||
return Err(format!("`{module}` is already the name of the module you are in."));
|
||||
}
|
||||
if created.is_some() {
|
||||
no_directive(&tree, text, ®ion)?;
|
||||
}
|
||||
let semantics = analyze(&tree, text);
|
||||
if let Some(path) = flow::hierarchical_escape(text, &semantics, ®ion) {
|
||||
return Err(hierarchical(&path));
|
||||
}
|
||||
let flow = flow::read(&scope, text, &semantics, ®ion)?;
|
||||
let packages = boundary::packages(&tree);
|
||||
let crossing =
|
||||
Crossing::read(text, &semantics, ®ion, &flow, &packages, created.is_some())?;
|
||||
|
||||
// The new module, then the instantiation read back out of it.
|
||||
let body = format!("{}{}", region.indent, slice(text, region.span));
|
||||
let module_text = render::new_module(
|
||||
new_name,
|
||||
&crossing.imports,
|
||||
&crossing.params,
|
||||
&crossing.ports,
|
||||
&ensure_newline(&body),
|
||||
);
|
||||
let instance = render::instantiation(new_name, &module_text, ®ion.indent)?;
|
||||
|
||||
let mut edits: Vec<(usize, Vec<TextEdit>)> = Vec::new();
|
||||
// What the verifier is allowed to let travel, and between which bytes:
|
||||
// `M`'s file loses exactly the pieces inside the region, and the new
|
||||
// file — named with an empty range, because it has no region of its
|
||||
// own — is the only place they may land.
|
||||
let mut moving: Vec<(usize, TextRange)> = Vec::new();
|
||||
let replace = TextEdit { range: region.span, new_text: instance };
|
||||
match &created {
|
||||
Some(path) => {
|
||||
let Some(there) = scope.index_of(path) else { return Err(not_in_scope(path)) };
|
||||
edits.push((here, vec![replace]));
|
||||
edits.push((
|
||||
there,
|
||||
vec![TextEdit { range: TextRange::empty(0), new_text: module_text.clone() }],
|
||||
));
|
||||
moving = vec![(here, region.span), (there, TextRange::empty(0))];
|
||||
}
|
||||
None => {
|
||||
let append = TextEdit {
|
||||
range: TextRange::empty(region.module_span.end),
|
||||
new_text: format!("\n\n{module_text}"),
|
||||
};
|
||||
edits.push((here, vec![replace, append]));
|
||||
}
|
||||
}
|
||||
edits.sort_by_key(|(i, _)| *i);
|
||||
moving.sort_by_key(|(i, _)| *i);
|
||||
|
||||
let what = format!("extracting `{new_name}` out of `{module}`");
|
||||
check::verify_move(&mut scope, &edits, &[&module, new_name], &what, &moving)?;
|
||||
confirm(&scope, &edits, new_name, &crossing, &what)?;
|
||||
|
||||
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
||||
for (i, file_edits) in edits {
|
||||
let Some(path) = scope.path(i) else { return Err(lost(&what)) };
|
||||
out.push((path.to_path_buf(), file_edits));
|
||||
}
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the edited text back and require the new module to declare exactly the
|
||||
/// ports and parameters the plan promised.
|
||||
///
|
||||
/// `verify_move` proves the edit is lexically and semantically honest; nothing
|
||||
/// in it proves the header lucisv wrote is the header it meant to write.
|
||||
fn confirm(
|
||||
scope: &Scope<'_>,
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
new_name: &str,
|
||||
crossing: &Crossing,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
for (i, file_edits) in edits {
|
||||
let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else {
|
||||
return Err(lost(what));
|
||||
};
|
||||
let edited = crate::apply(text, file_edits);
|
||||
let Ok(plan) = crate::instantiate::instantiation_plan(new_name, &edited, None) else {
|
||||
continue;
|
||||
};
|
||||
let ports: Vec<&str> = plan.ports.iter().map(|port| port.name.as_str()).collect();
|
||||
let params: Vec<&str> = plan.params.iter().map(|param| param.name.as_str()).collect();
|
||||
let wanted_ports: Vec<&str> = crossing.ports.iter().map(|p| p.name.as_str()).collect();
|
||||
let wanted_params: Vec<&str> = crossing.params.iter().map(|p| p.name.as_str()).collect();
|
||||
if ports != wanted_ports || params != wanted_params {
|
||||
return Err(format!(
|
||||
"{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.",
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(lost(what))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// odds and ends
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn inside(region: &Region<'_>, span: TextRange) -> bool {
|
||||
region.span.start <= span.start && span.end <= region.span.end
|
||||
}
|
||||
|
||||
fn inside_module(region: &Region<'_>, span: TextRange) -> bool {
|
||||
region.module_span.start <= span.start && span.end <= region.module_span.end
|
||||
}
|
||||
|
||||
fn slice(text: &str, span: TextRange) -> &str {
|
||||
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
fn ensure_newline(text: &str) -> String {
|
||||
match text.ends_with('\n') {
|
||||
true => text.to_string(),
|
||||
false => format!("{text}\n"),
|
||||
}
|
||||
}
|
||||
|
||||
fn push(out: &mut Vec<String>, name: String) {
|
||||
if !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every module an item instantiates, nested generate constructs included.
|
||||
fn collect_instantiated(item: &Item, out: &mut Vec<String>) {
|
||||
match &item.kind {
|
||||
ItemKind::Instantiation(inst) => push(out, inst.module.clone()),
|
||||
ItemKind::GenerateRegion { items, .. } => {
|
||||
for item in items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(block) => {
|
||||
for item in &block.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
for item in &gen_if.then.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
vlog_parser::ast::GenElse::If(_, nested) => {
|
||||
for item in &nested.then.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
vlog_parser::ast::GenElse::Block(block) => {
|
||||
for item in &block.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => {
|
||||
for item in &gen_for.body.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
for item in &case_item.body.items {
|
||||
collect_instantiated(item, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file the new module goes in: `N.sv`, beside the file it came out of.
|
||||
fn beside(file: &Path, new_name: &str) -> PathBuf {
|
||||
let parent = file.parent().map_or_else(PathBuf::new, Path::to_path_buf);
|
||||
parent.join(format!("{new_name}.sv"))
|
||||
}
|
||||
|
||||
/// A module name lucisv will write into a file name and a header: a plain
|
||||
/// identifier, never an escaped one.
|
||||
fn plain_identifier(name: &str) -> Result<(), String> {
|
||||
let mut chars = name.chars();
|
||||
let head = chars.next().filter(|c| c.is_ascii_alphabetic() || *c == '_');
|
||||
let tail = chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
||||
match head.is_some() && tail {
|
||||
true => Ok(()),
|
||||
false => Err(format!(
|
||||
"`{name}` is not a plain SystemVerilog identifier, and lucisv will not name a module — or a file — with anything else."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module the selection is in must be declared exactly once in the
|
||||
/// workspace: an extraction rewrites *this* `M`, and two of them means lucisv
|
||||
/// does not know whose ports the selection reads.
|
||||
fn declared_once(scope: &Scope<'_>, module: &str) -> Result<(), String> {
|
||||
let defs = scope.index().units(module).iter().filter(|def| def.kind.is_instantiable()).count();
|
||||
match defs {
|
||||
1 => Ok(()),
|
||||
0 => Err(format!("lucisv indexes no module named `{module}`.")),
|
||||
_ => Err(format!(
|
||||
"`{module}` is declared in more than one indexed file, so lucisv cannot tell which one the selection belongs to."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn undeclared(scope: &Scope<'_>, name: &str) -> Result<(), String> {
|
||||
match scope.index().units(name).is_empty() {
|
||||
true => Ok(()),
|
||||
false => {
|
||||
Err(format!("the workspace already declares `{name}`; pick a name nothing else uses."))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `timescale` or a `default_nettype` in force where `M` is written does not
|
||||
/// follow the items into a file of their own, and silently changing either one
|
||||
/// changes what the design does.
|
||||
fn no_directive(tree: &SourceFile, text: &str, region: &Region<'_>) -> Result<(), String> {
|
||||
for item in &tree.items {
|
||||
let ItemKind::Directive(raw) = &item.kind else { continue };
|
||||
if item.span.start > region.module_span.end {
|
||||
continue;
|
||||
}
|
||||
let word = raw.text.split_whitespace().next().unwrap_or("");
|
||||
if word == "`timescale" || word == "`default_nettype" || word == "`resetall" {
|
||||
return Err(format!(
|
||||
"`{}` writes `{word}` before the module the selection is in, and a new file would not inherit it; extract into the same file, or move the directive into an include both files use.",
|
||||
first_line(text, item.span.start)
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The file's own name is not to hand here, so a directive refusal names the
|
||||
/// line the directive is on instead.
|
||||
fn first_line(text: &str, at: u32) -> String {
|
||||
let line = text.get(..at as usize).map_or(0, |head| head.matches('\n').count()) + 1;
|
||||
format!("line {line}")
|
||||
}
|
||||
|
||||
fn count(n: usize, noun: &str) -> String {
|
||||
match n {
|
||||
1 => format!("1 {noun}"),
|
||||
n => format!("{n} {noun}s"),
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sentences
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn not_in_scope(file: &Path) -> String {
|
||||
format!("{} is not one of the files lucisv was given.", display(file))
|
||||
}
|
||||
|
||||
fn occupied(path: &Path) -> String {
|
||||
format!("there is already a `{}` beside this file; pick another name.", display(path))
|
||||
}
|
||||
|
||||
fn escaped(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is declared inside the selection and used outside it; move the declaration of `{name}` out of the selection first."
|
||||
)
|
||||
}
|
||||
|
||||
fn outside_module(name: &str, module: &str) -> String {
|
||||
format!(
|
||||
"the selection uses `{name}`, which is declared outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
/// The same refusal for a **member access**, which names the head first.
|
||||
/// `s.f` and `bus.data` cross the boundary as `s` and `bus` — the port or the
|
||||
/// variable — and `f` and `data` are names of *their* types; a sentence that
|
||||
/// leads with the field reads as if the field were a signal of `M`'s own.
|
||||
fn outside_module_member(head: &str, name: &str, module: &str) -> String {
|
||||
format!(
|
||||
"the selection uses `{head}.{name}`, and `{head}` is declared with a type written outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn unmovable(name: &str, module: &str, kind: SymbolKind) -> String {
|
||||
let what = match kind {
|
||||
SymbolKind::Genvar => "a `genvar`",
|
||||
SymbolKind::Function => "a function",
|
||||
SymbolKind::Task => "a task",
|
||||
SymbolKind::Typedef => "a type",
|
||||
SymbolKind::EnumVariant => "an enumeration member",
|
||||
SymbolKind::Instance => "an instance",
|
||||
SymbolKind::Modport => "a modport",
|
||||
SymbolKind::Clocking => "a clocking block",
|
||||
SymbolKind::Class => "a class",
|
||||
SymbolKind::Block => "a named block",
|
||||
_ => "a declaration",
|
||||
};
|
||||
format!(
|
||||
"the selection uses `{name}`, {what} `{module}` declares outside it; lucisv makes ports out of signals and parameters and nothing else, so it made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn header_names(module: &str, owner: &str, word: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{owner}` with something that names `{word}`, which is neither a parameter nor a name a module in another file could reach; lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn hierarchical(path: &str) -> String {
|
||||
format!(
|
||||
"the selection reads `{path}` through the design hierarchy, and a hierarchical path does not survive being moved into another module; lucisv made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
fn lost_name(name: &str) -> String {
|
||||
format!("lucisv lost track of the declaration of `{name}`, so it made no edits.")
|
||||
}
|
||||
|
||||
fn lost(what: &str) -> String {
|
||||
format!("lucisv could not name one of the files it edited for {what}.")
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! What the selection covers: the module it is written in, the run of whole
|
||||
//! module items it spans, and the bytes the extraction will delete.
|
||||
//!
|
||||
//! Nothing here reads the symbol table — this is the *shape* half of the
|
||||
//! refusal list, answered from the tree and the text alone: the selection has
|
||||
//! to cover whole items, and the items it covers have to be ones lucisv can
|
||||
//! move without changing what they mean where they land.
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, Module, SourceFile};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// The selection, resolved.
|
||||
pub(super) struct Region<'t> {
|
||||
/// The module the selection is written in.
|
||||
pub(super) module: &'t Module,
|
||||
/// Where that module is written, `module` keyword to `endmodule`.
|
||||
pub(super) module_span: TextRange,
|
||||
/// The items the selection covers, in source order.
|
||||
pub(super) items: Vec<&'t Item>,
|
||||
/// The bytes the extraction deletes from the module's file: the covered
|
||||
/// items and whatever of their own comments the selection covers too.
|
||||
pub(super) span: TextRange,
|
||||
/// The whitespace the region's first line begins with — what the
|
||||
/// instantiation written in its place is laid out against.
|
||||
pub(super) indent: String,
|
||||
}
|
||||
|
||||
impl<'t> Region<'t> {
|
||||
/// Read the selection, or say why lucisv will not extract it.
|
||||
pub(super) fn read(
|
||||
tree: &'t SourceFile,
|
||||
text: &str,
|
||||
selection: TextRange,
|
||||
) -> Result<Region<'t>, String> {
|
||||
let (module, module_span) =
|
||||
module_at(&tree.items, selection).ok_or_else(|| NO_MODULE.to_string())?;
|
||||
extractable(module)?;
|
||||
// A cursor is a selection of one item: an editor sends the caret's
|
||||
// own empty range when nothing is selected, and "extract the thing I
|
||||
// am standing on" is what the user means by it.
|
||||
let selection = match selection.is_empty() {
|
||||
false => selection,
|
||||
true => module
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.span)
|
||||
.find(|span| span.contains(selection.start) || span.end == selection.start)
|
||||
.ok_or_else(|| EMPTY.to_string())?,
|
||||
};
|
||||
let mut items: Vec<&Item> = Vec::new();
|
||||
let mut span: Option<TextRange> = None;
|
||||
for item in &module.items {
|
||||
let extent = extent(item, selection);
|
||||
if !overlaps(extent, selection) {
|
||||
continue;
|
||||
}
|
||||
if extent.start < selection.start || selection.end < extent.end {
|
||||
return Err(PARTIAL.to_string());
|
||||
}
|
||||
span = Some(match span {
|
||||
None => extent,
|
||||
Some(so_far) => TextRange::new(so_far.start, extent.end),
|
||||
});
|
||||
items.push(item);
|
||||
}
|
||||
let Some(span) = span else { return Err(EMPTY.to_string()) };
|
||||
for item in &items {
|
||||
movable(item)?;
|
||||
}
|
||||
Ok(Region { module, module_span, items, span, indent: indent_at(text, span.start) })
|
||||
}
|
||||
|
||||
/// The module's name.
|
||||
pub(super) fn module_name(&self) -> &str {
|
||||
&self.module.name
|
||||
}
|
||||
}
|
||||
|
||||
/// The `module`, `interface` or `program` whose body covers the whole
|
||||
/// selection — the parser writes all three as one node, and [`extractable`] is
|
||||
/// what says only the first is one lucisv extracts out of.
|
||||
fn module_at(items: &[Item], selection: TextRange) -> Option<(&Module, TextRange)> {
|
||||
for item in items {
|
||||
let ItemKind::Module(module) = &item.kind else { continue };
|
||||
if !item.span.contains(selection.start) {
|
||||
continue;
|
||||
}
|
||||
if selection.end > item.span.end {
|
||||
return None;
|
||||
}
|
||||
return Some((module, item.span));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Only a `module` is a thing lucisv extracts out of.
|
||||
///
|
||||
/// The parser gives a `module`, an `interface` and a `program` one node —
|
||||
/// their headers and bodies are the same grammar (IEEE 1800 §25.3) — and
|
||||
/// [`Module::kw`] is the only thing that says which was written. Extracting is
|
||||
/// a dataflow question about a boundary, and neither of the other two has the
|
||||
/// boundary this rule assumes: an `interface`'s signals *are* its surface,
|
||||
/// named by whoever instantiates it and driven from anywhere, so "what does
|
||||
/// this region drive" does not answer what a port should be; a `program`'s
|
||||
/// items are testbench code whose meaning depends on when they run.
|
||||
fn extractable(module: &Module) -> Result<(), String> {
|
||||
match module.kw.as_str() {
|
||||
"module" | "macromodule" => Ok(()),
|
||||
"interface" => Err(INTERFACE.to_string()),
|
||||
"program" => Err(PROGRAM.to_string()),
|
||||
kw => Err(format!(
|
||||
"the selection is inside a `{kw}`, and lucisv extracts module items out of a `module`, so it made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes one item owns for the purpose of the selection: the item itself,
|
||||
/// plus every comment and attribute of its own that the selection also covers.
|
||||
///
|
||||
/// A comment the user left *outside* the selection stays where it is, which is
|
||||
/// what makes a selection that starts on the item's own line do the obvious
|
||||
/// thing and one that starts a line earlier take the note with it.
|
||||
fn extent(item: &Item, selection: TextRange) -> TextRange {
|
||||
let mut spans = vec![item.span];
|
||||
spans.extend(item.meta.leading.iter().map(|c| c.span));
|
||||
spans.extend(item.meta.before_sep.iter().map(|c| c.span));
|
||||
spans.extend(item.meta.trailing.iter().map(|c| c.span));
|
||||
spans.extend(item.meta.attrs.iter().map(|a| a.span));
|
||||
let mut out = item.span;
|
||||
for span in spans {
|
||||
if span.start < selection.start || selection.end < span.end {
|
||||
continue;
|
||||
}
|
||||
out = TextRange::new(out.start.min(span.start), out.end.max(span.end));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn overlaps(a: TextRange, b: TextRange) -> bool {
|
||||
a.start < b.end && b.start < a.end
|
||||
}
|
||||
|
||||
/// The item kinds lucisv will not carry into another module, each with the
|
||||
/// sentence saying why.
|
||||
fn movable(item: &Item) -> Result<(), String> {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(_) => Err(kind_refusal("a port declaration")),
|
||||
ItemKind::ParamDecl(decl) => Err(kind_refusal(match decl.kw.as_str() {
|
||||
"localparam" => "a `localparam` declaration",
|
||||
_ => "a `parameter` declaration",
|
||||
})),
|
||||
ItemKind::Genvar(_) => Err(kind_refusal("a `genvar` declaration")),
|
||||
ItemKind::Bind(_) => Err(kind_refusal("a `bind` directive")),
|
||||
ItemKind::Initial(_) => Err(
|
||||
"the selection holds an `initial` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Final(_) => Err(
|
||||
"the selection holds a `final` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::MacroItem(_) => Err(
|
||||
"the selection holds a macro invocation, and lucisv does not expand macros, so it cannot tell what would move with it."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Directive(_) => Err(
|
||||
"the selection holds a compiler directive, and lucisv does not evaluate one, so it cannot tell what the selection means in another module."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Verbatim(_) => Err(
|
||||
"the selection holds a block lucisv keeps verbatim (an assertion, a `property`, a `sequence`, a `constraint` or a `covergroup` body it could not read), so it cannot tell which names cross the boundary."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Error(_) => Err(
|
||||
"part of the selection did not parse, so lucisv cannot tell what it would be moving."
|
||||
.to_string(),
|
||||
),
|
||||
ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_) => {
|
||||
Err(kind_refusal("a declaration of its own"))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn kind_refusal(what: &str) -> String {
|
||||
format!(
|
||||
"the selection holds {what}, which belongs to the module that wrote it; lucisv does not move one into a new module."
|
||||
)
|
||||
}
|
||||
|
||||
/// The whitespace the line holding `at` begins with.
|
||||
fn indent_at(text: &str, at: u32) -> String {
|
||||
let start = text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |n| n + 1);
|
||||
text.get(start..at as usize)
|
||||
.unwrap_or("")
|
||||
.chars()
|
||||
.take_while(|c| *c == ' ' || *c == '\t')
|
||||
.collect()
|
||||
}
|
||||
|
||||
const NO_MODULE: &str =
|
||||
"the selection is not inside one module's body, so there is nothing for lucisv to extract from.";
|
||||
const PARTIAL: &str =
|
||||
"the selection cuts an item in half; lucisv extracts whole module items, so select from the start of the first one to the end of the last.";
|
||||
const EMPTY: &str = "the selection covers no module item, so there is nothing to extract.";
|
||||
const INTERFACE: &str =
|
||||
"the selection is inside an `interface`, whose signals are its surface — every one of them is driven and read by whatever instantiates it — so there is no boundary for lucisv to infer ports across; lucisv extracts out of a `module`.";
|
||||
const PROGRAM: &str =
|
||||
"the selection is inside a `program`, whose items are testbench code whose meaning depends on when it runs; lucisv extracts out of a `module`.";
|
||||
@@ -0,0 +1,384 @@
|
||||
//! Writing the new module, and the instantiation that stands where its items
|
||||
//! used to be.
|
||||
//!
|
||||
//! Two rules govern everything here. A **port's type is the declaration's own
|
||||
//! text**, reassembled from the tree in the order `vlog_formatter`'s ANSI port
|
||||
//! printer writes it (direction, net, type, signing, packed dimensions, name),
|
||||
//! so what lucisv writes is what the formatter would; anything the tree says is
|
||||
//! not a plain name-signing-dimensions type — an anonymous aggregate, a
|
||||
//! parameterized reference, a virtual interface, an unpacked dimension — is
|
||||
//! refused rather than approximated. And the **instantiation is rendered from
|
||||
//! the new module's own text**, through
|
||||
//! [`instantiation_plan`](crate::instantiate::instantiation_plan), so the two
|
||||
//! halves of the edit cannot disagree about what `N`'s ports are.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
AnsiPort, DataDecl, DataType, Declarator, Dim, ItemKind, ListElem, Module, ParamDecl,
|
||||
ParamPort, PortDecl, PortList,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::instantiate::{instantiation_plan, Layout};
|
||||
|
||||
/// Where a name that crosses the boundary is declared in the module.
|
||||
pub(super) enum Site<'t> {
|
||||
/// An ANSI port of the header.
|
||||
Ansi(&'t AnsiPort),
|
||||
/// A name-only header port, with the body declarations that describe it.
|
||||
NonAnsi(&'t PortDecl, &'t Declarator, Option<(&'t DataDecl, &'t Declarator)>),
|
||||
/// A net or variable declared in the body.
|
||||
Data(&'t DataDecl, &'t Declarator),
|
||||
/// A parameter or localparam declared in the body.
|
||||
Param(&'t ParamDecl, &'t Declarator),
|
||||
/// A parameter declared in the header's `#( ... )`.
|
||||
ParamPort(&'t ParamPort),
|
||||
}
|
||||
|
||||
/// Every declaration of the module that a crossing name could name.
|
||||
pub(super) fn site_of<'t>(module: &'t Module, name: &str) -> Option<Site<'t>> {
|
||||
if let PortList::Ansi(ports) = &module.ports {
|
||||
if let Some(port) = ports.iter().filter_map(ListElem::ok).find(|p| p.name == name) {
|
||||
return Some(Site::Ansi(port));
|
||||
}
|
||||
}
|
||||
if let Some(params) = &module.param_ports {
|
||||
if let Some(param) = params.iter().filter_map(ListElem::ok).find(|p| p.name == name) {
|
||||
return Some(Site::ParamPort(param));
|
||||
}
|
||||
}
|
||||
let mut port: Option<(&PortDecl, &Declarator)> = None;
|
||||
let mut data: Option<(&DataDecl, &Declarator)> = None;
|
||||
for item in &module.items {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(decl) => {
|
||||
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
|
||||
port = Some((decl, d));
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(decl) => {
|
||||
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
|
||||
data = Some((decl, d));
|
||||
}
|
||||
}
|
||||
ItemKind::ParamDecl(decl) => {
|
||||
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
|
||||
return Some(Site::Param(decl, d));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match (port, data) {
|
||||
(Some((decl, declarator)), other) => Some(Site::NonAnsi(decl, declarator, other)),
|
||||
(None, Some((decl, declarator))) => Some(Site::Data(decl, declarator)),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One port of the new module, ready to be written.
|
||||
pub(super) struct Port {
|
||||
pub(super) name: String,
|
||||
/// `input logic [7:0] `, the name's own text excluded.
|
||||
pub(super) prefix: String,
|
||||
/// Every identifier that prefix spells — the direction and the type
|
||||
/// keywords among them. A port whose width is `[N-1:0]` names `N`, and
|
||||
/// `N` has to cross the boundary with it or the new module names nothing.
|
||||
pub(super) names: Vec<String>,
|
||||
}
|
||||
|
||||
/// One parameter of the new module.
|
||||
pub(super) struct Param {
|
||||
pub(super) name: String,
|
||||
/// `parameter int `, the name's own text excluded.
|
||||
pub(super) prefix: String,
|
||||
/// The default as `M` writes it, or an empty string when it writes none.
|
||||
pub(super) default: String,
|
||||
/// Every identifier its type and its default name, for the closure that
|
||||
/// carries the parameters one parameter depends on across with it.
|
||||
pub(super) names: Vec<String>,
|
||||
}
|
||||
|
||||
/// The declaration of a crossing signal, written as an ANSI port of the new
|
||||
/// module.
|
||||
pub(super) fn port(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
site: &Site<'_>,
|
||||
dir: &str,
|
||||
) -> Result<Port, String> {
|
||||
let (net, ty, unpacked) = match site {
|
||||
Site::Ansi(port) => (port.net.as_deref(), &port.ty, port.unpacked.as_slice()),
|
||||
Site::NonAnsi(decl, declarator, var) => {
|
||||
let (net, ty) = match var {
|
||||
Some((data, _)) if decl.net.is_none() && decl.ty.name.is_empty() => {
|
||||
(data.net.as_deref().or(decl.net.as_deref()), &data.ty)
|
||||
}
|
||||
_ => (decl.net.as_deref(), &decl.ty),
|
||||
};
|
||||
if let Some((data, other)) = var {
|
||||
if !data.qualifiers.is_empty() {
|
||||
return Err(qualified(module, name));
|
||||
}
|
||||
if !other.unpacked.is_empty() {
|
||||
return Err(unpacked_refusal(module, name));
|
||||
}
|
||||
}
|
||||
(net, ty, declarator.unpacked.as_slice())
|
||||
}
|
||||
Site::Data(decl, declarator) => {
|
||||
if !decl.qualifiers.is_empty() {
|
||||
return Err(qualified(module, name));
|
||||
}
|
||||
if decl.delay.is_some() {
|
||||
return Err(delayed(module, name));
|
||||
}
|
||||
(decl.net.as_deref(), &decl.ty, declarator.unpacked.as_slice())
|
||||
}
|
||||
Site::Param(..) | Site::ParamPort(_) => return Err(lost(name)),
|
||||
};
|
||||
if !unpacked.is_empty() {
|
||||
return Err(unpacked_refusal(module, name));
|
||||
}
|
||||
let ty = type_text(text, module, name, ty)?;
|
||||
let mut prefix = String::new();
|
||||
let mut word = |part: &str| {
|
||||
prefix.push_str(part);
|
||||
prefix.push(' ');
|
||||
};
|
||||
word(dir);
|
||||
if let Some(net) = net {
|
||||
word(net);
|
||||
}
|
||||
if !ty.is_empty() {
|
||||
word(&ty);
|
||||
}
|
||||
let names = words(&prefix);
|
||||
Ok(Port { name: name.to_string(), prefix, names })
|
||||
}
|
||||
|
||||
/// The declaration of a crossing parameter, written as a parameter of the new
|
||||
/// module.
|
||||
pub(super) fn param(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
site: &Site<'_>,
|
||||
) -> Result<Param, String> {
|
||||
let (is_type, ty, default) = match site {
|
||||
Site::Param(decl, declarator) => {
|
||||
(decl.is_type, &decl.ty, declarator.init.as_ref().map(|e| e.span))
|
||||
}
|
||||
Site::ParamPort(param) => {
|
||||
(param.is_type, ¶m.ty, param.default.as_ref().map(|e| e.span))
|
||||
}
|
||||
_ => return Err(lost(name)),
|
||||
};
|
||||
if is_type {
|
||||
return Err(format!(
|
||||
"`{module}`'s `{name}` is a type parameter, and lucisv does not carry one into a new module this round."
|
||||
));
|
||||
}
|
||||
let ty = type_text(text, module, name, ty)?;
|
||||
let mut prefix = String::from("parameter ");
|
||||
if !ty.is_empty() {
|
||||
prefix.push_str(&ty);
|
||||
prefix.push(' ');
|
||||
}
|
||||
let default = default.map(|span| slice(text, span).trim().to_string()).unwrap_or_default();
|
||||
if default.contains('\n') {
|
||||
return Err(format!(
|
||||
"`{module}` writes `{name}`'s default across several lines, and lucisv does not re-flow one into a new module's header."
|
||||
));
|
||||
}
|
||||
let mut names = words(&prefix);
|
||||
names.extend(words(&default));
|
||||
Ok(Param { name: name.to_string(), prefix, default, names })
|
||||
}
|
||||
|
||||
/// Everything a declaration writes between the direction and the name, as the
|
||||
/// source spells it: `logic [7:0]`, `my_pkg::word_t`, `signed [31:0]`.
|
||||
fn type_text(text: &str, module: &str, name: &str, ty: &DataType) -> Result<String, String> {
|
||||
if ty.virt.is_some() || ty.extra.is_some() {
|
||||
return Err(format!(
|
||||
"`{module}` declares `{name}` with a type lucisv does not move into a port list (an anonymous aggregate, a parameterized reference or a virtual interface)."
|
||||
));
|
||||
}
|
||||
let mut out = String::new();
|
||||
for part in [ty.name.as_str(), ty.signing.as_deref().unwrap_or("")] {
|
||||
if part.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(part);
|
||||
}
|
||||
let packed = dims(text, &ty.packed);
|
||||
if !packed.is_empty() {
|
||||
if !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(&packed);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn dims(text: &str, list: &[Dim]) -> String {
|
||||
list.iter().map(|dim| slice(text, dim.span)).collect()
|
||||
}
|
||||
|
||||
fn slice(text: &str, span: TextRange) -> &str {
|
||||
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Every whole word of an expression's text — what a parameter default may
|
||||
/// depend on.
|
||||
fn words(text: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
if !is_word_byte(bytes[i]) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let start = i;
|
||||
while i < bytes.len() && is_word_byte(bytes[i]) {
|
||||
i += 1;
|
||||
}
|
||||
let leading_digit = bytes[start].is_ascii_digit();
|
||||
let after_tick = start > 0 && bytes[start - 1] == b'\'';
|
||||
if !leading_digit && !after_tick {
|
||||
if let Some(word) = text.get(start..i) {
|
||||
out.push(word.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn is_word_byte(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the two texts
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The whole new module: header, the imports it needs, and the selection's own
|
||||
/// bytes, verbatim.
|
||||
///
|
||||
/// Verbatim is the point. The items are module items in `M` and module items
|
||||
/// in `N`, at the same nesting depth, so the source's own indentation is
|
||||
/// already right — and every comment, every attribute and every string travels
|
||||
/// byte for byte, which is what lets the splice verifier count them.
|
||||
pub(super) fn new_module(
|
||||
name: &str,
|
||||
imports: &[String],
|
||||
params: &[Param],
|
||||
ports: &[Port],
|
||||
body: &str,
|
||||
) -> String {
|
||||
let mut out = format!("module {name}");
|
||||
for path in imports {
|
||||
out.push_str("\n import ");
|
||||
out.push_str(path);
|
||||
out.push(';');
|
||||
}
|
||||
// A header import is written on its own line, which is where the formatter
|
||||
// puts one; the list after it then starts a line of its own rather than
|
||||
// continuing with a space.
|
||||
let sep = match imports.is_empty() {
|
||||
true => " ",
|
||||
false => "\n",
|
||||
};
|
||||
if !params.is_empty() {
|
||||
out.push_str(sep);
|
||||
out.push_str("#(\n");
|
||||
for (i, param) in params.iter().enumerate() {
|
||||
out.push_str(" ");
|
||||
out.push_str(¶m.prefix);
|
||||
out.push_str(¶m.name);
|
||||
if !param.default.is_empty() {
|
||||
out.push_str(" = ");
|
||||
out.push_str(¶m.default);
|
||||
}
|
||||
out.push_str(if i + 1 < params.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
out.push(')');
|
||||
}
|
||||
let sep = match params.is_empty() {
|
||||
true => sep,
|
||||
false => " ",
|
||||
};
|
||||
match ports.is_empty() {
|
||||
true => {
|
||||
out.push_str(sep);
|
||||
out.push_str("();\n");
|
||||
}
|
||||
false => {
|
||||
out.push_str(sep);
|
||||
out.push_str("(\n");
|
||||
for (i, port) in ports.iter().enumerate() {
|
||||
out.push_str(" ");
|
||||
out.push_str(&port.prefix);
|
||||
out.push_str(&port.name);
|
||||
out.push_str(if i + 1 < ports.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
out.push_str(");\n");
|
||||
}
|
||||
}
|
||||
out.push_str(body);
|
||||
if !body.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str("endmodule\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// The instantiation that replaces the selection, read back out of the new
|
||||
/// module's own text.
|
||||
///
|
||||
/// Every port connects to the signal of the same name — which is what the
|
||||
/// extraction just made true — and every parameter to the parameter of the
|
||||
/// same name.
|
||||
pub(super) fn instantiation(name: &str, module_text: &str, indent: &str) -> Result<String, String> {
|
||||
let mut plan = instantiation_plan(name, module_text, None)?;
|
||||
for port in &mut plan.ports {
|
||||
port.auto_connect = true;
|
||||
}
|
||||
let params = plan.params.len();
|
||||
let names: Vec<String> = plan.params.iter().map(|param| param.name.clone()).collect();
|
||||
let layout = Layout { base: indent.to_string(), step: " ".to_string() };
|
||||
Ok(plan.render_with(&layout, &mut |n, default| match n <= params {
|
||||
true => names.get(n - 1).cloned().unwrap_or_default(),
|
||||
false => default.to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sentences
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn unpacked_refusal(module: &str, name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` crosses the selection's boundary and `{module}` declares it with an unpacked dimension; lucisv does not turn one into a port this round."
|
||||
)
|
||||
}
|
||||
|
||||
fn qualified(module: &str, name: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{name}` with a qualifier (`var`, `const`, `automatic`), and lucisv does not move a qualifier into a port list."
|
||||
)
|
||||
}
|
||||
|
||||
fn delayed(module: &str, name: &str) -> String {
|
||||
format!(
|
||||
"`{module}` declares `{name}` with a net delay, and lucisv does not move a delay into a port list."
|
||||
)
|
||||
}
|
||||
|
||||
fn lost(name: &str) -> String {
|
||||
format!("lucisv lost track of the declaration of `{name}`, so it made no edits.")
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
//! 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<RefactorEdit, String> {
|
||||
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<String> {
|
||||
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<String> = 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, created: Vec::new() };
|
||||
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<ImportScope<'t>, 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<String>)>,
|
||||
/// 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<Block>,
|
||||
/// 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<Blocks, String> {
|
||||
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<TextEdit>, Vec<String>, usize, usize), String> {
|
||||
let mut warnings = Vec::new();
|
||||
let mut keep: Vec<bool> = Vec::with_capacity(self.blocks.len());
|
||||
let mut seen: Vec<&[(String, Option<String>)]> = 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::<Vec<_>>()
|
||||
.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<TextRange> {
|
||||
let mut spans: Vec<TextRange> = 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
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -315,7 +315,7 @@ fn terminate(out: &mut String, text: &str) {
|
||||
/// the question is exactly whether a `\` survives in the run of characters
|
||||
/// after the last whitespace. Conservative by construction: a false positive
|
||||
/// writes one harmless extra space.
|
||||
fn ends_escaped(text: &str) -> bool {
|
||||
pub(crate) fn ends_escaped(text: &str) -> bool {
|
||||
text.rsplit(char::is_whitespace).next().unwrap_or(text).contains('\\')
|
||||
}
|
||||
|
||||
|
||||
@@ -28,12 +28,18 @@
|
||||
//! spans instead of edits — see `docs/features/references-nav/README.md`.
|
||||
|
||||
mod check;
|
||||
mod extract;
|
||||
mod imports;
|
||||
mod instantiate;
|
||||
mod ports;
|
||||
mod references;
|
||||
mod rename;
|
||||
mod scope;
|
||||
|
||||
pub use extract::{extract_module, extract_site, extract_title, ExtractSite, Home};
|
||||
pub use imports::{
|
||||
imported_packages, organize_counts, organize_imports, organize_title, unused_imports,
|
||||
};
|
||||
pub use references::find_references;
|
||||
|
||||
pub use instantiate::{
|
||||
@@ -41,8 +47,9 @@ pub use instantiate::{
|
||||
PlanPort, Site,
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
|
||||
propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction,
|
||||
add_port, convert_to_ansi, enclosing_module, expand_wildcard, is_sites_phrase,
|
||||
may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port,
|
||||
sites_phrase, ModuleRef, PortAction,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
@@ -75,6 +82,13 @@ pub struct RefactorEdit {
|
||||
/// for (macro bodies, `endmodule :` labels). Informational only — a
|
||||
/// result with warnings is still safe to apply.
|
||||
pub warnings: Vec<String>,
|
||||
/// Files the refactoring **creates**. Each one also appears in `edits`,
|
||||
/// with exactly one insertion at offset 0 writing the whole file, so a
|
||||
/// caller that cannot create files can ignore this and get nothing; a
|
||||
/// caller that can (LSP's `CreateFile`) creates each of these first and
|
||||
/// then applies the edits as it applies every other one. Empty for every
|
||||
/// refactoring but [`extract_module`].
|
||||
pub created: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl RefactorEdit {
|
||||
|
||||
@@ -229,19 +229,19 @@ pub(super) fn element_spans(ports: &[DeclaredPort]) -> Vec<TextRange> {
|
||||
|
||||
/// One compiler directive written inside a port list or a module body, and
|
||||
/// where it is written.
|
||||
struct Directive {
|
||||
text: String,
|
||||
span: TextRange,
|
||||
pub(super) struct Directive {
|
||||
pub(super) text: String,
|
||||
pub(super) span: TextRange,
|
||||
}
|
||||
|
||||
/// What a directive does to the conditional nesting depth.
|
||||
enum Nesting {
|
||||
pub(super) enum Nesting {
|
||||
Open,
|
||||
Close,
|
||||
Neither,
|
||||
}
|
||||
|
||||
fn nesting_of(directive: &str) -> Nesting {
|
||||
pub(super) fn nesting_of(directive: &str) -> Nesting {
|
||||
let word = directive.split_whitespace().next().unwrap_or_default();
|
||||
match word {
|
||||
"`ifdef" | "`ifndef" => Nesting::Open,
|
||||
@@ -264,7 +264,7 @@ fn list_directives(module: &Module) -> Vec<Directive> {
|
||||
/// The directives written among a module's items — where a non-ANSI port
|
||||
/// declaration goes. A macro *item* (`` `ASSERT_INIT(...) ``) is not collected:
|
||||
/// it is a call, not a directive, and cannot open a conditional region.
|
||||
fn body_directives(module: &Module) -> Vec<Directive> {
|
||||
pub(super) fn body_directives(module: &Module) -> Vec<Directive> {
|
||||
module
|
||||
.items
|
||||
.iter()
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
//! Converting a Verilog-2001 header to an ANSI one: `module m (a, b);` with
|
||||
//! `input a; output [7:0] b; reg [7:0] b;` in the body becomes
|
||||
//! `module m (input a, output reg [7:0] b);` with the body declarations gone.
|
||||
//!
|
||||
//! **The edit is insertions, never a rewrite of the list.** Each header name
|
||||
//! keeps the bytes it already occupies; what an ANSI port adds is written
|
||||
//! *around* it — the direction, type and packed dimensions just before the
|
||||
//! name, an unpacked dimension just after it. Two things follow from that, and
|
||||
//! both are the reason it is done this way:
|
||||
//!
|
||||
//! * The header's own layout, commas and comments are not touched at all, so a
|
||||
//! one-per-line list stays one per line and a comment written beside a port
|
||||
//! name stays beside it.
|
||||
//! * `Shift::map` maps the port's name span onto exactly the bytes the name
|
||||
//! occupies afterwards, so `check::verify_splice`'s resolution check — which
|
||||
//! requires every reference outside the edits to resolve to the *same*
|
||||
//! declaration, at the same place — passes. A conversion that replaced the
|
||||
//! element wholesale would move the declaration the body's references point
|
||||
//! at, and the verifier would rightly refuse the whole refactoring.
|
||||
//!
|
||||
//! The merge itself is `merge.rs` (IEEE 1800 §23.2.2.2). This file locates the
|
||||
//! module, refuses everything lucisv will not convert, decides where each
|
||||
//! absorbed declaration's comments go, and writes the edits.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{
|
||||
GenBlock, GenElse, Item, ItemKind, ListElem, Module, NonAnsiPort, PortList,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::add::{body_directives, nesting_of, Directive, Nesting};
|
||||
use super::find::{find_module, locate_module, module_at, not_in_scope, ModuleSite};
|
||||
use super::list::{after_same_line_comments, comma_after, insert, line_indent, whole_line};
|
||||
use super::merge::{absorb, Absorbed};
|
||||
use super::{shape, ModuleRef, Plan};
|
||||
|
||||
/// One planned conversion: what to edit, and what the title will promise.
|
||||
pub(super) struct Conversion {
|
||||
pub(super) site: ModuleSite,
|
||||
pub(super) plan: Plan,
|
||||
/// How many ports the header declares — what the code action counts.
|
||||
pub(super) count: usize,
|
||||
}
|
||||
|
||||
pub(super) fn plan_convert(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<Conversion, String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let mut found = None;
|
||||
module_at(&tree.items, offset, &mut found);
|
||||
let Some(name) = found else {
|
||||
return Err("there is no module declaration at this position.".to_string());
|
||||
};
|
||||
let Some((module, _)) = find_module(&tree, &name) else {
|
||||
return Err(format!("lucisv can no longer find the declaration of `{name}`."));
|
||||
};
|
||||
let ports = header(module)?;
|
||||
unparsed(file, &diagnostics)?;
|
||||
let names = header_names(module, &ports)?;
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(format!(
|
||||
"`{name}`'s port list carries compiler directives, so which ports it declares depends on the configuration; lucisv does not preprocess, so it made no edits."
|
||||
));
|
||||
}
|
||||
if let Some(hidden) = in_generate(&module.items, &names) {
|
||||
return Err(format!(
|
||||
"`{name}` declares `{hidden}` inside a generate region, where lucisv will not read a port's declaration; it made no edits."
|
||||
));
|
||||
}
|
||||
let site = locate_module(scope, ModuleRef::Name(&name))?;
|
||||
if site.file != i {
|
||||
return Err(format!(
|
||||
"`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits."
|
||||
));
|
||||
}
|
||||
|
||||
let absorbed = absorb(text, &name, &module.items, &names)?;
|
||||
attributes_clear(&name, &absorbed)?;
|
||||
directives_clear(text, file, module, &absorbed)?;
|
||||
let comments = comments_of(text, file)?;
|
||||
let mut plan = Plan::default();
|
||||
// One declaration may declare several ports (`input a, b;`), and its
|
||||
// comments belong to the first of them: written onto both they would be
|
||||
// duplicated, which is as much a corruption as dropping them.
|
||||
let mut claimed: Vec<TextRange> = Vec::new();
|
||||
for (port, absorbed) in ports.iter().zip(&absorbed) {
|
||||
plan.add(i, port_edits(text, &name, port, absorbed, &comments, &mut claimed)?);
|
||||
}
|
||||
plan.add(i, deletions(text, &name, &absorbed, &comments)?);
|
||||
plan.expected.push((i, shape(text, &name)));
|
||||
Ok(Conversion { site, plan, count: ports.len() })
|
||||
}
|
||||
|
||||
/// The non-ANSI port list this conversion needs, or the sentence saying why
|
||||
/// there is not one.
|
||||
fn header(module: &Module) -> Result<Vec<&NonAnsiPort>, String> {
|
||||
let name = &module.name;
|
||||
if module.kw == "interface" || module.kw == "program" {
|
||||
return Err(format!(
|
||||
"`{name}` is an `{}`, not a module, and lucisv does not convert an {}'s non-ANSI header in this round; it made no edits.",
|
||||
module.kw, module.kw
|
||||
));
|
||||
}
|
||||
let ports = match &module.ports {
|
||||
PortList::NonAnsi(ports) => ports,
|
||||
PortList::Ansi(_) => {
|
||||
return Err(format!(
|
||||
"`{name}`'s header already declares its ports ANSI-style, so there is nothing to convert."
|
||||
))
|
||||
}
|
||||
PortList::Empty | PortList::None => {
|
||||
return Err(format!("`{name}` declares no ports, so there is nothing to convert."))
|
||||
}
|
||||
};
|
||||
if ports.iter().any(ListElem::is_error) {
|
||||
return Err(format!(
|
||||
"`{name}`'s header writes a port expression (IEEE 1800 §23.2.2.1's `.a({{x,y}})` or `{{x,y}}`), which has no ANSI spelling; lucisv made no edits."
|
||||
));
|
||||
}
|
||||
Ok(ports.iter().filter_map(ListElem::ok).collect())
|
||||
}
|
||||
|
||||
/// The header's names in header order, with a repeated one refused: a list
|
||||
/// that names a port twice is not one lucisv will guess at.
|
||||
fn header_names(module: &Module, ports: &[&NonAnsiPort]) -> Result<Vec<String>, String> {
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for port in ports {
|
||||
if names.contains(&port.name) {
|
||||
return Err(format!(
|
||||
"`{}`'s header names `{}` twice; lucisv will not guess which port that is.",
|
||||
module.name, port.name
|
||||
));
|
||||
}
|
||||
names.push(port.name.clone());
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// The refusal a file that does not parse earns. Stricter than the verifier's
|
||||
/// "no *new* diagnostic" rule, and for the same reason the `.*` expansion is:
|
||||
/// a header lucisv misread is a header whose ports it would declare twice.
|
||||
fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
|
||||
match diagnostics.first() {
|
||||
None => Ok(()),
|
||||
Some(problem) => Err(format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not convert its ports to ANSI.",
|
||||
display(file),
|
||||
problem.message,
|
||||
problem.line
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A header port declared inside a generate construct is a declaration in
|
||||
/// another scope, which lucisv will not absorb into the header.
|
||||
fn in_generate(items: &[Item], names: &[String]) -> Option<String> {
|
||||
fn walk(items: &[Item], names: &[String], inside: bool, found: &mut Option<String>) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(decl) if inside => {
|
||||
named(decl.declarators.iter().map(|d| &d.name), names, found);
|
||||
}
|
||||
ItemKind::DataDecl(decl) if inside => {
|
||||
named(decl.declarators.iter().map(|d| &d.name), names, found);
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, names, true, found),
|
||||
ItemKind::GenBlock(block) => walk(&block.items, names, true, found),
|
||||
ItemKind::GenFor(gen) => block(&gen.body, names, found),
|
||||
ItemKind::GenCase(gen) => {
|
||||
for arm in &gen.items {
|
||||
block(&arm.body, names, found);
|
||||
}
|
||||
}
|
||||
ItemKind::GenIf(gen) => {
|
||||
block(&gen.then, names, found);
|
||||
let mut els = gen.els.as_deref();
|
||||
while let Some(next) = els {
|
||||
match next {
|
||||
GenElse::If(_, gen) => {
|
||||
block(&gen.then, names, found);
|
||||
els = gen.els.as_deref();
|
||||
}
|
||||
GenElse::Block(b) => {
|
||||
block(b, names, found);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn block(b: &GenBlock, names: &[String], found: &mut Option<String>) {
|
||||
walk(&b.items, names, true, found);
|
||||
}
|
||||
fn named<'a>(
|
||||
declared: impl Iterator<Item = &'a String>,
|
||||
names: &[String],
|
||||
found: &mut Option<String>,
|
||||
) {
|
||||
for name in declared {
|
||||
if found.is_none() && names.contains(name) {
|
||||
*found = Some(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut found = None;
|
||||
walk(items, names, false, &mut found);
|
||||
found
|
||||
}
|
||||
|
||||
/// Refuse a declaration that carries an attribute instance.
|
||||
///
|
||||
/// `Item.span` covers the `(* ... *)` written before it, so the deletion takes
|
||||
/// the attribute with the declaration and only the *comments* are carried onto
|
||||
/// the port — a silent loss of something that changes what a synthesizer does.
|
||||
/// Where an attribute belongs in an ANSI port list is a design question rather
|
||||
/// than a merge rule, so the conversion refuses instead of guessing, the same
|
||||
/// way it refuses an initialiser or a qualifier. `check::never_dropped` counts
|
||||
/// attributes too, so a planner that ever misses one is refused a second time.
|
||||
fn attributes_clear(module: &str, absorbed: &[Absorbed<'_>]) -> Result<(), String> {
|
||||
for port in absorbed {
|
||||
for item in &port.items {
|
||||
let Some(attr) = item.meta.attrs.first() else { continue };
|
||||
return Err(format!(
|
||||
"`{}` on `{module}`'s declaration of `{}` would be dropped, and lucisv does not decide where an attribute belongs in an ANSI port list; move the attribute onto the port by hand, and it made no edits.",
|
||||
attr.text.trim(),
|
||||
port.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// lucisv does not preprocess, so a declaration it deletes must not be one an
|
||||
/// `` `ifdef`` arm holds, and no directive may stand between the declarations
|
||||
/// it deletes: either way the body it leaves behind is one no configuration
|
||||
/// ever had.
|
||||
fn directives_clear(
|
||||
text: &str,
|
||||
file: &Path,
|
||||
module: &Module,
|
||||
absorbed: &[Absorbed<'_>],
|
||||
) -> Result<(), String> {
|
||||
let directives = body_directives(module);
|
||||
if directives.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let spans: Vec<TextRange> =
|
||||
absorbed.iter().flat_map(|a| a.items.iter().map(|i| i.span)).collect();
|
||||
let (Some(first), Some(last)) =
|
||||
(spans.iter().map(|span| span.start).min(), spans.iter().map(|span| span.end).max())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let region = format!("`{}`'s body", module.name);
|
||||
for span in &spans {
|
||||
depth_zero(&directives, span.start, ®ion)?;
|
||||
}
|
||||
match directives.iter().find(|d| d.span.start >= first && d.span.start < last) {
|
||||
None => Ok(()),
|
||||
Some(directive) => Err(format!(
|
||||
"a compiler directive (`{}` at {}:{}) is written among the declarations converting `{}` would delete, so lucisv does not know what the body it leaves behind would say; it made no edits.",
|
||||
directive.text.trim().lines().next().unwrap_or_default().trim_end(),
|
||||
display(file),
|
||||
LineIndex::new(text).line_col(directive.span.start).0,
|
||||
module.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse a declaration that stands inside a conditional arm.
|
||||
fn depth_zero(directives: &[Directive], at: u32, region: &str) -> Result<(), String> {
|
||||
let mut depth = 0i32;
|
||||
for directive in directives.iter().filter(|d| d.span.start < at) {
|
||||
match nesting_of(&directive.text) {
|
||||
Nesting::Open => depth += 1,
|
||||
Nesting::Close => depth -= 1,
|
||||
Nesting::Neither => {}
|
||||
}
|
||||
}
|
||||
match depth {
|
||||
0 => Ok(()),
|
||||
_ => Err(format!(
|
||||
"{region} is conditionally compiled, and one of the declarations the conversion would delete stands inside an `ifdef arm; a port declared in one arm does not exist in the other, so lucisv made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every comment in the file, with the bytes it occupies — the same pieces
|
||||
/// `check::pieces` reads, so a comment this file moves is a comment the
|
||||
/// verifier can account for.
|
||||
fn comments_of(text: &str, file: &Path) -> Result<Vec<(TextRange, String)>, String> {
|
||||
let Ok(tokens) = tokenize(text) else {
|
||||
return Err(format!("{} does not lex, so lucisv will not edit it.", display(file)));
|
||||
};
|
||||
let mut out: Vec<(TextRange, String)> = Vec::new();
|
||||
let mut push = |comment: &Comment| out.push((comment.span, comment.text.clone()));
|
||||
for token in &tokens {
|
||||
token.leading.iter().for_each(&mut push);
|
||||
if let Some(trailing) = &token.trailing {
|
||||
push(trailing);
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
out.dedup_by_key(|(span, _)| *span);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The comments one absorbed declaration carries, and the bytes a deletion
|
||||
/// must therefore cover.
|
||||
#[derive(Default)]
|
||||
struct Carried {
|
||||
before: Vec<String>,
|
||||
after: Vec<String>,
|
||||
}
|
||||
|
||||
/// What one body item takes with it: its own bytes plus the comments written
|
||||
/// before and after it, which move onto the ANSI port.
|
||||
fn carried(
|
||||
text: &str,
|
||||
module: &str,
|
||||
item: &Item,
|
||||
comments: &[(TextRange, String)],
|
||||
) -> Result<(TextRange, Carried), String> {
|
||||
let start = item.meta.leading.first().map_or(item.span.start, |c| c.span.start);
|
||||
let end = item.meta.trailing.as_ref().map_or(item.span.end, |c| c.span.end);
|
||||
let mut carried = Carried::default();
|
||||
for (span, comment) in
|
||||
comments.iter().filter(|(span, _)| span.start >= start && span.end <= end)
|
||||
{
|
||||
if span.start >= item.span.start && span.end <= item.span.end {
|
||||
return Err(format!(
|
||||
"`{module}` writes the comment `{comment}` inside a declaration the conversion would delete, and lucisv will not decide where a comment written inside a declaration goes in an ANSI port; it made no edits."
|
||||
));
|
||||
}
|
||||
match span.end <= item.span.start {
|
||||
true => carried.before.push(comment.clone()),
|
||||
false => carried.after.push(comment.clone()),
|
||||
}
|
||||
}
|
||||
Ok((whole_line(text, TextRange::new(start, end)), carried))
|
||||
}
|
||||
|
||||
/// The insertions that turn one header name into an ANSI port declaration.
|
||||
///
|
||||
/// The comments the absorbed declarations carried go in one of two places.
|
||||
/// The first choice, for a comment written *after* a declaration, is the end
|
||||
/// of the port's own line — where the source had it, relative to what it
|
||||
/// describes. That is only free when nothing else is written there and the
|
||||
/// header wrote no comment of its own beside the port, and there is exactly
|
||||
/// one of them. Everything else goes on its own line above the port, which
|
||||
/// always works for a list written one port per line; a list written on one
|
||||
/// line takes a block comment inline and refuses a `//`.
|
||||
fn port_edits(
|
||||
text: &str,
|
||||
module: &str,
|
||||
port: &NonAnsiPort,
|
||||
absorbed: &Absorbed<'_>,
|
||||
comments: &[(TextRange, String)],
|
||||
claimed: &mut Vec<TextRange>,
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let mut moved = Carried::default();
|
||||
for item in &absorbed.items {
|
||||
let (_, carried) = carried(text, module, item, comments)?;
|
||||
// A declaration this port shares with an earlier one has already
|
||||
// handed its comments over; taking them again would write them twice.
|
||||
if claimed.contains(&item.span) {
|
||||
continue;
|
||||
}
|
||||
claimed.push(item.span);
|
||||
moved.before.extend(carried.before);
|
||||
moved.after.extend(carried.after);
|
||||
}
|
||||
let at = tail(text, port);
|
||||
// Exactly one comment may go beside the port, because two comments landing
|
||||
// on one line become *one* comment — a `//` runs to the end of the line and
|
||||
// the lexer merges what follows it into the same trailing comment — and a
|
||||
// refactoring that joins two comments the source kept apart is one the
|
||||
// verifier rightly refuses. The rest go above.
|
||||
let beside = moved.after.len() == 1
|
||||
&& after_same_line_comments(text, at).at == at
|
||||
&& line_free(text, at);
|
||||
let mut above = moved.before;
|
||||
if !beside {
|
||||
above.extend(moved.after.iter().cloned());
|
||||
}
|
||||
|
||||
let mut edits = vec![insert(port.span.start, prefix(text, module, port, absorbed, &above)?)];
|
||||
if !absorbed.unpacked.is_empty() {
|
||||
edits.push(insert(port.span.end, absorbed.unpacked.clone()));
|
||||
}
|
||||
if beside {
|
||||
edits.push(insert(at, format!(" {}", moved.after.join(" "))));
|
||||
}
|
||||
Ok(edits)
|
||||
}
|
||||
|
||||
/// What is written just before the port's name: the comments its declarations
|
||||
/// carried, then the declaration itself.
|
||||
fn prefix(
|
||||
text: &str,
|
||||
module: &str,
|
||||
port: &NonAnsiPort,
|
||||
absorbed: &Absorbed<'_>,
|
||||
above: &[String],
|
||||
) -> Result<String, String> {
|
||||
let mut out = String::new();
|
||||
match own_line(text, port.span.start) {
|
||||
Some(indent) => {
|
||||
for comment in above {
|
||||
out.push_str(comment);
|
||||
out.push('\n');
|
||||
out.push_str(&indent);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for comment in above {
|
||||
if !inline_safe(comment) {
|
||||
return Err(format!(
|
||||
"the comment `{comment}` on `{module}`'s declaration of `{}` would have to move into a port list written on one line, where it would swallow the rest of it; break `{module}`'s port list across lines first, and lucisv made no edits.",
|
||||
absorbed.name
|
||||
));
|
||||
}
|
||||
out.push_str(comment);
|
||||
out.push(' ');
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(&absorbed.prefix);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where a port's trailing comment goes: past the `,` that follows the name,
|
||||
/// or — for the last port — straight after it.
|
||||
fn tail(text: &str, port: &NonAnsiPort) -> u32 {
|
||||
comma_after(text, port.span.end).map_or(port.span.end, |comma| comma + 1)
|
||||
}
|
||||
|
||||
/// The deletions that take the absorbed body declarations away, comments
|
||||
/// included: each one moved onto its port above.
|
||||
fn deletions(
|
||||
text: &str,
|
||||
module: &str,
|
||||
absorbed: &[Absorbed<'_>],
|
||||
comments: &[(TextRange, String)],
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let mut ranges: Vec<TextRange> = Vec::new();
|
||||
for item in absorbed.iter().flat_map(|a| a.items.iter()) {
|
||||
let (range, _) = carried(text, module, item, comments)?;
|
||||
if !ranges.contains(&range) {
|
||||
ranges.push(range);
|
||||
}
|
||||
}
|
||||
Ok(ranges.into_iter().map(|range| TextEdit { range, new_text: String::new() }).collect())
|
||||
}
|
||||
|
||||
/// The indentation of the line `at` starts, or `None` when something else is
|
||||
/// written on that line before it.
|
||||
fn own_line(text: &str, at: u32) -> Option<String> {
|
||||
let indent = line_indent(text, at);
|
||||
let start = (at as usize).checked_sub(indent.len())?;
|
||||
(start == 0 || text.as_bytes().get(start - 1) == Some(&b'\n')).then_some(indent)
|
||||
}
|
||||
|
||||
/// Whether the rest of the line from `at` is blank — which is what makes room
|
||||
/// for a `//` comment.
|
||||
fn line_free(text: &str, at: u32) -> bool {
|
||||
text.get(at as usize..)
|
||||
.is_none_or(|rest| rest.split('\n').next().is_none_or(|line| line.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// Whether a comment can be written in the middle of a line: a block comment
|
||||
/// that stays on it.
|
||||
fn inline_safe(comment: &str) -> bool {
|
||||
comment.starts_with("/*") && !comment.contains('\n')
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Expanding `.*`: the wildcard connection written out as the named
|
||||
//! connections it stands for.
|
||||
//!
|
||||
//! **The rule, as implemented.** IEEE 1800 §23.3.2.4: a `.*` binds every port
|
||||
//! the instance does not connect explicitly to the *same-named* declaration
|
||||
//! visible in the scope the instantiation is written in. lucisv reads "a
|
||||
//! signal" strictly — a net, a variable, or a port of the enclosing module —
|
||||
//! because those are the only declarations a port connection may bind to; a
|
||||
//! parameter, a localparam, a genvar or a type of that name is not a signal
|
||||
//! and the wildcard does not bind it. A port with nothing to bind to is one
|
||||
//! the compiler would have rejected, so it is written `.name()` and named in a
|
||||
//! warning: saying so is the point of the expansion.
|
||||
//!
|
||||
//! Everything else is `propagate.rs`'s shape — the same `Scope`, the same
|
||||
//! declared-port reader, the same `Plan` verified by `finish` — with one
|
||||
//! difference: this refactoring *replaces* a token rather than appending after
|
||||
//! one, so the `.*`'s own span is the edit's range and the comment written
|
||||
//! after it is stepped over the way `append_to_list` steps over one.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connection, Connections, Instance, Instantiation, Item, ListElem};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::add::not_indexed;
|
||||
use super::find::{
|
||||
declared_ports, find_module, kind_visible_in, locate_module, not_in_scope, walk_instantiations,
|
||||
ModuleSite,
|
||||
};
|
||||
use super::list::{after_same_line_comments, conn_list_open, elem_spans, insert, line_indent};
|
||||
use super::{shape, ModuleRef, Plan};
|
||||
|
||||
/// One planned expansion: what to edit, and what the title will promise.
|
||||
pub(super) struct Expansion {
|
||||
pub(super) site: ModuleSite,
|
||||
pub(super) plan: Plan,
|
||||
/// How many connections the `.*` becomes.
|
||||
pub(super) count: usize,
|
||||
/// The instance the wildcard belongs to, for the verifier's sentence.
|
||||
pub(super) instance: String,
|
||||
}
|
||||
|
||||
pub(super) fn plan_expand(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<Expansion, String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(file, &diagnostics)?;
|
||||
let Wildcard { instantiation, instance, conns, wildcard } = wildcard_at(&tree.items, offset)?;
|
||||
if !instance.conn_directives.is_empty() {
|
||||
return Err(directives(&instance.name, "connection list"));
|
||||
}
|
||||
let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?;
|
||||
|
||||
let missing = unconnected(scope, &site, conns)?;
|
||||
if missing.is_empty() {
|
||||
return Err(format!(
|
||||
"`{}` already connects every port `{}` declares, so its `.*` binds nothing.",
|
||||
instance.name, site.name
|
||||
));
|
||||
}
|
||||
|
||||
let (connections, unbound) = written(scope, i, instance, &missing);
|
||||
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
|
||||
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
|
||||
return Err(format!(
|
||||
"lucisv cannot find the parentheses of `{}`'s connection list.",
|
||||
instance.name
|
||||
));
|
||||
};
|
||||
let previous = wildcard.checked_sub(1).and_then(|n| spans.get(n)).map_or(open + 1, |e| e.end);
|
||||
let Some(&at) = spans.get(wildcard) else {
|
||||
return Err("lucisv lost track of the `.*` it was expanding.".to_string());
|
||||
};
|
||||
|
||||
let mut plan = Plan { sites: 1, ..Plan::default() };
|
||||
plan.add(i, replacement(text, previous, at, &connections));
|
||||
if !unbound.is_empty() {
|
||||
plan.warnings.push(unbound_warning(text, file, instance, &unbound));
|
||||
}
|
||||
plan.expected.push((i, expected(text, &site.name, instance, conns, wildcard, &missing)));
|
||||
Ok(Expansion { site, plan, count: connections.len(), instance: instance.name.clone() })
|
||||
}
|
||||
|
||||
/// The refusal a file that does not parse earns. A connection list lucisv
|
||||
/// misread is a list whose ports it would connect twice, so — unlike the
|
||||
/// verifier's "no *new* diagnostic" rule — this one asks for none at all.
|
||||
fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
|
||||
match diagnostics.first() {
|
||||
None => Ok(()),
|
||||
Some(problem) => Err(format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not expand a `.*` in it.",
|
||||
display(file),
|
||||
problem.message,
|
||||
problem.line
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn directives(what: &str, list: &str) -> String {
|
||||
format!(
|
||||
"`{what}`'s {list} carries compiler directives, so which ports `.*` binds depends on the configuration; lucisv does not preprocess, so it made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
/// What the cursor found: an instance, its named connection list, and which
|
||||
/// element of it is the `.*`.
|
||||
struct Wildcard<'t> {
|
||||
instantiation: &'t Instantiation,
|
||||
instance: &'t Instance,
|
||||
conns: &'t [ListElem<Connection>],
|
||||
wildcard: usize,
|
||||
}
|
||||
|
||||
/// The instantiation the cursor names and the `.*` inside it, or the sentence
|
||||
/// saying why there is none to expand.
|
||||
fn wildcard_at(items: &[Item], offset: u32) -> Result<Wildcard<'_>, String> {
|
||||
let (instantiation, instance, bound) = instance_at(items, offset)?;
|
||||
if bound {
|
||||
return Err(format!(
|
||||
"`{}` is instantiated by a `bind` directive, where `.*` binds in the target's scope rather than in this one; lucisv does not expand it there.",
|
||||
instance.name
|
||||
));
|
||||
}
|
||||
let conns = match &instance.conns {
|
||||
Connections::Ordered(_) => {
|
||||
return Err(format!(
|
||||
"`{}` connects `{}`'s ports by position; there is no `.*` to expand.",
|
||||
instance.name, instantiation.module
|
||||
))
|
||||
}
|
||||
Connections::Named(conns) => conns.as_slice(),
|
||||
};
|
||||
let wildcards: Vec<usize> = conns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| c.ok().is_some_and(|c| c.name == "*"))
|
||||
.map(|(n, _)| n)
|
||||
.collect();
|
||||
match wildcards.as_slice() {
|
||||
[only] => Ok(Wildcard { instantiation, instance, conns, wildcard: *only }),
|
||||
[] => Err(format!("`{}` writes no `.*` to expand.", instance.name)),
|
||||
_ => Err(format!(
|
||||
"`{}` writes `.*` {} times, which is illegal; lucisv will not guess what it means.",
|
||||
instance.name,
|
||||
wildcards.len()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance under the cursor, or the only one of the statement the
|
||||
/// cursor's module name belongs to — `propagate`'s rule, plus whether the
|
||||
/// instantiation is a `bind` directive's.
|
||||
fn instance_at(items: &[Item], offset: u32) -> Result<(&Instantiation, &Instance, bool), String> {
|
||||
let mut all: Vec<(&Instantiation, bool)> = Vec::new();
|
||||
walk_instantiations(items, &mut |instantiation, bound| all.push((instantiation, bound)));
|
||||
let mut found = None;
|
||||
for (instantiation, bound) in all {
|
||||
for instance in &instantiation.instances {
|
||||
if instance.span.contains(offset) {
|
||||
found = Some((instantiation, instance, bound));
|
||||
}
|
||||
}
|
||||
if found.is_none() && instantiation.module_span.contains(offset) {
|
||||
let [only] = instantiation.instances.as_slice() else {
|
||||
return Err(format!(
|
||||
"this statement declares {} instances of `{}`; put the cursor on the one to expand.",
|
||||
instantiation.instances.len(),
|
||||
instantiation.module
|
||||
));
|
||||
};
|
||||
found = Some((instantiation, only, bound));
|
||||
}
|
||||
}
|
||||
found.ok_or_else(|| "there is no module instantiation at this position.".to_string())
|
||||
}
|
||||
|
||||
/// The declared ports the instance does not connect explicitly, in declaration
|
||||
/// order — exactly what the wildcard stands for.
|
||||
fn unconnected(
|
||||
scope: &mut Scope,
|
||||
site: &ModuleSite,
|
||||
conns: &[ListElem<Connection>],
|
||||
) -> Result<Vec<String>, String> {
|
||||
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(path, &diagnostics)?;
|
||||
let Some((module, _)) = find_module(&tree, &site.name) else {
|
||||
return Err(not_indexed(&site.name));
|
||||
};
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(directives(&site.name, "port list"));
|
||||
}
|
||||
Ok(declared_ports(module)
|
||||
.into_iter()
|
||||
.map(|port| port.name)
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Each missing port as the connection lucisv writes for it, plus the ports
|
||||
/// nothing in scope binds.
|
||||
fn written(
|
||||
scope: &mut Scope,
|
||||
file: usize,
|
||||
instance: &Instance,
|
||||
missing: &[String],
|
||||
) -> (Vec<String>, Vec<String>) {
|
||||
let at = instance.name_span.start;
|
||||
let mut connections = Vec::new();
|
||||
let mut unbound = Vec::new();
|
||||
for name in missing {
|
||||
let bound = signal_visible(scope, file, at, name);
|
||||
if !bound {
|
||||
unbound.push(name.clone());
|
||||
}
|
||||
connections.push(connection(name, bound));
|
||||
}
|
||||
(connections, unbound)
|
||||
}
|
||||
|
||||
/// `.name(name)`, or `.name()` for a port nothing binds — with the space an
|
||||
/// **escaped identifier** needs after it.
|
||||
///
|
||||
/// An escaped identifier runs from its `\` to the next whitespace and to
|
||||
/// nothing else (IEEE 1800 §5.6.1), so `.\my-port(\my-port)` is one enormous
|
||||
/// token that swallows the parens, the comma and the rest of the line. The
|
||||
/// instantiation skeleton learned this from QA (`instantiate::terminate`);
|
||||
/// the test for "does this end inside an escape" is shared rather than
|
||||
/// spelled twice.
|
||||
fn connection(name: &str, bound: bool) -> String {
|
||||
let mut out = String::from(".");
|
||||
terminate(&mut out, name);
|
||||
out.push('(');
|
||||
if bound {
|
||||
terminate(&mut out, name);
|
||||
}
|
||||
out.push(')');
|
||||
out
|
||||
}
|
||||
|
||||
fn terminate(out: &mut String, name: &str) {
|
||||
out.push_str(name);
|
||||
if crate::instantiate::ends_escaped(name) {
|
||||
out.push(' ');
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `.*` would bind `name` here: a net, a variable or a port of that
|
||||
/// name, declared in the instantiating scope or one enclosing it.
|
||||
///
|
||||
/// A parameter is deliberately not one. `parameter int clk = 0;` beside an
|
||||
/// instance leaves the module's `clk` port unbound, and writing `.clk(clk)`
|
||||
/// for it would connect a port to a constant — a legal, silent, wrong
|
||||
/// expansion. The kinds are the LRM's, not the ones a connection lucisv
|
||||
/// *writes* may name (`find::visible_in`).
|
||||
fn signal_visible(scope: &mut Scope, file: usize, offset: u32, name: &str) -> bool {
|
||||
let Some(analysis) = scope.analysis(file) else { return false };
|
||||
kind_visible_in(&analysis.semantics, offset, name)
|
||||
.is_some_and(|kind| matches!(kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port))
|
||||
}
|
||||
|
||||
/// The edits that put the connections where the `.*` was.
|
||||
///
|
||||
/// The layout is the list's own, read the way `append_to_list` reads it: the
|
||||
/// gap before the wildcard tells one-element-per-line from inline, and the
|
||||
/// indentation is the wildcard's own line's. A comment written after the `.*`
|
||||
/// on its own line stays with the **first** connection — the comma goes before
|
||||
/// it and the rest after it — because a `,` written after `//` is a `,` inside
|
||||
/// a comment, and because the comment was about the wildcard, whose first
|
||||
/// connection is what replaces it.
|
||||
fn replacement(text: &str, previous: u32, at: TextRange, connections: &[String]) -> Vec<TextEdit> {
|
||||
let one_per_line =
|
||||
text.get(previous as usize..at.start as usize).is_some_and(|gap| gap.contains('\n'));
|
||||
let indent = line_indent(text, at.start);
|
||||
let br = match one_per_line {
|
||||
true => format!("\n{indent}"),
|
||||
false => " ".to_string(),
|
||||
};
|
||||
let separator = format!(",{br}");
|
||||
let replace = |text: String| TextEdit { range: at, new_text: text };
|
||||
|
||||
let after = after_same_line_comments(text, at.end);
|
||||
let [first, rest @ ..] = connections else { return Vec::new() };
|
||||
if after.at == at.end || rest.is_empty() {
|
||||
return vec![replace(connections.join(&separator))];
|
||||
}
|
||||
vec![replace(format!("{first},")), insert(after.at, format!("{br}{}", rest.join(&separator)))]
|
||||
}
|
||||
|
||||
fn unbound_warning(text: &str, file: &Path, instance: &Instance, unbound: &[String]) -> String {
|
||||
let lines = LineIndex::new(text);
|
||||
format!(
|
||||
"no net, variable or port named {} is declared where `{}` is instantiated ({}:{}), so `.*` never bound {} — lucisv wrote {} unconnected.",
|
||||
unbound.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "),
|
||||
instance.name,
|
||||
display(file),
|
||||
lines.line_col(instance.name_span.start).0,
|
||||
if unbound.len() == 1 { "it" } else { "them" },
|
||||
if unbound.len() == 1 { "it" } else { "them" },
|
||||
)
|
||||
}
|
||||
|
||||
/// What the file must say afterwards: this instance's connection names with
|
||||
/// the `*` replaced, in place, by the ports it stood for.
|
||||
fn expected(
|
||||
text: &str,
|
||||
module: &str,
|
||||
instance: &Instance,
|
||||
conns: &[ListElem<Connection>],
|
||||
wildcard: usize,
|
||||
missing: &[String],
|
||||
) -> super::Shape {
|
||||
let mut names: Vec<String> =
|
||||
conns.iter().map(|c| c.ok().map(|c| c.name.clone()).unwrap_or_default()).collect();
|
||||
names.splice(wildcard..wildcard + 1, missing.iter().cloned());
|
||||
let mut shape = shape(text, module);
|
||||
for (name, conns) in &mut shape.instances {
|
||||
if name == &instance.name {
|
||||
*conns = names.clone();
|
||||
}
|
||||
}
|
||||
shape
|
||||
}
|
||||
@@ -143,34 +143,45 @@ pub(super) fn declared_ports(module: &Module) -> Vec<DeclaredPort> {
|
||||
/// Every instantiation written in a file, generate blocks and `bind`
|
||||
/// directives included.
|
||||
pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t Instantiation>) {
|
||||
walk_instantiations(items, &mut |instantiation, _| out.push(instantiation));
|
||||
}
|
||||
|
||||
/// [`collect_instantiations`]'s walk, saying of each instantiation whether it
|
||||
/// is a `bind` directive's own — which is where a `.*` binds in the *target's*
|
||||
/// scope rather than in the one it is written in, and therefore the one site
|
||||
/// the wildcard expansion declines.
|
||||
pub(super) fn walk_instantiations<'t>(
|
||||
items: &'t [Item],
|
||||
visit: &mut dyn FnMut(&'t Instantiation, bool),
|
||||
) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Instantiation(inst) => out.push(inst),
|
||||
ItemKind::Bind(bind) => out.push(&bind.inst),
|
||||
ItemKind::Module(module) => collect_instantiations(&module.items, out),
|
||||
ItemKind::Package { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenBlock(b) => collect_instantiations(&b.items, out),
|
||||
ItemKind::Instantiation(inst) => visit(inst, false),
|
||||
ItemKind::Bind(bind) => visit(&bind.inst, true),
|
||||
ItemKind::Module(module) => walk_instantiations(&module.items, visit),
|
||||
ItemKind::Package { items, .. } => walk_instantiations(items, visit),
|
||||
ItemKind::GenerateRegion { items, .. } => walk_instantiations(items, visit),
|
||||
ItemKind::GenBlock(b) => walk_instantiations(&b.items, visit),
|
||||
ItemKind::GenIf(gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
walk_gen_block(&gen.then, visit);
|
||||
let mut els = gen.els.as_deref();
|
||||
while let Some(next) = els {
|
||||
match next {
|
||||
GenElse::If(_, gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
walk_gen_block(&gen.then, visit);
|
||||
els = gen.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
collect_gen_block(block, out);
|
||||
walk_gen_block(block, visit);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen) => collect_gen_block(&gen.body, out),
|
||||
ItemKind::GenFor(gen) => walk_gen_block(&gen.body, visit),
|
||||
ItemKind::GenCase(gen) => {
|
||||
for arm in &gen.items {
|
||||
collect_gen_block(&arm.body, out);
|
||||
walk_gen_block(&arm.body, visit);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -178,8 +189,8 @@ pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t In
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_gen_block<'t>(block: &'t GenBlock, out: &mut Vec<&'t Instantiation>) {
|
||||
collect_instantiations(&block.items, out);
|
||||
fn walk_gen_block<'t>(block: &'t GenBlock, visit: &mut dyn FnMut(&'t Instantiation, bool)) {
|
||||
walk_instantiations(&block.items, visit);
|
||||
}
|
||||
|
||||
/// Whether a signal called `name` is visible at `offset` in a file — the test
|
||||
@@ -190,6 +201,32 @@ pub(super) fn name_visible(scope: &mut Scope, file: usize, offset: u32, name: &s
|
||||
}
|
||||
|
||||
pub(crate) fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool {
|
||||
kind_visible_in(semantics, offset, name).is_some_and(|kind| {
|
||||
matches!(
|
||||
kind,
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::TfArg
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// What a lookup of `name` from the innermost scope covering `offset` finds —
|
||||
/// the scope walk itself, without the judgement about which kinds count.
|
||||
///
|
||||
/// Two callers want different answers from the same walk: a connection lucisv
|
||||
/// *writes* may name anything a reader could have written there, while `.*`
|
||||
/// binds only a net, a variable or a port (IEEE 1800 §23.3.2.4), so the
|
||||
/// wildcard expansion asks the same question and reads the kind itself.
|
||||
pub(crate) fn kind_visible_in(
|
||||
semantics: &Semantics,
|
||||
offset: u32,
|
||||
name: &str,
|
||||
) -> Option<SymbolKind> {
|
||||
let scopes = semantics.scopes();
|
||||
// The innermost scope covering the offset: the smallest span that holds it.
|
||||
let mut best: Option<usize> = None;
|
||||
@@ -206,24 +243,13 @@ pub(crate) fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool
|
||||
}
|
||||
let mut at = best;
|
||||
while let Some(i) = at {
|
||||
let Some(current) = scopes.get(i) else { return false };
|
||||
let current = scopes.get(i)?;
|
||||
if let Some(symbol) = current.lookup_local(name) {
|
||||
return semantics.symbol(symbol).is_some_and(|s| {
|
||||
matches!(
|
||||
s.kind,
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::TfArg
|
||||
)
|
||||
});
|
||||
return semantics.symbol(symbol).map(|s| s.kind);
|
||||
}
|
||||
at = current.parent.map(|p| p.0 as usize);
|
||||
}
|
||||
false
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -174,7 +174,7 @@ pub(super) fn line_indent(text: &str, offset: u32) -> String {
|
||||
}
|
||||
|
||||
/// The `,` written after `end`, skipping whitespace and comments.
|
||||
fn comma_after(text: &str, end: u32) -> Option<u32> {
|
||||
pub(super) fn comma_after(text: &str, end: u32) -> Option<u32> {
|
||||
let mut at = end as usize;
|
||||
loop {
|
||||
let rest = text.get(at..)?;
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! IEEE 1800 §23.2.2.2: pairing each name of a non-ANSI header with the body
|
||||
//! declarations that describe it, and merging the two into the one ANSI port
|
||||
//! declaration that says the same thing.
|
||||
//!
|
||||
//! The LRM's rule in one paragraph. A non-ANSI header names its ports and the
|
||||
//! body declares them. The *port declaration* (`output [7:0] b;`) always
|
||||
//! carries the direction; when it also carries a net or a variable type
|
||||
//! (`output reg [7:0] b;`, `input wire a;`) the port is **completely
|
||||
//! declared** and declaring it again is an error. When it does not, a separate
|
||||
//! net or variable declaration of the same name (`reg [7:0] b;`) finishes it,
|
||||
//! and the two must agree: identical packed ranges, identical unpacked
|
||||
//! dimensions, one signing. The merge is the union — `output [7:0] b;` plus
|
||||
//! `reg [7:0] b;` is `output reg [7:0] b`.
|
||||
//!
|
||||
//! Everything this module produces is *text*, written in the order the
|
||||
//! formatter's own ANSI port printer writes it (`vlog_formatter`'s
|
||||
//! `ansi_port_cells`: direction, net, type, signing, packed dimensions, name,
|
||||
//! unpacked dimensions), so a converted header formats to itself.
|
||||
|
||||
use vlog_parser::ast::{DataDecl, DataType, Declarator, Dim, Item, ItemKind, PortDecl};
|
||||
|
||||
/// One header port, once its body declarations have been read and merged.
|
||||
pub(super) struct Absorbed<'t> {
|
||||
pub(super) name: String,
|
||||
/// The body items this port takes with it: its port declaration, and the
|
||||
/// net or variable declaration that completed it, if there was one.
|
||||
pub(super) items: Vec<&'t Item>,
|
||||
/// Everything an ANSI port writes before its name: `output reg [7:0] `.
|
||||
pub(super) prefix: String,
|
||||
/// Everything it writes after it: ` [0:3]` for an unpacked dimension.
|
||||
pub(super) unpacked: String,
|
||||
}
|
||||
|
||||
/// Where one declarator of one body declaration is written.
|
||||
struct Site<'t> {
|
||||
item: &'t Item,
|
||||
declarator: &'t Declarator,
|
||||
}
|
||||
|
||||
/// Read a module's body declarations and merge each header name with its own.
|
||||
///
|
||||
/// `names` is the header's port list in header order; the answer is in the
|
||||
/// same order, which is what makes the converted list the list the source
|
||||
/// wrote.
|
||||
pub(super) fn absorb<'t>(
|
||||
text: &str,
|
||||
module: &str,
|
||||
items: &'t [Item],
|
||||
names: &[String],
|
||||
) -> Result<Vec<Absorbed<'t>>, String> {
|
||||
let Body { ports, vars } = collect(module, items, names)?;
|
||||
let mut out = Vec::new();
|
||||
for name in names {
|
||||
let port = one(
|
||||
&ports,
|
||||
name,
|
||||
|| {
|
||||
format!(
|
||||
"`{module}`'s header names `{name}`, but its body declares no direction for it; a port with no declaration is illegal, so lucisv made no edits."
|
||||
)
|
||||
},
|
||||
|| {
|
||||
format!(
|
||||
"`{module}` declares a direction for `{name}` twice; lucisv will not guess which one is the port."
|
||||
)
|
||||
},
|
||||
)?;
|
||||
let var = match vars.iter().filter(|site| site.declarator.name == *name).count() {
|
||||
0 => None,
|
||||
1 => vars.iter().find(|site| site.declarator.name == *name),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"`{module}` declares `{name}` twice outside its port declaration; lucisv will not guess which one completes the port."
|
||||
))
|
||||
}
|
||||
};
|
||||
out.push(merged(text, module, name, port, var)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A module body as the merge reads it: the port declarations that give the
|
||||
/// directions, and the net/variable declarations that complete them.
|
||||
struct Body<'t> {
|
||||
ports: Vec<Site<'t>>,
|
||||
vars: Vec<Site<'t>>,
|
||||
}
|
||||
|
||||
/// Read the body, with the declarations lucisv will not absorb refused.
|
||||
fn collect<'t>(module: &str, items: &'t [Item], names: &[String]) -> Result<Body<'t>, String> {
|
||||
let mut ports = Vec::new();
|
||||
let mut vars = Vec::new();
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(decl) => {
|
||||
for declarator in &decl.declarators {
|
||||
if !names.contains(&declarator.name) {
|
||||
return Err(format!(
|
||||
"`{module}` declares a direction for `{}`, which its header does not name; lucisv made no edits.",
|
||||
declarator.name
|
||||
));
|
||||
}
|
||||
no_initialiser(module, declarator)?;
|
||||
ports.push(Site { item, declarator });
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(decl) => {
|
||||
let mine = decl.declarators.iter().filter(|d| names.contains(&d.name)).count();
|
||||
if mine == 0 {
|
||||
continue;
|
||||
}
|
||||
shared(module, decl, mine)?;
|
||||
for declarator in &decl.declarators {
|
||||
no_initialiser(module, declarator)?;
|
||||
vars.push(Site { item, declarator });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Body { ports, vars })
|
||||
}
|
||||
|
||||
/// A declaration that names a header port *and* something else cannot be
|
||||
/// deleted: the local it also declares would go with it.
|
||||
fn shared(module: &str, decl: &DataDecl, mine: usize) -> Result<(), String> {
|
||||
if mine == decl.declarators.len() {
|
||||
return no_qualifier(module, decl);
|
||||
}
|
||||
Err(format!(
|
||||
"`{module}` declares {} in one declaration, of which only {mine} {} a port; lucisv cannot absorb one without the other, so split the declaration first.",
|
||||
decl.declarators.iter().map(|d| format!("`{}`", d.name)).collect::<Vec<_>>().join(", "),
|
||||
if mine == 1 { "is" } else { "are" }
|
||||
))
|
||||
}
|
||||
|
||||
/// What lucisv refuses to carry from a variable declaration into a port list:
|
||||
/// a `var`/`const`/`automatic` qualifier, and a net delay.
|
||||
fn no_qualifier(module: &str, decl: &DataDecl) -> Result<(), String> {
|
||||
if let Some(qualifier) = decl.qualifiers.first() {
|
||||
return Err(format!(
|
||||
"`{module}` writes `{}` where it completes a port's declaration, and lucisv does not move a qualifier into a port list; it made no edits.",
|
||||
qualifier.text
|
||||
));
|
||||
}
|
||||
if decl.delay.is_some() {
|
||||
return Err(format!(
|
||||
"`{module}` writes a net delay where it completes a port's declaration, and lucisv does not move a delay into a port list; it made no edits."
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn no_initialiser(module: &str, declarator: &Declarator) -> Result<(), String> {
|
||||
match declarator.init {
|
||||
None => Ok(()),
|
||||
Some(_) => Err(format!(
|
||||
"`{module}` initialises `{}` where it declares it, and lucisv does not move an initialiser into a port list; it made no edits.",
|
||||
declarator.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one site declaring `name`, or the sentence for none and for several.
|
||||
fn one<'a, 't>(
|
||||
sites: &'a [Site<'t>],
|
||||
name: &str,
|
||||
none: impl Fn() -> String,
|
||||
several: impl Fn() -> String,
|
||||
) -> Result<&'a Site<'t>, String> {
|
||||
let mut found = sites.iter().filter(|site| site.declarator.name == name);
|
||||
let first = found.next().ok_or_else(none)?;
|
||||
match found.next() {
|
||||
None => Ok(first),
|
||||
Some(_) => Err(several()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One header name plus its declarations, written out as an ANSI port.
|
||||
fn merged<'t>(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
port: &Site<'t>,
|
||||
var: Option<&Site<'t>>,
|
||||
) -> Result<Absorbed<'t>, String> {
|
||||
let ItemKind::PortDecl(decl) = &port.item.kind else {
|
||||
return Err(format!("lucisv lost track of `{module}`'s declaration of `{name}`."));
|
||||
};
|
||||
let variable = match var.map(|site| &site.item.kind) {
|
||||
Some(ItemKind::DataDecl(decl)) => Some(decl),
|
||||
_ => None,
|
||||
};
|
||||
if variable.is_some() && complete(decl) {
|
||||
return Err(format!(
|
||||
"`{module}` gives `{name}` a type in its port declaration and declares it again; IEEE 1800 §23.2.2.2 makes that an error, so lucisv made no edits."
|
||||
));
|
||||
}
|
||||
plain(module, name, &decl.ty)?;
|
||||
if let Some(variable) = variable {
|
||||
plain(module, name, &variable.ty)?;
|
||||
}
|
||||
|
||||
let net = decl.net.clone().or_else(|| variable.and_then(|v| v.net.clone()));
|
||||
let ty = pick_name(&decl.ty, variable.map(|v| &v.ty));
|
||||
let signing = signing(
|
||||
module,
|
||||
name,
|
||||
decl.ty.signing.clone(),
|
||||
variable.and_then(|v| v.ty.signing.clone()),
|
||||
)?;
|
||||
let var_packed = variable.map_or(&[][..], |v| v.ty.packed.as_slice());
|
||||
let packed = dims(text, module, name, "packed range", &decl.ty.packed, var_packed)?;
|
||||
let unpacked = dims(
|
||||
text,
|
||||
module,
|
||||
name,
|
||||
"unpacked dimension",
|
||||
&port.declarator.unpacked,
|
||||
var.map_or(&[][..], |site| site.declarator.unpacked.as_slice()),
|
||||
)?;
|
||||
|
||||
let mut prefix = String::new();
|
||||
let mut word = |part: &str| {
|
||||
prefix.push_str(part);
|
||||
prefix.push(' ');
|
||||
};
|
||||
word(&decl.dir);
|
||||
for part in [net.as_deref(), ty.as_deref(), signing.as_deref()].into_iter().flatten() {
|
||||
word(part);
|
||||
}
|
||||
if !packed.is_empty() {
|
||||
word(&packed);
|
||||
}
|
||||
|
||||
let mut items = vec![port.item];
|
||||
if let Some(site) = var {
|
||||
items.push(site.item);
|
||||
}
|
||||
let unpacked = match unpacked.is_empty() {
|
||||
true => String::new(),
|
||||
false => format!(" {unpacked}"),
|
||||
};
|
||||
Ok(Absorbed { name: name.to_string(), items, prefix, unpacked })
|
||||
}
|
||||
|
||||
/// Whether a port declaration already says what the port *is* — a net type or
|
||||
/// a data type — which is what makes it complete under §23.2.2.2.
|
||||
fn complete(decl: &PortDecl) -> bool {
|
||||
decl.net.is_some() || !decl.ty.name.is_empty()
|
||||
}
|
||||
|
||||
/// A type lucisv writes into a port list is a name, a signing and packed
|
||||
/// dimensions and nothing else: an anonymous `enum`/`struct` body, a
|
||||
/// parameterized `#( ... )` reference or a `virtual` interface type is text
|
||||
/// lucisv will not move for the user.
|
||||
fn plain(module: &str, name: &str, ty: &DataType) -> Result<(), String> {
|
||||
match ty.virt.is_none() && ty.extra.is_none() {
|
||||
true => Ok(()),
|
||||
false => Err(format!(
|
||||
"`{module}` declares `{name}` with a type lucisv does not move into a port list (an anonymous aggregate, a parameterized reference or a virtual interface); it made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type name the merge writes: the port declaration's own, or — when it
|
||||
/// declared none — the one the variable declaration finished it with.
|
||||
fn pick_name(port: &DataType, var: Option<&DataType>) -> Option<String> {
|
||||
let from_var = var.map(|ty| ty.name.clone()).filter(|name| !name.is_empty());
|
||||
match port.name.is_empty() {
|
||||
true => from_var,
|
||||
false => Some(port.name.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The signing the merge writes. Two halves of one declaration must not
|
||||
/// disagree; `None` on either side is silence, not disagreement.
|
||||
fn signing(
|
||||
module: &str,
|
||||
name: &str,
|
||||
port: Option<String>,
|
||||
var: Option<String>,
|
||||
) -> Result<Option<String>, String> {
|
||||
match (port, var) {
|
||||
(Some(a), Some(b)) if a == b => Ok(Some(a)),
|
||||
(Some(a), Some(b)) => Err(format!(
|
||||
"`{module}` declares `{name}` `{a}` in its port declaration and `{b}` where it completes it; IEEE 1800 §23.2.2.2 asks the two to agree, so lucisv made no edits."
|
||||
)),
|
||||
(Some(a), None) | (None, Some(a)) => Ok(Some(a)),
|
||||
(None, None) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The dimensions the merge writes, as the source spells them. Two lists that
|
||||
/// are both written must be the same list — that is the LRM's "identical
|
||||
/// range" — compared with the whitespace taken out, so `[7 : 0]` and `[7:0]`
|
||||
/// agree.
|
||||
fn dims(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
what: &str,
|
||||
port: &[Dim],
|
||||
var: &[Dim],
|
||||
) -> Result<String, String> {
|
||||
let written = |list: &[Dim]| -> String {
|
||||
list.iter()
|
||||
.map(|dim| text.get(dim.span.start as usize..dim.span.end as usize).unwrap_or_default())
|
||||
.collect()
|
||||
};
|
||||
let (a, b) = (written(port), written(var));
|
||||
if a.is_empty() || b.is_empty() {
|
||||
return Ok(match a.is_empty() {
|
||||
true => b,
|
||||
false => a,
|
||||
});
|
||||
}
|
||||
let tight = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
|
||||
match tight(&a) == tight(&b) {
|
||||
true => Ok(a),
|
||||
false => Err(format!(
|
||||
"`{module}` declares `{name}` with the {what} `{a}` in its port declaration and `{b}` where it completes it; IEEE 1800 §23.2.2.2 asks for identical ones, so lucisv made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,11 @@
|
||||
//! parenthesis finding they share.
|
||||
|
||||
mod add;
|
||||
mod ansi;
|
||||
mod expand;
|
||||
mod find;
|
||||
mod list;
|
||||
mod merge;
|
||||
mod propagate;
|
||||
mod remove;
|
||||
|
||||
@@ -31,13 +34,15 @@ pub(crate) use find::{find_module, visible_in};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Connections, ItemKind};
|
||||
use vlog_parser::ast::{Connections, ItemKind, Module, PortList};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
use add::{parse_port_decl, plan_add};
|
||||
use ansi::plan_convert;
|
||||
use expand::plan_expand;
|
||||
use find::{collect_instantiations, declared_ports, locate_module, module_at};
|
||||
use propagate::plan_propagate;
|
||||
use remove::{locate_port, plan_remove};
|
||||
@@ -125,6 +130,65 @@ pub fn propagate_ports(
|
||||
Ok(finish(&mut scope, plan, &site.name, &what)?.0)
|
||||
}
|
||||
|
||||
/// Write out the `.*` at `offset`: every port the instantiation does not
|
||||
/// connect explicitly, bound to the same-named signal in the instantiating
|
||||
/// scope (IEEE 1800 §23.3.2.4), in the module's declaration order.
|
||||
///
|
||||
/// A port with no such signal is one the wildcard never bound — a compiler
|
||||
/// would have rejected the instantiation — so it is written `.name()` and
|
||||
/// named in a warning. Nothing outside the cursor's own file is edited.
|
||||
pub fn expand_wildcard(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
Ok(expansion(files, file, offset)?.0)
|
||||
}
|
||||
|
||||
/// The expansion and how many connections it writes — what a code action's
|
||||
/// title promises.
|
||||
fn expansion(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(RefactorEdit, usize), String> {
|
||||
let mut scope = Scope::build(files);
|
||||
let expansion = plan_expand(&mut scope, file, offset)?;
|
||||
let what = format!("expanding the `.*` of `{}`", expansion.instance);
|
||||
let edit = finish(&mut scope, expansion.plan, &expansion.site.name, &what)?.0;
|
||||
Ok((edit, expansion.count))
|
||||
}
|
||||
|
||||
/// Rewrite a Verilog-2001 header as an ANSI one: every port the header names
|
||||
/// gains the direction, type, signing and dimensions its body declarations
|
||||
/// gave it (IEEE 1800 §23.2.2.2), and those declarations go.
|
||||
///
|
||||
/// The header's own layout, commas and comments are untouched — what an ANSI
|
||||
/// port adds is inserted around each name — and a comment on an absorbed
|
||||
/// declaration moves onto the port it described. Nothing outside the module's
|
||||
/// own file is edited.
|
||||
pub fn convert_to_ansi(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
Ok(conversion(files, file, offset)?.0)
|
||||
}
|
||||
|
||||
/// The conversion and how many ports it declares — what a code action's title
|
||||
/// promises.
|
||||
fn conversion(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(RefactorEdit, usize), String> {
|
||||
let mut scope = Scope::build(files);
|
||||
let conversion = plan_convert(&mut scope, file, offset)?;
|
||||
let what = format!("converting `{}`'s ports to ANSI", conversion.site.name);
|
||||
let edit = finish(&mut scope, conversion.plan, &conversion.site.name, &what)?.0;
|
||||
Ok((edit, conversion.count))
|
||||
}
|
||||
|
||||
/// Every port refactoring available at a position, each with its edit already
|
||||
/// computed and verified — which is what lets a code action carry its own
|
||||
/// `WorkspaceEdit` instead of a command the editor has to resolve.
|
||||
@@ -153,6 +217,24 @@ pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Ve
|
||||
edit,
|
||||
});
|
||||
}
|
||||
if let Ok((edit, count)) = expansion(files, file, offset) {
|
||||
out.push(PortAction {
|
||||
title: format!(
|
||||
"lucisv: expand .* ({count} connection{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
edit,
|
||||
});
|
||||
}
|
||||
if let Ok((edit, count)) = conversion(files, file, offset) {
|
||||
out.push(PortAction {
|
||||
title: format!(
|
||||
"lucisv: convert ports to ANSI ({count} port{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
edit,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -213,10 +295,29 @@ pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)),
|
||||
_ => false,
|
||||
});
|
||||
match on_body_declaration {
|
||||
true => vec![name],
|
||||
false => Vec::new(),
|
||||
if on_body_declaration || in_non_ansi_header(module, offset) {
|
||||
return vec![name];
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Whether the cursor is anywhere in the header of a module written the
|
||||
/// Verilog-2001 way — the one position the ANSI conversion is offered at that
|
||||
/// no other port refactoring cares about.
|
||||
///
|
||||
/// The header is everything from the module's keyword to the first item it
|
||||
/// declares (that item's own leading comments included, since a cursor there
|
||||
/// is still above the body). An ANSI module answers `false`: nothing would be
|
||||
/// offered, and the gate exists to keep a cursor that carries no action from
|
||||
/// materializing a workspace.
|
||||
fn in_non_ansi_header(module: &Module, offset: u32) -> bool {
|
||||
if !matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
return false;
|
||||
}
|
||||
let body = module.items.first().map(|item| {
|
||||
item.meta.leading.first().map_or(item.span.start, |comment| comment.span.start)
|
||||
});
|
||||
offset < body.unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
/// The module whose declaration covers this offset — what
|
||||
@@ -249,6 +350,17 @@ pub fn sites_phrase(sites: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a title's parenthesized tail is one [`sites_phrase`] wrote.
|
||||
///
|
||||
/// A server that recounts an offered title's instantiations from its index
|
||||
/// must not recount a title counting something else: `lucisv: expand .* (3
|
||||
/// connections)` says how many connections one `.*` becomes, which no
|
||||
/// instantiation census can answer. One spelling of the phrase, and one
|
||||
/// reader of it, both here.
|
||||
pub fn is_sites_phrase(phrase: &str) -> bool {
|
||||
phrase == sites_phrase(0) || phrase.starts_with("updates ")
|
||||
}
|
||||
|
||||
/// Everything a port refactoring wants done, before it is verified.
|
||||
#[derive(Default)]
|
||||
struct Plan {
|
||||
@@ -316,7 +428,7 @@ fn finish(
|
||||
edits.push((path.to_path_buf(), file_edits));
|
||||
}
|
||||
edits.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok((RefactorEdit { edits, warnings: plan.warnings }, plan.sites))
|
||||
Ok((RefactorEdit { edits, warnings: plan.warnings, created: Vec::new() }, plan.sites))
|
||||
}
|
||||
|
||||
/// What one file says about a module's signature: the module's own declared
|
||||
|
||||
@@ -171,7 +171,7 @@ pub fn rename(
|
||||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(RefactorEdit { edits: out, warnings })
|
||||
Ok(RefactorEdit { edits: out, warnings, created: Vec::new() })
|
||||
}
|
||||
|
||||
/// A new name must lex as exactly one identifier and must not be a keyword.
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
//! `convert_to_ansi`: a Verilog-2001 header rewritten ANSI-style.
|
||||
//!
|
||||
//! Behaviour tests, written against the public API the way an editor calls it.
|
||||
//! The merge rules are IEEE 1800 §23.2.2.2's, one test each; the refusals are
|
||||
//! the list in `docs/features/ansi-conversion/README.md`, one test each.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{convert_to_ansi, port_actions, RefactorEdit, TextEdit};
|
||||
|
||||
const TOP: &str = "/rtl/m.sv";
|
||||
|
||||
fn files(source: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![(PathBuf::from(TOP), source.to_string())]
|
||||
}
|
||||
|
||||
/// Apply an edit to the one file it touches.
|
||||
fn applied(source: &str, edit: &RefactorEdit) -> String {
|
||||
let (_, edits) = edit.edits.first().expect("one file edited");
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for TextEdit { range, new_text } in edits {
|
||||
out.push_str(&source[cursor..range.start as usize]);
|
||||
out.push_str(new_text);
|
||||
cursor = range.end as usize;
|
||||
}
|
||||
out.push_str(&source[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Convert at the module's name, which is inside every non-ANSI header.
|
||||
fn convert(source: &str) -> Result<String, String> {
|
||||
let at = source.find("module ").map_or(0, |i| i + 7) as u32;
|
||||
let edit = convert_to_ansi(&files(source), Path::new(TOP), at)?;
|
||||
assert!(edit.edits.len() == 1, "only the module's own file is edited");
|
||||
Ok(applied(source, &edit))
|
||||
}
|
||||
|
||||
/// The sentence a refusal is.
|
||||
fn refused(source: &str) -> String {
|
||||
convert(source).expect_err("this one is refused")
|
||||
}
|
||||
|
||||
fn count_comments(text: &str) -> usize {
|
||||
text.match_indices("//").count() + text.match_indices("/*").count()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// IEEE 1800 §23.2.2.2, one merge rule at a time
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_bare_port_declaration_becomes_a_bare_ansi_port() {
|
||||
let source = "module m (a, b);\n input a;\n inout b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (input a, inout b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vector_port_keeps_its_packed_range() {
|
||||
let source = "module m (b);\n output [7:0] b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output [7:0] b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_completed_by_a_variable_declaration_merges_the_two() {
|
||||
// The LRM's own example: `output [7:0] b; reg [7:0] b;` is `output reg
|
||||
// [7:0] b`.
|
||||
let source = "module m (b);\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output reg [7:0] b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scalar_port_completed_by_a_scalar_variable_merges_too() {
|
||||
let source = "module m (b);\n output b;\n reg b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output reg b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_completed_by_a_logic_declaration_merges() {
|
||||
let source = "module m (b);\n output b;\n logic [3:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (output logic [3:0] b);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_completed_by_a_net_declaration_merges() {
|
||||
let source = "module m (a);\n input a;\n wire [1:0] a;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (input wire [1:0] a);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_declaration_that_is_already_complete_needs_no_second_one() {
|
||||
let source = "module m (a);\n input wire signed [7:0] a;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input wire signed [7:0] a);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_written_on_either_half_reaches_the_ansi_port() {
|
||||
let port = "module m (b);\n output signed [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(port).expect("converted"),
|
||||
"module m (output reg signed [7:0] b);\nendmodule\n"
|
||||
);
|
||||
let var = "module m (b);\n output [7:0] b;\n reg signed [7:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(var).expect("converted"),
|
||||
"module m (output reg signed [7:0] b);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packed_range_written_on_only_one_half_is_the_merged_one() {
|
||||
let source = "module m (b);\n output b;\n reg [7:0] b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output reg [7:0] b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_unpacked_dimensions_survive_the_merge() {
|
||||
let source = "module m (mem);\n output [7:0] mem [0:3];\n reg [7:0] mem [0:3];\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (output reg [7:0] mem [0:3]);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_declaration_may_declare_several_ports() {
|
||||
let source = "module m (a, b, c);\n input a, b;\n output c;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input a, input b, output c);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_defined_type_is_written_as_the_source_spells_it() {
|
||||
let source = "module m (a);\n input a;\n pkg::word_t a;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (input pkg::word_t a);\nendmodule\n");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// layout, comments and the body
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_one_per_line_header_stays_one_per_line() {
|
||||
let source = "module m (\n a,\n b\n);\n input a;\n output [7:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n input a,\n output [7:0] b\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_headers_own_comments_are_not_touched() {
|
||||
let source = "module m (\n a, // the clock\n b\n);\n input a;\n output b;\nendmodule\n";
|
||||
let out = convert(source).expect("converted");
|
||||
assert!(out.contains("input a, // the clock"), "{out}");
|
||||
assert_eq!(count_comments(&out), count_comments(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comment_moves_onto_the_port_it_described() {
|
||||
let source =
|
||||
"module m (\n a,\n b\n);\n input a; // the clock\n output b; // the data\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n input a, // the clock\n output b // the data\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_comment_moves_onto_its_own_line_above_the_port() {
|
||||
let source =
|
||||
"module m (\n a,\n b\n);\n // the clock\n input a;\n output b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n // the clock\n input a,\n output b\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_halves_of_a_merged_port_keep_their_comments() {
|
||||
// Two comments never become one: a `//` swallows the line, so only one
|
||||
// may sit beside the port and the rest go above it.
|
||||
let source = "module m (\n b\n);\n output [7:0] b; // the port\n reg [7:0] b; // the storage\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n // the port\n // the storage\n output reg [7:0] b\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_comment_moves_into_an_inline_header() {
|
||||
let source = "module m (a, b);\n /* first */ input a;\n output b;\nendmodule\n";
|
||||
let out = convert(source).expect("converted");
|
||||
assert!(out.contains("/* first */ input a"), "{out}");
|
||||
assert_eq!(count_comments(&out), count_comments(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_comment_in_the_module_survives_the_conversion() {
|
||||
let source = concat!(
|
||||
"// about the file\n",
|
||||
"module m (\n",
|
||||
" a, // in the header\n",
|
||||
" b\n",
|
||||
");\n",
|
||||
" // above the input\n",
|
||||
" input a; // beside the input\n",
|
||||
" /* above the output */\n",
|
||||
" output [7:0] b; /* beside the output */\n",
|
||||
" // an ordinary body comment\n",
|
||||
" wire c;\n",
|
||||
"endmodule\n"
|
||||
);
|
||||
let out = convert(source).expect("converted");
|
||||
assert_eq!(count_comments(&out), count_comments(source), "{out}");
|
||||
for comment in [
|
||||
"// about the file",
|
||||
"// in the header",
|
||||
"// above the input",
|
||||
"// beside the input",
|
||||
"/* above the output */",
|
||||
"/* beside the output */",
|
||||
"// an ordinary body comment",
|
||||
] {
|
||||
assert!(out.contains(comment), "{comment} is gone from {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_written_between_the_declarations_is_left_alone() {
|
||||
let source =
|
||||
"module m (a, b);\n input a;\n parameter W = 8;\n output [W-1:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input a, output [W-1:0] b);\n parameter W = 8;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_declarations_that_are_not_ports_stay_where_they_are() {
|
||||
let source = "module m (a);\n input a;\n wire b;\n reg [3:0] c;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input a);\n wire b;\n reg [3:0] c;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_twenty_port_header_of_mixed_declarations_converts_whole() {
|
||||
let mut header = String::from("module wide (\n");
|
||||
let mut body = String::new();
|
||||
for n in 0..20 {
|
||||
let comma = if n == 19 { "" } else { "," };
|
||||
header.push_str(&format!(" p{n}{comma}\n"));
|
||||
match n % 5 {
|
||||
0 => body.push_str(&format!(" input p{n};\n")),
|
||||
1 => body.push_str(&format!(" input [7:0] p{n};\n")),
|
||||
2 => body.push_str(&format!(" output p{n};\n reg p{n};\n")),
|
||||
3 => {
|
||||
body.push_str(&format!(" output signed [3:0] p{n};\n wire signed [3:0] p{n};\n"))
|
||||
}
|
||||
_ => body.push_str(&format!(" inout wire p{n};\n")),
|
||||
}
|
||||
}
|
||||
let source = format!("{header});\n{body}endmodule\n");
|
||||
let out = convert(&source).expect("converted");
|
||||
assert!(out.contains(" input p0,"), "{out}");
|
||||
assert!(out.contains(" input [7:0] p1,"), "{out}");
|
||||
assert!(out.contains(" output reg p2,"), "{out}");
|
||||
assert!(out.contains(" output wire signed [3:0] p3,"), "{out}");
|
||||
assert!(out.contains(" inout wire p4,"), "{out}");
|
||||
assert!(out.contains(" inout wire p19\n);"), "{out}");
|
||||
assert!(!out.contains(" input p0;"), "the body declarations are gone: {out}");
|
||||
assert_eq!(out.matches("p19").count(), 1, "{out}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// idempotency
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn converting_a_converted_header_refuses_because_it_is_already_ansi() {
|
||||
let source = "module m (a, b);\n input a;\n output [7:0] b;\nendmodule\n";
|
||||
let once = convert(source).expect("converted");
|
||||
let again = convert(&once).expect_err("nothing left to convert");
|
||||
assert!(again.contains("already declares its ports ANSI-style"), "{again}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_position_in_no_module_is_refused() {
|
||||
let source = "// nothing here\nmodule m (a);\n input a;\nendmodule\n";
|
||||
let said = convert_to_ansi(&files(source), Path::new(TOP), 2).expect_err("no module");
|
||||
assert_eq!(said, "there is no module declaration at this position.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_outside_the_scope_is_refused() {
|
||||
let source = "module m (a);\n input a;\nendmodule\n";
|
||||
let said = convert_to_ansi(&files(source), Path::new("/elsewhere.sv"), 8)
|
||||
.expect_err("outside the scope");
|
||||
assert!(said.contains("is not one of the files lucisv indexes"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ansi_header_is_refused() {
|
||||
let said = refused("module m (input a);\nendmodule\n");
|
||||
assert!(said.contains("already declares its ports ANSI-style"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_with_no_ports_is_refused() {
|
||||
assert!(refused("module m ();\nendmodule\n").contains("declares no ports"));
|
||||
assert!(refused("module m;\nendmodule\n").contains("declares no ports"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_is_out_of_scope_this_round() {
|
||||
let source = "interface it (a);\n input a;\nendinterface\n";
|
||||
let at = source.find("it (").expect("name") as u32;
|
||||
let said = convert_to_ansi(&files(source), Path::new(TOP), at).expect_err("an interface");
|
||||
assert!(said.contains("is an `interface`, not a module"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_expression_is_refused() {
|
||||
let concat = "module m ({x, y}, b);\n input x, y;\n input b;\nendmodule\n";
|
||||
assert!(refused(concat).contains("writes a port expression"), "{}", refused(concat));
|
||||
let named = "module m (.a({x, y}), b);\n input x, y;\n input b;\nendmodule\n";
|
||||
assert!(refused(named).contains("writes a port expression"), "{}", refused(named));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_refused() {
|
||||
let source = "module m (a);\n input a;\n always @(posedge do begin end\nendmodule\n";
|
||||
assert!(refused(source).contains("does not parse"), "{}", refused(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_name_with_no_declaration_is_refused() {
|
||||
let source = "module m (a, c);\n input a;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("names `c`, but its body declares no direction for it"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_for_a_name_the_header_does_not_carry_is_refused() {
|
||||
let source = "module m (a);\n input a;\n output z;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(
|
||||
said.contains("declares a direction for `z`, which its header does not name"),
|
||||
"{said}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_declared_twice_is_refused() {
|
||||
let source = "module m (a);\n input a;\n input a;\nendmodule\n";
|
||||
assert!(refused(source).contains("declares a direction for `a` twice"), "{}", refused(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_declared_twice_is_refused() {
|
||||
let source = "module m (b);\n output b;\n reg b;\n reg b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("declares `b` twice outside its port declaration"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_port_declared_again_is_refused() {
|
||||
let source = "module m (b);\n output reg b;\n reg b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("IEEE 1800 §23.2.2.2 makes that an error"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_ranges_that_disagree_are_refused() {
|
||||
let source = "module m (b);\n output [7:0] b;\n reg [3:0] b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("packed range"), "{said}");
|
||||
assert!(said.contains("asks for identical ones"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpacked_dimensions_that_disagree_are_refused() {
|
||||
let source = "module m (mem);\n output [7:0] mem [0:3];\n reg [7:0] mem [0:7];\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("unpacked dimension"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_that_disagrees_is_refused() {
|
||||
let source = "module m (b);\n output signed [7:0] b;\n reg unsigned [7:0] b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("`signed`") && said.contains("`unsigned`"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_shared_with_a_local_is_refused() {
|
||||
let source = "module m (b);\n output [7:0] b;\n reg [7:0] b, scratch;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("split the declaration first"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_initialiser_is_refused() {
|
||||
let source = "module m (b);\n output b;\n reg b = 1'b0;\nendmodule\n";
|
||||
assert!(refused(source).contains("does not move an initialiser"), "{}", refused(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_on_an_absorbed_declaration_is_refused() {
|
||||
// `Item.span` covers the `(* ... *)`, so the deletion would take it with
|
||||
// the declaration and only the comments are carried; `(* keep *)` changes
|
||||
// what a synthesizer does, and where an attribute belongs in an ANSI port
|
||||
// list is a design question rather than a merge rule.
|
||||
let source = "module m (a);\n (* keep *) input a;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("`(* keep *)` on `m`'s declaration of `a` would be dropped"), "{said}");
|
||||
assert!(said.contains("move the attribute onto the port by hand"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_on_the_completing_declaration_is_refused_too() {
|
||||
// The other half of the merge is absorbed by the same deletion.
|
||||
let source = "module m (b);\n output b;\n (* mark_debug = \"true\" *) reg b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("would be dropped"), "{said}");
|
||||
assert!(said.contains("mark_debug"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_inside_a_generate_region_is_refused() {
|
||||
let source = "module m (b);\n output b;\n generate\n reg b;\n endgenerate\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("inside a generate region"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compiler_directives_in_the_port_list_are_refused() {
|
||||
let source = "module m (\n a,\n`ifdef WIDE\n b,\n`endif\n c\n);\n input a;\n input b;\n input c;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("port list carries compiler directives"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_inside_a_conditional_arm_is_refused() {
|
||||
let source = "module m (a, b);\n input a;\n`ifdef WIDE\n input b;\n`endif\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("conditionally compiled"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_between_the_declarations_is_refused() {
|
||||
let source = "module m (a, b);\n input a;\n`include \"more.svh\"\n input b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("is written among the declarations"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_written_inside_a_declaration_is_refused() {
|
||||
let source = "module m (a);\n input /* which */ a;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("inside a declaration the conversion would delete"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_comment_that_has_nowhere_to_go_is_refused() {
|
||||
let source = "module m (a, b);\n input a; // the clock\n output b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("break `m`'s port list across lines first"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_in_the_workspace_is_refused() {
|
||||
let source = "module m (a);\n input a;\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from(TOP), source.to_string()),
|
||||
(PathBuf::from("/rtl/other.sv"), source.to_string()),
|
||||
];
|
||||
let said = convert_to_ansi(&files, Path::new(TOP), 8).expect_err("declared twice");
|
||||
assert!(said.contains("is declared in more than one indexed file"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_that_names_a_port_twice_is_refused() {
|
||||
let source = "module m (a, a);\n input a;\nendmodule\n";
|
||||
assert!(refused(source).contains("names `a` twice"), "{}", refused(source));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the code action
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_action_is_offered_anywhere_in_a_non_ansi_header() {
|
||||
let source = "module m (\n a,\n b\n);\n input a;\n output [7:0] b;\nendmodule\n";
|
||||
let files = files(source);
|
||||
for needle in ["module m", "m (", "a,", "b\n)"] {
|
||||
let at = source.find(needle).expect(needle) as u32;
|
||||
let titles: Vec<String> =
|
||||
port_actions(&files, Path::new(TOP), at).into_iter().map(|a| a.title).collect();
|
||||
assert!(
|
||||
titles.iter().any(|t| t == "lucisv: convert ports to ANSI (2 ports)"),
|
||||
"at {needle:?}: {titles:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_action_is_not_offered_in_the_body_or_in_an_ansi_module() {
|
||||
let source = "module m (\n a\n);\n input a;\n wire w;\n assign w = a;\nendmodule\n";
|
||||
let at = source.find("assign").expect("body") as u32;
|
||||
assert!(port_actions(&files(source), Path::new(TOP), at).is_empty());
|
||||
|
||||
let ansi = "module m (input a);\n wire w;\n assign w = a;\nendmodule\n";
|
||||
let at = ansi.find("module m").expect("header") as u32;
|
||||
let titles: Vec<String> =
|
||||
port_actions(&files(ansi), Path::new(TOP), at).into_iter().map(|a| a.title).collect();
|
||||
assert!(!titles.iter().any(|t| t.contains("convert ports to ANSI")), "{titles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_action_says_one_port_in_the_singular() {
|
||||
let source = "module m (a);\n input a;\nendmodule\n";
|
||||
let at = source.find("module m").expect("header") as u32;
|
||||
let titles: Vec<String> =
|
||||
port_actions(&files(source), Path::new(TOP), at).into_iter().map(|a| a.title).collect();
|
||||
assert!(titles.contains(&"lucisv: convert ports to ANSI (1 port)".to_string()), "{titles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_on_a_declaration_of_two_ports_is_written_once() {
|
||||
// The declaration is absorbed by both ports; its comment belongs to the
|
||||
// first of them and must not be copied onto the second.
|
||||
let source = "module m (\n a,\n b\n);\n input a, b; // both of them\nendmodule\n";
|
||||
let out = convert(source).expect("converted");
|
||||
assert_eq!(out.matches("// both of them").count(), 1, "{out}");
|
||||
assert_eq!(out, "module m (\n input a, // both of them\n input b\n);\nendmodule\n");
|
||||
}
|
||||
@@ -10,9 +10,10 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, ListElem, PortList};
|
||||
use vlog_refactor::{
|
||||
add_port, instantiation_plan, module_definition, port_actions, prepare_rename, rename, Layout,
|
||||
ModuleRef,
|
||||
add_port, convert_to_ansi, expand_wildcard, extract_module, instantiation_plan,
|
||||
module_definition, port_actions, prepare_rename, rename, Home, Layout, ModuleRef,
|
||||
};
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
@@ -260,3 +261,690 @@ fn module_names_in(text: &str) -> Vec<String> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_expanded_in_the_corpus_is_something_the_formatter_accepts() {
|
||||
// The `.*` sites in the corpus are real ones — testbenches and formal
|
||||
// wrappers, where the wildcard is written most — and the property that
|
||||
// matters is the same one the whole formatter lives by: what the
|
||||
// refactoring writes must format, and formatting it twice must not move
|
||||
// it. The edit is applied to a *copy* of the text; nothing is written back
|
||||
// to `corpus/`.
|
||||
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 expanded: Vec<String> = Vec::new();
|
||||
let mut refused: Vec<String> = Vec::new();
|
||||
for (path, text) in &sources {
|
||||
if expanded.len() >= 3 {
|
||||
break;
|
||||
}
|
||||
let Some(offset) = wildcard_offset(text) else { continue };
|
||||
let started = Instant::now();
|
||||
match expand_wildcard(&sources, path, offset) {
|
||||
Err(said) => refused.push(format!("{}: {said}", path.display())),
|
||||
Ok(edit) => {
|
||||
let edits = edit.edits_for(path);
|
||||
assert!(!edits.is_empty(), "{} was expanded with no edit", path.display());
|
||||
let mut copy = text.clone();
|
||||
for change in edits.iter().rev() {
|
||||
copy.replace_range(
|
||||
change.range.start as usize..change.range.end as usize,
|
||||
&change.new_text,
|
||||
);
|
||||
}
|
||||
assert_ne!(©, text, "the expansion changed nothing in {}", path.display());
|
||||
let once = vlog_formatter::format_source(©, &config).unwrap_or_else(|e| {
|
||||
panic!("the formatter refuses the expansion of {}: {e}\n{copy}", path.display())
|
||||
});
|
||||
let twice =
|
||||
vlog_formatter::format_source(&once, &config).expect("formats a second time");
|
||||
assert_eq!(once, twice, "formatting {}'s expansion diverges", path.display());
|
||||
expanded.push(format!(
|
||||
"{} in {:.2}s ({} edits)",
|
||||
path.display(),
|
||||
started.elapsed().as_secs_f64(),
|
||||
edits.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("corpus `.*` expansions:\n {}", expanded.join("\n "));
|
||||
if !refused.is_empty() {
|
||||
println!("refused:\n {}", refused.join("\n "));
|
||||
}
|
||||
assert!(expanded.len() >= 3, "three real expansions, got {expanded:?}; refused: {refused:?}");
|
||||
}
|
||||
|
||||
/// The offset of the first `.*` connection a file writes, found the way the
|
||||
/// plan's census counts them: a `.*` followed by a `,` or a `)`.
|
||||
fn wildcard_offset(text: &str) -> Option<u32> {
|
||||
let mut at = 0usize;
|
||||
while let Some(found) = text.get(at..)?.find(".*") {
|
||||
let start = at + found;
|
||||
let rest = text.get(start + 2..)?.trim_start();
|
||||
if rest.starts_with(',') || rest.starts_with(')') {
|
||||
return Some(start as u32);
|
||||
}
|
||||
at = start + 2;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// TODO §51 — the non-ANSI → ANSI conversion
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The census the plan asks for: how many modules in the corpus write a
|
||||
/// Verilog-2001 header, and does every one of them convert?
|
||||
///
|
||||
/// **The count is zero, and that is the finding.** common_cells, ibex,
|
||||
/// opentitan and picorv32 are all written ANSI-style — even picorv32, the
|
||||
/// oldest of them — so there is no non-ANSI header in 860 files to convert.
|
||||
/// The assertion is therefore written as a census rather than as a number: it
|
||||
/// converts *every* one it finds, and stays honest the day the corpus gains
|
||||
/// one. The real-RTL exercise the conversion does get is
|
||||
/// `an_ansi_header_written_the_2001_way_converts_back_to_itself` below, which
|
||||
/// makes its material out of the corpus's own ANSI modules.
|
||||
#[test]
|
||||
fn every_non_ansi_module_in_the_corpus_converts() {
|
||||
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 sites: Vec<(PathBuf, String, u32)> = sources
|
||||
.iter()
|
||||
.flat_map(|(path, text)| {
|
||||
non_ansi_modules(text).into_iter().map(move |(name, at)| (path.clone(), name, at))
|
||||
})
|
||||
.collect();
|
||||
println!("corpus non-ANSI module headers: {}", sites.len());
|
||||
|
||||
let mut refused: Vec<String> = Vec::new();
|
||||
for (path, name, at) in &sites {
|
||||
let Some((_, text)) = sources.iter().find(|(held, _)| held == path) else { continue };
|
||||
match convert_to_ansi(&sources, path, *at) {
|
||||
Err(said) => refused.push(format!("{} :: {name}: {said}", path.display())),
|
||||
Ok(edit) => {
|
||||
let copy = edited(text, edit.edits_for(path));
|
||||
let once = vlog_formatter::format_source(©, &config).unwrap_or_else(|e| {
|
||||
panic!("the formatter refuses {} :: {name}: {e}\n{copy}", path.display())
|
||||
});
|
||||
let twice =
|
||||
vlog_formatter::format_source(&once, &config).expect("formats a second time");
|
||||
assert_eq!(once, twice, "{} :: {name} does not converge", path.display());
|
||||
assert_eq!(
|
||||
port_names(©, name),
|
||||
port_names(text, name),
|
||||
"{} :: {name} changed its port list",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("refused: {}\n {}", refused.len(), refused.join("\n "));
|
||||
}
|
||||
|
||||
/// Real RTL, made non-ANSI and converted back.
|
||||
///
|
||||
/// The corpus writes no Verilog-2001 header, so this test manufactures them out
|
||||
/// of real ones: a corpus module's ANSI port list is rewritten the 2001 way —
|
||||
/// bare names in the header, each declaration moved into the body verbatim —
|
||||
/// and `convert_to_ansi` is asked to undo it. Three properties, on real port
|
||||
/// lists of up to a few dozen ports:
|
||||
///
|
||||
/// * the converted file **parses with no diagnostic** and formats, and
|
||||
/// formatting it twice does not move it;
|
||||
/// * its module declares the **same ports, in the same order, with the same
|
||||
/// direction, net, type, signing and dimensions** as the module the corpus
|
||||
/// ships — [`signature`], which is the whole of what the conversion promises;
|
||||
/// * and the file's comment count is unchanged.
|
||||
///
|
||||
/// Not byte-identity after formatting: the formatter keeps the *author's*
|
||||
/// column alignment in an ANSI port list, and a refactoring writes edited
|
||||
/// source rather than formatted source, so the alignment the corpus wrote by
|
||||
/// hand is not something the conversion undertakes to reproduce.
|
||||
///
|
||||
/// Nothing is written back to `corpus/`; every edit is applied to a copy.
|
||||
#[test]
|
||||
fn an_ansi_header_written_the_2001_way_converts_back_to_itself() {
|
||||
let Some(files) = corpus() else { return };
|
||||
let sources = read(&files);
|
||||
let config = vlog_formatter::Config::default();
|
||||
|
||||
let mut done: Vec<String> = Vec::new();
|
||||
for (path, text) in &sources {
|
||||
if done.len() >= 5 {
|
||||
break;
|
||||
}
|
||||
let Some((name, legacy)) = as_non_ansi(text) else { continue };
|
||||
let mut scratch = sources.clone();
|
||||
let Some(slot) = scratch.iter_mut().find(|(held, _)| held == path) else { continue };
|
||||
slot.1 = legacy.clone();
|
||||
let at = legacy.find(&format!("module {name}")).expect("the header") as u32;
|
||||
|
||||
let started = Instant::now();
|
||||
let edit = match convert_to_ansi(&scratch, path, at) {
|
||||
Ok(edit) => edit,
|
||||
Err(said) => {
|
||||
println!("skipped {} :: {name}: {said}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let back = edited(&legacy, edit.edits_for(path));
|
||||
assert!(
|
||||
vlog_parser::parse_source_tolerant(&back).1.is_empty(),
|
||||
"{} :: {name} does not parse after the conversion\n{back}",
|
||||
path.display()
|
||||
);
|
||||
assert_eq!(
|
||||
signature(&back, &name),
|
||||
signature(text, &name),
|
||||
"{} :: {name} did not come back to what the corpus ships",
|
||||
path.display()
|
||||
);
|
||||
assert_eq!(
|
||||
back.matches("//").count() + back.matches("/*").count(),
|
||||
text.matches("//").count() + text.matches("/*").count(),
|
||||
"{} :: {name} lost or gained a comment",
|
||||
path.display()
|
||||
);
|
||||
let once = vlog_formatter::format_source(&back, &config).expect("the conversion formats");
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats a second time");
|
||||
assert_eq!(once, twice, "{} :: {name} does not converge", path.display());
|
||||
done.push(format!(
|
||||
"{} :: {name} in {:.2}s",
|
||||
path.display(),
|
||||
started.elapsed().as_secs_f64()
|
||||
));
|
||||
}
|
||||
println!("round-tripped:\n {}", done.join("\n "));
|
||||
assert!(done.len() >= 5, "five real round trips, got {done:?}");
|
||||
}
|
||||
|
||||
/// Every module in a file whose header is a `PortList::NonAnsi`, with the
|
||||
/// offset of its name.
|
||||
fn non_ansi_modules(text: &str) -> Vec<(String, u32)> {
|
||||
fn walk(items: &[Item], out: &mut Vec<(String, u32)>) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Module(module) => {
|
||||
if matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
out.push((module.name.clone(), module.name_span.start));
|
||||
}
|
||||
walk(&module.items, out);
|
||||
}
|
||||
ItemKind::Package { items, .. } => walk(items, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(&vlog_parser::parse_source_tolerant(text).0.items, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// What a module's ANSI port list says, port by port: direction, net type,
|
||||
/// data type, signing, packed and unpacked dimensions, and the name.
|
||||
///
|
||||
/// The whole of what the conversion promises, and the one thing a
|
||||
/// non-ANSI header and the ANSI header it becomes must agree about.
|
||||
/// Whitespace is taken out, since a `[7 : 0]` and a `[7:0]` are one range.
|
||||
fn signature(text: &str, module: &str) -> Vec<String> {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
fn walk<'t>(items: &'t [Item], module: &str) -> Option<&'t vlog_parser::ast::Module> {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Module(found) if found.name == module => return Some(found),
|
||||
ItemKind::Module(found) => {
|
||||
if let Some(found) = walk(&found.items, module) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
ItemKind::Package { items, .. } => {
|
||||
if let Some(found) = walk(items, module) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
let tight = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
|
||||
let dims = |list: &[vlog_parser::ast::Dim]| -> String {
|
||||
list.iter()
|
||||
.map(|d| tight(text.get(d.span.start as usize..d.span.end as usize).unwrap_or("")))
|
||||
.collect()
|
||||
};
|
||||
let Some(module) = walk(&tree.items, module) else { return Vec::new() };
|
||||
let PortList::Ansi(ports) = &module.ports else { return Vec::new() };
|
||||
ports
|
||||
.iter()
|
||||
.filter_map(ListElem::ok)
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{}|{}|{}|{}|{}|{}|{}",
|
||||
p.dir.clone().unwrap_or_default(),
|
||||
p.net.clone().unwrap_or_default(),
|
||||
p.ty.name,
|
||||
p.ty.signing.clone().unwrap_or_default(),
|
||||
dims(&p.ty.packed),
|
||||
dims(&p.unpacked),
|
||||
p.name
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The port names a module declares, in order.
|
||||
fn port_names(text: &str, module: &str) -> Vec<String> {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
fn walk(items: &[Item], module: &str) -> Option<Vec<String>> {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Module(found) if found.name == module => {
|
||||
return Some(match &found.ports {
|
||||
PortList::Ansi(ports) => {
|
||||
ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect()
|
||||
}
|
||||
PortList::NonAnsi(ports) => {
|
||||
ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect()
|
||||
}
|
||||
PortList::Empty | PortList::None => Vec::new(),
|
||||
})
|
||||
}
|
||||
ItemKind::Module(found) => {
|
||||
if let Some(names) = walk(&found.items, module) {
|
||||
return Some(names);
|
||||
}
|
||||
}
|
||||
ItemKind::Package { items, .. } => {
|
||||
if let Some(names) = walk(items, module) {
|
||||
return Some(names);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
walk(&tree.items, module).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// One file's first ANSI module rewritten the Verilog-2001 way: the header
|
||||
/// keeps the names, each declaration moves into the body verbatim.
|
||||
///
|
||||
/// `None` for a file with no module the rewrite is faithful for — a port with
|
||||
/// a default value, a comment inside the list, an interface port or a
|
||||
/// direction-less continuation port all make the two spellings say different
|
||||
/// things, and this is a test fixture rather than a second refactoring.
|
||||
fn as_non_ansi(text: &str) -> Option<(String, String)> {
|
||||
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let ItemKind::Module(module) = &tree
|
||||
.items
|
||||
.iter()
|
||||
.find(|item| {
|
||||
matches!(&item.kind, ItemKind::Module(m)
|
||||
if m.kw == "module" && m.port_directives.is_empty())
|
||||
})?
|
||||
.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let PortList::Ansi(ports) = &module.ports else { return None };
|
||||
let ports: Vec<&vlog_parser::ast::AnsiPort> =
|
||||
ports.iter().map(ListElem::ok).collect::<Option<Vec<_>>>()?;
|
||||
let (first, last) = (ports.first()?, ports.last()?);
|
||||
let list = text.get(first.span.start as usize..last.span.end as usize)?;
|
||||
if list.contains("//") || list.contains("/*") {
|
||||
return None;
|
||||
}
|
||||
for port in &ports {
|
||||
let plain = port.dir.is_some()
|
||||
&& port.default.is_none()
|
||||
&& port.meta.leading.is_empty()
|
||||
&& port.meta.trailing.is_none()
|
||||
&& port.meta.before_sep.is_empty()
|
||||
&& port.after_dir.is_empty()
|
||||
&& port.before_name.is_empty()
|
||||
&& port.ty.extra.is_none()
|
||||
&& port.ty.virt.is_none();
|
||||
if !plain {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// The header's `;`, which is where the body declarations go.
|
||||
let semi = last.span.end as usize + text.get(last.span.end as usize..)?.find(';')? + 1;
|
||||
// Each element is replaced by its own name, so the list keeps the layout
|
||||
// the file wrote — the conversion is asked to put the declarations back,
|
||||
// not to reflow anything.
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for port in &ports {
|
||||
out.push_str(text.get(cursor..port.span.start as usize)?);
|
||||
out.push_str(&port.name);
|
||||
cursor = port.span.end as usize;
|
||||
}
|
||||
out.push_str(text.get(cursor..semi)?);
|
||||
for port in &ports {
|
||||
out.push_str("\n ");
|
||||
out.push_str(text.get(port.span.start as usize..port.span.end as usize)?);
|
||||
out.push(';');
|
||||
}
|
||||
out.push_str(text.get(semi..)?);
|
||||
Some((module.name.clone(), out))
|
||||
}
|
||||
|
||||
/// A copy of `text` with one file's edits applied.
|
||||
fn edited(text: &str, edits: &[vlog_refactor::TextEdit]) -> String {
|
||||
let mut copy = text.to_string();
|
||||
for change in edits.iter().rev() {
|
||||
copy.replace_range(
|
||||
change.range.start as usize..change.range.end as usize,
|
||||
&change.new_text,
|
||||
);
|
||||
}
|
||||
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::<usize>(),
|
||||
"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<u32> {
|
||||
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)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// extracting a module out of real RTL (TODO §53.1)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Where the extraction trial reads its design from. `corpus/` by default;
|
||||
/// `LUCISV_EXTRACT_ROOT` points it at a **copy** of another tree — which is how
|
||||
/// the opentitan trial is run without touching that checkout.
|
||||
fn extract_root() -> Option<Vec<PathBuf>> {
|
||||
let root = match std::env::var("LUCISV_EXTRACT_ROOT") {
|
||||
Ok(path) => PathBuf::from(path),
|
||||
Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"),
|
||||
};
|
||||
if !root.is_dir() {
|
||||
eprintln!("{} not checked out — skipping", root.display());
|
||||
return None;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
collect(&root, &mut files);
|
||||
files.sort();
|
||||
Some(files)
|
||||
}
|
||||
|
||||
/// The first `always` block or continuous assignment of each module, as a
|
||||
/// selection an extraction could be asked about.
|
||||
fn regions(text: &str) -> Vec<(String, u32, u32)> {
|
||||
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
||||
if !diagnostics.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for item in &tree.items {
|
||||
let ItemKind::Module(module) = &item.kind else { continue };
|
||||
let found = module.items.iter().find(|item| {
|
||||
matches!(item.kind, ItemKind::Always { .. } | ItemKind::ContAssign(_))
|
||||
&& item.meta.leading.is_empty()
|
||||
});
|
||||
if let Some(region) = found {
|
||||
out.push((module.name.clone(), region.span.start, region.span.end));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many of a design's names fail to resolve. The census the trial holds
|
||||
/// fixed: an extraction moves items and writes a header, so the number of
|
||||
/// names nothing binds may not grow.
|
||||
fn unresolved_over(sources: &[(PathBuf, String)]) -> usize {
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut out = 0usize;
|
||||
for (_, text) in sources {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let external = vlog_semantic::resolve_external(&semantics, &index);
|
||||
for (n, reference) in semantics.references().iter().enumerate() {
|
||||
if reference.resolved().is_some() {
|
||||
continue;
|
||||
}
|
||||
let id = vlog_semantic::ReferenceId(n as u32);
|
||||
if !matches!(external.get(id), Some(vlog_semantic::ExternalTarget::Resolved(_))) {
|
||||
out += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_regions_of_real_rtl_extract_into_modules_that_parse_format_and_converge() {
|
||||
let Some(files) = extract_root() else { return };
|
||||
let sources = read(&files);
|
||||
assert!(!sources.is_empty(), "the tree exists but holds no Verilog");
|
||||
let config = vlog_formatter::Config::default();
|
||||
let before = unresolved_over(&sources);
|
||||
|
||||
let started = Instant::now();
|
||||
let mut done: Vec<String> = Vec::new();
|
||||
let mut refusals = 0usize;
|
||||
'files: for (path, text) in &sources {
|
||||
for (module, start, end) in regions(text) {
|
||||
if done.len() == 5 {
|
||||
break 'files;
|
||||
}
|
||||
let name = format!("{module}_lucisv_extracted");
|
||||
let edit = match extract_module(&sources, path, start, end, &name, Home::NewFile) {
|
||||
Ok(edit) => edit,
|
||||
// Printed, not only counted: which regions the trial refuses
|
||||
// and why is the other half of a reproducible run (2026-09-06
|
||||
// rework — the opentitan numbers in the feature README are
|
||||
// this list).
|
||||
Err(said) => {
|
||||
refusals += 1;
|
||||
println!(" refused {} `{module}`: {said}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// The two halves, as the editor would write them.
|
||||
let mut after: Vec<(PathBuf, String)> = sources.clone();
|
||||
for created in &edit.created {
|
||||
after.push((created.clone(), String::new()));
|
||||
}
|
||||
for (file, edits) in &edit.edits {
|
||||
let Some(slot) = after.iter_mut().find(|(held, _)| held == file) else {
|
||||
panic!("{} edits {} which is not in scope", name, file.display())
|
||||
};
|
||||
let mut out = slot.1.clone();
|
||||
for one in edits.iter().rev() {
|
||||
out.replace_range(
|
||||
one.range.start as usize..one.range.end as usize,
|
||||
&one.new_text,
|
||||
);
|
||||
}
|
||||
slot.1 = out;
|
||||
}
|
||||
|
||||
// Both files parse, format, and formatting them again is a no-op.
|
||||
for (file, edits) in &edit.edits {
|
||||
let text = &after.iter().find(|(held, _)| held == file).expect("edited").1;
|
||||
let (_, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
||||
assert!(
|
||||
diagnostics.is_empty(),
|
||||
"{name}: {} no longer parses: {diagnostics:?}\n{text}",
|
||||
file.display()
|
||||
);
|
||||
let once = vlog_formatter::format_source(text, &config).unwrap_or_else(|e| {
|
||||
panic!("{name}: the formatter refuses {}: {e}", file.display())
|
||||
});
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
||||
assert_eq!(once, twice, "{name}: {} does not converge", file.display());
|
||||
let _ = edits;
|
||||
}
|
||||
|
||||
// The census over the whole design, the two files together.
|
||||
let now = unresolved_over(&after);
|
||||
assert!(now <= before, "{name}: {} names went unresolved, up from {before}", now);
|
||||
// Printed, not only asserted: the trial's numbers are what the
|
||||
// feature README records, and a census that merely *held* is the
|
||||
// evidence the extraction was honest (2026-09-06 rework).
|
||||
println!(" {name} in {}: census {before} -> {now}", path.display());
|
||||
done.push(name);
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"extract over {} files: {} regions extracted, {} refused, in {:.2}s",
|
||||
sources.len(),
|
||||
done.len(),
|
||||
refusals,
|
||||
started.elapsed().as_secs_f64()
|
||||
);
|
||||
assert_eq!(done.len(), 5, "five real regions must extract: {done:?}");
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
//! Behavior tests for `expand_wildcard`: what the `.*` expansion writes, what
|
||||
//! it refuses, and what the formatter says about the result.
|
||||
//!
|
||||
//! 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::{expand_wildcard, port_actions, 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
|
||||
}
|
||||
|
||||
/// The three-port module every test instantiates.
|
||||
const SUB: &str =
|
||||
"module sub (\n input logic clk,\n input logic rst,\n output logic done\n);\nendmodule\n";
|
||||
|
||||
/// The workspace, the expansion, and the cursor's file afterwards.
|
||||
fn expand(top: &str, needle: &str) -> Result<(RefactorEdit, String), String> {
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let edit = expand_wildcard(&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 {
|
||||
expand(top, needle).expect_err("a refusal").to_string()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what it writes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_wildcard_becomes_every_port_the_instance_does_not_name() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .*\n );\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .rst(rst),\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
assert_eq!(edit.file_count(), 1, "nothing outside the cursor's file is touched");
|
||||
assert!(edit.warnings.is_empty(), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_list_stays_inline() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .done(done));\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_alone_on_its_line_writes_one_connection_per_line() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .*\n );\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .rst(rst),\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_alone_inline_writes_one_line() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .done(done));\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_with_no_signal_in_scope_is_written_unconnected_and_said_out_loud() {
|
||||
let top = "module top;\n logic clk, rst;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .rst(rst), .done());\nendmodule\n"
|
||||
);
|
||||
let warning = edit.warnings.join("\n");
|
||||
assert!(warning.contains("`done`"), "{warning}");
|
||||
assert!(warning.contains("no net, variable or port named"), "{warning}");
|
||||
assert!(warning.contains("top.sv:3"), "the site is named: {warning}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_named_parameter_is_not_a_signal_the_wildcard_binds() {
|
||||
// IEEE 1800 §23.3.2.4: `.*` binds a port to a net or variable of the same
|
||||
// name. `done` here is a constant, and `.done(done)` would connect an
|
||||
// output port to it — legal-looking, silent, and wrong.
|
||||
let top = "module top;\n logic clk, rst;\n localparam int done = 1;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains(".done()"), "{text}");
|
||||
assert!(!text.contains(".done(done)"), "the parameter is not bound: {text}");
|
||||
assert!(edit.warnings.join("\n").contains("`done`"), "{:?}", edit.warnings);
|
||||
|
||||
// ...and the same for a `parameter` in the header.
|
||||
let top = "module top #(parameter int done = 1) ();\n logic clk, rst;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains(".done()"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_genvar_of_the_same_name_is_not_bound_either() {
|
||||
let sub = "module sub (\n input logic clk,\n input logic i\n);\nendmodule\n";
|
||||
let top = "module top;\n logic clk;\n for (genvar i = 0; i < 2; i++) begin : g\n sub u_sub (.*);\n end\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", sub), ("/rtl/top.sv", top)]);
|
||||
let edit =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*")).expect("expands");
|
||||
let text = applied(&workspace, &edit, "/rtl/top.sv");
|
||||
assert!(text.contains(".clk(clk), .i()"), "a genvar is not a net or a variable: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_blocks_own_declaration_is_in_scope_and_so_is_the_modules() {
|
||||
let top = "module top;\n logic clk, rst;\n if (1) begin : g\n logic done;\n sub u_sub (.*);\n end\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert!(
|
||||
text.contains("sub u_sub (.clk(clk), .rst(rst), .done(done));"),
|
||||
"the block's `done` and the module's `clk`/`rst`: {text}"
|
||||
);
|
||||
assert!(edit.warnings.is_empty(), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ports_are_written_in_the_modules_declaration_order() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.done(done), .*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains(".done(done), .clk(clk), .rst(rst)"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_written_before_an_explicit_connection_expands_in_place() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*, .done(done));\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains("(.clk(clk), .rst(rst), .done(done))"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_implicit_or_empty_connection_counts_as_explicit() {
|
||||
// `.clk` and `.rst()` are connections the source wrote, so `.*` never
|
||||
// bound those ports and the expansion must not write them a second time.
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk, .rst(), .*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk, .rst(), .done(done));\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// comments
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_comment_after_the_wildcard_stays_with_the_first_connection() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .* // and the rest\n );\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .rst(rst), // and the rest\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_comment_before_the_wildcard_stays_before_the_first_connection() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n // bind the rest\n .*\n );\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n // bind the rest\n .rst(rst),\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_comment_written_inside_the_wildcard_refuses_rather_than_dropping_it() {
|
||||
// The comment sits between the `.` and the `*`, inside the element the
|
||||
// expansion replaces. Comments are never dropped (invariant 3), and lucisv
|
||||
// will not decide where this one should move.
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (. /* here */ *);\nendmodule\n";
|
||||
let said = refusal(top, ". /* here */ *");
|
||||
assert!(said.contains("comments are never dropped"), "{said}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_without_a_wildcard_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk));\nendmodule\n";
|
||||
assert!(refusal(top, "u_sub").contains("writes no `.*` to expand"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_that_is_not_an_instantiation_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*);\nendmodule\n";
|
||||
assert!(refusal(top, "logic clk").contains("no module instantiation at this position"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positional_connection_list_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (clk, rst, done);\nendmodule\n";
|
||||
let said = refusal(top, "u_sub");
|
||||
assert!(said.contains("by position"), "{said}");
|
||||
assert!(said.contains("no `.*` to expand"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_wildcards_in_one_instance_are_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*, .*);\nendmodule\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("writes `.*` 2 times"), "{said}");
|
||||
assert!(said.contains("illegal"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_inside_a_bind_directive_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\nendmodule\nbind top sub u_sub (.*);\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("`bind` directive"), "{said}");
|
||||
assert!(said.contains("target's scope"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_workspace_does_not_declare_is_refused() {
|
||||
let top = "module top;\n logic clk;\n nowhere u_x (.*);\nendmodule\n";
|
||||
assert!(refusal(top, ".*").contains("indexes no module named `nowhere`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_refused() {
|
||||
let workspace = files(&[
|
||||
("/rtl/sub.sv", SUB),
|
||||
("/rtl/other.sv", SUB),
|
||||
("/rtl/top.sv", "module top;\n logic clk, rst, done;\n sub u_sub (.*);\nendmodule\n"),
|
||||
]);
|
||||
let top = &workspace[2].1.clone();
|
||||
let said = expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"))
|
||||
.expect_err("a refusal");
|
||||
assert!(said.contains("declared in more than one indexed file"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_refused_on_either_side() {
|
||||
// The cursor's own file.
|
||||
let top = "module top;\n logic clk;\n sub u_sub (.*);\n always @(begin\nendmodule\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("does not parse"), "{said}");
|
||||
assert!(said.contains("top.sv"), "{said}");
|
||||
|
||||
// ...and the module's.
|
||||
let workspace = files(&[
|
||||
("/rtl/sub.sv", "module sub (input logic clk);\n always @(begin\nendmodule\n"),
|
||||
("/rtl/top.sv", "module top;\n logic clk;\n sub u_sub (.*);\nendmodule\n"),
|
||||
]);
|
||||
let top = workspace[1].1.clone();
|
||||
let said = expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(&top, ".*"))
|
||||
.expect_err("a refusal");
|
||||
assert!(said.contains("sub.sv"), "{said}");
|
||||
assert!(said.contains("does not parse"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_list_carrying_compiler_directives_is_refused() {
|
||||
let workspace = files(&[
|
||||
(
|
||||
"/rtl/sub.sv",
|
||||
"module sub (\n input logic clk\n`ifdef HAS_RST\n , input logic rst\n`endif\n);\nendmodule\n",
|
||||
),
|
||||
("/rtl/top.sv", "module top;\n logic clk, rst;\n sub u_sub (.*);\nendmodule\n"),
|
||||
]);
|
||||
let top = workspace[1].1.clone();
|
||||
let said = expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(&top, ".*"))
|
||||
.expect_err("a refusal");
|
||||
assert!(said.contains("carries compiler directives"), "{said}");
|
||||
assert!(said.contains("depends on the configuration"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_list_carrying_compiler_directives_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n`ifdef X\n .rst(rst),\n`endif\n .*\n );\nendmodule\n";
|
||||
let said = refusal(top, ".*\n )");
|
||||
assert!(said.contains("connection list carries compiler directives"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_that_binds_nothing_is_refused_rather_than_deleted() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .done(done), .*);\nendmodule\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("already connects every port"), "{said}");
|
||||
assert!(said.contains("binds nothing"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_declaring_several_instances_asks_for_a_cursor_on_one() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_a (.*), u_b (.*);\nendmodule\n";
|
||||
let said = refusal(top, "sub u_a");
|
||||
assert!(said.contains("declares 2 instances"), "{said}");
|
||||
assert!(said.contains("put the cursor on the one to expand"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_outside_the_workspace_is_refused() {
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB)]);
|
||||
let said =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/elsewhere.sv"), 0).expect_err("a refusal");
|
||||
assert!(said.contains("is not one of the files lucisv indexes"), "{said}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the code action, and what the formatter says
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_action_is_offered_at_the_wildcard_with_its_count_in_the_title() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let actions = port_actions(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"));
|
||||
let titles: Vec<&str> = actions.iter().map(|a| a.title.as_str()).collect();
|
||||
assert!(titles.contains(&"lucisv: expand .* (2 connections)"), "{titles:?}");
|
||||
// The wildcard is why `propagate` declines here, so it is the only offer.
|
||||
assert_eq!(titles.len(), 1, "{titles:?}");
|
||||
|
||||
// One connection is one connection, not "1 connections".
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let actions = port_actions(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"));
|
||||
assert_eq!(actions[0].title, "lucisv: expand .* (1 connection)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_offered_where_the_expansion_would_be_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*, .*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let actions = port_actions(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"));
|
||||
assert!(actions.is_empty(), "{:?}", actions.iter().map(|a| &a.title).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expanded_file_formats_and_formatting_it_again_changes_nothing() {
|
||||
let config = vlog_formatter::Config::default();
|
||||
for top in [
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .*);\nendmodule\n",
|
||||
"module top;\n logic clk, rst;\n sub u_sub (\n .clk(clk),\n .* // the rest\n );\nendmodule\n",
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .*\n );\nendmodule\n",
|
||||
] {
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
let once = vlog_formatter::format_source(&text, &config)
|
||||
.unwrap_or_else(|e| panic!("the formatter refuses the expansion: {e}\n{text}"));
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
||||
assert_eq!(once, twice, "formatting the expansion does not converge");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_port_name_is_terminated_on_both_sides_of_the_parens() {
|
||||
// An escaped identifier runs to the next whitespace and to nothing else
|
||||
// (IEEE 1800 §5.6.1), so `.\my-port(\my-port)` is one token that swallows
|
||||
// the parens and the rest of the line. The instantiation skeleton learned
|
||||
// this from QA; the expansion writes the same shape.
|
||||
let sub = "module sub (\n input logic \\my-port ,\n input logic clk\n);\nendmodule\n";
|
||||
let top = "module top;\n logic clk;\n logic \\my-port ;\n sub u_sub (.*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", sub), ("/rtl/top.sv", top)]);
|
||||
let edit =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*")).expect("expands");
|
||||
let text = applied(&workspace, &edit, "/rtl/top.sv");
|
||||
assert!(text.contains("(.\\my-port (\\my-port ), .clk(clk))"), "{text}");
|
||||
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&text);
|
||||
assert!(diagnostics.is_empty(), "{diagnostics:?}\n{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unbound_escaped_port_is_terminated_too() {
|
||||
let sub = "module sub (\n input logic \\my-port ,\n input logic clk\n);\nendmodule\n";
|
||||
let top = "module top;\n logic clk;\n sub u_sub (.*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", sub), ("/rtl/top.sv", top)]);
|
||||
let edit =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*")).expect("expands");
|
||||
let text = applied(&workspace, &edit, "/rtl/top.sv");
|
||||
assert!(text.contains("(.\\my-port (), .clk(clk))"), "{text}");
|
||||
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&text);
|
||||
assert!(diagnostics.is_empty(), "{diagnostics:?}\n{text}");
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
//! Extracting a selection of whole module items into a module of its own —
|
||||
//! TODO §53.1.
|
||||
//!
|
||||
//! Three groups. What the extraction *writes* (a combinational region, a
|
||||
//! sequential one, one carrying a parameter and an import, the two homes the
|
||||
//! new module can have); every **refusal**, one test per sentence; and the
|
||||
//! acceptance checks that say the result is real Verilog — it parses, the
|
||||
//! formatter accepts it, formatting it twice changes nothing, and the two
|
||||
//! files together name every signal the one file named.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{extract_module, extract_site, Home, RefactorEdit};
|
||||
|
||||
const M: &str = "/rtl/m.sv";
|
||||
|
||||
fn files(text: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![(PathBuf::from(M), text.to_string())]
|
||||
}
|
||||
|
||||
fn workspace(entries: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
entries.iter().map(|(p, t)| (PathBuf::from(*p), t.to_string())).collect()
|
||||
}
|
||||
|
||||
/// The byte range of `needle` in `text`.
|
||||
fn at(text: &str, needle: &str) -> (u32, u32) {
|
||||
let start = text.find(needle).expect("needle") as u32;
|
||||
(start, start + needle.len() as u32)
|
||||
}
|
||||
|
||||
/// One file's text after the edit. A file the extraction creates starts empty.
|
||||
fn applied(text: &str, edit: &RefactorEdit, path: &str) -> String {
|
||||
let created = edit.created.iter().any(|created| created == Path::new(path));
|
||||
let mut out = match created {
|
||||
true => String::new(),
|
||||
false => text.to_string(),
|
||||
};
|
||||
for one in edit.edits_for(Path::new(path)).iter().rev() {
|
||||
out.replace_range(one.range.start as usize..one.range.end as usize, &one.new_text);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Extract `needle` out of `text` into `name`, into a file of its own.
|
||||
fn extract(text: &str, needle: &str, name: &str) -> Result<RefactorEdit, String> {
|
||||
let (start, end) = at(text, needle);
|
||||
extract_module(&files(text), Path::new(M), start, end, name, Home::NewFile)
|
||||
}
|
||||
|
||||
/// The two halves of an extraction, as the editor would have them.
|
||||
fn halves(text: &str, needle: &str, name: &str) -> (String, String) {
|
||||
let edit = extract(text, needle, name).expect("extracts");
|
||||
let new = format!("/rtl/{name}.sv");
|
||||
(applied(text, &edit, M), applied(text, &edit, &new))
|
||||
}
|
||||
|
||||
/// Every result has to be Verilog the formatter accepts and leaves alone the
|
||||
/// second time — the acceptance bar every refactoring in this crate meets.
|
||||
fn accepted(label: &str, text: &str) {
|
||||
let config = vlog_formatter::Config::default();
|
||||
let once = vlog_formatter::format_source(text, &config)
|
||||
.unwrap_or_else(|e| panic!("the formatter refuses {label}: {e}\n{text}"));
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
||||
assert_eq!(once, twice, "formatting {label} does not converge");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what it writes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const COMB: &str = "\
|
||||
module m (
|
||||
input logic [7:0] a,
|
||||
input logic [7:0] b,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] s;
|
||||
assign s = a + b; // the sum
|
||||
assign q = s ^ 8'hFF;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_combinational_region_reads_two_names_and_drives_one() {
|
||||
let (old, new) = halves(COMB, "assign s = a + b; // the sum", "sum");
|
||||
assert_eq!(
|
||||
new,
|
||||
"\
|
||||
module sum (
|
||||
input logic [7:0] a,
|
||||
input logic [7:0] b,
|
||||
output logic [7:0] s
|
||||
);
|
||||
assign s = a + b; // the sum
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
assert!(old.contains("sum u_sum (\n .a(a),\n .b(b),\n .s(s)\n );"), "{old}");
|
||||
// The comment travelled: it is in the new file and gone from the old one.
|
||||
assert!(!old.contains("// the sum"), "{old}");
|
||||
accepted("the new module", &new);
|
||||
accepted("what is left", &old);
|
||||
}
|
||||
|
||||
const SEQ: &str = "\
|
||||
module m (
|
||||
input logic clk,
|
||||
input logic rst_n,
|
||||
input logic [7:0] d,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] r;
|
||||
always_ff @(posedge clk or negedge rst_n) begin
|
||||
if (!rst_n) r <= '0;
|
||||
else r <= d;
|
||||
end
|
||||
assign q = r;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_sequential_region_makes_the_clock_an_input_and_the_register_an_output() {
|
||||
let start = SEQ.find("always_ff").expect("always") as u32;
|
||||
let end = SEQ.find(" end\n").expect("end") as u32 + 5;
|
||||
let edit = extract_module(&files(SEQ), Path::new(M), start, end, "reg_stage", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(SEQ, &edit, "/rtl/reg_stage.sv");
|
||||
assert!(new.contains("input logic clk,"), "{new}");
|
||||
assert!(new.contains("input logic rst_n,"), "{new}");
|
||||
assert!(new.contains("input logic [7:0] d,"), "{new}");
|
||||
assert!(new.contains("output logic [7:0] r"), "{new}");
|
||||
accepted("the sequential module", &new);
|
||||
accepted("what is left", &applied(SEQ, &edit, M));
|
||||
}
|
||||
|
||||
const PARAM: &str = "\
|
||||
package w_pkg;
|
||||
typedef logic [7:0] word_t;
|
||||
endpackage
|
||||
|
||||
module m #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input word_t a,
|
||||
output word_t q
|
||||
);
|
||||
import w_pkg::*;
|
||||
localparam int MASK = W - 1;
|
||||
word_t t;
|
||||
assign t = a & word_t'(MASK);
|
||||
assign q = t;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_region_using_a_parameter_and_an_import_carries_both() {
|
||||
let (old, new) = halves(PARAM, "assign t = a & word_t'(MASK);", "masker");
|
||||
// The `localparam` the selection reads becomes a parameter of the new
|
||||
// module, and so does the parameter *its own default* names.
|
||||
assert!(new.contains("parameter int W = 8,"), "{new}");
|
||||
assert!(new.contains("parameter int MASK = W - 1"), "{new}");
|
||||
assert!(new.contains("import w_pkg::*;"), "{new}");
|
||||
assert!(new.contains("input word_t a,"), "{new}");
|
||||
assert!(new.contains("output word_t t"), "{new}");
|
||||
assert!(old.contains(".W(W),"), "{old}");
|
||||
assert!(old.contains(".MASK(MASK)"), "{old}");
|
||||
accepted("the parameterized module", &new);
|
||||
accepted("what is left", &old);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_a_ports_own_width_names_crosses_with_it() {
|
||||
// The corpus found this one: `binary_to_gray`'s `N` is read by no
|
||||
// statement the selection carries — only by the *type* of the port the
|
||||
// extraction is about to write — so a closure over the region's
|
||||
// references alone left the new module naming nothing.
|
||||
let text = "\
|
||||
module m #(
|
||||
parameter int N = -1
|
||||
) (
|
||||
input logic [N-1:0] a,
|
||||
output logic [N-1:0] q
|
||||
);
|
||||
assign q = a ^ (a >> 1);
|
||||
endmodule
|
||||
";
|
||||
let (old, new) = halves(text, "assign q = a ^ (a >> 1);", "gray");
|
||||
assert!(new.contains("parameter int N = -1"), "{new}");
|
||||
assert!(new.contains("input logic [N-1:0] a,"), "{new}");
|
||||
assert!(new.contains("output logic [N-1:0] q"), "{new}");
|
||||
assert!(old.contains(".N(N)"), "{old}");
|
||||
accepted("the new module", &new);
|
||||
accepted("what is left", &old);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_import_in_the_header_is_carried_across() {
|
||||
// The opentitan trial found this one: the binder records a wildcard
|
||||
// import in a reference's `paths` as `p::*` — the spelling the source
|
||||
// wrote — not as `p::<name>`, so a judgement matching on the latter
|
||||
// copied no import at all and the new file named a package's types with
|
||||
// nothing importing them.
|
||||
let pkg = "package p;\n typedef logic [1:0] w_t;\n parameter int W = 2;\nendpackage\n";
|
||||
let top = "\
|
||||
module m import p::*;
|
||||
(
|
||||
input logic [W-1:0] a,
|
||||
output w_t q
|
||||
);
|
||||
assign q = w_t'(a);
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/p.sv", pkg), (M, top)]);
|
||||
let (start, end) = at(top, "assign q = w_t'(a);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "caster", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(top, &edit, "/rtl/caster.sv");
|
||||
assert!(new.contains("import p::*;"), "{new}");
|
||||
assert!(new.contains("input logic [W-1:0] a,"), "{new}");
|
||||
assert!(new.contains("output w_t q"), "{new}");
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("`p::*`")), "{:?}", edit.warnings);
|
||||
accepted("the new module", &new);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_import_is_carried_across_only_when_the_name_it_supplies_is_needed() {
|
||||
let a = "package a_pkg;\n typedef logic [1:0] a_t;\nendpackage\n";
|
||||
let b = "package b_pkg;\n typedef logic [3:0] b_t;\nendpackage\n";
|
||||
let top = "\
|
||||
module m (
|
||||
input logic [1:0] i,
|
||||
output logic [1:0] o
|
||||
);
|
||||
import a_pkg::a_t;
|
||||
import b_pkg::b_t;
|
||||
assign o = a_t'(i);
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/a.sv", a), ("/rtl/b.sv", b), (M, top)]);
|
||||
let (start, end) = at(top, "assign o = a_t'(i);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "caster", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(top, &edit, "/rtl/caster.sv");
|
||||
assert!(new.contains("import a_pkg::a_t;"), "{new}");
|
||||
assert!(!new.contains("b_pkg"), "an import nothing moved needs is not copied: {new}");
|
||||
accepted("the new module", &new);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type_declared_in_the_module_that_a_crossing_ports_type_names_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic [7:0] i,
|
||||
output logic [7:0] o
|
||||
);
|
||||
typedef logic [7:0] local_t;
|
||||
local_t mid;
|
||||
assign mid = i;
|
||||
assign o = mid;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign mid = i;");
|
||||
assert!(message.contains("`local_t`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_create_files_gets_the_module_below_the_one_it_came_from() {
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, end, "sum", Home::SameFile)
|
||||
.expect("extracts");
|
||||
assert!(edit.created.is_empty(), "nothing is created");
|
||||
assert_eq!(edit.file_count(), 1, "one file is touched");
|
||||
let text = applied(COMB, &edit, M);
|
||||
assert!(text.contains("endmodule\n\nmodule sum ("), "{text}");
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("did not say it can create files")));
|
||||
accepted("the one-file result", &text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_module_is_named_in_the_warnings_with_the_file_it_went_to() {
|
||||
let edit = extract(COMB, "assign s = a + b; // the sum", "sum").expect("extracts");
|
||||
assert_eq!(edit.created, vec![PathBuf::from("/rtl/sum.sv")]);
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("`sum.sv`")), "{:?}", edit.warnings);
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("3 ports")), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_whose_module_the_index_knows_gives_its_outputs_the_right_direction() {
|
||||
let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n";
|
||||
let top = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
logic mid;
|
||||
sub u_sub (.i(i), .o(mid));
|
||||
assign o = mid;
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "sub u_sub (.i(i), .o(mid));");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "wrap", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(top, &edit, "/rtl/wrap.sv");
|
||||
assert!(new.contains("input logic i,"), "{new}");
|
||||
assert!(new.contains("output logic mid"), "{new}");
|
||||
accepted("the wrapper", &new);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The sentence an extraction of `needle` refuses with.
|
||||
fn refusal(text: &str, needle: &str) -> String {
|
||||
extract(text, needle, "n").expect_err("a refusal")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_an_item_is_refused() {
|
||||
let (start, _) = at(COMB, "assign s = a + b;");
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, start + 8, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("cuts an item in half"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_outside_every_module_is_refused() {
|
||||
let text = "package p;\n typedef int t;\nendpackage\n";
|
||||
let (start, end) = at(text, "typedef int t;");
|
||||
let edit = extract_module(&files(text), Path::new(M), start, end, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("not inside one module's body"));
|
||||
}
|
||||
|
||||
/// The same three items, written as each of the three declarations the parser
|
||||
/// gives one node to.
|
||||
const INTERFACE: &str =
|
||||
"interface bus_if;\n logic [7:0] a;\n logic [7:0] q;\n assign q = a;\nendinterface\n";
|
||||
const PROGRAM: &str = "program p;\n logic a;\n logic q;\n assign q = a;\nendprogram\n";
|
||||
const MODULE: &str = "module m;\n logic [7:0] a;\n logic [7:0] q;\n assign q = a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_selection_inside_an_interface_or_a_program_is_refused() {
|
||||
// `vlog_parser` writes a `module`, an `interface` and a `program` as one
|
||||
// `ItemKind::Module`, and only `Module::kw` says which — so the gate has
|
||||
// to ask. QA's finding V2: without it an `interface` body extracted into a
|
||||
// module instantiated inside what remained an `interface`, and four names
|
||||
// in opentitan's `aes_masking_reseed_if.sv` stopped resolving.
|
||||
let said = refusal(INTERFACE, "assign q = a;");
|
||||
assert!(said.contains("inside an `interface`"), "{said}");
|
||||
assert!(said.contains("signals are its surface"), "{said}");
|
||||
|
||||
let said = refusal(PROGRAM, "assign q = a;");
|
||||
assert!(said.contains("inside a `program`"), "{said}");
|
||||
assert!(said.contains("testbench code"), "{said}");
|
||||
|
||||
// The same three items written as a module still extract.
|
||||
assert!(extract(MODULE, "assign q = a;", "n").is_ok(), "a `module` is still extractable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_action_is_not_offered_inside_an_interface_or_a_program() {
|
||||
// The cheap gate reads the same `Region`, so the lightbulb never appears
|
||||
// where the engine would refuse.
|
||||
for text in [INTERFACE, PROGRAM] {
|
||||
let (start, end) = at(text, "assign q = a;");
|
||||
assert!(extract_site(text, start, end).is_none(), "not offered in: {text}");
|
||||
}
|
||||
let (start, end) = at(MODULE, "assign q = a;");
|
||||
assert!(extract_site(MODULE, start, end).is_some(), "and still offered in a module");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_a_parameter_a_genvar_and_a_bind_are_each_refused_by_name() {
|
||||
let non_ansi = "module m (a);\n input a;\n wire b;\n assign b = a;\nendmodule\n";
|
||||
assert!(refusal(non_ansi, "input a;").contains("a port declaration"));
|
||||
|
||||
let param = "module m;\n localparam int W = 8;\n wire [W-1:0] x;\nendmodule\n";
|
||||
assert!(refusal(param, "localparam int W = 8;").contains("a `localparam` declaration"));
|
||||
|
||||
let genvar = "module m;\n genvar g;\nendmodule\n";
|
||||
assert!(refusal(genvar, "genvar g;").contains("a `genvar` declaration"));
|
||||
|
||||
let bind = "module m;\n bind m sub u_s ();\nendmodule\n";
|
||||
assert!(refusal(bind, "bind m sub u_s ();").contains("a `bind` directive"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_call_and_a_compiler_directive_are_refused() {
|
||||
let macro_item = "module m;\n `ASSERT(a, b)\n wire w;\nendmodule\n";
|
||||
assert!(refusal(macro_item, "`ASSERT(a, b)").contains("macro invocation"));
|
||||
|
||||
let directive = "module m;\n`ifdef FOO\n`endif\n wire w;\nendmodule\n";
|
||||
assert!(refusal(directive, "`ifdef FOO").contains("compiler directive"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_initial_and_a_final_block_are_refused_as_testbench_code() {
|
||||
let initial = "module m;\n logic x;\n initial x = 1'b0;\nendmodule\n";
|
||||
assert!(refusal(initial, "initial x = 1'b0;").contains("`initial` block"));
|
||||
|
||||
let last = "module m;\n logic x;\n final $display(\"%d\", x);\nendmodule\n";
|
||||
assert!(refusal(last, "final $display(\"%d\", x);").contains("`final` block"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_inside_the_selection_and_used_outside_it_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
wire t;
|
||||
assign t = a;
|
||||
assign q = t;
|
||||
endmodule
|
||||
";
|
||||
// `t`'s declaration is in the selection; `assign q = t;` is not.
|
||||
let (start, _) = at(text, "wire t;");
|
||||
let (_, end) = at(text, "assign t = a;");
|
||||
let edit = extract_module(&files(text), Path::new(M), start, end, "n", Home::NewFile);
|
||||
let message = edit.expect_err("a refusal");
|
||||
assert!(
|
||||
message.contains("move the declaration of `t` out of the selection first"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_driven_on_both_sides_of_the_selection_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic a,
|
||||
input logic b,
|
||||
output logic q
|
||||
);
|
||||
always_comb q = a;
|
||||
always_comb q = b;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "always_comb q = a;");
|
||||
assert!(message.contains("`q` is driven on both sides of the selection."), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_or_function_the_selection_calls_from_outside_it_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] q
|
||||
);
|
||||
function automatic logic [7:0] twice(input logic [7:0] x);
|
||||
return x + x;
|
||||
endfunction
|
||||
assign q = twice(a);
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign q = twice(a);");
|
||||
assert!(message.contains("`twice`"), "{message}");
|
||||
assert!(message.contains("a function"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_passed_to_a_routine_inside_the_selection_refuses_rather_than_guesses() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic clk,
|
||||
output logic [7:0] q
|
||||
);
|
||||
always_ff @(posedge clk) begin
|
||||
$cast(q, 8'h01);
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "always_ff @(posedge clk) begin\n $cast(q, 8'h01);\n end");
|
||||
assert!(message.contains("passes `q` to a task or function"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_reference_out_of_the_selection_is_refused() {
|
||||
let sub = "module sub (\n input logic i\n);\n logic probe;\nendmodule\n";
|
||||
let top = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
sub u_sub (.i(i));
|
||||
assign o = u_sub.probe;
|
||||
endmodule
|
||||
";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "assign o = u_sub.probe;");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile);
|
||||
let message = edit.expect_err("a refusal");
|
||||
assert!(message.contains("through the design hierarchy"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crossing_name_with_an_unpacked_dimension_is_refused() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic [7:0] a,
|
||||
output logic [7:0] q
|
||||
);
|
||||
logic [7:0] mem [0:3];
|
||||
assign q = mem[0] ^ a;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign q = mem[0] ^ a;");
|
||||
assert!(message.contains("unpacked dimension"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_workspace_already_declares_is_refused() {
|
||||
let sub = "module taken;\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/lib/taken.sv", sub), (M, COMB)]);
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "taken", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("already declares `taken`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_refused() {
|
||||
let twin = "module m;\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/twin.sv", twin), (M, COMB)]);
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("declared in more than one indexed file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timescale_a_new_file_would_not_inherit_is_refused_and_the_same_file_is_not() {
|
||||
let text = format!("`timescale 1ns/1ps\n{COMB}");
|
||||
let (start, end) = at(&text, "assign s = a + b; // the sum");
|
||||
let sources = vec![(PathBuf::from(M), text.clone())];
|
||||
let refused = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
let message = refused.expect_err("a refusal");
|
||||
assert!(message.contains("`timescale"), "{message}");
|
||||
// The same directive is no obstacle when the module stays in the file.
|
||||
extract_module(&sources, Path::new(M), start, end, "sum", Home::SameFile)
|
||||
.expect("the same file inherits it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_nettype_is_refused_the_same_way() {
|
||||
let text = format!("`default_nettype none\n{COMB}");
|
||||
let (start, end) = at(&text, "assign s = a + b; // the sum");
|
||||
let sources = vec![(PathBuf::from(M), text.clone())];
|
||||
let refused = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
assert!(refused.expect_err("a refusal").contains("`default_nettype"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_not_an_identifier_is_refused_before_anything_else() {
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
for name in ["", "2fast", "\\odd-name", "with space"] {
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, end, name, Home::NewFile);
|
||||
assert!(
|
||||
edit.expect_err("a refusal").contains("not a plain SystemVerilog identifier"),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positional_instantiation_inside_the_selection_is_refused() {
|
||||
let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n";
|
||||
let top =
|
||||
"module m (\n input logic i,\n output logic o\n);\n sub u_sub (i, o);\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "sub u_sub (i, o);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("by position"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_instantiation_inside_the_selection_is_refused() {
|
||||
let sub = "module sub (\n input logic i,\n output logic o\n);\nendmodule\n";
|
||||
let top = "module m (\n input logic i,\n output logic o\n);\n sub u_sub (.*);\nendmodule\n";
|
||||
let sources = workspace(&[("/rtl/sub.sv", sub), (M, top)]);
|
||||
let (start, end) = at(top, "sub u_sub (.*);");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("`.*`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_of_a_module_the_index_does_not_know_is_refused() {
|
||||
let top = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
stranger u_s (.i(i), .o(o));
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(top, "stranger u_s (.i(i), .o(o));");
|
||||
assert!(message.contains("no single indexed declaration"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_outside_the_module_in_the_same_file_is_refused_for_a_new_file() {
|
||||
let text = "\
|
||||
typedef logic [7:0] byte_t;
|
||||
|
||||
module m (
|
||||
input byte_t a,
|
||||
output byte_t q
|
||||
);
|
||||
byte_t t;
|
||||
assign t = a;
|
||||
assign q = t;
|
||||
endmodule
|
||||
";
|
||||
let message = refusal(text, "assign t = a;");
|
||||
assert!(message.contains("declared outside `m` in the same file"), "{message}");
|
||||
// The same selection is fine when the module stays in that file.
|
||||
let (start, end) = at(text, "assign t = a;");
|
||||
extract_module(&files(text), Path::new(M), start, end, "n", Home::SameFile)
|
||||
.expect("the same file sees it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_covers_nothing_is_refused() {
|
||||
let (start, _) = at(COMB, "module m");
|
||||
let edit = extract_module(&files(COMB), Path::new(M), start, start, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("no module item"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_refused() {
|
||||
let text = "module m;\n assign = ;\nendmodule\n";
|
||||
let edit = extract_module(&files(text), Path::new(M), 0, text.len() as u32, "n", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("does not parse"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_occupied_file_name_is_refused() {
|
||||
let sources = workspace(&[("/rtl/sum.sv", "// notes\n"), (M, COMB)]);
|
||||
let (start, end) = at(COMB, "assign s = a + b; // the sum");
|
||||
let edit = extract_module(&sources, Path::new(M), start, end, "sum", Home::NewFile);
|
||||
assert!(edit.expect_err("a refusal").contains("already a `sum.sv`"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the cheap gate
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_gate_names_the_module_and_everything_the_engine_will_read() {
|
||||
let text = "\
|
||||
module m (
|
||||
input logic i,
|
||||
output logic o
|
||||
);
|
||||
import p::*;
|
||||
sub u_sub (.i(i), .o(o));
|
||||
endmodule
|
||||
";
|
||||
let (start, end) = at(text, "sub u_sub (.i(i), .o(o));");
|
||||
let site = extract_site(text, start, end).expect("a site");
|
||||
assert_eq!(site.module, "m");
|
||||
assert_eq!(site.default_name, "m_extracted");
|
||||
assert_eq!(site.units, vec!["m".to_string(), "sub".to_string(), "p".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gate_is_empty_where_the_engine_would_refuse_for_want_of_an_item() {
|
||||
assert!(extract_site(COMB, 0, 3).is_none(), "outside every module");
|
||||
assert!(extract_site("not verilog at all", 0, 4).is_none(), "an unparsed buffer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_with_no_selection_extracts_the_item_it_is_on() {
|
||||
let at_assign = COMB.find("assign s").expect("assign") as u32 + 3;
|
||||
let edit =
|
||||
extract_module(&files(COMB), Path::new(M), at_assign, at_assign, "sum", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let new = applied(COMB, &edit, "/rtl/sum.sv");
|
||||
assert!(new.contains("assign s = a + b;"), "{new}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the census: the design still names what it named
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_two_files_together_name_every_signal_the_one_file_named() {
|
||||
// The reference census the corpus trials run, in miniature: the names the
|
||||
// design writes down are the same before and after, because an extraction
|
||||
// moves items and adds a header, and adds no name that was not there.
|
||||
let start = SEQ.find("always_ff").expect("always") as u32;
|
||||
let end = SEQ.find(" end\n").expect("end") as u32 + 5;
|
||||
let edit = extract_module(&files(SEQ), Path::new(M), start, end, "reg_stage", Home::NewFile)
|
||||
.expect("extracts");
|
||||
let old = applied(SEQ, &edit, M);
|
||||
let new = applied(SEQ, &edit, "/rtl/reg_stage.sv");
|
||||
let before = words(SEQ);
|
||||
let after: Vec<String> = words(&old).into_iter().chain(words(&new)).collect();
|
||||
for name in ["clk", "rst_n", "d", "q", "r"] {
|
||||
let was = before.iter().filter(|w| *w == name).count();
|
||||
let now = after.iter().filter(|w| *w == name).count();
|
||||
assert!(now >= was, "`{name}` was named {was} times and is now named {now}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier-shaped word of a text.
|
||||
fn words(text: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut word = String::new();
|
||||
for c in text.chars() {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
word.push(c);
|
||||
} else if !word.is_empty() {
|
||||
out.push(std::mem::take(&mut word));
|
||||
}
|
||||
}
|
||||
if !word.is_empty() {
|
||||
out.push(word);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crossing_member_access_names_the_head_and_the_field_second() {
|
||||
// QA's LOW: `b.data` and `s.f` cross the boundary as `b` and `s` — the
|
||||
// port and the variable — and a sentence leading with the field reads as
|
||||
// if the field were a signal of `m`'s own.
|
||||
let iface = "interface bus_if;\n logic data;\n modport mp (output data);\nendinterface\nmodule m (bus_if.mp b, input logic a);\n logic q;\n assign b.data = a;\n assign q = a;\nendmodule\n";
|
||||
let said = refusal(iface, "assign b.data = a;");
|
||||
assert!(said.contains("uses `b.data`"), "{said}");
|
||||
assert!(said.contains("`b` is declared with a type written outside `m`"), "{said}");
|
||||
|
||||
let packed = "typedef struct packed {\n logic f;\n logic g;\n} s_t;\nmodule m (input logic a, output s_t s);\n logic q;\n assign s.f = a;\n assign q = a;\nendmodule\n";
|
||||
let said = refusal(packed, "assign s.f = a;");
|
||||
assert!(said.contains("uses `s.f`"), "{said}");
|
||||
assert!(said.contains("`s` is declared with a type written outside `m`"), "{said}");
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -88,6 +88,28 @@ fn a_connection_with_no_signal_of_that_name_is_left_as_a_todo() {
|
||||
assert!(warnings(&edit).contains("`u1` (top.sv:2)"), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_port_may_leave_a_second_todo_where_the_first_one_already_is() {
|
||||
// A module gains its ports one at a time, so the second addition finds the
|
||||
// first one's `/* TODO: connect */` already sitting in the file and writes
|
||||
// another. `check::never_dropped` refuses an edit that writes a comment it
|
||||
// is not deleting — this is the one flow that legitimately does, and the
|
||||
// reason the rule keeps a whitelist of the text the engine writes itself.
|
||||
let first = files(&[
|
||||
("/rtl/sub.sv", SUB),
|
||||
("/rtl/top.sv", "module top;\n sub u1 (.clk(c), .rst(r));\nendmodule\n"),
|
||||
]);
|
||||
let edit = add_port(&first, ModuleRef::Name("sub"), "input logic cfg").expect("adds `cfg`");
|
||||
let second = files(&[
|
||||
("/rtl/sub.sv", &applied(&first, &edit, "/rtl/sub.sv")),
|
||||
("/rtl/top.sv", &applied(&first, &edit, "/rtl/top.sv")),
|
||||
]);
|
||||
let edit = add_port(&second, ModuleRef::Name("sub"), "input logic mode").expect("adds `mode`");
|
||||
let top = applied(&second, &edit, "/rtl/top.sv");
|
||||
assert_eq!(top.matches("/* TODO: connect */").count(), 2, "{top}");
|
||||
assert!(top.contains(".cfg(/* TODO: connect */), .mode(/* TODO: connect */)"), "{top}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_per_line_connection_list_stays_one_per_line() {
|
||||
let workspace = files(&[
|
||||
|
||||
@@ -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<String>),
|
||||
/// 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<String>,
|
||||
/// 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<Vec<ImportUse>, 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<ImportScope<'t>> {
|
||||
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<ImportScope<'t>>) {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
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<String> = 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<UnusedImport> {
|
||||
let mut out: Vec<UnusedImport> = 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<TextRange> {
|
||||
let mut out: Vec<TextRange> =
|
||||
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<Vec<(String, bool)>, 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)]));
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -97,7 +97,7 @@ request.
|
||||
| L6 | `->>` non-blocking event trigger; stream `with [range]`; cast bases other than a name/system call; drive strength on a net declaration; net delay written after the type; `let` at statement position; `#(min:typ:max)` clocking skew. | expressions-2 / interfaces / dv-statements READMEs, TODO §11 skips. |
|
||||
| L7 | `` `ifdef `` conditions never evaluated (both arms listed); no macro expansion; stringification passes through. | TODO §7 non-goal — by design, like Verible. |
|
||||
| ~~L8~~ | ~~Execute-command spelling of the instantiation skeleton for clients without `inlineCompletion` (topo §2.9-19).~~ — **delivered 2026-09-02 by TODO §26**: `lucisv.instantiate [uri, position, module]`, planned through the ghost's own `nearest_definition`/`plan_for`, rendered plainly and pushed as a `workspace/applyEdit`. Documented with a keymap in `editors/nvim/README.md`. | inline-instantiation README. |
|
||||
| L9 | `codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved. | TODO §10 deferred. |
|
||||
| ~~L9~~ | ~~`codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved.~~ — **delivered 2026-09-04/05 by TODO §37** (lazy resolve, 11.8× on the cursor path; the inlay zero ruled correct — `pins_if` is outside the default scope) and **ruled** (a widen stays one bar per session). | TODO §10 closed. |
|
||||
| L10 | Cosmetic: an enum body one-lined when short; `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` column (they are plain macro statements — no block for the formatter to see). | Probe observations. |
|
||||
|
||||
---
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,662 @@
|
||||
# dut-hierarchy
|
||||
|
||||
## Goal
|
||||
|
||||
A design holds hundreds of modules and one — or a few — that matter: the DUT,
|
||||
usually with a testbench above it. The hierarchy pane treats every module the
|
||||
same, so the module the user actually works on is buried among roots that are
|
||||
alphabetically ahead of it and its DV bench is a root of its own. This feature
|
||||
lets the user **star a module as DUT** from the pane's context menu and splits
|
||||
the pane into sections: per starred DUT, **the DUT with its children** (its
|
||||
forward instance subtree, the DUT at the very top) and **the DUT's parents** (an
|
||||
upward tree from the DUT through every module that instantiates it,
|
||||
transitively — typically the DV), then one **all other modules** section. One
|
||||
DUT gives three sections, two DUTs five. Unstar from the same menu. Everything
|
||||
is composed in the extension over the snapshot the server already sends
|
||||
(`lucisv/moduleHierarchy`: `files`, `modules`, `instances`, flat) — the server
|
||||
changes nothing in this round.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The pane is a `WebviewView`, not a `TreeDataProvider`.** That was decided in
|
||||
`docs/features/vscode-hierarchy-sidebar` (a webview is the only API at the
|
||||
extension's VS Code floor with a persistent search input inside the view).
|
||||
Consequences for this feature are in Handshakes: there is no `viewItem`
|
||||
context key and no `view/item/context` menu; the row menu is the pane's own
|
||||
HTML menu, driven by a per-row `contextValue` the host computes.
|
||||
- The reverse edge "module → modules that instantiate it" is exactly the
|
||||
forward edge read backwards: an instance contributes an edge only when its
|
||||
type resolves to exactly one declaration (`instance.targetId`), which is the
|
||||
same rule the forward tree uses. An unresolved or ambiguous type contributes
|
||||
no upward edge, so an ambiguous DUT name has an empty parents tree — the same
|
||||
answer the forward view gives for ambiguity.
|
||||
- Two declarations of one module name are two modules. A starred *name* that
|
||||
several declarations carry is resolved to the first in the model's
|
||||
deterministic order and the section is marked `ambiguous`; the other
|
||||
declarations keep their ordinary place in the pane.
|
||||
- **`others` is additive** (the lead's ruling, 2026-09-05, replacing the
|
||||
question this bullet used to ask). The owner's spec is "any dangling module
|
||||
that is not a child of the DUT would be put in a different section", so
|
||||
`others` holds **every module that is in no DUT's forward subtree and in no
|
||||
DUT's ancestor closure** — not `model.roots` minus that set. Its roots are the
|
||||
members of that set with no parent left inside it: a monitor the DV bench
|
||||
instantiates beside the DUT is not a child of the DUT, and with the bench
|
||||
excluded it has no parent on screen, so it is re-rooted at the top of
|
||||
`others`. A module that still has an ordinary parent stays under it and is not
|
||||
re-rooted, so nothing is shown twice. An `others` root's forward subtree is
|
||||
the plain, unfiltered one: a module that is also below a DUT is still shown
|
||||
under its parent here, exactly as before. A DUT itself can never appear in
|
||||
`others` — everything that instantiates it is in its ancestor closure and is
|
||||
therefore excluded.
|
||||
- Starring is an explicit user act, so it may expand rows on the user's behalf:
|
||||
the two new sections and the DUT row inside each open once, when the DUT list
|
||||
changes. This is the second exception to the owner's 2026-08-29 rule that
|
||||
nothing expands by itself (the first is a bookmark's ancestor chain).
|
||||
- **A bookmark is painted wherever its own path is on screen**, and a path is
|
||||
what is stored — not an instance. Bookmarking inside a DUT section stores the
|
||||
DUT-relative path (`aes.u_ctrl`) and is painted there; bookmarking under a
|
||||
root stores the full path and is painted there. The two are different paths
|
||||
to one instantiation, so a bookmark made in one place is not painted in the
|
||||
other, and a bookmark whose path runs through an excluded module
|
||||
(`tb.u_dut.…` while `dut` is starred) is not painted at all until the DUT is
|
||||
unstarred — the module it names may well still be on screen, but not at that
|
||||
path. Nothing is ever *lost*: the model
|
||||
still resolves the path, so `refresh()` never drops it. Tested in
|
||||
`hierarchySections_test.js::aBookmarkIsPaintedWhereverItsPathIsShown`.
|
||||
- The `lucisv.hierarchy.duts` setting is a workspace-level list a team checks
|
||||
in. Its entries cannot be unstarred from the pane, because the pane cannot
|
||||
edit a checked-in file on the user's behalf; the menu says so.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `hierarchyModel.js` — three additive changes, no behaviour change
|
||||
|
||||
Consumed: `buildHierarchy`'s flat model (`modules`, `byId`, `roots`, per-instance
|
||||
`targetId`), `childrenOf`, `treeRows`, `idForPath`, `searchHierarchy`.
|
||||
|
||||
Promised/changed by this feature (all additive, the plain pane byte-identical):
|
||||
|
||||
- `rootNode` is now exported. `hierarchySections.js` builds a section's root
|
||||
from it and re-ids it with the section prefix; every descendant id is derived
|
||||
from the parent id, so one prefix moves a whole subtree into its section.
|
||||
- `treeRows`' rows and `searchRow`'s rows carry `moduleName` (for a tree
|
||||
instance row, the instantiated type — the same string the label shows in
|
||||
parentheses). It is what lets the star/unstar decision be a pure function of a
|
||||
row.
|
||||
- `bookmarkChain` keeps its roots-first walk and, **only when that finds
|
||||
nothing**, retries over every module. A row inside a DUT section has a
|
||||
DUT-relative full path (`aes.u_ctrl`), and without the retry bookmarking such
|
||||
a row would store a path that can never be re-resolved. Every path that
|
||||
resolved before resolves to the same chain.
|
||||
|
||||
### `hierarchyView.js` ← `hierarchySections.js`
|
||||
|
||||
- `sections(model, duts)` → the section list (below).
|
||||
- `sectionRows(model, sections, expanded, bookmarkPath)` → `{ rows, nodes }` in
|
||||
exactly the shape `treeRows` returns, with the section header at depth 0 and
|
||||
everything under it shifted one level.
|
||||
- `decorate(rows, duts, locked)` → the same rows with a `contextValue`
|
||||
(`module`, `module.dut`, `module.dut.locked`, `instance`, …) and, for a locked
|
||||
DUT, a `title` tooltip.
|
||||
- `menuTable()` → `contextValue` → the menu items that row offers. Sent once per
|
||||
render; the webview renders `payload.menus[row.contextValue]` and has no rule
|
||||
of its own.
|
||||
- `sectionPrefixes(duts)` → the id prefixes, so the bookmark's ancestor
|
||||
expansion reaches the copy of the chain inside each section.
|
||||
- `defaultOpenIds(sections)` / `OTHERS_ID` → what a star opens once, and the
|
||||
one section it closes.
|
||||
|
||||
### `media/hierarchy.js` (the renderer)
|
||||
|
||||
- Builds the row menu from `payload.menus[row.contextValue]` instead of a fixed
|
||||
list, and opens it for any row whose `contextValue` has items (module rows
|
||||
included — previously only instances had a menu).
|
||||
- Renders `row.icon` when the host sends one (section and notice rows) and
|
||||
`row.title` as the row tooltip.
|
||||
|
||||
### The server — nothing
|
||||
|
||||
No request, notification or schema change. The upward tree is one pass over the
|
||||
snapshot already sent.
|
||||
|
||||
### Requested of the lead (docs this lane may not edit)
|
||||
|
||||
See "Docs to apply at merge (lead)".
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 56.1 model: reverse map, `sections()`, others-exclusion, cycle cut
|
||||
(`editors/vscode/hierarchySections.js`)
|
||||
- [x] 56.2 view: section nodes, icons, context values, persistence, setting
|
||||
union (`editors/vscode/hierarchyView.js`, `media/hierarchy.js`)
|
||||
- [x] 56.3 commands, menus, `package.json`, tests, acceptance checklist row
|
||||
- [x] Gates: `node --test editors/vscode/*_test.js`; server smoke; the vsix
|
||||
package step; the plain view pinned unchanged
|
||||
- [x] A real opentitan snapshot through `sections()` with `aes`, then
|
||||
`aes` + `hmac`
|
||||
- [x] Rework (lead's ruling): `others` is additive — every module outside every
|
||||
DUT, re-rooted where the exclusion took its parents
|
||||
(`editors/vscode/hierarchySections.js`, `hierarchySections_test.js`)
|
||||
- [x] Hygiene: `extract_test.js` in `.vscodeignore`
|
||||
- [ ] Docs the lead applies: `README.md`, `docs/site/` editors page
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-05 — dev (the whole of §56)
|
||||
|
||||
**Shipped.**
|
||||
|
||||
- `editors/vscode/hierarchySections.js` (new, 284 production lines): the reverse
|
||||
index, `sections()`, the upward tree, `sectionRows()`, `decorate()` and
|
||||
`menuTable()`.
|
||||
- `editors/vscode/hierarchySections_test.js` (new): every shape §56 lists.
|
||||
- `editors/vscode/hierarchyModel.js`: `rootNode` exported, `moduleName` on
|
||||
tree/search rows, `bookmarkChain`'s all-modules retry.
|
||||
- `editors/vscode/hierarchyView.js`: the DUT list (workspaceState + setting),
|
||||
the three commands, section rendering, the seeded default expansion, the
|
||||
menu table in the render payload.
|
||||
- `editors/vscode/media/hierarchy.js`, `media/hierarchy.css`: a menu built from
|
||||
the payload, section/notice icons, row tooltips.
|
||||
- `editors/vscode/package.json`: three commands, three more `view/title`
|
||||
entries, the `lucisv.hierarchy.duts` setting.
|
||||
- `editors/vscode/.vscodeignore`: the new test file is not shipped.
|
||||
- `editors/vscode/README.md`, `docs/manual-acceptance.md`: the user-facing text.
|
||||
|
||||
**The section algorithm.** `sections(model, duts)` walks the starred list in
|
||||
order. For each name it emits `{ kind: 'dut', name, root }` — `rootNode` for the
|
||||
named module, re-ided `dut:<name>/root:<id>`, so the subtree under it is exactly
|
||||
the one the plain pane shows — and `{ kind: 'parents', name, root }`, whose root
|
||||
is the same module as an *upward* node (`parents:<name>/up:<id>`) and whose
|
||||
children come from the reverse index: one child per (module, instance) pair with
|
||||
`instance.targetId === node.moduleId`, labelled with the instantiating module
|
||||
and `via <instance name>`. The walk carries a `seen` set down the path, so a
|
||||
cycle (`a` instantiates `b` instantiates `a`) closes with one row marked
|
||||
`recursive` that does not open again — the same shape the forward tree uses.
|
||||
Both trees are lazy: children are built when a row is opened, never before.
|
||||
|
||||
While walking, the DUT's forward subtree and its full ancestor closure are
|
||||
collected into one `excluded` set of module ids. `{ kind: 'others', roots }` is
|
||||
`model.roots` filtered by that set. Two consequences, both intended and tested:
|
||||
|
||||
- **Both below and above.** A module below DUT1 and above DUT2 is in both DUT
|
||||
sections (it is reached by two different walks, with two different id
|
||||
prefixes, and opens independently in each) and is excluded from `others`.
|
||||
- **The excluded-root cost.** `others` loses a root that is an ancestor of a
|
||||
DUT, and with it anything only reachable through that root. See Assumptions.
|
||||
|
||||
A starred name the snapshot does not hold keeps both of its sections; each shows
|
||||
a single non-expandable notice row, so the section count stays `2 × DUTs + 1`
|
||||
whatever the index says.
|
||||
|
||||
**Persistence and the setting.** The starred list lives in `workspaceState`
|
||||
under `lucisv.hierarchy.duts`, an array of names in the order starred, written
|
||||
on every star/unstar/clear and read (and sanitized — non-strings and blanks
|
||||
dropped) in the constructor. The `lucisv.hierarchy.duts` *setting* (string
|
||||
array, `window` scope — the pane is workspace-wide, not per file) is read on
|
||||
every render and on
|
||||
`onDidChangeConfiguration`. The effective list is the union, **setting entries
|
||||
first in setting order, then starred entries the setting does not already
|
||||
name**; setting entries are "locked": starring one again is a no-op, unstarring
|
||||
one is refused with the reason, and their rows carry the locked `contextValue`
|
||||
whose menu holds one disabled item whose tooltip says where the DUT comes from.
|
||||
`lucisv.hierarchy.clearDuts` empties the starred list only, and says so when the
|
||||
setting still names DUTs.
|
||||
|
||||
**Deviation from the plan, and why.** §56.3 asks for `view/item/context` entries
|
||||
gated on `viewItem`. The pane is a `WebviewView`; VS Code has no `viewItem`
|
||||
context key for it and would never show such a menu, so contributing one would
|
||||
be dead configuration. The intent — "the menu shows Unstar DUT on a starred
|
||||
module and Star as DUT on any other" — is delivered by the pane's own HTML menu:
|
||||
the host stamps every row with a `contextValue` and ships one `menuTable()` per
|
||||
render, and the renderer shows exactly the items that table names. The three
|
||||
commands are contributed and work from the palette (each takes an optional
|
||||
module name, and prompts with a Quick Pick when invoked without one), and
|
||||
`view/title` carries "Clear DUTs" and the existing entries. The `when` clauses
|
||||
that do exist (`view == lucisv.hierarchy`) and the whole `contextValue` → menu
|
||||
table are asserted in `hierarchySections_test.js`.
|
||||
|
||||
**Second deviation.** The plan's "others" is exclusive (see Assumptions); the
|
||||
owner's sentence "all other modules" could be read as additive, which would
|
||||
re-root a DV bench's monitor when its bench is excluded. The plan won; the lead
|
||||
should rule if the manual pass finds it surprising on opentitan. On `hw/ip` the
|
||||
whole cost of the exclusion is three roots out of 295, all of them benches, so
|
||||
it reads as intended there. *(Superseded the same day: the lead ruled for the
|
||||
additive reading — see the rework entry below. Everything above describes what
|
||||
the first round shipped, `others` included.)*
|
||||
|
||||
**Two corrections made while reviewing my own code, both with the reasoning
|
||||
written next to them.** (1) `treeOrSections` records the "already seeded" key
|
||||
even when the DUT list is empty, so starring the same module again after a
|
||||
"Clear DUTs" seeds its sections again instead of trusting a stale key; it is
|
||||
only weakly observable (the expansion set keeps the ids), so the test asserts
|
||||
the re-starred sections are open rather than the key itself. (2)
|
||||
`collectSubtree` walks with its own visited set rather than the shared
|
||||
exclusion set: a module already excluded as DUT1's *ancestor* would otherwise
|
||||
stop DUT2's downward walk at it, leaving that walk short. With today's root
|
||||
choice the difference cannot change `others.roots` (nothing below a module is a
|
||||
root), so it is a defensive correction with no test of its own — said here
|
||||
rather than left silent.
|
||||
|
||||
**Files touched outside the plan's expected set.** Three, all consequences of
|
||||
the two above: `editors/vscode/media/hierarchy.js` and `media/hierarchy.css`
|
||||
(the pane's renderer is where a webview's row menu lives, so the star/unstar
|
||||
items had to be built there), and `editors/vscode/.vscodeignore` (the new test
|
||||
file must not ship). Noted while there and **not** fixed, because it is not
|
||||
this feature's: `extract_test.js` is missing from `.vscodeignore` and is
|
||||
therefore packaged into the .vsix — a one-line hygiene fix for whoever owns
|
||||
that file next.
|
||||
|
||||
**Not done.** Nothing in the plan is unfinished. Two things a later round could
|
||||
take further, both written down rather than smuggled in: the additive reading
|
||||
of `others` above, and a bookmark that follows an instantiation rather than a
|
||||
path (see Assumptions).
|
||||
|
||||
**Opentitan, real snapshot** (release server over `hw/ip`, `index.scope` pushed
|
||||
to `workspace`, scratch `storagePath`, read-only — `git status --porcelain` on
|
||||
the checkout showed the same three pre-existing modified files before and
|
||||
after). 835 files, 847 modules, 295 roots, `complete: true`.
|
||||
|
||||
| starred | sections | DUT section | parents section | others |
|
||||
|---|---|---|---|---|
|
||||
| — | 1 | — | — | 295 roots |
|
||||
| `aes` | **3** | `aes`, 5 direct children, 577 rows fully open | `aes` → `aes_tb`, `aes_wrap`, **`tb`**; `aes_wrap` → `aes_wrap_tb` (5 rows) | 292 roots |
|
||||
| `aes`, `hmac` | **5** | + `hmac`, 11 direct children, 302 rows | + `hmac` → `tb` (2 rows) | 291 roots |
|
||||
|
||||
The DV bench is in `aes`'s parents section, which is the point of the feature.
|
||||
The three roots `aes` drops from `others` are `aes_tb`, `aes_wrap_tb` and `tb`
|
||||
— exactly its transitive ancestors; `hmac` drops the *other* declaration named
|
||||
`tb` (two files declare one, and they are two modules). `sections()` over the
|
||||
whole of `hw/ip` costs 2.85 ms the first time (it builds the reverse index) and
|
||||
0.15 ms after.
|
||||
|
||||
**Gates.** `tools/guard.sh -- node --test editors/vscode/*_test.js`: 5 files,
|
||||
all pass. `cargo build --release -p lucisv_server` + `tools/guard.sh -- node
|
||||
editors/vscode/smoke.js target/release/lucisv-server`: OK. `npx @vscode/vsce
|
||||
package` into the scratchpad: OK (the contributions validate).
|
||||
|
||||
### 2026-09-05 — dev (rework: `others` is additive)
|
||||
|
||||
The lead ruled on the question the first round left open (Assumptions, now
|
||||
rewritten): the owner's "any dangling module that is not a child of the DUT
|
||||
would be put in a different section" is additive, so a monitor beside the DUT
|
||||
under the same bench belongs in `others`, and the exclusive formula that put it
|
||||
in *no* section was wrong. Only `others` changed — the two DUT sections, the id
|
||||
scheme, the memoized reverse index and the seeded expansion are untouched.
|
||||
|
||||
**The algorithm.** `othersRoots(model, excluded)` replaces
|
||||
`model.roots.filter(…)`. The set is every module not in `excluded` (unchanged:
|
||||
each DUT's forward subtree plus its ancestor closure); its roots are the members
|
||||
with no parent left in the set, emitted in three passes over one shared
|
||||
`covered` set:
|
||||
|
||||
1. `model.roots` minus the excluded — today's answer, and with nothing starred
|
||||
it is still the whole answer, byte-identical to `model.roots`. Each one marks
|
||||
its forward subtree covered.
|
||||
2. Every remaining module that is neither excluded nor covered and has no
|
||||
parent in the set: re-rooted. This is the monitor whose bench is in the
|
||||
DUT's parents section.
|
||||
3. Whatever is still uncovered is inside a recursive component no root enters —
|
||||
the model's own fallback rule, and marked `recursive` the way the model
|
||||
marks it.
|
||||
|
||||
Roots come out in the model's order (alphabetically, then the fallbacks), which
|
||||
is exactly how `buildHierarchy` orders `model.roots`, so the section does not
|
||||
grow an odd tail. Coverage is what prevents duplicates: a module reachable from
|
||||
one excluded and one ordinary parent is covered by the ordinary parent's walk in
|
||||
pass 1 and is never re-rooted. It cannot be duplicated the long way round
|
||||
either, and that is a property of the exclusion rather than of the pass order: a
|
||||
path from one module of the set to another can never leave the set, because a
|
||||
module above an ancestor of the DUT is itself an ancestor, and a module below
|
||||
the DUT's subtree is itself in it — both excluded. So a pass-2 candidate is
|
||||
reachable from no other root in the section. A root's forward subtree is still the plain,
|
||||
unfiltered one — a module that is also below a DUT is shown under its parent
|
||||
here as before, and a *DUT* can never turn up in it, because everything that
|
||||
instantiates a DUT is in that DUT's ancestor closure. Coverage skips a module it
|
||||
has already descended through, so the whole pass is one walk over the graph.
|
||||
|
||||
**Tests** (`hierarchySections_test.js`, 16 → 21). A `graph({ module: [types] })`
|
||||
helper builds the small snapshots. New: the monitor beside the DUT (`bench →
|
||||
{dut, monitor}` — `monitor` is a root of `others`, `bench` is in the parents
|
||||
section, and every module in the snapshot is asserted to be on screen
|
||||
somewhere); a module under **two** excluded benches (re-rooted once, not twice);
|
||||
a module with one excluded and one ordinary parent (shown once, under the
|
||||
ordinary parent); two DUTs whose benches nest (`bench → {dut1, sub_bench}`,
|
||||
`sub_bench → {dut2, monitor}` — five sections, `monitor` re-rooted); and a cycle
|
||||
reachable only through an excluded bench (pass 3 — opened at a `recursive`
|
||||
root). The existing exclusion test keeps its name's meaning but is renamed
|
||||
`othersHoldsEveryModuleOutsideEveryDut`: starring `leaf2` now re-roots `leaf1`
|
||||
and `leaf3`, which it used to hide. `thePlainViewIsUntouched` is unchanged and
|
||||
green.
|
||||
|
||||
**Opentitan, re-derived** (release server over `hw/ip`, `index.scope` pushed to
|
||||
`workspace`, scratch `storagePath`; `git status --porcelain` on the checkout
|
||||
showed the same three pre-existing modified files before and after). 835 files,
|
||||
847 modules, 295 roots, `complete: true`.
|
||||
|
||||
| starred | others before | others after | re-rooted |
|
||||
|---|---|---|---|
|
||||
| — | 295 | 295 | — |
|
||||
| `aes` | 292 | **297** | `aes_tb_c_dpi`, `aes_tb_reqs`, `tlul_adapter_tb_reqs`, `tlul_delayer`, `vh_regs` |
|
||||
| `aes`, `hmac` | 291 | **297** | the five above + `hmac_if` |
|
||||
|
||||
All five are instantiated only by `aes_tb` (`hw/ip/aes/pre_dv/aes_tb/rtl/`),
|
||||
which is one of `aes`'s excluded ancestors; `hmac_if` is instantiated only by
|
||||
`hmac`'s `tb`. Every one of them was in no section at all before this rework.
|
||||
No root the old formula kept was lost, and a walk over the new `others` roots
|
||||
plus the DUT sections reaches every one of the 847 modules — nothing is off
|
||||
screen with `aes` or with `aes` + `hmac` starred.
|
||||
|
||||
**Cost.** `sections(model, ['aes'])` over the whole of `hw/ip`: 1.9 ms → 3.5 ms
|
||||
on the first call (both dominated by building the reverse index) and 0.03 ms →
|
||||
0.33 ms on later ones — one extra walk over 847 modules per render of a starred
|
||||
pane. With nothing starred the pane never calls `sections()` at all
|
||||
(`treeOrSections` returns `treeRows`), so the plain view pays nothing.
|
||||
|
||||
**Also fixed here** (the hygiene item the first round found and left):
|
||||
`extract_test.js` is now in `editors/vscode/.vscodeignore`, so no `*_test.js`
|
||||
ships in the .vsix — confirmed against the packaged file list.
|
||||
|
||||
**Gates.** `tools/guard.sh -- node --test editors/vscode/*_test.js`: 5 files, 5
|
||||
pass, 0 fail. `npx @vscode/vsce package` into the scratchpad: OK, 338 files.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-06 — QA (Sonnet 5)
|
||||
|
||||
**Scope.** Read the plan (TODO §56), the dev's account (this README, both
|
||||
work-log entries), and the diffs of every file it lists. Attacked the model
|
||||
and view with scratch tests (removed afterwards, none of the lane's files
|
||||
touched besides this log and the TODO checkbox), re-derived the opentitan
|
||||
numbers against the real, read-only checkout, and ran every gate.
|
||||
|
||||
**1. Sections — attacked on the existing fixtures, `graph()`, and new scratch
|
||||
graphs (`/private/tmp/.../scratchpad/attack_sections.js`, removed).** All of
|
||||
the following hold, matching the algorithm's own description and this
|
||||
README's Assumptions:
|
||||
|
||||
- Zero/one/two DUTs: `2n+1` sections, order = starred order (pinned by the
|
||||
dev's `oneDutIsThreeSectionsAndTwoAreFive`).
|
||||
- A DUT that is a root: its parents section holds only the DUT row, no
|
||||
children (`parents.root.hasChildren === false`) — verified with a fresh
|
||||
`dut → leaf` graph.
|
||||
- A DUT that is a leaf: its DUT section is the DUT alone
|
||||
(`dut.root.hasChildren === false`) — verified with `bench → dut`.
|
||||
- A DUT instantiated twice by one parent: the parents tree shows the parent
|
||||
**twice**, one row per instance, each with its own `via <instance>` label
|
||||
and its own row id — a 2-way explore tree, as the plan asked. Verified with
|
||||
`bench → [[dut,u_dut_a],[dut,u_dut_b]]`.
|
||||
- A module instantiated by two benches, itself instantiating the DUT: the
|
||||
upward tree branches at that node (two children under `mid`). Verified.
|
||||
- A parent chain of depth 6: the upward walk climbs all six levels,
|
||||
`depth` incrementing by one per hop. Verified.
|
||||
- Two DUTs where DUT2 is inside DUT1's subtree (`dut1 → dut2 → leaf`): DUT2
|
||||
appears both under DUT1's forward tree (unfiltered — `dutSection`'s root is
|
||||
always the plain subtree) and as its own two sections; DUT1 appears in
|
||||
DUT2's parents tree. Five sections, all present and correctly shaped.
|
||||
Verified, and the mirror (starring DUT2 before DUT1) changes only section
|
||||
*order*, never content.
|
||||
- The same module starred twice: `sections()` itself performs **no dedup** —
|
||||
`sections(model, ['dut','dut'])` yields 5 sections (two DUT×2 pairs plus
|
||||
others). Dedup is the caller's job: `hierarchyView.js`'s `moduleNames()`
|
||||
wraps every stored/configured list in a `Set` before it ever reaches
|
||||
`sections()`, and this is exercised in the dev's own `hierarchyView_test.js`
|
||||
(`configuredDuts = ['top', '']`, the blank and any repeat dropped). Pinning
|
||||
this contract here so a future caller of `sections()` that skips
|
||||
`moduleNames()` doesn't get a silent surprise (see LOW finding below).
|
||||
- A starred name absent from the snapshot: both its sections keep a single
|
||||
non-expandable "not in the index" notice row; section count stays `2n+1`
|
||||
(dev's `aStarredNameTheSnapshotLacksKeepsItsSections`, re-run, green).
|
||||
- A starred name matching two declarations: `ambiguous: true` on both
|
||||
sections, header says "ambiguous", the **first** declaration in the model's
|
||||
order is what is shown (dev's `twoDeclarationsOfOneNameAreMarkedAmbiguous`).
|
||||
Went one step further than the existing test: confirmed the Assumptions
|
||||
claim that "an ambiguous DUT name has an empty parents tree" actually holds
|
||||
— with two declarations of `dut`, `tb`'s instance of `dut` becomes
|
||||
itself ambiguous (`instance.definitions.length === 2`), so `targetId` is
|
||||
unset and the reverse index carries no edge to either declaration;
|
||||
`parents.root.hasChildren` is `false`. This isn't special-cased code, it
|
||||
falls out of `parentIndex` using `instance.targetId` — correct and matches
|
||||
the forward view's own ambiguity answer, as documented.
|
||||
- A cycle through the DUT itself (`a → b → a`, starred `a`): both the forward
|
||||
walk and the upward walk terminate at one `recursive`-marked row that does
|
||||
not reopen (dev's `theParentsWalkCutsACycle`); re-verified.
|
||||
- **Others is additive and complete.** Re-ran the dev's own reasoning as a
|
||||
fuzz test: a seeded-random 40-module DAG (0.15 edge probability, i < j only
|
||||
so it's acyclic — plus deliberately keeping a couple of exact-duplicate
|
||||
edges to also exercise the twice-instantiated case), 200 random DUT
|
||||
selections (1–3 DUTs each). For every trial: every one of the 40 modules is
|
||||
on screen in some section, and no module is both an `others` root and a
|
||||
member of any starred DUT's forward subtree. 200/200 trials passed with no
|
||||
failures.
|
||||
- No module appears in `others` *and* in a DUT subtree: covered by the fuzz
|
||||
test above (assertion is exactly this) and by the dev's own
|
||||
`othersHoldsEveryModuleOutsideEveryDut`/`aModuleUnderAnExcludedBenchIsReRootedInOthers`.
|
||||
- A module both below DUT1 and above DUT2: dev's
|
||||
`aModuleBothBelowOneDutAndAboveAnotherIsInBothSections` — two rows, two ids,
|
||||
neither in `others`; re-run, green.
|
||||
- Re-rooted module ordering: `othersRoots` emits in `model.roots`' own order
|
||||
(alphabetical, then fallbacks) — confirmed by reading `othersRoots` and by
|
||||
the passing `aModuleUnderTwoExcludedBenchesIsReRootedOnce` /
|
||||
`aCycleReachableOnlyThroughAnExcludedBenchStillHasARoot` tests (recursive
|
||||
fallback root correctly marked).
|
||||
- A module with one excluded and one ordinary parent: shown once, under the
|
||||
ordinary parent, never re-rooted (dev's
|
||||
`aModuleWithOneOrdinaryParentIsNotReRooted`; re-run, green).
|
||||
- **The plain view is byte-identical to `model.roots` with no DUT.** Read
|
||||
`thePlainViewIsUntouched`: it is a real deep-equality check over every
|
||||
visible field (`id, kind, label, detail, depth, hasChildren, expanded,
|
||||
warning, bookmarked`) between `decorate(treeRows(...).rows, [], [])` and
|
||||
`treeRows(...).rows` directly — not a placeholder. Also confirmed
|
||||
structurally: `treeOrSections()` in `hierarchyView.js` calls `treeRows`
|
||||
directly and never calls `sections()` at all when `duts.length === 0`, so
|
||||
the plain pane pays zero extra cost, exactly as claimed.
|
||||
|
||||
**2. View/persistence.** Read and re-ran `hierarchyView_test.js`'s DUT block
|
||||
(lines ~199–330): the fake-`workspaceState` round trip (star, "reload" via a
|
||||
second `HierarchyView` over the same `state` map, order kept, `7` and `''`
|
||||
dropped by `moduleNames`'s sanitizer); the setting union (setting entries
|
||||
first, locked, unstar refused with the exact reason string, re-star a
|
||||
no-op with an information message); `onDidChangeConfiguration` re-render
|
||||
(`configurationChanged({...})` reshapes the section list); `clearDuts` clears
|
||||
stars only (locked setting DUT's section survives, with a message naming it);
|
||||
the seeded expansion opens the two new sections and the DUT row at depth 1 in
|
||||
each, `others` stays closed, and — the dev's own "two corrections" note —
|
||||
re-starring the same module after a `clearDuts` reseeds (`seededFor` keeps
|
||||
recording even at `duts.length === 0`). All green as shipped.
|
||||
|
||||
Added one attack of my own the plan explicitly asked for and the existing
|
||||
tests don't cover directly: **collapsing a DUT section survives an unrelated
|
||||
snapshot refresh.** Built a second fake-`vscode` harness
|
||||
(`attack_sections.js`, removed after the run) that stars a DUT, collapses its
|
||||
section via a `toggle` message, then fires the `lucisv/moduleHierarchyChanged`
|
||||
notification handler with the *same* starred list and waits out the refresh
|
||||
debounce. The section stayed collapsed. This is exactly what
|
||||
`seedExpansion`'s `if (this.seededFor === key) return;` guard promises (`key`
|
||||
is unchanged when the DUT list doesn't change), and it held.
|
||||
|
||||
**Search inside sections and reveal-on-open — read, not just tested, because
|
||||
the plan's phrasing assumed more than the feature does.** `render()` in
|
||||
`hierarchyView.js` sends search results (`searchHierarchy`) as a **flat** list
|
||||
whenever the query box is non-empty, entirely independent of which sections
|
||||
are open or which DUTs are starred — this is pre-existing behaviour from
|
||||
`vscode-hierarchy-sidebar`, unchanged by §56. A search hit still gets a
|
||||
correct `contextValue` via `decorate(found.rows, duts, locked)`, so
|
||||
star/unstar works from a search result, but there is no per-section grouping
|
||||
of search results to "resolve into" — search was never section-shaped, before
|
||||
or after this feature, and nothing in the README's Handshakes claims
|
||||
otherwise ("the existing search... behaviour work[s] inside every section"
|
||||
means it keeps working, not that it becomes section-aware). Not a defect.
|
||||
Likewise, **no "reveal a file's module when it is opened" feature exists
|
||||
anywhere in this codebase** — grepped `editors/vscode` for
|
||||
`onDidOpenTextDocument`/`activeTextEditor`/`revealOnOpen` and found nothing,
|
||||
in this feature or the sidebar it builds on. The QA brief's "reveal-on-open of
|
||||
a file whose module is only in a parents section" item does not correspond to
|
||||
an implemented or claimed capability; the only reveal behaviour that exists is
|
||||
bookmark-driven (`setBookmark` expands the bookmarked row's ancestors), which
|
||||
*is* implemented per-section (`sectionPrefixes`) and is covered by
|
||||
`aBookmarkIsPaintedWhereverItsPathIsShown` — re-run, green, and its claims
|
||||
(DUT-relative path painted inside the section, ordinary path painted at the
|
||||
root, a path through an excluded module painted nowhere but never dropped)
|
||||
all hold on inspection of `isBookmarked`/`bookmarkChain`'s retry.
|
||||
|
||||
**Bookmark painting inside a DUT section.** Matches the README exactly: a
|
||||
bookmark is a stored *path*, painted wherever that exact path resolves to an
|
||||
id on screen (`isBookmarked` matches the bookmark id or `.../<id>` suffix per
|
||||
section prefix). Re-verified `bookmarkChain`'s all-modules retry does not
|
||||
change any *previously resolving* path's id (the retry only changes which
|
||||
node search order finds a match through; `rootNode(model, module, false)`'s
|
||||
`false` for `fallback` affects only `detail`/`warning` display fields on a
|
||||
node that is never rendered — the chain is an array of ids, and `rootNode`'s
|
||||
`id` field does not depend on `fallback`). No crash, no incorrect painting in
|
||||
any of the model/view tests or the scratch attacks.
|
||||
|
||||
**3. Menus/commands.**
|
||||
|
||||
- `menuTable()` per render: read and re-verified against
|
||||
`contextValuesAndMenusSayWhatEachRowOffers` — a starred row → `[UNSTAR]`, an
|
||||
ordinary row → `[STAR]` (or `INSTANCE_ACTIONS + STAR/UNSTAR` for an
|
||||
instance), a locked row → one disabled item with the setting-naming
|
||||
tooltip. Every `contextValue` `decorate()` can produce has a menu entry
|
||||
(asserted by the same test's closing loop) — no row can silently offer
|
||||
nothing.
|
||||
- The three commands exist in `package.json`'s `contributes.commands`
|
||||
(`starDut`, `unstarDut`, `clearDuts`) and in `view/title` gated
|
||||
`"when": "view == lucisv.hierarchy"` — confirmed by reading `package.json`
|
||||
directly and by the dev's `packageJsonContributesTheCommandsMenusAndSetting`
|
||||
test, both green.
|
||||
- Ran every command through the extension's registered handler with the
|
||||
dev's fake `vscode` (`commands.get(...)`), with and without a module name:
|
||||
`starDut('top')` (named) and `starDut()` (Quick Pick, `picked` captures the
|
||||
candidate list — confirmed sorted, deduped, and scoped correctly: "every
|
||||
module name" for starring, "only what this workspace starred" for
|
||||
unstarring). Both paths work; re-run, green.
|
||||
- The `lucisv.hierarchy.duts` setting's `contributes.configuration` entry:
|
||||
`type: "array"`, `items.type: "string"`, `scope: "window"`,
|
||||
`default: []`, with a `markdownDescription` naming both the checked-in and
|
||||
starred routes and the lock — read directly in `package.json` and pinned by
|
||||
the dev's test.
|
||||
- `.vscodeignore` excludes every `*_test.js`: listed all five
|
||||
(`extract_test.js`, `hierarchyModel_test.js`, `hierarchySections_test.js`,
|
||||
`hierarchyView_test.js`, `restart_test.js`) against the file and confirmed
|
||||
none of them, nor any other `*_test.js`, appears in `npx @vscode/vsce
|
||||
package`'s file listing (§5 below).
|
||||
|
||||
**4. Opentitan (read-only, scratch index store).** Re-derived the dev's table
|
||||
independently, with my own hand-rolled LSP client
|
||||
(`/private/tmp/.../scratchpad/opentitan_client.js`, removed after the run) —
|
||||
`initializationOptions.storagePath` under the scratchpad,
|
||||
`lucisv.index.scope: "workspace"` pushed via `workspace/didChangeConfiguration`,
|
||||
`rootUri`/`workspaceFolders` pointed at `hw/ip`, polling
|
||||
`lucisv/moduleHierarchy` until `complete: true`.
|
||||
|
||||
| starred | sections | others roots | direct parents |
|
||||
|---|---|---|---|
|
||||
| — | 1 | 295 | — |
|
||||
| `aes` | 3 | 297 | `aes_tb`, `aes_wrap`, `tb` |
|
||||
| `aes`, `hmac` | 5 | 297 | `aes`: same three; `hmac`: `tb` |
|
||||
|
||||
835 files, 847 modules, 295 roots, `complete: true` — matches the dev's
|
||||
numbers exactly. The five re-rooted names the dev called out
|
||||
(`aes_tb_c_dpi`, `aes_tb_reqs`, `tlul_adapter_tb_reqs`, `tlul_delayer`,
|
||||
`vh_regs`) are present in the `others` list for `aes`; `hmac_if` joins them
|
||||
only once `hmac` is also starred — matches. Verified independently (not just
|
||||
by trusting the label) that opentitan really does declare 31 separate modules
|
||||
named `tb` across `hw/ip` (`grep -rl '^module tb\b'`), so `aes`'s `tb` and
|
||||
`hmac`'s `tb` genuinely are two different modules, as the dev's note claims.
|
||||
`sections(['aes'])`: 4.2 ms cold, 0.6 ms warm (my machine/session, not a
|
||||
controlled comparison against the dev's 2.85 ms/0.15 ms, but the same order of
|
||||
magnitude and the same qualitative shape — most of the cost is the one-time
|
||||
reverse-index build). **Full-reachability check**: walked the module graph
|
||||
directly (not the rendered tree, to stay linear over 847 nodes) from every
|
||||
DUT's forward+ancestor closure plus every `others` root's forward subtree —
|
||||
**847 of 847 modules reachable** for both `['aes']` and `['aes','hmac']`. No
|
||||
module is off screen in either configuration.
|
||||
|
||||
`git -C /Users/guoliangchen/repo/opentitan status --porcelain` before and
|
||||
after this session's use: unchanged, exactly the three pre-existing modified
|
||||
files (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**5. Gates.**
|
||||
|
||||
- `tools/guard.sh -- node --test editors/vscode/*_test.js`: 5 files, 5 pass, 0
|
||||
fail (`extract_test.js`, `hierarchyModel_test.js`,
|
||||
`hierarchySections_test.js`, `hierarchyView_test.js`, `restart_test.js`).
|
||||
- `tools/guard.sh -m 8 -t 900 -- cargo build --release -p lucisv_server`:
|
||||
already up to date (0.02 s, no crate source changed by this lane — verified
|
||||
`git status --porcelain -- crates/` is empty), binary present.
|
||||
- `tools/guard.sh -- node editors/vscode/smoke.js target/release/lucisv-server`:
|
||||
OK, 20 messages, includes a passing `lucisv/moduleHierarchy` round trip.
|
||||
- `npx @vscode/vsce package` into the scratchpad: OK, 338 files, 3.1 MB, no
|
||||
`*_test.js` in the listing; guard not required (not a test/fuzzer/sweep, and
|
||||
it finished in a few seconds well under any memory concern, consistent with
|
||||
how the dev logged the same step).
|
||||
- No guard kill on any run.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- LOW — `sections(model, duts)` performs no de-duplication of its own `duts`
|
||||
argument (confirmed by direct test: two identical names cost two identical
|
||||
section pairs). Today's only caller (`hierarchyView.js`'s `treeOrSections`)
|
||||
always passes `this.duts()`, which is already deduped through
|
||||
`moduleNames()`'s `Set`, so this is not reachable from the shipped extension
|
||||
today. Worth a one-line doc comment on `sections()` saying the caller owns
|
||||
dedup, so a future caller (a test, a second view) doesn't get a surprise
|
||||
five-section render from `['aes','aes']`. Not blocking.
|
||||
- LOW — the QA brief's "search inside every section" and "reveal-on-open of a
|
||||
file" items don't correspond to implemented behaviour: search has always
|
||||
been flat/section-independent (pre-existing, unchanged by §56), and no
|
||||
file-open reveal feature exists in this extension at all (verified by grep
|
||||
across `editors/vscode` for `onDidOpenTextDocument`/`activeTextEditor`/
|
||||
`revealOnOpen`). Recorded here so the brief isn't silently treated as
|
||||
satisfied; nothing to fix in the dev's code — the feature never promised
|
||||
either shape.
|
||||
- No MEDIUM or HIGH findings. Every shape in TODO §56, the model's own
|
||||
Assumptions, and the rework's stated invariants held under direct testing,
|
||||
fuzzing (200 random DUT selections over a random 40-module DAG), and a real
|
||||
847-module snapshot.
|
||||
|
||||
**Verdict: PASS.** No rework needed. The two LOW items above are hygiene notes
|
||||
for a later round, not conditions on this one.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-06 — lead.** Accepted after one ruling; ships in 0.48.0. This is
|
||||
the owner's request built as asked — star from the row menu, the DUT with
|
||||
its children at the very top, its parents as an upward tree, all other
|
||||
modules in one collapsible section, two sections per DUT plus one — and
|
||||
built where it belongs, in the extension over the snapshot the server
|
||||
already sends, with no server change. The one deviation (a webview row
|
||||
menu rather than `view/item/context`, because the pane is a `WebviewView`)
|
||||
delivers the intent exactly. The ruling: the first version's "others"
|
||||
dropped any module reachable only through a DUT's ancestors — a monitor
|
||||
beside the DUT under the same bench — which the owner's "any dangling
|
||||
module not a child of the DUT" does not allow; the rework re-roots them,
|
||||
and on opentitan that put five real modules under `aes_tb` back on screen,
|
||||
with a walk over every section reaching all 847 modules in both
|
||||
configurations and QA's 200-trial fuzz finding no overlap and no gap. The
|
||||
setting-with-lock for a team's checked-in DUTs is a good addition. QA's
|
||||
LOWs (a doc comment on `sections()`'s de-dup contract; two brief items
|
||||
that name no shipped capability) need nothing.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
`docs/topo.md`: one new node, `dut-hierarchy`, with a single inbound edge from
|
||||
`vscode-hierarchy-sidebar` (it consumes that feature's model and renderer and
|
||||
adds nothing the server sees). No edge to any Rust crate — the server is
|
||||
untouched by this round.
|
||||
|
||||
For `README.md`'s VS Code section and the site's editors page:
|
||||
|
||||
> **DUT-centred hierarchy.** Right-click a module in the Hierarchy pane and
|
||||
> choose **Star as DUT**. The pane splits into sections: the DUT with its
|
||||
> children, the DUT's parents (an upward tree through everything that
|
||||
> instantiates it — usually the testbench), and every module in neither —
|
||||
> including whatever the bench held beside the DUT, which that last section
|
||||
> re-roots rather than hide. Star a
|
||||
> second DUT and you get five sections. Unstar from the same menu, or clear
|
||||
> every DUT from the pane's title bar. Starred DUTs are remembered per
|
||||
> workspace; a team can also check them in with
|
||||
> `"lucisv.hierarchy.duts": ["aes", "hmac"]`, and DUTs that come from the
|
||||
> setting are shown locked.
|
||||
@@ -0,0 +1,657 @@
|
||||
# expand-wildcard
|
||||
|
||||
TODO §50 — the first of the §8 refactoring backlog to ship. One engine
|
||||
function, one code action, one command.
|
||||
|
||||
## Goal
|
||||
|
||||
`sub u_x (.clk(clk), .*);` binds every remaining port of `sub` to the
|
||||
same-named signal in the scope the instantiation is written in (IEEE 1800
|
||||
§23.3.2.4). **Expanding** the wildcard writes those bindings out: the
|
||||
refactoring an RTL engineer reaches for the moment a port list is about to
|
||||
diverge from the wrapper around it, and the one the ports engine already
|
||||
refuses to edit around — `add_port` and `remove_port` warn and leave a `.*`
|
||||
site alone, and `propagate_ports` declines a wildcard outright, because none of
|
||||
them can rewrite a connection nobody wrote. After this round the user can turn
|
||||
the wildcard into text first and then use all three.
|
||||
|
||||
The engine is `vlog_refactor::expand_wildcard`, so Vim, VS Code and any future
|
||||
CLI get identical behavior; `lucisv_server` maps the protocol and decides
|
||||
nothing. Whole-edit-or-nothing, through the ports engine's lexical splice and
|
||||
its "the file still parses" verifier: 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_refactor/src/lib.rs
|
||||
pub fn expand_wildcard(files: &[(PathBuf, String)], file: &Path, offset: u32)
|
||||
-> Result<RefactorEdit, String>;
|
||||
// new beside `sites_phrase`, for the server's title arithmetic:
|
||||
pub fn is_sites_phrase(phrase: &str) -> bool;
|
||||
```
|
||||
|
||||
`files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence
|
||||
convention are M2's, unchanged. `port_actions` gained a third offer, so the
|
||||
code-action path needed no new entry point at all.
|
||||
|
||||
## The rule, exactly as implemented
|
||||
|
||||
At the cursor's instantiation — the instance whose span covers the offset, or
|
||||
the only instance of the statement whose module name it covers, which is
|
||||
`propagate_ports`'s own rule:
|
||||
|
||||
1. The connection list must be **named** and hold exactly **one** `.*`.
|
||||
2. Every port the instantiated module declares that the list does **not**
|
||||
name explicitly is what the wildcard stands for, in the module's
|
||||
**declaration order**. `.clk`, `.clk()` and `.clk(x)` all count as
|
||||
explicit — they are connections the source wrote, so `.*` never bound
|
||||
those ports.
|
||||
3. For each of them, lucisv asks `vlog_semantic` what the name means in the
|
||||
scope the *instance name* sits in — the generate block's, then its
|
||||
parents', up to the module's:
|
||||
- **a net, a variable, or a port** of that name → `.name(name)`;
|
||||
- **anything else, or nothing** → `.name()`, and a warning naming every
|
||||
port left that way.
|
||||
|
||||
"A signal" is read strictly, and that is the whole of the LRM rule that
|
||||
matters here: a **parameter**, a **localparam**, a **genvar**, a **type**,
|
||||
an **instance** or a **task/function argument** of the same name is *not* a
|
||||
net or a variable, so `.*` does not bind it. This is a narrower set than
|
||||
the one `add_port`/`propagate_ports` use when they *write* a connection
|
||||
(`find::visible_in`, which happily writes `.p(p)` for a parameter, because
|
||||
there the user asked for a connection and a parameter is a legal
|
||||
expression). Here the question is not "what could be connected" but "what
|
||||
*was* connected", and connecting an output port to a constant because a
|
||||
`localparam` happened to share its name would be a legal-looking, silent,
|
||||
wrong expansion. The two readers share one scope walk
|
||||
(`find::kind_visible_in`) so they cannot come to disagree about *which*
|
||||
declaration a name means, only about whether that kind counts.
|
||||
4. A port with nothing to bind to is one the wildcard never bound either —
|
||||
the compiler would have rejected the instantiation — so `.name()` plus the
|
||||
warning is the honest answer, and saying it out loud is half the point of
|
||||
the expansion. (It found two real ones in OpenTitan; see Acceptance.)
|
||||
|
||||
### Escaped identifiers
|
||||
|
||||
A port named `\my-port` is written `.\my-port (\my-port )`, with the space an
|
||||
escaped identifier needs after it: an escaped identifier runs from its `\` to
|
||||
the next **whitespace** and to nothing else (IEEE 1800 §5.6.1), so
|
||||
`.\my-port(\my-port)` would be one enormous token swallowing the parens, the
|
||||
comma and the rest of the line. `instantiate.rs` learned this from a QA
|
||||
finding on the skeleton renderer; `ends_escaped` is now `pub(crate)` and the
|
||||
expansion asks the same question rather than spelling the rule a second time.
|
||||
Two behavior tests pin it, bound and unbound.
|
||||
|
||||
### Layout
|
||||
|
||||
The `.*` element is **replaced**, in place, by the generated connections. The
|
||||
list's own layout is copied the way `append_to_list` copies it: the gap before
|
||||
the wildcard (from the previous element, or from the list's `(`) decides
|
||||
**one connection per line** — at the wildcard's own indentation — from
|
||||
**inline**, `, `-separated. Refactored output is *edited source*, not
|
||||
reformatted source (umbrella Handshakes); the user runs the formatter
|
||||
afterwards if they want more, and the acceptance tests below prove the
|
||||
formatter is happy with what is written.
|
||||
|
||||
### Comments
|
||||
|
||||
- A comment written **before** the `.*` is outside the replaced span and stays
|
||||
exactly where it is, which puts it before the first generated connection.
|
||||
- A comment written **after** it on the same line (`.* // and the rest`) gets
|
||||
the `append_to_list` treatment, for the same reason: the comma is written
|
||||
*before* the comment and the remaining connections after it, so the comment
|
||||
stays with the **first** generated connection instead of drifting onto the
|
||||
last, and no `,` is ever written inside a `//`.
|
||||
- A comment written **inside** the element (`. /* here */ *`) is inside the
|
||||
span the expansion replaces, so the verifier's comment rule refuses the
|
||||
whole refactoring. Comments are never dropped (invariant 3), and lucisv will
|
||||
not decide where that one should move.
|
||||
|
||||
## The refusal list — exact
|
||||
|
||||
`expand_wildcard` refuses when:
|
||||
|
||||
1. **The position is not an instantiation** — *"there is no module
|
||||
instantiation at this position."*
|
||||
2. **The statement declares several instances** — *"this statement declares 2
|
||||
instances of `sub`; put the cursor on the one to expand."*
|
||||
3. **The instance is a `bind` directive's** — *"`u_x` is instantiated by a
|
||||
`bind` directive, where `.*` binds in the target's scope rather than in
|
||||
this one; lucisv does not expand it there."* §23.3.2.4 resolves a bound
|
||||
instance's wildcard in the *target's* scope, which lucisv would have to
|
||||
elaborate a hierarchy to know. Out of scope for this round, and said so.
|
||||
(This is the majority of real `.*` sites in OpenTitan — see Acceptance.)
|
||||
4. **The list connects positionally** — *"`u_x` connects `sub`'s ports by
|
||||
position; there is no `.*` to expand."*
|
||||
5. **There is no `.*`** — *"`u_x` writes no `.*` to expand."*
|
||||
6. **There is more than one** — *"`u_x` writes `.*` 2 times, which is illegal;
|
||||
lucisv will not guess what it means."*
|
||||
7. **Either file carries a parse diagnostic** — *"top.sv does not parse (… at
|
||||
line N), so lucisv will not expand a `.*` in it."* Stricter than the
|
||||
verifier's "no *new* diagnostic" rule on purpose: a connection list lucisv
|
||||
misread is a list whose ports it would connect a second time, and a
|
||||
duplicate connection is not a refactoring, it is corruption.
|
||||
8. **The instantiated module's port list carries compiler directives** —
|
||||
*"`sub`'s port list carries compiler directives, so which ports `.*` binds
|
||||
depends on the configuration; lucisv does not preprocess, so it made no
|
||||
edits."* Writing every arm's ports out produces a connection list no
|
||||
configuration ever had. The same sentence guards the **connection list's**
|
||||
own directives, where lucisv equally cannot tell which connections are
|
||||
explicit in which arm.
|
||||
9. **The module is unknown or declared twice** — `locate_module`'s two
|
||||
existing sentences, unchanged.
|
||||
10. **Nothing is left to bind** — *"`u_x` already connects every port `sub`
|
||||
declares, so its `.*` binds nothing."* Not in the plan's list; derived
|
||||
from `propagate_ports`'s refusal 16 (*"a 'did nothing' success is a worse
|
||||
answer than a sentence"*). Deleting the `.*` instead would be a different
|
||||
refactoring — a removal, with a removal's comma and comment problems —
|
||||
and nobody asked for it.
|
||||
11. **The file is outside the in-scope set**, and **verification fails**
|
||||
(the five checks in `docs/features/refactor-ports/README.md`), the ports
|
||||
engine's own rules unchanged.
|
||||
|
||||
Refusals 3–8 and 10 are pinned by a behavior test each; 1, 2, 4, 5, 6, 9 and
|
||||
the outside-the-scope one too. Nothing is offered as a code action where the
|
||||
refactoring would be refused, so the lightbulb never appears to explain itself.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The `.*` is the only thing the edit touches.** Nothing outside the
|
||||
cursor's own file is read for the edit itself (the module's declaration is
|
||||
read, not edited), so `RefactorEdit` names one file. That is what makes the
|
||||
lazy code action exact rather than optimistic: the offer's two files —
|
||||
buffer plus declaration — are already everything the resolve will read.
|
||||
- **A third offer costs a third attempt.** `port_actions` tries three
|
||||
refactorings where it tried two, and each one builds its own `Scope` (the
|
||||
index over the files it was handed) before it can refuse. So an offered
|
||||
menu is now three index builds over that file set rather than two — but the
|
||||
file set is the thing §37.1 already shrank: on the lazy path it is the
|
||||
buffer plus one declaration, and the gate (`may_have_port_action`, one parse
|
||||
of one file, no workspace, no I/O) still answers "nothing here" for almost
|
||||
every cursor before any of the three runs. Nothing in this round re-reads
|
||||
the fan-out that §37.1 took off the cursor path. A `Scope` shared by all
|
||||
three attempts is the obvious next economy and is deliberately not taken
|
||||
here: it changes the signatures of three shipped refactorings for a saving
|
||||
only the eager path sees.
|
||||
- **lucisv does not elaborate.** "Is a signal called `p` in scope here?" is a
|
||||
lexical-scope question `vlog_semantic` answers. A name that would come from
|
||||
a wildcard package import lucisv cannot resolve reads as *not in scope*, so
|
||||
the port is written `.p()` — visibly, in the warning, never `.p(p)` on a
|
||||
guess. This is the ports engine's standing assumption; the difference is
|
||||
that here a wrong "not in scope" writes an unconnected port rather than a
|
||||
`/* TODO */`, which is why the warning names every one of them.
|
||||
- **lucisv does not preprocess**, so a port list or a connection list split
|
||||
across `` `ifdef`` arms is refused rather than read straight through (the
|
||||
refusals above). This is stricter than `add_port`, which warns and appends
|
||||
outside every arm; appending one element is configuration-independent,
|
||||
while enumerating a whole port set is not.
|
||||
- **A module name is unique in scope**, and the index is the server's
|
||||
authority on where it is declared — the ports engine's assumptions,
|
||||
unchanged.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`** (no change required): `parse_source_tolerant`
|
||||
and its `ParseDiagnostic` (refusal 7), `LineIndex`, `TextRange`, and
|
||||
`ast::{Connection, Connections, Instance, Instantiation, Item, ListElem}` —
|
||||
`Connection::name == "*"` is how the wildcard is recognized, and
|
||||
`Connection::span` (the element's *code* extent, comments outside it) is what
|
||||
makes the replacement exact. `Instance::conn_directives` is what makes refusal
|
||||
8's second half possible.
|
||||
|
||||
**Consumed from `vlog_semantic`** (no change required, nothing patched):
|
||||
`Semantics::{scopes, symbols, symbol}`, `Scope::{span, parent, lookup_local}`,
|
||||
and `SymbolKind` — the kind is now *read* rather than only matched against a
|
||||
fixed set (below).
|
||||
|
||||
**Changed inside `vlog_refactor`** — four edits to existing files, all of them
|
||||
pure factorings with no behavior change:
|
||||
|
||||
- `ports/find.rs`: `collect_instantiations` is now a wrapper over
|
||||
`walk_instantiations`, which reports of each instantiation whether it is a
|
||||
`bind` directive's own. Same walk, same order, one extra bit; every existing
|
||||
caller ignores the bit.
|
||||
- `ports/find.rs`: `visible_in`'s scope walk moved into `kind_visible_in`,
|
||||
which returns the `SymbolKind` it found; `visible_in` is that function plus
|
||||
the kind set it always had, so `add_port`, `propagate_ports` and
|
||||
`instantiate.rs` answer byte-for-byte as before.
|
||||
- `ports/mod.rs`: `expand_wildcard`, `expansion` (the edit plus its connection
|
||||
count) and the third `port_actions` offer; plus `is_sites_phrase` beside
|
||||
`sites_phrase`.
|
||||
- `instantiate.rs`: `ends_escaped` is `pub(crate)` instead of private. One
|
||||
word; no call site changed.
|
||||
|
||||
**Promised to `lucisv_server`**: everything the other port refactorings
|
||||
promise. `expand_wildcard` does not panic, returns no partial edit, sorts and
|
||||
de-overlaps its edits, and its warnings are informational.
|
||||
`PortAction.title` is user-facing text the server does not rewrite — with one
|
||||
new obligation, which is why `is_sites_phrase` exists: the server *does*
|
||||
rewrite the count in an offered title from its index, and the expansion's
|
||||
count is not an instantiation census. The server now asks before recounting.
|
||||
|
||||
**Changed in `lucisv_server`** (protocol layer only): `EXPAND_WILDCARD`
|
||||
(`lucisv.expandWildcard`) added to `ports::commands()` and to
|
||||
`ports::execute`; `ports::counted` gated on `vlog_refactor::is_sites_phrase`.
|
||||
The dispatch arm, the capability advertisement and the code-action path needed
|
||||
no change — commands are advertised from `commands()` and every
|
||||
`workspace/executeCommand` already routes through `ports::execute`. **The VS
|
||||
Code extension needed nothing**: `editors/vscode/package.json` contributes only
|
||||
its own webview commands, and server commands are discovered over LSP.
|
||||
|
||||
**Requested of nobody.** No change was needed in `vlog_parser`,
|
||||
`vlog_semantic`, `vlog_formatter` or `lucisv_core`.
|
||||
|
||||
**One new dev-dependency**: `vlog_formatter` on `vlog_refactor`, **tests
|
||||
only**, the arrangement `vlog_linter` already uses and with the same
|
||||
justification written into `Cargo.toml`: the acceptance tests assert that what
|
||||
the expansion writes is something the formatter accepts and leaves alone the
|
||||
second time, and that cross-tool guarantee cannot be asserted from either
|
||||
crate alone. The library still depends on `vlog_parser` + `vlog_semantic`
|
||||
alone (`cargo tree -p vlog_refactor -e normal`), and no cycle is possible:
|
||||
`vlog_formatter` depends on `vlog_parser` and nothing else.
|
||||
|
||||
## The LSP surface
|
||||
|
||||
| Surface | What it says |
|
||||
|---|---|
|
||||
| Code action, kind `refactor.rewrite.lucisv.ports` | *"lucisv: expand .* (3 connections)"* — offered at a `.*` under the cursor, lazily (`offers` → `resolve`, §37.1) or eagerly (`code_actions`), whichever the client supports. |
|
||||
| `lucisv.expandWildcard [uri, Position]` | The same edit for a client with no lightbulb — a Vim user's keybinding. |
|
||||
|
||||
The count is the connections the wildcard becomes, and it is exact in the
|
||||
offer already: the offer's file set (buffer + declaring file) is everything
|
||||
the expansion reads. It is written `1 connection` for one, which is why the
|
||||
plan's *"(N connections)"* is a shape rather than a literal.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 50.1 `expand_wildcard` engine (`ports/expand.rs`, 308 lines, 233 of
|
||||
them code) + every refusal above
|
||||
- [x] 50.1 the LRM kind rule, sharing one scope walk with `visible_in`
|
||||
- [x] 50.1 layout (multi-line vs inline) and the three comment positions
|
||||
- [x] 50.2 code action through the lazy offer path, with `is_sites_phrase`
|
||||
keeping the index from recounting its title — pinned at the level that
|
||||
matters rather than as a predicate unit test: the server test
|
||||
`the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit`
|
||||
asserts the offered title is `lucisv: expand .* (1 connection)` in a
|
||||
workspace whose instantiation census would have said something else,
|
||||
and the e2e session asserts the same string over the wire
|
||||
- [x] 50.2 `lucisv.expandWildcard` in `commands()` / `execute`
|
||||
- [x] 50.1 escaped identifiers terminated on both sides of the parens
|
||||
- [x] Tests: 32 behavior tests in `vlog_refactor/tests/expand.rs`, 1 corpus
|
||||
acceptance test in `tests/corpus.rs`, 3 in `lucisv_server`'s `ports.rs`,
|
||||
1 e2e session over the wire
|
||||
- [x] Gates: `cargo fmt` per crate, clippy `--all-targets` clean, the
|
||||
workspace suite, the corpus gate, byte-identity vs 0.45.0, the VS Code
|
||||
smoke test
|
||||
- [x] OpenTitan read-only census and ten scratch expansions
|
||||
- [ ] Deferred, deliberately: a `.*` inside a `bind` directive (refusal 3) —
|
||||
it needs the target's scope, which is elaboration, not lexical lookup.
|
||||
It is the *majority* of real wildcard sites in OpenTitan, so it is worth
|
||||
a backlog line of its own.
|
||||
- [ ] Deferred: the inverse refactoring (named connections → `.*`), which is
|
||||
§8's list, not this round's.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
`README.md`, `docs/topo.md`, `docs/repository-analysis.md` and `docs/site/`
|
||||
are the lead's; the text for them is here rather than edited in place.
|
||||
|
||||
**`README.md` — the refactoring list** gains a row beside
|
||||
"connect missing ports":
|
||||
|
||||
> | **expand `.*`** | Writes a wildcard connection out as the named
|
||||
> connections it stands for, in the module's declaration order — a port with
|
||||
> no same-named signal in scope becomes `.p()` and is named in a warning.
|
||||
> Code action at the `.*`, or `lucisv.expandWildcard`. |
|
||||
|
||||
**`docs/site/` (editors / language-tools page)** — the same sentence in the
|
||||
code-action list: *"expand `.*` — the wildcard connection written out as the
|
||||
`.p(p)` connections it stands for, so the port list can then diverge from the
|
||||
wrapper around it."*
|
||||
|
||||
**TODO.md §8** (the refactoring backlog): the `.*`-expansion line gains
|
||||
*"— shipped in 0.46.0, `docs/features/expand-wildcard/README.md`"*, and the
|
||||
list gains a new backlog entry: *"expand a `.*` written in a `bind` directive
|
||||
(needs the target's scope — elaboration, not lexical lookup)."*
|
||||
|
||||
**`docs/topo.md`**: one new edge to record — `vlog_refactor ──▶
|
||||
vlog_formatter` **(dev-dependency, tests only)**, the same shape §2's
|
||||
`vlog_linter ──▶ vlog_formatter` dev edge already has. No production edge
|
||||
changed.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — dev agent.** Built `ports/expand.rs`, the third `port_actions`
|
||||
offer, and the fourth command. The decisions worth recording:
|
||||
|
||||
- **A replacement, not an append plus a deletion.** `propagate_ports` was the
|
||||
obvious template, and it appends — but the `.*` has to *go*, and the
|
||||
cleanest expression of that is one `TextEdit` whose range is the element's
|
||||
own span. `check::pieces_match` already handles a replacement exactly (it
|
||||
skips old pieces overlapping a non-empty edit range and splices the edit's
|
||||
own pieces in at its start); `Shift::map` already handles the length change
|
||||
(`a_longer_replacement_shifts_forward` was written for it in M2). So the
|
||||
verifier needed nothing new, which is the outcome hard invariant 4 wants:
|
||||
no widening of anybody's forgiveness, no new attack surface to test.
|
||||
- **The comment rule fell out.** Because the edit's range is the element's
|
||||
*code* span, a comment before or after the `.*` is not inside it and is
|
||||
simply not touched; a comment *inside* it is, and the splice verifier's
|
||||
comment rule refuses the whole thing. Two of the three comment cases are
|
||||
therefore properties of the span choice rather than code, and the third is
|
||||
a refusal rather than a guess. The one piece of code is the
|
||||
comma-before-the-line-comment split, lifted verbatim from
|
||||
`append_to_list`'s reasoning.
|
||||
- **Parameters are the crux, and they get their own kind reader.** The LRM
|
||||
binds `.*` to a net or a variable. `find::visible_in` — the "may lucisv
|
||||
write `.p(p)` here" test the other two refactorings use — says yes to
|
||||
parameters, localparams, genvars and task arguments as well, and that is
|
||||
right *for them*: the user asked for a connection and a parameter is a legal
|
||||
expression. It is wrong here, where the question is what the wildcard
|
||||
already bound. Rather than adding a flag to `visible_in`, the scope walk was
|
||||
factored into `kind_visible_in` (which returns the kind) and each caller
|
||||
states its own set. Both readers therefore agree about which declaration a
|
||||
name means — the thing that must never diverge — and disagree only where
|
||||
they should.
|
||||
- **Two refusals stricter than `add_port`'s.** A file with a parse diagnostic,
|
||||
and a list carrying compiler directives, are *warnings* or read-throughs
|
||||
elsewhere in the ports engine. Here they are refusals, because this
|
||||
refactoring enumerates a whole port set rather than appending one element:
|
||||
a misread list connects a port twice, and an `` `ifdef``-split port list
|
||||
expands into a connection list no configuration ever had. Both are cheap to
|
||||
detect and impossible for the verifier to catch (the result parses, resolves
|
||||
and matches its shape — it is simply not what the source meant).
|
||||
- **`is_sites_phrase` was the one real surprise.** `ports::counted` in the
|
||||
server rewrites *any* offered title ending in `(…)` with the index's
|
||||
instantiation count, which would have turned "expand .* (3 connections)"
|
||||
into "expand .* (updates 5 instantiations)" — a wrong sentence produced by
|
||||
a function that had never been wrong before, because until now every title
|
||||
with a count carried the same count. The predicate lives next to
|
||||
`sites_phrase` in the engine so the phrase has one spelling and one reader.
|
||||
- **The bind refusal is not a corner case.** 24 of the 31 `.*` sites under
|
||||
OpenTitan's `hw/ip` are inside a `bind` directive. Refusing them is correct
|
||||
(§23.3.2.4 resolves those in the target's scope), and it is the reason the
|
||||
acceptance sample had to be drawn from a wider tree than `hw/ip` to reach
|
||||
ten — recorded in Acceptance and as a backlog line above.
|
||||
|
||||
Checks at the end are in Acceptance and in the gate list. No
|
||||
`unwrap`/`expect`/`panic!` and no `unsafe` in any library path (test modules
|
||||
only); `expand.rs` is 308 lines with no function over 45, and every file it
|
||||
touches stayed inside the size rule — `ports/mod.rs` 433, `ports/find.rs` 283,
|
||||
`lucisv_server/src/ports.rs` 1 430 of which 981 are its `#[cfg(test)]` module.
|
||||
|
||||
## Gates
|
||||
|
||||
All guarded (`tools/guard.sh`, 8 GB / 30 min defaults); no guard kill.
|
||||
|
||||
- **fmt**: `cargo fmt -p vlog_refactor`, `cargo fmt -p lucisv_server`;
|
||||
`cargo fmt --all -- --check` clean.
|
||||
- **clippy**: `cargo clippy --all-targets`, **0 warnings**, and no new
|
||||
`#[allow]` anywhere in the diff.
|
||||
- **suite**: `cargo test --workspace` — **3 876 passed, 0 failed, 44 ignored**
|
||||
across 50 test binaries (baseline 3 839, +37: 32 behavior, 1 corpus, 3
|
||||
server unit, 1 e2e).
|
||||
- **corpus gate**: `tools/corpus_check.sh` — **814/820 (99.3%)**, the same six
|
||||
known parse errors (`ibex` compare_helper / riscv_core_setting.tpl /
|
||||
latch_map.v / riscv_instr_cover_group, `picorv32` romload testbench /
|
||||
smtbmc mulcmp), **0 verification errors, 0 crashes**.
|
||||
- **formatter byte-identity**: `lucisv format --stdout` over all corpus files,
|
||||
this build vs `~/.cache/lucisv-baselines/lucisv-0.45.0` — **854 checked, 0
|
||||
differing**, 6 refused by both. `git diff` over `vlog_formatter`,
|
||||
`vlog_parser` and `verify.rs` is empty; this round touched neither.
|
||||
- **vsix smoke**: `node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 20 messages.
|
||||
- **opentitan after the round**: `git -C ~/repo/opentitan status --porcelain`
|
||||
shows only the three pre-existing modifications. Every run over it was
|
||||
read-only, and every edited copy went to the session scratchpad.
|
||||
|
||||
## Acceptance
|
||||
|
||||
### The corpus
|
||||
|
||||
`cargo test -p vlog_refactor --test corpus` gained
|
||||
`a_wildcard_expanded_in_the_corpus_is_something_the_formatter_accepts`: the
|
||||
first three corpus files with a `.*` are expanded into an in-memory copy and
|
||||
the copy must format, and formatting it twice must not move it. It expands
|
||||
`common_cells`' `cdc_2phase_clearable_tb.sv`, `cdc_2phase_synth.sv` and
|
||||
`cdc_2phase_tb.sv` (~2.4 s each in debug, the index build over 860 files) and
|
||||
refuses the three `formal/*_properties.sv` sites — every one of them a `bind`.
|
||||
|
||||
### OpenTitan (read-only)
|
||||
|
||||
Counted with the plan's grep and with the engine's own scan, which also sees a
|
||||
`.*` whose `,`/`)` is on the next line:
|
||||
|
||||
| Tree | Files | `.*` sites | Expanded | Refused |
|
||||
|---|---|---|---|---|
|
||||
| `hw/ip` | 1 807 | **31** (29 by line-based grep) | 7 | 24, every one a `bind` |
|
||||
| `hw` (all of OpenTitan's Verilog) | 3 979 | **66** | **9** | 57: **50** `bind`, **6** `pinmux` declared in three tops, **1** `ibex_top`'s `` `ifdef``-split port list |
|
||||
|
||||
**Deviation from the plan, stated plainly: ten expandable sites do not
|
||||
exist.** The plan asked for ten scratch expansions; OpenTitan holds nine.
|
||||
Every `.sv`/`.svh`/`.v` file in the repository is under `hw/` (checked), and
|
||||
of its 66 wildcard sites, 57 are refused — 50 of them by the `bind` rule,
|
||||
which is correct and is the backlog line above. So the sample is **all nine**
|
||||
of them rather than a chosen ten, plus the three corpus expansions in the test
|
||||
suite: twelve real-world expansions, all verified the same way. Each of the
|
||||
seven refusal categories that fired did so for a reason on the list, including
|
||||
two the synthetic tests could only fake: `pinmux` really is declared three
|
||||
times in OpenTitan (one per top), and `ibex_top`'s port list really is split
|
||||
across `` `ifdef`` arms.
|
||||
|
||||
Every expansion was written to a **copy** under the session scratchpad;
|
||||
nothing was written into `/Users/guoliangchen/repo/opentitan`, and
|
||||
`git -C … status --porcelain` shows the same three pre-existing modifications
|
||||
before and after (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
Each of the nine: the copy parses with **zero** diagnostics, formats, formats
|
||||
again to the same bytes, and holds the **same instance count** as the
|
||||
original. Two of them carry a warning, and both are real findings rather than
|
||||
lucisv guessing:
|
||||
|
||||
- `kmac/fpv/tb/sha3_fpv.sv` — `u_sha3`'s `.*` covers nine ports of `sha3`
|
||||
(`rand_update_o`, `squeezing_o`, `block_processed_o`, `run_req_o`,
|
||||
`run_ack_i`, `lc_escalate_en_i`, `sparse_fsm_error_o`, `count_error_o`,
|
||||
`keccak_storage_rst_error_o`) that the FPV wrapper's own header does not
|
||||
declare. The wrapper has drifted behind the module it wraps; the wildcard
|
||||
was hiding it, and the expansion says so.
|
||||
- `kmac/fpv/tb/sha3pad_fpv.sv` — the same story for `u_keccak`, five ports.
|
||||
|
||||
The five `aes/dv/err_injection_if/fi_*_wrapper.sv` expansions are the
|
||||
textbook case: `fi_core_if fi_if (.*)` becomes
|
||||
`fi_core_if fi_if (.clk_i(clk_i), .rst_ni(rst_ni), .aes_ctrl_cs(aes_ctrl_cs))`.
|
||||
The last two are `vendor/lowrisc_ibex`'s icache agent interfaces.
|
||||
|
||||
Reproduced by a throwaway probe binary in the session scratchpad
|
||||
(`otprobe`), which depends on `vlog_refactor` + `vlog_formatter` +
|
||||
`vlog_parser` by path, walks a tree read-only, and writes every edited copy
|
||||
into the scratchpad. Nothing of it is checked in.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 — QA agent.** Attacked the engine directly
|
||||
(`vlog_refactor::expand_wildcard`, temporary `#[test]`s added and removed —
|
||||
`tests/zz_qa_expand_attack.rs`, `tests/zz_qa_corpus_sweep.rs`, never
|
||||
committed) plus the shipped suites, the two full-workspace gates, a
|
||||
full-`hw/` opentitan census (not just the plan's ten), and a diff of every
|
||||
opentitan scratch expansion against its original. Verdict: **PASS**.
|
||||
|
||||
### LRM-rule matrix (18 scratch tests, all against a fresh build)
|
||||
|
||||
| # | Case | Result |
|
||||
|---|---|---|
|
||||
| enclosing module's own port | binds (`.clk(clk)`) | as specified |
|
||||
| typedef of the same name | not bound, `.done()` + warning | as specified |
|
||||
| instance name of the same name | not bound, `.done()` + warning | as specified |
|
||||
| instantiation lexically inside a function body | no panic (refusal or edit, either is fine — the plan only asks for no crash) | no crash |
|
||||
| sibling generate block's declaration | not visible, `.done()` + warning | as specified |
|
||||
| declared *after* the instantiation, module scope | still visible and bound | as specified — declaration order does not matter |
|
||||
| `import pkg::*` bringing a same-named package variable into scope | **not bound** — `.name()` + warning, exactly as an unrelated name would be | matches the README's stated assumption, see below |
|
||||
| port name shared by both the instantiated and enclosing module | binds (the common case) | as specified |
|
||||
| width/type mismatch (`input logic [7:0] clk` vs a 1-bit `clk` in scope) | still binds by name, no warning | as specified — lucisv cannot check types, README says so |
|
||||
| interface port (`bus_if.master b`, interface instance `bus_if b()` of the same name) | **not bound** — `.b()` + warning | see finding QA-1 below |
|
||||
| escaped port name `\my-port` | bound and terminated on both sides of the parens (`.\my-port (\my-port )`), and unbound the same way | dev's own tests, re-verified |
|
||||
| port with an unpacked dimension (`input logic [7:0] data [4]`) | binds (`.data(data)`) | as specified |
|
||||
|
||||
None of the eighteen attack tests found a mis-binding (an output silently
|
||||
tied to a parameter, a genvar, a typedef, an instance, or anything else the
|
||||
LRM does not call a signal) or a crash. Two are worth recording explicitly:
|
||||
|
||||
- **The package-import choice, pinned.** A name reaching the instantiating
|
||||
scope only through `import pkg::*;` is read as **not in scope**: `.*`
|
||||
writes `.name()` and warns, exactly as if the name did not exist anywhere.
|
||||
Traced to source: `kind_visible_in`
|
||||
(`crates/vlog_refactor/src/ports/find.rs:214-253`) walks
|
||||
`Scope::lookup_local` up the `parent` chain only, and never reads
|
||||
`Scope.imports` — the second, separate lookup
|
||||
`vlog_semantic::resolve::{lexical, unit}` perform to make a wildcard
|
||||
import's names resolvable for *reference* resolution
|
||||
(`crates/vlog_semantic/src/resolve.rs:607-684`). So `vlog_semantic`'s own
|
||||
full resolver *can* see a wildcard-imported name; `kind_visible_in`
|
||||
deliberately (per the README's Assumptions section) does not re-implement
|
||||
that half of it. This matches the feature's stated assumption
|
||||
word-for-word ("a name that would come from a wildcard package import
|
||||
lucisv cannot resolve reads as *not in scope*") — **not a defect**, a
|
||||
documented, safe-by-construction limitation: it under-expands (leaves a
|
||||
port unconnected and says so) rather than mis-expands. Filing it here
|
||||
because the plan asked to "pin it and report the choice."
|
||||
- **QA-1 (LOW, pre-existing, not introduced by this round): interface
|
||||
instances are never a `.*` target.** `bus_if b(); sub u_sub(.*)` where
|
||||
`sub` declares `bus_if.master b` leaves `.b()` unconnected with a warning,
|
||||
even though the interface instance `b` is exactly the identifier IEEE 1800
|
||||
§23.3.2.4 means to bind an interface port to. Root cause: an interface
|
||||
instantiation gets `SymbolKind::Instance`
|
||||
(`crates/vlog_semantic/src/bind/item.rs:306`, the same kind a module
|
||||
instantiation gets — interfaces are modeled as `Module`s with a different
|
||||
keyword), and `signal_visible`'s allowed set
|
||||
(`crates/vlog_refactor/src/ports/expand.rs:266-270`) is `Net | Var | Port`
|
||||
only. This is not new: `find::visible_in`, which `add_port` and
|
||||
`propagate_ports` already share, excludes `Instance` from its own allowed
|
||||
set too (`crates/vlog_refactor/src/ports/find.rs:203-217`), so no port
|
||||
refactoring in the engine today treats an interface instance as a
|
||||
connectable signal by name. Nothing in this round narrowed that — it is
|
||||
inherited, and it fails safe (unconnected + warned, never mis-bound) — but
|
||||
it means every interface-port wildcard site in a design is likely to
|
||||
surface a spurious warning rather than a clean bind. Worth a backlog line
|
||||
for the ports engine generally, not a blocker for §50.
|
||||
|
||||
### Text/layout and refusals
|
||||
|
||||
Re-verified against source and by test: trailing-comma legality (no result
|
||||
ever ends `,)` or has a dangling comma before a line comment), idempotency
|
||||
(expanding the result a second time refuses with the exact "writes no `.*`
|
||||
to expand" sentence; formatting twice converges; re-expanding the *formatted*
|
||||
result also correctly refuses), comment-count preservation, `#(...)`
|
||||
parameterized instantiations, and a cursor placed inside one instance of a
|
||||
two-instance statement (`sub u_a (.*), u_b (.*);`) expanding only that
|
||||
instance rather than tripping the "declares 2 instances" refusal — confirmed
|
||||
this refusal fires only when the cursor is on the shared module name/keyword,
|
||||
matching `propagate_ports`'s documented rule. All eleven refusal sentences
|
||||
in the README's list were exercised (by the dev's own 32-test suite, which
|
||||
this session re-ran clean) and match character-for-character.
|
||||
|
||||
**Server, cursor away from the `.*`:** a cursor placed on `.clk(clk)` inside
|
||||
the *same* instantiation as a `.*` still offers `lucisv: expand .* (2
|
||||
connections)` — the cursor rule is instance-level (any offset inside the
|
||||
instance's span), not token-level, matching `propagate_ports`'s and
|
||||
`remove_port`'s own precedent. This is not a bug: the plan's "only the port
|
||||
actions that apply" is satisfied — every offered action is one that would
|
||||
actually succeed at that instance, and none is limited to the exact `.*`
|
||||
token by design elsewhere in the engine either.
|
||||
|
||||
### Corpus (full sweep, not a sample)
|
||||
|
||||
Independently re-implemented the dev's own `.*` census (a `.*` followed by
|
||||
`,`/`)`, matching the engine's own scan rather than a naïve line grep) and
|
||||
ran it over every corpus file, not just the first three the dev's acceptance
|
||||
test samples: **21 sites, 11 expanded, 10 refused** — 6 `bind` directives, 2
|
||||
"declared in more than one indexed file" (`formal_tb`, genuinely declared
|
||||
twice under `corpus/ibex/formal/`), 1 compiler-directives-in-the-port-list
|
||||
(`ibex_top`), 1 "no module instantiation at this position" (a `.*` mentioned
|
||||
inside a *comment* in `formal_tb_frag.svh`, correctly refused rather than
|
||||
corrupting anything). Every one of the 11 expansions: same instance count
|
||||
before/after, zero parse diagnostics afterward, formats, and converges on a
|
||||
second format. No panics anywhere in the sweep (38.7 s under
|
||||
`tools/guard.sh`, no kill).
|
||||
|
||||
### OpenTitan (read-only, full `hw/`, not a ten-site sample)
|
||||
|
||||
Reproduced independently with a throwaway probe (`otqa`, path-dependent on
|
||||
`vlog_refactor`/`vlog_formatter`/`vlog_parser`, built and run under
|
||||
`tools/guard.sh -m 8 -t 600`, nothing checked in): **66 sites, 9 expanded, 57
|
||||
refused (50 bind, 6 declared-twice/pinmux, 1 compiler-directives/`ibex_top`)
|
||||
— exactly the dev's table.** `git -C ~/repo/opentitan status --porcelain`
|
||||
showed only the three pre-existing modifications both before and after.
|
||||
|
||||
Diffed each of the nine scratch expansions against its opentitan original:
|
||||
**every diff touches only the `.*` element** — one line replaced for the
|
||||
seven simple sites (the five `fi_*_wrapper.sv` interfaces plus the two
|
||||
`ibex_icache_*_if.sv` checkers), a multi-line replacement confined to the
|
||||
`u_sha3`/`u_keccak` instantiation block for the two FPV files. Nothing else
|
||||
in any of the nine files changed.
|
||||
|
||||
Verified the two FPV warnings are real, not lucisv guessing: grepped
|
||||
`hw/ip/kmac/rtl/sha3.sv`'s port list and confirmed all nine names in
|
||||
`sha3_fpv.sv`'s warning (`rand_update_o`, `squeezing_o`, `block_processed_o`,
|
||||
`run_req_o`, `run_ack_i`, `lc_escalate_en_i`, `sparse_fsm_error_o`,
|
||||
`count_error_o`, `keccak_storage_rst_error_o`) are genuine output/input ports
|
||||
of `sha3` absent from `sha3_fpv`'s own header; same check against
|
||||
`hw/ip/kmac/rtl/keccak_round.sv` for `sha3pad_fpv.sv`'s five
|
||||
(`rand_update_o`, `lc_escalate_en_i`, `sparse_fsm_error_o`,
|
||||
`round_count_error_o`, `rst_storage_error_o`). Both wrappers have genuinely
|
||||
drifted behind the modules they wrap.
|
||||
|
||||
### Gates (guarded, re-run independently)
|
||||
|
||||
- `cargo clippy -p vlog_refactor -p lucisv_server --all-targets` — **0
|
||||
warnings**; `cargo clippy --all-targets` over the whole workspace also
|
||||
clean.
|
||||
- `cargo fmt -p vlog_refactor -p lucisv_server -- --check` and
|
||||
`cargo fmt --all -- --check` — clean.
|
||||
- `tools/guard.sh -t 1800 -- cargo test --workspace` — **3 876 passed, 0
|
||||
failed, 44 ignored**, 50 test binaries — matches the dev's number exactly.
|
||||
No guard kill.
|
||||
- `tools/guard.sh -t 900 -- tools/corpus_check.sh` — **814/820 (99.3%)
|
||||
parsed & formattable, 0 verification errors, 0 crashes**, same six known
|
||||
parse errors — matches exactly.
|
||||
- Byte-identity: `lucisv format --stdout` over every corpus file, this build
|
||||
vs `~/.cache/lucisv-baselines/lucisv-0.45.0` — **860 total, 854 checked
|
||||
identical, 0 differing, 6 refused by both** — matches exactly.
|
||||
- `node editors/vscode/smoke.js target/release/lucisv-server` — OK, 20
|
||||
messages.
|
||||
|
||||
### Findings
|
||||
|
||||
- **QA-1 (LOW, informational, not a blocker):** interface instances are
|
||||
never bound by `.*` (nor writable by `add_port`/`propagate_ports`) because
|
||||
`SymbolKind::Instance` is outside every port refactoring's allowed-kind
|
||||
set. Pre-existing across the ports engine, not introduced by §50; fails
|
||||
safe (unconnected + warned). Suggest a backlog line for the ports engine
|
||||
generally: "an interface instance of the same name as an interface port
|
||||
should bind, per IEEE 1800 §23.3.2.4."
|
||||
- **Package-import scope choice — verified as documented, not a defect.**
|
||||
See the matrix above; matches the README's Assumptions section exactly.
|
||||
- No corruption, no dropped comments, no panics, no idempotency break, no
|
||||
byte-identity regression found in any of the above. All temporary test
|
||||
files and scratch copies were removed after verification; the repository
|
||||
tree touched by this QA pass is unchanged apart from this log entry and
|
||||
the §50 QA checkbox in `TODO.md`.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.46.0 with §51. The engine is
|
||||
one replacement edit through the ports engine's existing splice and
|
||||
verifier, which is exactly the shape a lexical refactoring should have,
|
||||
and the LRM rule is read strictly — a parameter or genvar of the same name
|
||||
does not bind, which is what the compiler would say. The refusal list is
|
||||
complete and each refusal is a sentence. The dev found and fixed a real
|
||||
title-rewrite bug in the lazy offer path on the way (`counted` rewrote
|
||||
any parenthesised title). Ten expandable opentitan sites do not exist —
|
||||
57 of the 66 `.*` sites are inside `bind` directives, which need the
|
||||
target's scope and are filed as a backlog entry — so the nine that do
|
||||
exist were all expanded and verified, and two of them surfaced real
|
||||
drift between an FPV wrapper and the module it wraps. The vlog_formatter
|
||||
dev-dependency mirrors the linter's and is recorded in topo.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<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`:
|
||||
|
||||
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.
|
||||
@@ -21,6 +21,9 @@ hour. Record the release, the date and any failure in the table at the end.
|
||||
| 12 | Old server: point `lucisv.server.path` at `~/.cache/lucisv-baselines/lucisv-0.39.0`'s sibling server if kept, else skip. | Extension warns about the version mismatch and still works. Reset the setting. |
|
||||
| 13 | The other VSIX shape: install the `lucisv-<v>-universal.vsix` (no bundled server) with the CLI on PATH. | Same behaviour as steps 1–5. |
|
||||
| 14 | Restart the server (command palette: "lucisv: Restart Server"). | Diagnostics return within a few seconds; no duplicate status items. |
|
||||
| 15 | Hierarchy pane: right-click `aes` → "Star as DUT". | Three sections: "DUT: aes" (open, `aes` and its five children), "Parents of aes" (open, `aes` above `aes_tb`, `aes_wrap`, `tb`), "Other modules" (closed, 297 roots — the 292 plain ones plus the five `aes_tb` held beside `aes`, re-rooted). Right-click `aes` again → "Unstar DUT" puts the plain tree back exactly as it was. |
|
||||
| 16 | Star `aes`, then `hmac`. | Five sections in that order; "Other modules" has 297 roots; each section opens and closes on its own; a module under both keeps its own open state in each. Title bar "Clear DUTs" removes both. |
|
||||
| 17 | Add `"lucisv.hierarchy.duts": ["aes"]` to the workspace `.vscode/settings.json`. | The section appears without starring; right-clicking `aes` offers only a greyed "DUT from settings" whose tooltip names the setting; "Clear DUTs" leaves it. Remove the setting again. |
|
||||
|
||||
## Runs
|
||||
|
||||
|
||||
+10
-1
@@ -73,8 +73,17 @@
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vs-code" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">VS Code</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#neovim-011" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Neovim 0.11+</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#workspace-indexing" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Workspace indexing</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#smoke-test" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Smoke test</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vs-code" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">VS Code</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#neovim-011" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Neovim 0.11+</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#workspace-indexing" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Workspace indexing</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#smoke-test" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Smoke test</span></a></li></ul></nav></starlight-toc><script type="module" src="/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js"></script></div></div></div></aside><div class="main-pane astro-abfeecmu"><main data-pagefind-body class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><h1 id="_top" class="astro-2sm4b3ln">Editors & LSP</h1></div></div><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><div class="sl-markdown-content"><p><code dir="auto">lucisv-server</code> is a synchronous language server over stdio. It keeps open buffers as in-memory overlays, updates the workspace index incrementally, and returns the same formatting and lint behaviLine truncated
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="vs-code">VS Code</h2><a class="sl-anchor-link" href="#vs-code"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “VS Code”</span></a></div>
|
||||
<p>Install the <code dir="auto">.vsix</code> attached to a lucisv release:</p>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">code</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--install-extension</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">lucisv-0.9.0.vsix</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="code --install-extension lucisv-0.9.0.vsix"><div></div></button></div></figure></div>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame is-terminal not-content"><figcaption class="header"><span class="title"></span><span class="sr-only">Terminal window</span></figcaption><pre data-language="bash"><code><div class="ec-line"><div class="code"><span style="--0:#82AAFF;--1:#3B61B0">code</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#82AAFF;--1:#3B61B0">--install-extension</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#ECC48D;--1:#3B61B0">lucisv-<version>-darwin-arm64.vsix</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#919F9F;--1:#5F636F"># or the linux/windows package for your machine</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="code --install-extension lucisv-<version>-darwin-arm64.vsix # or the linux/windows package for your machine"><div></div></button></div></figure></div>
|
||||
<p>The extension registers Verilog/SystemVerilog file types, syntax highlighting, snippets, color settings, configuration, and starts <code dir="auto">lucisv-server</code> from <code dir="auto">PATH</code> by default.</p>
|
||||
<p><strong>DUT-centred hierarchy.</strong> Right-click a module in the Hierarchy pane and
|
||||
choose <strong>Star as DUT</strong>. The pane splits into sections: the DUT with its
|
||||
children, the DUT’s parents (an upward tree through everything that
|
||||
instantiates it — usually the testbench), and all other modules, re-rooted
|
||||
where their only parents are the DUT’s ancestors. Star a second DUT and you
|
||||
get five sections. Unstar from the same menu, or clear every DUT from the
|
||||
pane’s title bar. Starred DUTs are remembered per workspace; a team can also
|
||||
check them in with <code dir="auto">"lucisv.hierarchy.duts": ["aes", "hmac"]</code>, and DUTs that
|
||||
come from the setting are shown locked.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="neovim-011">Neovim 0.11+</h2><a class="sl-anchor-link" href="#neovim-011"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Neovim 0.11+”</span></a></div>
|
||||
<div class="expressive-code"><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="lua"><code><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">vim</span><span style="--0:#D6DEEB;--1:#403F53">.filetype.</span><span style="--0:#C5E478;--1:#3B61B0">add</span><span style="--0:#D6DEEB;--1:#403F53">({ </span><span style="--0:#C5E478;--1:#3B61B0">extension</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> {</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">v</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">verilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#C5E478;--1:#3B61B0">vh</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">verilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">,</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">sv</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">systemverilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#C5E478;--1:#3B61B0">svh</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">systemverilog</span><span style="--0:#D9F5DD;--1:#111111">'</span></div></div><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">} })</span></div></div><div class="ec-line"><div class="code">
|
||||
</div></div><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">vim</span><span style="--0:#D6DEEB;--1:#403F53">.lsp.</span><span style="--0:#C5E478;--1:#3B61B0">config</span><span style="--0:#D6DEEB;--1:#403F53">(</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, {</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">cmd</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> { </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv-server</span><span style="--0:#D9F5DD;--1:#111111">' </span><span style="--0:#D6DEEB;--1:#403F53">},</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">filetypes</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> { </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">verilog</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">systemverilog</span><span style="--0:#D9F5DD;--1:#111111">' </span><span style="--0:#D6DEEB;--1:#403F53">},</span></div></div><div class="ec-line"><div class="code"><span class="indent"> </span><span style="--0:#C5E478;--1:#3B61B0">root_markers</span><span style="--0:#D6DEEB;--1:#403F53"> </span><span style="--0:#7FDBCA;--1:#096E72">=</span><span style="--0:#D6DEEB;--1:#403F53"> { </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv.toml</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">.lucisv.toml</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">, </span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">.git</span><span style="--0:#D9F5DD;--1:#111111">' </span><span style="--0:#D6DEEB;--1:#403F53">},</span></div></div><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">})</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">vim</span><span style="--0:#D6DEEB;--1:#403F53">.lsp.</span><span style="--0:#C5E478;--1:#3B61B0">enable</span><span style="--0:#D6DEEB;--1:#403F53">(</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#ECC48D;--1:#984E4D">lucisv</span><span style="--0:#D9F5DD;--1:#111111">'</span><span style="--0:#D6DEEB;--1:#403F53">)</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="vim.filetype.add({ extension = { v = 'verilog', vh = 'verilog', sv = 'systemverilog', svh = 'systemverilog'} })vim.lsp.config('lucisv', { cmd = { 'lucisv-server' }, filetypes = { 'verilog', 'systemverilog' }, root_markers = { 'lucisv.toml', '.lucisv.toml', '.git' },})vim.lsp.enable('lucisv')"><div></div></button></div></figure></div>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_8310bcd6c3","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_ccc426eeeb","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
Binary file not shown.
Binary file not shown.
+1
-1
@@ -188,4 +188,4 @@ surface for instance paths; it is still under QA and is not a released API.</p>
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="release-surface">Release surface</h2><a class="sl-anchor-link" href="#release-surface"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Release surface”</span></a></div>
|
||||
<p>The supported publication surface is seven VS Code <code dir="auto">.vsix</code> packages plus checksums: five platform packages (Apple Silicon/Intel macOS, x86-64/ARM64 static-musl Linux, Windows), one all-platform package, and one universal package requiring binaries on <code dir="auto">PATH</code>. Both <code dir="auto">lucisv</code> and <code dir="auto">lucisv-server</code> are bundled in platform packages. Standalone binaries are built by the tooling but are not published as release assets. The release tooling audits file type, dynamic linkage, and the glibc ceiling for cross-built artifacts.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/architecture.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rust-api/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/architecture.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rust-api/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+1
-1
@@ -277,4 +277,4 @@ remains an error.</p>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>An error outranks “would change.” Every file involved in an error is left untouched.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/cli.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T05:03:07.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/syntax/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Supported syntax</span></span></a><a href="/reference/rules/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/cli.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/syntax/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Supported syntax</span></span></a><a href="/reference/rules/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+12
-2
@@ -289,7 +289,17 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
<tr>
|
||||
<td>Port actions</td>
|
||||
<td>code actions / commands</td>
|
||||
<td>Adds, removes, and propagates module ports</td>
|
||||
<td>Adds, removes, and propagates module ports; expands a <code dir="auto">.*</code> wildcard into the named connections it stands for (a port with no same-named signal in scope becomes <code dir="auto">.p()</code> and is named in a warning) — <code dir="auto">lucisv.expandWildcard</code>; 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 — <code dir="auto">lucisv.convertToAnsi</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Organize imports</td>
|
||||
<td>code action (<code dir="auto">source.organizeImports</code>) / command</td>
|
||||
<td>Removes the <code dir="auto">import pkg::*;</code> 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 — <code dir="auto">lucisv.organizeImports</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Extract module</td>
|
||||
<td>code action (<code dir="auto">refactor.extract</code>) / command</td>
|
||||
<td>Select whole module items and name the module: ports and parameters inferred from what the selection reads and drives, <code dir="auto">import</code>s carried across, the items moved byte for byte, the replacing instantiation rendered from the new module’s own text; a new file where the editor can create one, below the source module otherwise. Refuses with a sentence wherever a direction cannot be known — <code dir="auto">lucisv.extractModule</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Instantiate module</td>
|
||||
@@ -342,4 +352,4 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
</table>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="workspace-lifecycle">Workspace lifecycle</h2><a class="sl-anchor-link" href="#workspace-lifecycle"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Workspace lifecycle”</span></a></div>
|
||||
<p>The server handles <code dir="auto">didOpen</code>, incremental <code dir="auto">didChange</code>, <code dir="auto">didSave</code>, <code dir="auto">didClose</code>, 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.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-06T04:04:14.000Z">Sep 6, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+11
-2
@@ -70,7 +70,7 @@
|
||||
})();
|
||||
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#always-comb-blocking" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">always-comb-blocking</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#always-ff-non-blocking" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">always-ff-non-blocking</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#case-missing-default" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">case-missing-default</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#empty-item" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">empty-item</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#enum-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">enum-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#explicit-parameter-storage-type" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">explicit-parameter-storage-type</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#module-filename" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">module-filename</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#module-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">module-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#multiply-driven" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">multiply-driven</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#no-tabs" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">no-tabs</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#no-trailing-whitespace" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">no-trailing-whitespace</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#parameter-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">parameter-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#struct-union-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">struct-union-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#undriven-net" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">undriven-net</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#unused-signal" style="--depth: 0;" claLine truncated
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#always-comb-blocking" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">always-comb-blocking</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#always-ff-non-blocking" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">always-ff-non-blocking</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#case-missing-default" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">case-missing-default</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#empty-item" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">empty-item</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#enum-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">enum-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#explicit-parameter-storage-type" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">explicit-parameter-storage-type</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#module-filename" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">module-filename</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#module-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">module-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#multiply-driven" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">multiply-driven</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#no-tabs" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">no-tabs</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#no-trailing-whitespace" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">no-trailing-whitespace</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#parameter-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">parameter-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#struct-union-name-style" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">struct-union-name-style</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#undriven-net" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">undriven-net</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#unused-signal" style="--depth: 0;" claLine truncated
|
||||
<p>Every rule is in one of three <strong>severity</strong> classes. <code dir="auto">error</code> is code that would very likely fail to compile, elaborate or synthesize; <code dir="auto">warning</code> is code that compiles and very likely does not mean what it says; <code dir="auto">style</code> is code that is correct and reads badly. The class is the word in the CLI diagnostic line (<code dir="auto">FILE:LINE:COL: warning: …</code>), the <code dir="auto">severity</code> field of <code dir="auto">--output-format json</code>, and the colour of the editor’s squiggle — and it is accepted wherever a rule name is, so <code dir="auto">--ignore style</code> and <code dir="auto">--select error</code> both work.</p>
|
||||
<p>Every <code dir="auto">error</code>-class rule is held to one discipline: it goes <strong>silent whenever the run cannot answer</strong> — 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 <code dir="auto"> `include</code>d. A wrong accusation in that class is worse than a hundred missed ones.</p>
|
||||
<p>This page is hand-written prose. The generated truth is <code dir="auto">lucisv check --rules-doc</code>, which prints every rule with its class, default, fix and rationale straight from the registry — <strong>and every option a rule takes, with its kind and default</strong>.</p>
|
||||
@@ -454,6 +454,13 @@
|
||||
<td>Remove ineffective suppressions</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="#unused-import"><code dir="auto">unused-import</code></a></td>
|
||||
<td style="text-align: center">style</td>
|
||||
<td style="text-align: center">off</td>
|
||||
<td style="text-align: center">safe</td>
|
||||
<td>Remove an <code dir="auto">import</code> nothing in the scope reaches through</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="#void-cast"><code dir="auto">void-cast</code></a></td>
|
||||
<td style="text-align: center">warning</td>
|
||||
<td style="text-align: center">on</td>
|
||||
@@ -634,6 +641,8 @@
|
||||
<p>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.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="unused-waiver">unused-waiver</h2><a class="sl-anchor-link" href="#unused-waiver"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “unused-waiver”</span></a></div>
|
||||
<p>Reports malformed, unknown, or ineffective waiver comments when their target rule is enabled. A waiver for a disabled rule is not judged.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="unused-import">unused-import</h2><a class="sl-anchor-link" href="#unused-import"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “unused-import”</span></a></div>
|
||||
<p>An <code dir="auto">import pkg::*;</code> or <code dir="auto">import pkg::item;</code> 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 <code dir="auto">pkg::y</code> does not use the import; an <code dir="auto">export pkg::…</code> in the same package does (a package may only re-export what it imported, IEEE 1800 §26.6). <strong>Off by default, and silent without a project</strong>: 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 <code dir="auto">import</code> line; the <code dir="auto">Organize imports</code> code action does the same and also merges duplicates and sorts the run.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="wire-reg-mixup">wire-reg-mixup</h2><a class="sl-anchor-link" href="#wire-reg-mixup"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “wire-reg-mixup”</span></a></div>
|
||||
<p>Reports <code dir="auto">reg</code> in <code dir="auto">.sv</code> and <code dir="auto">.svh</code> files and recommends <code dir="auto">logic</code>. Verilog <code dir="auto">.v</code>/<code dir="auto">.vh</code> files and unnamed stdin are exempt; <code dir="auto">wire</code> remains valid and is never flagged.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="duplicate-declaration">duplicate-declaration</h2><a class="sl-anchor-link" href="#duplicate-declaration"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “duplicate-declaration”</span></a></div>
|
||||
@@ -748,4 +757,4 @@
|
||||
<p>Reports a <code dir="auto">;</code> written after a <code dir="auto">`uvm_*</code> macro invocation. The macros expand to a <code dir="auto">begin … end</code>, so the <code dir="auto">;</code> is a null statement — usually inert, and not after <code dir="auto">if (x) </code>uvm_info(…); else …<code dir="auto">, where the </code>else<code dir="auto">then belongs to nothing. Off by default in both, because the semicolon is written everywhere in existing UVM code. No fix: deleting it is exactly the edit that is unsafe in the shape the rule exists for. Verible's</code>uvm-macro-semicolon`, same default.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="v2001-generate-begin">v2001-generate-begin</h2><a class="sl-anchor-link" href="#v2001-generate-begin"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “v2001-generate-begin”</span></a></div>
|
||||
<p>Reports a bare <code dir="auto">begin … end</code> written directly inside a <code dir="auto">generate … endgenerate</code> with no <code dir="auto">if</code>, <code dir="auto">for</code> or <code dir="auto">case</code> around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same recovered block <code dir="auto">module-begin-block</code> reads, one scope in. Verible’s <code dir="auto">v2001-generate-begin</code>, same default.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rules.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/cli/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a><a href="/reference/language-tools/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rules.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-06T01:00:31.000Z">Sep 6, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/cli/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a><a href="/reference/language-tools/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+1
-1
@@ -654,4 +654,4 @@ a codec-version decision so stale caches cannot silently omit answers.</p>
|
||||
</tbody>
|
||||
</table>
|
||||
<aside aria-label="Types" class="starlight-aside starlight-aside--note"><p class="starlight-aside__title" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="starlight-aside__icon"><path d="M12 11a1 1 0 0 0-1 1v4a1 1 0 0 0 2 0v-4a1 1 0 0 0-1-1Zm.38-3.92a1 1 0 0 0-.76 0 1 1 0 0 0-.33.21 1.15 1.15 0 0 0-.21.33 1 1 0 0 0 .21 1.09c.097.088.209.16.33.21A1 1 0 0 0 13 8a1.05 1.05 0 0 0-.29-.71 1 1 0 0 0-.33-.21ZM12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 18a8 8 0 1 1 0-16.001A8 8 0 0 1 12 20Z"/></svg>Types</p><div class="starlight-aside__content"><p>The crates also expose their data models—AST nodes, diagnostics, rule traits, workspace identifiers, edits, plans, and formatter document nodes. This page intentionally indexes callable behavior; generated Rust API docs remain the right place for field-level type details.</p></div></aside>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rust-api.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/language-tools/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a><a href="/reference/architecture/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Architecture</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rust-api.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/language-tools/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a><a href="/reference/architecture/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Architecture</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+1
-1
@@ -303,4 +303,4 @@ re-arms logging for newly introduced mistakes. An empty editor selection is
|
||||
the fallback sentinel, so it does not clear a non-empty project selection.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="cache">Cache</h2><a class="sl-anchor-link" href="#cache"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Cache”</span></a></div>
|
||||
<p>Successful “already formatted” verdicts are cached under <code dir="auto">.lucisv_cache/</code>. Entries are keyed by file, content hash, line length, indentation, and lucisv version. Files that would change or fail are never cached. Use <code dir="auto">--no-cache</code> to disable reads and writes or <code dir="auto">--cache-dir</code> to relocate the store.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/start/configuration.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T06:45:48.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/quick-start/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Quick start</span></span></a><a href="/guides/formatter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/start/configuration.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/quick-start/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Quick start</span></span></a><a href="/guides/formatter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
@@ -10,11 +10,21 @@ description: Set up lucisv-server in VS Code, Neovim, Vim, and other Language Se
|
||||
Install the `.vsix` attached to a lucisv release:
|
||||
|
||||
```bash
|
||||
code --install-extension lucisv-0.9.0.vsix
|
||||
code --install-extension lucisv-<version>-darwin-arm64.vsix # or the linux/windows package for your machine
|
||||
```
|
||||
|
||||
The extension registers Verilog/SystemVerilog file types, syntax highlighting, snippets, color settings, configuration, and starts `lucisv-server` from `PATH` by default.
|
||||
|
||||
**DUT-centred hierarchy.** Right-click a module in the Hierarchy pane and
|
||||
choose **Star as DUT**. The pane splits into sections: the DUT with its
|
||||
children, the DUT's parents (an upward tree through everything that
|
||||
instantiates it — usually the testbench), and all other modules, re-rooted
|
||||
where their only parents are the DUT's ancestors. Star a second DUT and you
|
||||
get five sections. Unstar from the same menu, or clear every DUT from the
|
||||
pane's title bar. Starred DUTs are remembered per workspace; a team can also
|
||||
check them in with `"lucisv.hierarchy.duts": ["aes", "hmac"]`, and DUTs that
|
||||
come from the setting are shown locked.
|
||||
|
||||
## Neovim 0.11+
|
||||
|
||||
```lua
|
||||
|
||||
@@ -68,7 +68,9 @@ 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 |
|
||||
| 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` |
|
||||
| Extract module | code action (`refactor.extract`) / command | Select whole module items and name the module: ports and parameters inferred from what the selection reads and drives, `import`s carried across, the items moved byte for byte, the replacing instantiation rendered from the new module's own text; a new file where the editor can create one, below the source module otherwise. Refuses with a sentence wherever a direction cannot be known — `lucisv.extractModule` |
|
||||
| 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 |
|
||||
|
||||
@@ -3,7 +3,7 @@ title: Lint rules
|
||||
description: Complete reference for every lucisv lint rule, its severity, default, fix, and rationale.
|
||||
---
|
||||
|
||||
<span class="badge">73 rules indexed</span>
|
||||
<span class="badge">74 rules indexed</span>
|
||||
|
||||
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.
|
||||
|
||||
@@ -121,6 +121,11 @@ what a change on the pointed-to side must not silently break.
|
||||
| `vlog_linter ──▶ vlog_semantic` | depends | `analyze`, `Semantics::{symbols, references, references_of}` for semantic rules, including signal usage and duplicate-declaration checks. `Semantics::duplicates()` was added by linter-expansion-1 without changing persisted facts. `LintContext::semantics()` computes analysis lazily when a rule asks for it. Justified in `vlog_linter/Cargo.toml`; adds no external code (`vlog_semantic` is `vlog_parser` + std). |
|
||||
| `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). |
|
||||
| `lucisv_server ◀── vlog_refactor` (extract-module) | depends | `RefactorEdit::created` — the files an edit creates, read by `lucisv_server::extract` to emit `CreateFile` document changes when `ClientAbilities::create_files` (read at `initialize`: `workspace.workspaceEdit.documentChanges` + `resourceOperations: create`) allows, else the same-file fallback (§53.1, 2026-09-06). |
|
||||
| `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.) |
|
||||
@@ -528,6 +533,7 @@ promise:
|
||||
| `vscode-hierarchy-sidebar ◀──▶ index-persistence / hover-line-index / incremental-index` | handshake | **`FACTS_FORMAT` 4 → 5**, one bump for three additions: `Def::decl_span`; `InstantiationEdge::instances` (a `Vec<InstanceOccurrence>` — the statement edge stays one-per-statement, so call hierarchy and code-lens counts are unchanged and the census is still the one `instantiations::sites` walk); and client positions — `DeclLines::positions: Option<DeclPositions>` on **file-scope declarations only**, plus `Utf16Range` on every instance occurrence. Members deliberately carry none: they outnumber units by two orders of magnitude, and the `U`/`M` groups are separate, so a member costs no field at all. `FileFacts::from_analysis` grew a `src: &str` parameter (a position cannot be read off a line table). Measured store cost of the positions: +1.69 % on the 820-file corpus, +1.86 % on opentitan. |
|
||||
| `vscode-hierarchy-sidebar ──▶ vlog_parser` | depends | `LineIndex::utf16_position` — byte offset to (0-based line, UTF-16 column), moved down beside the line table so the semantic index and `lucisv_server::convert::Positions` cannot answer differently. `Positions::position` is now a wrapper over it; the cross-crate equality is test-pinned. |
|
||||
| `vscode-hierarchy-sidebar ◀──▶ workspace-index` | handshake | `WorkspaceIndex::units_of(kind)` — file-scope declarations of one kind, in name order, walking the unit table alone. The cheap half of `workspace_symbols("")` for a caller that never wants members; 15 ms per snapshot on opentitan. |
|
||||
| `dut-hierarchy ──▶ vscode-hierarchy-sidebar` | depends | TODO §56 (2026-09-06): `hierarchySections.js` consumes the sidebar's model (`rootNode`, the reverse instance index memoised on the model) and its webview renderer's row menu; no edge to any Rust crate — the server is untouched. |
|
||||
| `hover-line-index ──▶ port-detail-spans / index-persistence` | depends + handshake | `DeclLines { name, detail }` rides each indexed `Decl`, so ordinary and split-port hover headings do not reread a file just to compute a line. The record grew again and **`FACTS_FORMAT` went 3 → 4**; the server's bounded `FileView` cache supplies the text/`LineIndex` only when a snippet or a non-indexed position still needs it. Its four invalidation points are `set_document`, `close_document`, `update_one`, and a whole rebuild. |
|
||||
| `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and `IncludeGraph::absorb` publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. |
|
||||
| `scan-interleave ──▶ hover-line-index` | depends | Delivers hover-line-index's measured startup-wait request: a startup scan above 64 files drains queued messages between files. A rescan deliberately still holds requests; what an answer sees never depends on elapsed wall time. |
|
||||
@@ -662,6 +668,7 @@ update the filing README(s) and this file.
|
||||
| ~~29~~ | ~~An unknown rule name in the **editor's** `lucisv.lint.select`/`ignore` is still dropped silently, while §42 logs the same mistake in a project file (and `lucisv.lint.options` logs its bad entries). Wants the same once-only log through `notification.rs`.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.1):** `settings::rules` records every dropped name in `ClientSettings::lint_name_warnings` as `lucisv.lint.<select|ignore>: unknown rule: <name>`; `apply_settings` logs what the previous settings value did not already say — once per (setting, name), re-armed by a changed list. | lint-config-contract (QA) | lucisv_server |
|
||||
| ~~30~~ | ~~**An unreadable directory aborts the whole walk.** `Walk::dir` propagates `read_dir`'s error with `?`, so one permission-denied directory anywhere under the start — reachable now that a symlink to an outside directory is followed once (§2.9-8's ruling) — drops every file already found and fails the run. Found by walk-cycles' QA on a link to `/`. Wanted: skip the directory and say so through a warning channel the walk does not have today (the filelist-missing-file precedent), which is also where a dangling source link's warning belongs.~~ — **delivered 2026-09-05 by small-items-4 (TODO §45.2):** `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink; an unreadable directory, an unreadable `.gitignore` and a dangling source link are warned about (`warning: <path>: <message>` on the CLI's stderr before the report, exit code unchanged; logged once per scan by the server through `report_scope`) and the walk continues. | walk-cycles (QA) | lucisv_core / lucisv / lucisv_server |
|
||||
| 31 | **DPI-export name binding remains open.** Package re-export resolution closed §2.9-16, but the name in a DPI export is still not a semantic reference. Keep this separate from the delivered package-member traversal. | dpi-export request (b); package-reexports | vlog_semantic |
|
||||
| 32 | **The refactoring verifier does not catch a same-file relocation of a never-dropped piece written as two well-formed edits** (delete here, insert there): `verify_move` computes `after` by applying the edits, so `positions_match`'s reconstruction cannot diverge from it and equation 3 of the ledger is unreachable through any real caller. No planner produces the shape today. Wanted: an independent `after` (the client's applied text, or a second reconstruction) and a test that isolates equation 3. Found by extract-module's QA re-attack. | extract-inline-module (QA) | vlog_refactor |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
# The two checks are pre-publish/developer checks, not part of the shipped
|
||||
# extension. `restart.js` itself IS shipped — `extension.js` requires it.
|
||||
smoke.js
|
||||
extract_test.js
|
||||
restart_test.js
|
||||
hierarchyModel_test.js
|
||||
hierarchySections_test.js
|
||||
hierarchyView_test.js
|
||||
.vscode/**
|
||||
.gitignore
|
||||
@@ -5,6 +5,37 @@ for you. The extension and its bundled language server share one version
|
||||
number; the full engineering notes live in the
|
||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||
|
||||
## 0.48.2 — 2026-09-06
|
||||
|
||||
- The 0.48.0 package was built without the DUT-centred hierarchy view
|
||||
and 0.48.1 never built; 0.48.2 is the same release packaged correctly.
|
||||
Install this one.
|
||||
|
||||
## 0.48.0 — 2026-09-06
|
||||
|
||||
- **DUT-centred hierarchy.** Right-click a module → Star as DUT: the
|
||||
pane shows the DUT with its children at the top, its parents (the DV
|
||||
bench) as an upward tree, and everything else in a collapsible
|
||||
section. Star several; unstar from the same menu; or pin DUTs for the
|
||||
team with `lucisv.hierarchy.duts`.
|
||||
|
||||
## 0.47.0 — 2026-09-06
|
||||
|
||||
- **Organize imports** on save or from the lightbulb: unused
|
||||
`import pkg::*;` lines removed, duplicates merged, the run sorted.
|
||||
- **Extract module**: select whole items, pick "extract selection into
|
||||
module", type a name — a new file with the inferred ports and an
|
||||
instantiation in its place.
|
||||
|
||||
## 0.46.0 — 2026-09-05
|
||||
|
||||
- **Expand `.*`**: a lightbulb on a wildcard connection writes out the
|
||||
named connections it stands for, flagging any port nothing in scope
|
||||
would have bound.
|
||||
- **Convert ports to ANSI**: a lightbulb anywhere in a Verilog-2001
|
||||
header rewrites it in ANSI form, absorbing the body declarations and
|
||||
keeping every comment.
|
||||
|
||||
## 0.45.0 — 2026-09-05
|
||||
|
||||
- **Rename follows hierarchical paths across files.** Renaming a
|
||||
|
||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||
setup.
|
||||
|
||||
The current release is **0.45.0**. Its platform packages include both
|
||||
The current release is **0.48.2**. Its platform packages include both
|
||||
`lucisv-server` and the `lucisv` command-line tool:
|
||||
|
||||
| Package target | Machines |
|
||||
@@ -63,6 +63,13 @@ Most features work as soon as a supported file opens:
|
||||
- Open the **lucisv** Activity Bar icon for an instance-oriented design tree.
|
||||
Every level starts collapsed; its fixed search field fuzzy-matches module and
|
||||
instance names in memory, and click or the instance context menu navigates.
|
||||
- Right-click the module you actually work on and choose **Star as DUT**. The
|
||||
pane splits into three collapsible sections — the DUT with its children, the
|
||||
DUT's parents (an upward tree through everything that instantiates it, which
|
||||
is usually the testbench), and every other module — including whatever the
|
||||
bench held beside the DUT, which that last section re-roots rather than hide.
|
||||
A second DUT adds two more sections. **Unstar DUT** from the same menu, or
|
||||
**Clear DUTs** from the pane's title bar, puts the plain tree back.
|
||||
- Hover a symbol, press `F12`, find references, search workspace symbols, or
|
||||
open the call/type hierarchy using VS Code's standard commands.
|
||||
- Type a module name at module-item scope to insert a complete instance. Inside
|
||||
@@ -136,6 +143,7 @@ enabling both paths formats twice.
|
||||
| Code lenses | Shows the workspace-wide instantiation count above every module/interface; click to jump to a site |
|
||||
| Call hierarchy | Incoming calls answer “who instantiates this?”; outgoing calls answer “what does this instantiate?” |
|
||||
| Design hierarchy sidebar | Alphabetical instance paths from every top-level module, collapsed until you open them, in-memory fuzzy module/instance search, exact instance/definition jumps, path copy, bookmark highlighting, and split-right opening |
|
||||
| DUT sections | Star a module as DUT and the pane splits into its own subtree, an upward tree of everything that instantiates it, and every module in neither — two sections per DUT plus one. Stars are remembered per workspace; `lucisv.hierarchy.duts` is the checked-in list a team shares |
|
||||
| Type hierarchy | Walks class `extends` relationships to supertypes and workspace subtypes |
|
||||
|
||||
### Highlighting and presentation
|
||||
@@ -274,6 +282,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
|
||||
| `lucisv.indent` | unset | Indent width, 1–8; falls back to the editor tab size, then 2 |
|
||||
| `lucisv.exclude` | `[]` | Extra index exclusions added to the project's own patterns |
|
||||
| `lucisv.filelist` | `""` | EDA `.f` filelist to index instead of walking the folder |
|
||||
| `lucisv.hierarchy.duts` | `[]` | Modules the Hierarchy pane treats as DUTs, by name — the checked-in list a team shares. Each one adds two sections ahead of "Other modules"; a DUT from this setting is shown locked and can only be removed here |
|
||||
| `lucisv.index.scope` | `folder` | Index the folders your open files live in, or every workspace folder with `workspace`; answers stay scope-relative until the scope reaches a folder |
|
||||
| `lucisv.index.scopeDepth` | `0` | How many folders above an open file the `folder` scope starts from; `1` lets a file in `rtl/` index `include/` beside it |
|
||||
| `lucisv.index.maxFileSize` | `1 MiB` | Largest walked file the index reads, in bytes; `0` removes the cap, and a file you open is always indexed in full |
|
||||
@@ -365,6 +374,22 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.48.0 highlights
|
||||
|
||||
Version 0.48.0 makes the hierarchy pane DUT-centred: star a module and
|
||||
see it with its children, its parents, and everything else in their own
|
||||
sections.
|
||||
|
||||
## Release 0.47.0 highlights
|
||||
|
||||
Version 0.47.0 adds organize imports (with organize-on-save) and extract
|
||||
module with dataflow-inferred ports.
|
||||
|
||||
## Release 0.46.0 highlights
|
||||
|
||||
Version 0.46.0 adds two refactorings: expand `.*` and convert ports to
|
||||
ANSI, both verified whole-edit with every comment kept.
|
||||
|
||||
## Release 0.45.0 highlights
|
||||
|
||||
Version 0.45.0 makes rename follow hierarchical paths across files,
|
||||
|
||||
@@ -13,6 +13,7 @@ const path = require('path');
|
||||
const vscode = require('vscode');
|
||||
const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node');
|
||||
const { createRestarter } = require('./restart');
|
||||
const { executeCommand } = require('./extract');
|
||||
const { HierarchyView } = require('./hierarchyView');
|
||||
|
||||
/** The single client, kept only so `deactivate` can stop it. */
|
||||
@@ -187,6 +188,24 @@ function activate(context) {
|
||||
// still request a snapshot, but receive no unsolicited lucisv traffic.
|
||||
hierarchyView: true,
|
||||
},
|
||||
// The one place this extension steps between a server command and the
|
||||
// server. `lucisv.extractModule` needs a name for the new module and LSP
|
||||
// has no prompt, so the server's code action carries the command with a
|
||||
// default name and this asks the user for a better one before it goes out
|
||||
// (docs/features/extract-inline-module/README.md). Every other command
|
||||
// passes through untouched. It has to be middleware rather than a command
|
||||
// of our own: the language client registers every command the server
|
||||
// advertises, so a second registration of the same id would collide with
|
||||
// it at activation.
|
||||
middleware: {
|
||||
executeCommand: (command, args, next) =>
|
||||
executeCommand(
|
||||
{ showInputBox: (options) => vscode.window.showInputBox(options) },
|
||||
command,
|
||||
args,
|
||||
next,
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// The one thing "extract into module" needs that LSP has no request for:
|
||||
// asking the user what to call the new module.
|
||||
//
|
||||
// The server offers the code action with a `Command` rather than an edit —
|
||||
// `lucisv.extractModule [uri, range, defaultName]` — precisely so a client can
|
||||
// step in between the click and the edit. This file is that step.
|
||||
//
|
||||
// **Through the language client's middleware, not through a second command.**
|
||||
// `vscode-languageclient` registers every command the server advertises in
|
||||
// `executeCommandProvider` with `vscode.commands.registerCommand`, so an
|
||||
// extension that registered `lucisv.extractModule` itself would collide with
|
||||
// it at activation. `middleware.executeCommand` is the seam the client provides
|
||||
// for exactly this: it sees the command on its way out, may change the
|
||||
// arguments, and hands them to `next`. One command id, one server contract,
|
||||
// and every other client — Vim, a CLI — runs the same command with the default
|
||||
// name and gets the same edit.
|
||||
//
|
||||
// Nothing here knows about `vscode`: the dependencies come in as an object, so
|
||||
// `extract_test.js` drives the whole flow headlessly.
|
||||
// See docs/features/extract-inline-module/README.md.
|
||||
|
||||
/** The command the server's code action carries. */
|
||||
const EXTRACT_MODULE = 'lucisv.extractModule';
|
||||
|
||||
/**
|
||||
* A plain SystemVerilog identifier, which is the only thing the engine will
|
||||
* name a module — and a file — with. Checked here as well as in the engine so
|
||||
* the user is told while the box is open rather than by an error afterwards.
|
||||
*/
|
||||
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
||||
|
||||
/**
|
||||
* What the input box says about what has been typed so far, or `undefined`
|
||||
* when it is a name lucisv would accept.
|
||||
*
|
||||
* The message is the one the engine would refuse with, in the present tense:
|
||||
* an editor's validation is read while typing, not after.
|
||||
*/
|
||||
function validateModuleName(value) {
|
||||
const name = (value || '').trim();
|
||||
if (name === '') return 'The new module needs a name.';
|
||||
if (!IDENTIFIER.test(name)) {
|
||||
return 'A module name is a plain SystemVerilog identifier: a letter or `_`, then letters, digits, `_` or `$`.';
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The language client's `executeCommand` middleware.
|
||||
*
|
||||
* - `deps.showInputBox` — `vscode.window.showInputBox`, which resolves to the
|
||||
* typed string or to `undefined` when the user pressed Escape.
|
||||
* - `command`, `args`, `next` — what the client hands every middleware.
|
||||
*
|
||||
* Every command but this one goes straight through. This one asks for a name,
|
||||
* and a cancelled box resolves to `undefined` without ever reaching the
|
||||
* server: an extraction nobody named is one nobody asked for.
|
||||
*/
|
||||
async function executeCommand(deps, command, args, next) {
|
||||
if (command !== EXTRACT_MODULE) return next(command, args);
|
||||
const [uri, range, suggested] = args || [];
|
||||
const name = await deps.showInputBox({
|
||||
title: 'Extract into module',
|
||||
prompt: 'Name for the new module',
|
||||
value: typeof suggested === 'string' ? suggested : '',
|
||||
validateInput: validateModuleName,
|
||||
});
|
||||
if (name === undefined) return undefined;
|
||||
const trimmed = name.trim();
|
||||
if (validateModuleName(trimmed) !== undefined) return undefined;
|
||||
return next(command, [uri, range, trimmed]);
|
||||
}
|
||||
|
||||
module.exports = { EXTRACT_MODULE, executeCommand, validateModuleName };
|
||||
@@ -0,0 +1,137 @@
|
||||
// Checks for `extract.js`: the input box that names the module the server is
|
||||
// about to extract, and what it does when the user does not name one.
|
||||
//
|
||||
// node extract_test.js
|
||||
//
|
||||
// Exits 0 on success, 1 on any failure. Plain node, no dependencies and no
|
||||
// test runner — the same style as `restart_test.js` next to it.
|
||||
//
|
||||
// The fakes below script only what `extract.js` is allowed to depend on: an
|
||||
// input box that resolves to a string or to `undefined`, and a `next` that
|
||||
// records what it was handed. Nothing here re-implements VS Code.
|
||||
// See docs/features/extract-inline-module/README.md.
|
||||
|
||||
const { EXTRACT_MODULE, executeCommand, validateModuleName } = require('./extract');
|
||||
|
||||
let checks = 0;
|
||||
|
||||
function ok(condition, what) {
|
||||
checks += 1;
|
||||
if (!condition) fail(what);
|
||||
}
|
||||
|
||||
function equal(got, want, what) {
|
||||
checks += 1;
|
||||
const a = JSON.stringify(got);
|
||||
const b = JSON.stringify(want);
|
||||
if (a !== b) fail(`${what}: got ${a}, want ${b}`);
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
console.error(`extract: FAIL — ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** A `next` that records every call and answers with a marker. */
|
||||
function recorder() {
|
||||
const calls = [];
|
||||
const next = (command, args) => {
|
||||
calls.push({ command, args });
|
||||
return Promise.resolve('applied');
|
||||
};
|
||||
return { calls, next };
|
||||
}
|
||||
|
||||
/** An input box that answers `answer` and records the options it was given. */
|
||||
function box(answer) {
|
||||
const seen = [];
|
||||
const showInputBox = (options) => {
|
||||
seen.push(options);
|
||||
return Promise.resolve(answer);
|
||||
};
|
||||
return { seen, showInputBox };
|
||||
}
|
||||
|
||||
const ARGS = ['file:///rtl/m.sv', { start: { line: 6 }, end: { line: 6 } }, 'm_extracted'];
|
||||
|
||||
async function aNameTypedIntoTheBoxReachesTheServer() {
|
||||
const { calls, next } = recorder();
|
||||
const { seen, showInputBox } = box('adder');
|
||||
const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(result, 'applied', 'the server’s answer comes back to the client');
|
||||
equal(calls.length, 1, 'the command is sent once');
|
||||
equal(calls[0].command, EXTRACT_MODULE, 'under its own name');
|
||||
equal(calls[0].args[0], ARGS[0], 'the uri is passed through');
|
||||
equal(calls[0].args[1], ARGS[1], 'and so is the range');
|
||||
equal(calls[0].args[2], 'adder', 'the typed name replaces the default');
|
||||
equal(seen.length, 1, 'one box is shown');
|
||||
equal(seen[0].value, 'm_extracted', 'prefilled with the default the server proposed');
|
||||
}
|
||||
|
||||
async function surroundingWhitespaceIsTrimmedOffTheName() {
|
||||
const { calls, next } = recorder();
|
||||
const { showInputBox } = box(' adder\t');
|
||||
await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(calls[0].args[2], 'adder', 'a name is what is left after the spaces');
|
||||
}
|
||||
|
||||
async function anEscapedBoxSendsNothingAtAll() {
|
||||
const { calls, next } = recorder();
|
||||
const { showInputBox } = box(undefined);
|
||||
const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(result, undefined, 'a cancelled extraction answers nothing');
|
||||
equal(calls.length, 0, 'and reaches the server not at all');
|
||||
}
|
||||
|
||||
async function aNameTheEngineWouldRefuseIsNotSentEither() {
|
||||
// The box's own validator should stop this, but a client that ignores
|
||||
// `validateInput` must not get a file called `2fast.sv` out of it.
|
||||
for (const typed of ['', ' ', '2fast', 'with space', '\\odd-name']) {
|
||||
const { calls, next } = recorder();
|
||||
const { showInputBox } = box(typed);
|
||||
const result = await executeCommand({ showInputBox }, EXTRACT_MODULE, ARGS, next);
|
||||
equal(result, undefined, `\`${typed}\` is not a module name`);
|
||||
equal(calls.length, 0, `\`${typed}\` never reaches the server`);
|
||||
}
|
||||
}
|
||||
|
||||
async function everyOtherCommandGoesStraightThrough() {
|
||||
const { calls, next } = recorder();
|
||||
let shown = 0;
|
||||
const showInputBox = () => {
|
||||
shown += 1;
|
||||
return Promise.resolve('never');
|
||||
};
|
||||
const args = ['file:///rtl/m.sv', { line: 3, character: 0 }];
|
||||
const result = await executeCommand({ showInputBox }, 'lucisv.organizeImports', args, next);
|
||||
equal(result, 'applied', 'the other commands answer as they always did');
|
||||
equal(shown, 0, 'and no box is shown for them');
|
||||
equal(calls, [{ command: 'lucisv.organizeImports', args }], 'passed through unchanged');
|
||||
}
|
||||
|
||||
function theValidatorSaysWhatTheEngineWouldSay() {
|
||||
equal(validateModuleName('adder'), undefined, 'a plain identifier is fine');
|
||||
equal(validateModuleName('_adder$2'), undefined, 'so are `_`, digits and `$` after the first');
|
||||
ok(validateModuleName('').includes('needs a name'), 'an empty box says so');
|
||||
ok(validateModuleName(' ').includes('needs a name'), 'and so does a blank one');
|
||||
ok(validateModuleName('2fast').includes('plain SystemVerilog identifier'), 'a leading digit');
|
||||
ok(validateModuleName('a b').includes('plain SystemVerilog identifier'), 'a space');
|
||||
ok(validateModuleName('\\odd-name').includes('plain SystemVerilog identifier'), 'an escaped name');
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const watchdog = setTimeout(
|
||||
() => fail('timed out after 5s — a promise this test waits on never settled'),
|
||||
5000,
|
||||
);
|
||||
theValidatorSaysWhatTheEngineWouldSay();
|
||||
await aNameTypedIntoTheBoxReachesTheServer();
|
||||
await surroundingWhitespaceIsTrimmedOffTheName();
|
||||
await anEscapedBoxSendsNothingAtAll();
|
||||
await aNameTheEngineWouldRefuseIsNotSentEither();
|
||||
await everyOtherCommandGoesStraightThrough();
|
||||
clearTimeout(watchdog);
|
||||
console.log(`extract: OK — ${checks} checks over the extract input box`);
|
||||
}
|
||||
|
||||
main().catch((error) => fail(error.stack || String(error)));
|
||||
@@ -406,6 +406,7 @@ function searchRow(entry) {
|
||||
id: searchId(entry),
|
||||
kind: entry.kind,
|
||||
label: searchLabel(entry),
|
||||
moduleName: entry.kind === 'module' ? entry.module.moduleName : entry.instance.moduleName,
|
||||
// Where the row lives, since a flat hit has no one path to show.
|
||||
detail: entry.kind === 'module' ? 'module' : `in ${entry.module.moduleName}`,
|
||||
depth: 0,
|
||||
@@ -457,6 +458,9 @@ function treeRows(model, expanded, bookmarkPath) {
|
||||
kind: node.kind,
|
||||
label: node.label,
|
||||
detail: node.detail,
|
||||
// The module the row is about — for an instance, its type. What the DUT
|
||||
// sections decide a row's context menu from.
|
||||
moduleName: node.moduleName,
|
||||
depth: node.depth,
|
||||
hasChildren: node.hasChildren,
|
||||
expanded: expanded.has(node.id),
|
||||
@@ -528,13 +532,24 @@ function instanceNode(model, parent, instance) {
|
||||
///
|
||||
/// Walked from the roots rather than looked up in a table of every path,
|
||||
/// because that table is the thing this file stopped building.
|
||||
///
|
||||
/// A DUT section's rows carry a path relative to the DUT (`aes.u_ctrl`), whose
|
||||
/// head is a module no root walk can reach, so a head that names no root is
|
||||
/// retried over every module. The roots-first order keeps every path that
|
||||
/// resolved before resolving to exactly the same chain.
|
||||
function bookmarkChain(model, path) {
|
||||
if (typeof path !== 'string' || path === '') return undefined;
|
||||
const [head, ...rest] = path.split('.');
|
||||
const fromRoots = uniqueChain(model, model.roots.map(({ module }) => module), head, rest);
|
||||
if (fromRoots) return fromRoots;
|
||||
return uniqueChain(model, model.modules, head, rest);
|
||||
}
|
||||
|
||||
function uniqueChain(model, modules, head, rest) {
|
||||
let found;
|
||||
for (const { module, fallback } of model.roots) {
|
||||
for (const module of modules) {
|
||||
if (module.moduleName !== head) continue;
|
||||
const chain = descend(model, rootNode(model, module, fallback), rest);
|
||||
const chain = descend(model, rootNode(model, module, false), rest);
|
||||
if (!chain) continue;
|
||||
if (found) return undefined; // the path names more than one row
|
||||
found = chain;
|
||||
@@ -567,6 +582,7 @@ module.exports = {
|
||||
fuzzyScore,
|
||||
idForPath,
|
||||
locationKey,
|
||||
rootNode,
|
||||
searchHierarchy,
|
||||
searchTarget,
|
||||
treeRows,
|
||||
|
||||
@@ -109,6 +109,11 @@ function bookmarksResolveByPathWithoutATableOfEveryPath() {
|
||||
assert.equal(idForPath(model, 'TB.dut.inst1.inst2'), chain[3]);
|
||||
assert.equal(idForPath(model, 'TB.dut.nope'), undefined);
|
||||
assert.equal(idForPath(model, ''), undefined);
|
||||
// A head that names no root is retried over every module, because a row in a
|
||||
// DUT section carries a path relative to the DUT (§56). Roots still win: the
|
||||
// chains above are the ones a root walk produced.
|
||||
assert.equal(bookmarkChain(model, 'block.inst2').length, 2);
|
||||
assert.equal(bookmarkChain(model, 'block.nope'), undefined);
|
||||
// Expanding the chain's ancestors is what reveals the row.
|
||||
const { rows } = treeRows(model, new Set(chain.slice(0, -1)), 'TB.dut.inst1.inst2');
|
||||
assert.equal(rows.filter((row) => row.bookmarked).length, 1);
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
// DUT-centred sections over the flat hierarchy model. A design holds hundreds
|
||||
// of modules and one — or a few — that matter: the DUT, usually with a
|
||||
// testbench above it. Starring a module splits the pane into, per DUT, its
|
||||
// forward subtree and an upward tree of everything that instantiates it, and
|
||||
// then one section for every module that is in neither. No `vscode` dependency,
|
||||
// so plain Node tests cover all of it. See
|
||||
// docs/features/dut-hierarchy/README.md.
|
||||
//
|
||||
// **Nothing here materializes a tree.** Sections are composed out of the same
|
||||
// lazily-expanded nodes `hierarchyModel.js` builds: a section holds one root
|
||||
// node, and the level below a row is built when the user opens it. The one
|
||||
// thing built per snapshot is the reverse index — module → the instances that
|
||||
// name it — which is a single pass over the modules already resident.
|
||||
//
|
||||
// Ids are prefixed per section (`dut:aes/root:file#1:7`), and every descendant
|
||||
// id is derived from its parent's, so one prefix moves a whole subtree into its
|
||||
// own section. That is what lets a module that is below one DUT and above
|
||||
// another appear in both sections and open independently in each.
|
||||
|
||||
const { childrenOf, idForPath, rootNode } = require('./hierarchyModel');
|
||||
|
||||
/** The menu items an instance row has always offered, in their fixed order. */
|
||||
const INSTANCE_ACTIONS = [
|
||||
{ action: 'copyPath', label: 'Copy Full Path' },
|
||||
{ action: 'definition', label: 'Show Definition' },
|
||||
{ action: 'instance', label: 'Show Instance' },
|
||||
{ action: 'bookmark', label: 'Highlight / Bookmark' },
|
||||
{ action: 'openRight', label: 'Open on the Right' },
|
||||
];
|
||||
|
||||
const STAR = { action: 'starDut', label: 'Star as DUT' };
|
||||
const UNSTAR = { action: 'unstarDut', label: 'Unstar DUT' };
|
||||
/** A DUT the workspace settings name cannot be unstarred from the pane, because
|
||||
* the pane will not edit a checked-in file on the user's behalf. */
|
||||
const LOCKED = {
|
||||
action: 'lockedDut',
|
||||
label: 'DUT from settings',
|
||||
disabled: true,
|
||||
title: 'This DUT comes from the lucisv.hierarchy.duts setting. Remove it there to unstar it.',
|
||||
};
|
||||
|
||||
function compareText(a, b) {
|
||||
const foldedA = a.toLowerCase();
|
||||
const foldedB = b.toLowerCase();
|
||||
if (foldedA < foldedB) return -1;
|
||||
if (foldedA > foldedB) return 1;
|
||||
if (a < b) return -1;
|
||||
if (a > b) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function compareEdges(a, b) {
|
||||
return compareText(a.module.moduleName, b.module.moduleName)
|
||||
|| compareText(a.instance.instanceName, b.instance.instanceName)
|
||||
|| compareText(a.instance.site.uri, b.instance.site.uri)
|
||||
|| a.instance.site.selectionRange.start.line - b.instance.site.selectionRange.start.line;
|
||||
}
|
||||
|
||||
/// Module id → the `{ module, instance }` edges that instantiate it, in a
|
||||
/// deterministic order. One pass per snapshot, memoized on the model, because
|
||||
/// the upward tree asks this question once per opened row.
|
||||
function parentIndex(model) {
|
||||
if (model.parentsByTarget) return model.parentsByTarget;
|
||||
const index = new Map();
|
||||
for (const module of model.modules) {
|
||||
for (const instance of module.instances) {
|
||||
if (!instance.targetId) continue;
|
||||
const found = index.get(instance.targetId) || [];
|
||||
found.push({ module, instance });
|
||||
index.set(instance.targetId, found);
|
||||
}
|
||||
}
|
||||
for (const edges of index.values()) edges.sort(compareEdges);
|
||||
model.parentsByTarget = index;
|
||||
return index;
|
||||
}
|
||||
|
||||
/// The declarations of a starred name: the first one is what the sections show,
|
||||
/// and more than one makes the section ambiguous.
|
||||
function declarationsNamed(model, name) {
|
||||
return model.modules.filter((module) => module.moduleName === name);
|
||||
}
|
||||
|
||||
/// The section list §56 specifies: per starred DUT, in starred order, its
|
||||
/// forward subtree and its upward tree, then everything else.
|
||||
function sections(model, duts) {
|
||||
const list = [];
|
||||
const excluded = new Set();
|
||||
for (const name of duts) {
|
||||
const found = declarationsNamed(model, name);
|
||||
const [module] = found;
|
||||
list.push(dutSection(model, name, module, found.length > 1));
|
||||
list.push(parentsSection(model, name, module, found.length > 1));
|
||||
if (!module) continue;
|
||||
collectSubtree(model, module, excluded);
|
||||
collectAncestors(model, module, excluded);
|
||||
}
|
||||
list.push({ kind: 'others', roots: othersRoots(model, excluded) });
|
||||
return list;
|
||||
}
|
||||
|
||||
/// The `others` section's roots. "All other modules" is **additive**: `others`
|
||||
/// holds every module that is in no DUT's forward subtree and no DUT's ancestor
|
||||
/// closure — not `model.roots` minus that set. A monitor the DV bench
|
||||
/// instantiates beside the DUT is not a child of the DUT, so it belongs here;
|
||||
/// the exclusion took away every parent it had, so it is re-rooted at the top
|
||||
/// of the section rather than dropped out of the pane.
|
||||
///
|
||||
/// The roots are the members of that set with no parent left inside it. A
|
||||
/// module that still has one is shown under that parent, so nothing appears
|
||||
/// twice: reachable from one excluded and one ordinary parent, it stays where
|
||||
/// it always was. Nothing appears twice the long way round either — a path from
|
||||
/// one module of the set to another cannot leave it, because a module *above*
|
||||
/// an ancestor of the DUT is itself an ancestor and a module *below* the DUT's
|
||||
/// subtree is itself in it, and both are excluded. Roots come out in the
|
||||
/// model's own order — alphabetically, then the ones only a cycle reaches,
|
||||
/// which is what `model.roots` does.
|
||||
///
|
||||
/// A root's forward subtree is the plain one, **unfiltered**: a module that is
|
||||
/// also below a DUT is still shown under its parent here, exactly as it is
|
||||
/// today. A DUT itself can never turn up in it — everything that instantiates a
|
||||
/// DUT is in that DUT's ancestor closure and is therefore excluded from the set
|
||||
/// this walks.
|
||||
function othersRoots(model, excluded) {
|
||||
const plain = new Set();
|
||||
const recursive = new Set();
|
||||
const covered = new Set();
|
||||
const take = (module, into) => {
|
||||
into.add(module.id);
|
||||
coverSubtree(model, module, covered);
|
||||
};
|
||||
|
||||
// The pane's own roots, minus the excluded: with nothing starred this is the
|
||||
// whole answer and it is byte-identical to `model.roots`.
|
||||
for (const { module, fallback } of model.roots) {
|
||||
if (!excluded.has(module.id)) take(module, fallback ? recursive : plain);
|
||||
}
|
||||
// Then what the exclusion orphaned: every parent it has is inside a DUT
|
||||
// section, and no root reaches it, so this is the only place left to show it.
|
||||
for (const module of model.modules) {
|
||||
if (excluded.has(module.id) || covered.has(module.id)) continue;
|
||||
if (hasParentInOthers(model, module, excluded)) continue;
|
||||
take(module, plain);
|
||||
}
|
||||
// Whatever is still unreached is inside a recursive component that no root
|
||||
// enters — the model's own fallback rule, marked the way it marks it.
|
||||
for (const module of model.modules) {
|
||||
if (excluded.has(module.id) || covered.has(module.id)) continue;
|
||||
take(module, recursive);
|
||||
}
|
||||
|
||||
const roots = model.modules.filter((module) => plain.has(module.id))
|
||||
.map((module) => ({ module, fallback: false }));
|
||||
for (const module of model.modules) {
|
||||
if (recursive.has(module.id)) roots.push({ module, fallback: true });
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
/// Does a module the `others` set still holds instantiate this one? Then it is
|
||||
/// already on screen under that module and must not be re-rooted beside it.
|
||||
function hasParentInOthers(model, module, excluded) {
|
||||
return (parentIndex(model).get(module.id) || [])
|
||||
.some((edge) => !excluded.has(edge.module.id));
|
||||
}
|
||||
|
||||
/// Everything an `others` root puts on screen: its forward subtree over the
|
||||
/// module graph, excluded modules included, because that subtree is not
|
||||
/// filtered. A module already covered was descended through, so is everything
|
||||
/// below it — which is what keeps the whole pass linear.
|
||||
function coverSubtree(model, start, covered) {
|
||||
const stack = [start];
|
||||
while (stack.length > 0) {
|
||||
const module = stack.pop();
|
||||
if (covered.has(module.id)) continue;
|
||||
covered.add(module.id);
|
||||
for (const instance of module.instances) {
|
||||
const target = instance.targetId && model.byId.get(instance.targetId);
|
||||
if (target) stack.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function dutSection(model, name, module, ambiguous) {
|
||||
if (!module) return { kind: 'dut', name, root: undefined, ambiguous };
|
||||
// Exactly the node the plain view would show for this module, including its
|
||||
// `recursive` marking when the module is only a root because of a cycle.
|
||||
const plain = model.roots.find((root) => root.module.id === module.id);
|
||||
const root = rootNode(model, module, Boolean(plain && plain.fallback));
|
||||
root.id = `${prefixFor('dut', name)}${root.id}`;
|
||||
return { kind: 'dut', name, root, ambiguous };
|
||||
}
|
||||
|
||||
function parentsSection(model, name, module, ambiguous) {
|
||||
if (!module) return { kind: 'parents', name, root: undefined, ambiguous };
|
||||
return { kind: 'parents', name, root: upRootNode(model, name, module), ambiguous };
|
||||
}
|
||||
|
||||
/// The DUT itself, as the root of the upward tree.
|
||||
function upRootNode(model, name, module) {
|
||||
return {
|
||||
id: `${prefixFor('parents', name)}up:${module.id}`,
|
||||
kind: 'module',
|
||||
up: true,
|
||||
moduleName: module.moduleName,
|
||||
label: module.moduleName,
|
||||
detail: '',
|
||||
depth: 0,
|
||||
parentId: null,
|
||||
fullPath: undefined,
|
||||
hasChildren: (parentIndex(model).get(module.id) || []).length > 0,
|
||||
warning: false,
|
||||
definition: module.definition,
|
||||
definitions: [module.definition],
|
||||
site: undefined,
|
||||
moduleId: module.id,
|
||||
seen: new Set([module.id]),
|
||||
};
|
||||
}
|
||||
|
||||
/// One module that instantiates `parent`'s module, named by the instance that
|
||||
/// does it. A module already on the path upward closes a cycle: it is shown,
|
||||
/// marked, and does not open again — the forward tree's rule, upside down.
|
||||
function upNode(model, parent, { module, instance }) {
|
||||
const repeated = parent.seen.has(module.id);
|
||||
const seen = new Set(parent.seen);
|
||||
seen.add(module.id);
|
||||
return {
|
||||
id: `${parent.id}>${instance.id}`,
|
||||
kind: 'module',
|
||||
up: true,
|
||||
moduleName: module.moduleName,
|
||||
instanceName: instance.instanceName,
|
||||
label: module.moduleName,
|
||||
detail: repeated ? 'recursive' : `via ${instance.instanceName}`,
|
||||
depth: parent.depth + 1,
|
||||
parentId: parent.id,
|
||||
fullPath: undefined,
|
||||
hasChildren: !repeated && (parentIndex(model).get(module.id) || []).length > 0,
|
||||
warning: repeated,
|
||||
definition: module.definition,
|
||||
definitions: [module.definition],
|
||||
site: instance.site,
|
||||
moduleId: module.id,
|
||||
seen,
|
||||
};
|
||||
}
|
||||
|
||||
/// The level below a row, whichever direction its section runs in.
|
||||
function childrenIn(model, node) {
|
||||
if (!node.up) return childrenOf(model, node);
|
||||
return (parentIndex(model).get(node.moduleId) || [])
|
||||
.map((edge) => upNode(model, node, edge));
|
||||
}
|
||||
|
||||
/// Every module reachable downward from the DUT, over the module graph rather
|
||||
/// than the expanded tree, so a diamond costs one visit and a cycle terminates.
|
||||
///
|
||||
/// The visited set is this walk's own, not the shared `into`: a module already
|
||||
/// in `into` may have been put there as another DUT's *ancestor*, in which case
|
||||
/// nothing below it has been collected yet and stopping there would leave the
|
||||
/// exclusion short.
|
||||
function collectSubtree(model, start, into) {
|
||||
const stack = [start];
|
||||
const seen = new Set();
|
||||
while (stack.length > 0) {
|
||||
const module = stack.pop();
|
||||
if (seen.has(module.id)) continue;
|
||||
seen.add(module.id);
|
||||
into.add(module.id);
|
||||
for (const instance of module.instances) {
|
||||
const target = instance.targetId && model.byId.get(instance.targetId);
|
||||
if (target) stack.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The same walk upward: every module that instantiates the DUT, transitively.
|
||||
function collectAncestors(model, start, into) {
|
||||
const index = parentIndex(model);
|
||||
const stack = [start];
|
||||
const seen = new Set();
|
||||
while (stack.length > 0) {
|
||||
const module = stack.pop();
|
||||
if (seen.has(module.id)) continue;
|
||||
seen.add(module.id);
|
||||
into.add(module.id);
|
||||
for (const edge of index.get(module.id) || []) stack.push(edge.module);
|
||||
}
|
||||
}
|
||||
|
||||
/// The id prefix a DUT's two sections stamp on their rows. The bookmark's
|
||||
/// ancestor expansion needs them: the chain the model resolves is unprefixed,
|
||||
/// and the copy of it inside a section is the same chain behind one of these.
|
||||
function sectionPrefixes(duts) {
|
||||
return duts.flatMap((name) => [prefixFor('dut', name), prefixFor('parents', name)]);
|
||||
}
|
||||
|
||||
function prefixFor(kind, name) {
|
||||
return `${kind}:${name}/`;
|
||||
}
|
||||
|
||||
/** The `others` section's row id; it has no DUT name to be keyed by. */
|
||||
const OTHERS_ID = 'sec:others';
|
||||
|
||||
function headerId(section) {
|
||||
return section.kind === 'others' ? OTHERS_ID : `sec:${section.kind}:${section.name}`;
|
||||
}
|
||||
|
||||
/// What a star opens on the user's behalf, once, when the DUT list changes: the
|
||||
/// two new sections and the DUT row at the top of each. Starring is an explicit
|
||||
/// act — the second exception to "nothing expands by itself", after a
|
||||
/// bookmark's ancestor chain.
|
||||
function defaultOpenIds(list) {
|
||||
const ids = [];
|
||||
for (const section of list) {
|
||||
if (section.kind === 'others') continue;
|
||||
ids.push(headerId(section));
|
||||
if (section.root) ids.push(section.root.id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function headerLabel(section) {
|
||||
if (section.kind === 'dut') return `DUT: ${section.name}`;
|
||||
if (section.kind === 'parents') return `Parents of ${section.name}`;
|
||||
return 'Other modules';
|
||||
}
|
||||
|
||||
function headerIcon(section) {
|
||||
if (section.kind === 'dut') return '★';
|
||||
return section.kind === 'parents' ? '↑' : '▤';
|
||||
}
|
||||
|
||||
function headerDetail(section) {
|
||||
if (section.kind === 'others') return `${section.roots.length}`;
|
||||
return section.ambiguous ? 'ambiguous' : '';
|
||||
}
|
||||
|
||||
/// The rows the sectioned tree shows: every section header, and under an open
|
||||
/// header the rows of its tree. Same shape as `treeRows`, one level deeper.
|
||||
function sectionRows(model, list, expanded, bookmarkPath) {
|
||||
const rows = [];
|
||||
const nodes = new Map();
|
||||
const bookmarkId = bookmarkPath ? idForPath(model, bookmarkPath) : undefined;
|
||||
|
||||
function push(node) {
|
||||
nodes.set(node.id, node);
|
||||
rows.push({
|
||||
id: node.id,
|
||||
kind: node.kind,
|
||||
label: node.label,
|
||||
detail: node.detail,
|
||||
moduleName: node.moduleName,
|
||||
depth: node.depth + 1,
|
||||
hasChildren: node.hasChildren,
|
||||
expanded: expanded.has(node.id),
|
||||
warning: node.warning,
|
||||
bookmarked: isBookmarked(node.id, bookmarkId),
|
||||
});
|
||||
if (!expanded.has(node.id) || !node.hasChildren) return;
|
||||
for (const child of childrenIn(model, node)) push(child);
|
||||
}
|
||||
|
||||
for (const section of list) {
|
||||
const id = headerId(section);
|
||||
rows.push({
|
||||
id,
|
||||
kind: 'section',
|
||||
label: headerLabel(section),
|
||||
detail: headerDetail(section),
|
||||
icon: headerIcon(section),
|
||||
depth: 0,
|
||||
hasChildren: true,
|
||||
expanded: expanded.has(id),
|
||||
warning: false,
|
||||
bookmarked: false,
|
||||
});
|
||||
if (!expanded.has(id)) continue;
|
||||
if (section.kind === 'others') {
|
||||
for (const root of section.roots) push(rootNode(model, root.module, root.fallback));
|
||||
} else if (section.root) {
|
||||
push(section.root);
|
||||
} else {
|
||||
rows.push(missingRow(section, id));
|
||||
}
|
||||
}
|
||||
return { rows, nodes, bookmarkId };
|
||||
}
|
||||
|
||||
/// A starred name the snapshot no longer holds keeps its sections rather than
|
||||
/// vanishing silently: the user renamed or deleted the module and needs to see
|
||||
/// that, not a pane that quietly forgot what they starred.
|
||||
function missingRow(section, id) {
|
||||
return {
|
||||
id: `${id}/missing`,
|
||||
kind: 'notice',
|
||||
label: `${section.name} is not in the index`,
|
||||
detail: '',
|
||||
icon: '⚠',
|
||||
depth: 1,
|
||||
hasChildren: false,
|
||||
expanded: false,
|
||||
warning: true,
|
||||
bookmarked: false,
|
||||
};
|
||||
}
|
||||
|
||||
/// A bookmark is a path from a root, and the same path exists once per section
|
||||
/// that contains it — behind that section's prefix.
|
||||
function isBookmarked(id, bookmarkId) {
|
||||
if (!bookmarkId) return false;
|
||||
return id === bookmarkId || id.endsWith(`/${bookmarkId}`);
|
||||
}
|
||||
|
||||
/// What a row's menu is chosen by: its kind, whether its module is a DUT, and
|
||||
/// whether that DUT came from the settings rather than from a star.
|
||||
function decorate(rows, duts, locked) {
|
||||
const starred = new Set(duts);
|
||||
const fromSettings = new Set(locked);
|
||||
return rows.map((row) => {
|
||||
if (row.kind === 'section' || row.kind === 'notice') {
|
||||
return { ...row, contextValue: row.kind };
|
||||
}
|
||||
if (!row.moduleName || !starred.has(row.moduleName)) {
|
||||
return { ...row, contextValue: row.kind };
|
||||
}
|
||||
if (!fromSettings.has(row.moduleName)) {
|
||||
return { ...row, contextValue: `${row.kind}.dut` };
|
||||
}
|
||||
return { ...row, contextValue: `${row.kind}.dut.locked`, title: LOCKED.title };
|
||||
});
|
||||
}
|
||||
|
||||
/// `contextValue` → the menu that row offers. Sent once per render, so the
|
||||
/// renderer holds no rule of its own and this table is the whole contract.
|
||||
function menuTable() {
|
||||
return {
|
||||
section: [],
|
||||
notice: [],
|
||||
module: [STAR],
|
||||
'module.dut': [UNSTAR],
|
||||
'module.dut.locked': [LOCKED],
|
||||
instance: [...INSTANCE_ACTIONS, STAR],
|
||||
'instance.dut': [...INSTANCE_ACTIONS, UNSTAR],
|
||||
'instance.dut.locked': [...INSTANCE_ACTIONS, LOCKED],
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
LOCKED,
|
||||
OTHERS_ID,
|
||||
decorate,
|
||||
defaultOpenIds,
|
||||
menuTable,
|
||||
parentIndex,
|
||||
sectionPrefixes,
|
||||
sectionRows,
|
||||
sections,
|
||||
};
|
||||
@@ -0,0 +1,622 @@
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { buildHierarchy, treeRows } = require('./hierarchyModel');
|
||||
const {
|
||||
LOCKED,
|
||||
decorate,
|
||||
defaultOpenIds,
|
||||
menuTable,
|
||||
sectionPrefixes,
|
||||
sectionRows,
|
||||
sections,
|
||||
} = require('./hierarchySections');
|
||||
|
||||
// The same schema-2 wire the model tests use: a file table, four-number ranges,
|
||||
// no ids and no per-instance `definitions`.
|
||||
function site(file, line, start, end) {
|
||||
return { file, range: [line, 0, line, end + 3], selectionRange: [line, start, line, end] };
|
||||
}
|
||||
|
||||
/** A DV bench above a DUT above three leaves, plus two unrelated modules. */
|
||||
function fixture() {
|
||||
const files = [
|
||||
'file:///tb.sv', 'file:///dut.sv', 'file:///l1.sv', 'file:///l2.sv',
|
||||
'file:///l3.sv', 'file:///lonely.sv', 'file:///other.sv',
|
||||
];
|
||||
return {
|
||||
schemaVersion: 2,
|
||||
revision: 7,
|
||||
complete: true,
|
||||
files,
|
||||
modules: [
|
||||
{ moduleName: 'tb', definition: site(0, 0, 7, 9), instances: [
|
||||
{ instanceName: 'u_dut', moduleName: 'dut', site: site(0, 1, 4, 9) },
|
||||
] },
|
||||
{ moduleName: 'dut', definition: site(1, 0, 7, 10), instances: [
|
||||
{ instanceName: 'u_l1', moduleName: 'leaf1', site: site(1, 1, 6, 10) },
|
||||
{ instanceName: 'u_l2', moduleName: 'leaf2', site: site(1, 2, 6, 10) },
|
||||
{ instanceName: 'u_l3', moduleName: 'leaf3', site: site(1, 3, 6, 10) },
|
||||
] },
|
||||
{ moduleName: 'leaf1', definition: site(2, 0, 7, 12), instances: [] },
|
||||
{ moduleName: 'leaf2', definition: site(3, 0, 7, 12), instances: [] },
|
||||
{ moduleName: 'leaf3', definition: site(4, 0, 7, 12), instances: [] },
|
||||
{ moduleName: 'lonely', definition: site(5, 0, 7, 13), instances: [] },
|
||||
{ moduleName: 'other_top', definition: site(6, 0, 7, 16), instances: [] },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** A snapshot from `{ module: [instantiated type, …] }`: one file and one
|
||||
* declaration per module, and one instance `u_<type>` per named type. */
|
||||
function graph(spec) {
|
||||
const names = Object.keys(spec);
|
||||
return {
|
||||
schemaVersion: 2,
|
||||
revision: 1,
|
||||
complete: true,
|
||||
files: names.map((name) => `file:///${name}.sv`),
|
||||
modules: names.map((name, at) => ({
|
||||
moduleName: name,
|
||||
definition: site(at, 0, 7, 7 + name.length),
|
||||
instances: spec[name].map((type, index) => ({
|
||||
instanceName: `u_${type}`,
|
||||
moduleName: type,
|
||||
site: site(at, index + 1, 4, 9),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every id in a section list, opened all the way down. */
|
||||
function openEverything(model, list) {
|
||||
const expanded = new Set();
|
||||
for (let pass = 0; pass < 12; pass += 1) {
|
||||
const { rows } = sectionRows(model, list, expanded, '');
|
||||
const before = expanded.size;
|
||||
for (const row of rows) if (row.hasChildren) expanded.add(row.id);
|
||||
if (expanded.size === before) break;
|
||||
}
|
||||
return sectionRows(model, list, expanded, '');
|
||||
}
|
||||
|
||||
function shape(model, list) {
|
||||
return openEverything(model, list).rows.map((row) => `${' '.repeat(row.depth)}${row.label}`);
|
||||
}
|
||||
|
||||
function noDutIsOneSectionAndThePlainRoots() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, []);
|
||||
assert.equal(list.length, 1, 'zero DUTs is the others section on its own');
|
||||
assert.equal(list[0].kind, 'others');
|
||||
assert.deepEqual(
|
||||
list[0].roots.map(({ module }) => module.moduleName),
|
||||
model.roots.map(({ module }) => module.moduleName),
|
||||
'and it holds exactly today’s roots',
|
||||
);
|
||||
}
|
||||
|
||||
function oneDutIsThreeSectionsAndTwoAreFive() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const one = sections(model, ['dut']);
|
||||
assert.deepEqual(one.map((section) => section.kind), ['dut', 'parents', 'others']);
|
||||
const two = sections(model, ['dut', 'other_top']);
|
||||
assert.deepEqual(
|
||||
two.map((section) => `${section.kind}:${section.name || ''}`),
|
||||
['dut:dut', 'parents:dut', 'dut:other_top', 'parents:other_top', 'others:'],
|
||||
'per DUT its own two sections, in starred order, then one others',
|
||||
);
|
||||
}
|
||||
|
||||
function theDutSectionIsTheForwardSubtreeAndTheParentsSectionIsTheUpwardTree() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, ['dut']);
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: dut',
|
||||
' dut',
|
||||
' u_l1 (leaf1)',
|
||||
' u_l2 (leaf2)',
|
||||
' u_l3 (leaf3)',
|
||||
'Parents of dut',
|
||||
' dut',
|
||||
' tb',
|
||||
'Other modules',
|
||||
' lonely',
|
||||
' other_top',
|
||||
]);
|
||||
|
||||
// The upward row says which instance reaches the DUT, and points at the
|
||||
// instantiating module's own declaration.
|
||||
const { rows, nodes } = openEverything(model, list);
|
||||
const upward = rows.find((row) => row.label === 'tb' && row.depth === 2);
|
||||
assert.equal(upward.detail, 'via u_dut');
|
||||
const node = nodes.get(upward.id);
|
||||
assert.equal(node.definition.uri, 'file:///tb.sv', 'the parent module’s declaration');
|
||||
assert.equal(node.site.uri, 'file:///tb.sv');
|
||||
assert.equal(node.kind, 'module');
|
||||
|
||||
// The DUT's own subtree is the node the plain view shows for it: same
|
||||
// children, same order, same labels.
|
||||
const plainDut = treeRows(model, new Set(), '').rows;
|
||||
assert(!plainDut.some((row) => row.label === 'dut'), 'dut is not a root of the plain view');
|
||||
const dutRows = rows.filter((row) => row.depth >= 2 && row.id.startsWith('dut:dut/'));
|
||||
assert.deepEqual(dutRows.map((row) => row.label), ['u_l1 (leaf1)', 'u_l2 (leaf2)', 'u_l3 (leaf3)']);
|
||||
}
|
||||
|
||||
function othersHoldsEveryModuleOutsideEveryDut() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const [, , others] = sections(model, ['dut']);
|
||||
assert.deepEqual(
|
||||
others.roots.map(({ module }) => module.moduleName),
|
||||
['lonely', 'other_top'],
|
||||
'tb is above the DUT and is gone; the two unrelated roots stay',
|
||||
);
|
||||
// A leaf is below the DUT and was never a root, so nothing changed for it;
|
||||
// what the exclusion actually removes is the ancestor root.
|
||||
const plainRoots = model.roots.map(({ module }) => module.moduleName);
|
||||
assert.deepEqual(plainRoots, ['lonely', 'other_top', 'tb']);
|
||||
|
||||
// Starring a leaf takes `tb` (an ancestor) and `dut` (an ancestor) out, which
|
||||
// leaves the two *other* leaves with no parent on screen: they are not below
|
||||
// the DUT, so others re-roots them, in the model's alphabetical order.
|
||||
const [, , leafOthers] = sections(model, ['leaf2']);
|
||||
assert.deepEqual(
|
||||
leafOthers.roots.map(({ module }) => module.moduleName),
|
||||
['leaf1', 'leaf3', 'lonely', 'other_top'],
|
||||
);
|
||||
}
|
||||
|
||||
/** The bench beside the DUT: `monitor` is not a child of the DUT, so it is in
|
||||
* others — re-rooted, because the exclusion took its only parent. */
|
||||
function aModuleUnderAnExcludedBenchIsReRootedInOthers() {
|
||||
const model = buildHierarchy(graph({
|
||||
bench: ['dut', 'monitor'], dut: ['leaf'], monitor: ['probe'], leaf: [], probe: [], spare: [],
|
||||
}));
|
||||
const list = sections(model, ['dut']);
|
||||
const [, , others] = list;
|
||||
assert.deepEqual(others.roots.map(({ module }) => module.moduleName), ['monitor', 'spare']);
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: dut',
|
||||
' dut',
|
||||
' u_leaf (leaf)',
|
||||
'Parents of dut',
|
||||
' dut',
|
||||
' bench',
|
||||
'Other modules',
|
||||
' monitor',
|
||||
' u_probe (probe)',
|
||||
' spare',
|
||||
]);
|
||||
// Nothing the snapshot holds is off screen while the DUT is starred.
|
||||
const shown = new Set(shape(model, list).map((line) => line.trim().replace(/^.*\((.*)\)$/, '$1')));
|
||||
for (const module of model.modules) {
|
||||
assert(shown.has(module.moduleName), `${module.moduleName} is in no section`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Two benches instantiate one module and both are excluded: it is re-rooted
|
||||
* once, not once per bench. */
|
||||
function aModuleUnderTwoExcludedBenchesIsReRootedOnce() {
|
||||
const model = buildHierarchy(graph({
|
||||
bench_a: ['dut', 'shared'], bench_b: ['dut', 'shared'], dut: [], shared: [],
|
||||
}));
|
||||
const [, , others] = sections(model, ['dut']);
|
||||
assert.deepEqual(others.roots.map(({ module }) => module.moduleName), ['shared']);
|
||||
assert.equal(others.roots.length, 1);
|
||||
}
|
||||
|
||||
/** One excluded parent and one ordinary one: the module keeps its place under
|
||||
* the ordinary parent and is not re-rooted beside it. */
|
||||
function aModuleWithOneOrdinaryParentIsNotReRooted() {
|
||||
const model = buildHierarchy(graph({
|
||||
bench: ['dut', 'util'], top: ['util'], dut: [], util: [],
|
||||
}));
|
||||
const list = sections(model, ['dut']);
|
||||
const [, , others] = list;
|
||||
assert.deepEqual(others.roots.map(({ module }) => module.moduleName), ['top']);
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: dut',
|
||||
' dut',
|
||||
'Parents of dut',
|
||||
' dut',
|
||||
' bench',
|
||||
'Other modules',
|
||||
' top',
|
||||
' u_util (util)',
|
||||
]);
|
||||
const util = shape(model, list).filter((line) => line.includes('util'));
|
||||
assert.equal(util.length, 1, 'shown once, under the parent it always had');
|
||||
}
|
||||
|
||||
/** DUT2's bench is a sibling of DUT1 under one top bench: both are excluded,
|
||||
* and the monitor beside DUT2 is the only thing others re-roots. */
|
||||
function twoDutsSharingABenchLeaveOthersCorrect() {
|
||||
const model = buildHierarchy(graph({
|
||||
bench: ['dut1', 'sub_bench'], sub_bench: ['dut2', 'monitor'],
|
||||
dut1: [], dut2: [], monitor: [], spare: [],
|
||||
}));
|
||||
const list = sections(model, ['dut1', 'dut2']);
|
||||
assert.equal(list.length, 5);
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: dut1',
|
||||
' dut1',
|
||||
'Parents of dut1',
|
||||
' dut1',
|
||||
' bench',
|
||||
'DUT: dut2',
|
||||
' dut2',
|
||||
'Parents of dut2',
|
||||
' dut2',
|
||||
' sub_bench',
|
||||
' bench',
|
||||
'Other modules',
|
||||
' monitor',
|
||||
' spare',
|
||||
]);
|
||||
}
|
||||
|
||||
/** A cycle whose only way in is an excluded bench: no member has a parent
|
||||
* outside it, so others opens it at the model's own fallback root. */
|
||||
function aCycleReachableOnlyThroughAnExcludedBenchStillHasARoot() {
|
||||
const model = buildHierarchy(graph({
|
||||
bench: ['dut', 'a'], a: ['b'], b: ['a'], dut: [],
|
||||
}));
|
||||
const list = sections(model, ['dut']);
|
||||
const [, , others] = list;
|
||||
assert.deepEqual(others.roots.map(({ module }) => module.moduleName), ['a']);
|
||||
assert.equal(others.roots[0].fallback, true, 'marked recursive, as the plain view marks it');
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: dut',
|
||||
' dut',
|
||||
'Parents of dut',
|
||||
' dut',
|
||||
' bench',
|
||||
'Other modules',
|
||||
' a',
|
||||
' u_b (b)',
|
||||
' u_a (a)',
|
||||
]);
|
||||
}
|
||||
|
||||
/** `mid` is below DUT1 and above DUT2: it belongs to both DUT sections and to
|
||||
* neither others. */
|
||||
function aModuleBothBelowOneDutAndAboveAnotherIsInBothSections() {
|
||||
const model = buildHierarchy({
|
||||
schemaVersion: 2,
|
||||
revision: 1,
|
||||
complete: true,
|
||||
files: ['file:///top.sv', 'file:///mid.sv', 'file:///low.sv', 'file:///spare.sv'],
|
||||
modules: [
|
||||
{ moduleName: 'top', definition: site(0, 0, 7, 10), instances: [
|
||||
{ instanceName: 'u_mid', moduleName: 'mid', site: site(0, 1, 4, 9) },
|
||||
] },
|
||||
{ moduleName: 'mid', definition: site(1, 0, 7, 10), instances: [
|
||||
{ instanceName: 'u_low', moduleName: 'low', site: site(1, 1, 4, 9) },
|
||||
] },
|
||||
{ moduleName: 'low', definition: site(2, 0, 7, 10), instances: [] },
|
||||
{ moduleName: 'spare', definition: site(3, 0, 7, 12), instances: [] },
|
||||
],
|
||||
});
|
||||
const list = sections(model, ['top', 'low']);
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: top',
|
||||
' top',
|
||||
' u_mid (mid)',
|
||||
' u_low (low)',
|
||||
'Parents of top',
|
||||
' top',
|
||||
'DUT: low',
|
||||
' low',
|
||||
'Parents of low',
|
||||
' low',
|
||||
' mid',
|
||||
' top',
|
||||
'Other modules',
|
||||
' spare',
|
||||
]);
|
||||
const [, , , , others] = list;
|
||||
assert.deepEqual(others.roots.map(({ module }) => module.moduleName), ['spare']);
|
||||
|
||||
// The same module in two sections is two rows with two ids, so opening one
|
||||
// never opens the other.
|
||||
const { rows } = openEverything(model, list);
|
||||
const midRows = rows.filter((row) => row.label.includes('mid'));
|
||||
assert.equal(midRows.length, 2);
|
||||
assert.equal(new Set(midRows.map((row) => row.id)).size, 2);
|
||||
assert(midRows.some((row) => row.id.startsWith('dut:top/')));
|
||||
assert(midRows.some((row) => row.id.startsWith('parents:low/')));
|
||||
}
|
||||
|
||||
/** `a` instantiates `b` instantiates `a`: the upward walk cuts the cycle with
|
||||
* its visited set, exactly as the forward walk does. */
|
||||
function theParentsWalkCutsACycle() {
|
||||
const model = buildHierarchy({
|
||||
schemaVersion: 2,
|
||||
revision: 1,
|
||||
complete: true,
|
||||
files: ['file:///a.sv', 'file:///b.sv'],
|
||||
modules: [
|
||||
{ moduleName: 'a', definition: site(0, 0, 7, 8), instances: [
|
||||
{ instanceName: 'u_b', moduleName: 'b', site: site(0, 1, 4, 7) },
|
||||
] },
|
||||
{ moduleName: 'b', definition: site(1, 0, 7, 8), instances: [
|
||||
{ instanceName: 'u_a', moduleName: 'a', site: site(1, 1, 4, 7) },
|
||||
] },
|
||||
],
|
||||
});
|
||||
const list = sections(model, ['a']);
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: a',
|
||||
' a',
|
||||
' u_b (b)',
|
||||
' u_a (a)',
|
||||
'Parents of a',
|
||||
' a',
|
||||
' b',
|
||||
' a',
|
||||
'Other modules',
|
||||
]);
|
||||
const { rows } = openEverything(model, list);
|
||||
const cut = rows.filter((row) => row.id.startsWith('parents:a/') && row.detail === 'recursive');
|
||||
assert.equal(cut.length, 1, 'the edge that closes the cycle is marked once');
|
||||
assert.equal(cut[0].label, 'a');
|
||||
assert.equal(cut[0].hasChildren, false, 'and does not open again');
|
||||
assert.equal(cut[0].warning, true);
|
||||
}
|
||||
|
||||
function aStarredNameTheSnapshotLacksKeepsItsSections() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, ['renamed_away']);
|
||||
assert.equal(list.length, 3, 'a missing DUT still costs three sections');
|
||||
assert.equal(list[0].root, undefined);
|
||||
assert.deepEqual(shape(model, list), [
|
||||
'DUT: renamed_away',
|
||||
' renamed_away is not in the index',
|
||||
'Parents of renamed_away',
|
||||
' renamed_away is not in the index',
|
||||
'Other modules',
|
||||
' lonely',
|
||||
' other_top',
|
||||
' tb',
|
||||
' u_dut (dut)',
|
||||
' u_l1 (leaf1)',
|
||||
' u_l2 (leaf2)',
|
||||
' u_l3 (leaf3)',
|
||||
]);
|
||||
const notice = openEverything(model, list).rows.find((row) => row.kind === 'notice');
|
||||
assert.equal(notice.hasChildren, false);
|
||||
assert.equal(notice.warning, true);
|
||||
}
|
||||
|
||||
function twoDeclarationsOfOneNameAreMarkedAmbiguous() {
|
||||
const raw = fixture();
|
||||
raw.files.push('file:///dut-again.sv');
|
||||
raw.modules.push({ moduleName: 'dut', definition: site(7, 0, 7, 10), instances: [] });
|
||||
const model = buildHierarchy(raw);
|
||||
const [dut, parents] = sections(model, ['dut']);
|
||||
assert.equal(dut.ambiguous, true);
|
||||
assert.equal(parents.ambiguous, true);
|
||||
assert(dut.root, 'the first declaration in the model’s order is what is shown');
|
||||
const header = sectionRows(model, [dut], new Set(), '').rows[0];
|
||||
assert.equal(header.detail, 'ambiguous');
|
||||
}
|
||||
|
||||
function sectionsAreCollapsedUntilOpenedAndOnlyTheDutOnesOpenByDefault() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, ['dut']);
|
||||
const closed = sectionRows(model, list, new Set(), '');
|
||||
assert.deepEqual(
|
||||
closed.rows.map((row) => row.label),
|
||||
['DUT: dut', 'Parents of dut', 'Other modules'],
|
||||
'a closed section builds none of its tree',
|
||||
);
|
||||
assert(closed.rows.every((row) => row.kind === 'section' && row.hasChildren && !row.expanded));
|
||||
|
||||
const seeded = new Set(defaultOpenIds(list));
|
||||
assert.deepEqual([...seeded], ['sec:dut:dut', 'dut:dut/root:file:///dut.sv#0:7',
|
||||
'sec:parents:dut', 'parents:dut/up:file:///dut.sv#0:7']);
|
||||
assert(!seeded.has('sec:others'), 'others is not opened for the user');
|
||||
assert.deepEqual(
|
||||
sectionRows(model, list, seeded, '').rows.map((row) => row.label),
|
||||
['DUT: dut', 'dut', 'u_l1 (leaf1)', 'u_l2 (leaf2)', 'u_l3 (leaf3)',
|
||||
'Parents of dut', 'dut', 'tb', 'Other modules'],
|
||||
'starring opens the two sections and the DUT row inside each, one level',
|
||||
);
|
||||
}
|
||||
|
||||
function sectionRowsMatchTheShapeTheViewAlreadyRenders() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, ['dut']);
|
||||
const { rows } = openEverything(model, list);
|
||||
const keys = ['id', 'kind', 'label', 'detail', 'depth', 'hasChildren', 'expanded',
|
||||
'warning', 'bookmarked'];
|
||||
for (const row of rows) {
|
||||
for (const key of keys) assert(key in row, `${key} is missing from ${row.label}`);
|
||||
assert.equal(typeof row.depth, 'number');
|
||||
}
|
||||
// Depth 0 is the header; everything under it is one level deeper than the
|
||||
// plain tree would put it.
|
||||
assert.equal(rows.filter((row) => row.depth === 0).length, 3);
|
||||
}
|
||||
|
||||
/** A bookmark is a path, and it is painted wherever that path is on screen —
|
||||
* behind the section prefix as readily as at the top level. */
|
||||
function aBookmarkIsPaintedWhereverItsPathIsShown() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const openAll = (list) => {
|
||||
const expanded = new Set();
|
||||
for (let pass = 0; pass < 12; pass += 1) {
|
||||
for (const row of sectionRows(model, list, expanded, '').rows) {
|
||||
if (row.hasChildren) expanded.add(row.id);
|
||||
}
|
||||
}
|
||||
return expanded;
|
||||
};
|
||||
|
||||
// Bookmarked from inside the DUT section, the path is DUT-relative
|
||||
// (`dut.u_l2`) — which resolves only because `bookmarkChain` retries over
|
||||
// every module — and it is found behind the section's prefix.
|
||||
const starred = sections(model, ['dut']);
|
||||
const inDut = sectionRows(model, starred, openAll(starred), 'dut.u_l2').rows
|
||||
.filter((row) => row.bookmarked);
|
||||
assert.equal(inDut.length, 1);
|
||||
assert.equal(inDut[0].label, 'u_l2 (leaf2)');
|
||||
assert(inDut[0].id.startsWith('dut:dut/'));
|
||||
assert.deepEqual(sectionPrefixes(['dut']), ['dut:dut/', 'parents:dut/']);
|
||||
|
||||
// Bookmarked from the others section, the path is the ordinary one and the
|
||||
// ordinary id matches.
|
||||
const elsewhere = sections(model, ['other_top']);
|
||||
const inOthers = sectionRows(model, elsewhere, openAll(elsewhere), 'tb.u_dut.u_l2').rows
|
||||
.filter((row) => row.bookmarked);
|
||||
assert.equal(inOthers.length, 1);
|
||||
assert.equal(inOthers[0].label, 'u_l2 (leaf2)');
|
||||
|
||||
// The documented consequence: a path whose root the exclusion removed is not
|
||||
// on screen, so nothing is painted. The bookmark is not dropped — the model
|
||||
// still resolves it — and unstarring brings it back.
|
||||
const hidden = sectionRows(model, starred, openAll(starred), 'tb.u_dut.u_l2').rows
|
||||
.filter((row) => row.bookmarked);
|
||||
assert.equal(hidden.length, 0, 'tb is above the DUT, so that path has no rows');
|
||||
assert(idForPathStillResolves(model, 'tb.u_dut.u_l2'), 'and the bookmark survives');
|
||||
}
|
||||
|
||||
function idForPathStillResolves(model, path) {
|
||||
return Boolean(require('./hierarchyModel').idForPath(model, path));
|
||||
}
|
||||
|
||||
function contextValuesAndMenusSayWhatEachRowOffers() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, ['dut']);
|
||||
const { rows } = openEverything(model, list);
|
||||
const decorated = decorate(rows, ['dut'], []);
|
||||
const byLabel = (label) => decorated.find((row) => row.label === label);
|
||||
assert.equal(byLabel('DUT: dut').contextValue, 'section');
|
||||
assert.equal(byLabel('dut').contextValue, 'module.dut', 'the starred module offers Unstar');
|
||||
assert.equal(byLabel('tb').contextValue, 'module', 'any other module offers Star');
|
||||
assert.equal(byLabel('u_l1 (leaf1)').contextValue, 'instance');
|
||||
|
||||
// An instance row is starred by its type, not by its instance name — checked
|
||||
// on the plain rows, where `u_dut` is on screen (with `dut` starred its own
|
||||
// root is above the DUT and excluded).
|
||||
const plain = decorate(treeRows(model, new Set(openEverything(model, sections(model, []))
|
||||
.rows.map((row) => row.id)), '').rows, ['dut'], []);
|
||||
assert.equal(plain.find((row) => row.label === 'u_dut (dut)').contextValue, 'instance.dut');
|
||||
assert.equal(plain.find((row) => row.label === 'tb').contextValue, 'module');
|
||||
|
||||
const table = menuTable();
|
||||
assert.deepEqual(table.section, []);
|
||||
assert.deepEqual(table.module.map((item) => item.action), ['starDut']);
|
||||
assert.deepEqual(table['module.dut'].map((item) => item.action), ['unstarDut']);
|
||||
assert.deepEqual(table.instance.map((item) => item.action),
|
||||
['copyPath', 'definition', 'instance', 'bookmark', 'openRight', 'starDut']);
|
||||
assert.deepEqual(table['instance.dut'].map((item) => item.action),
|
||||
['copyPath', 'definition', 'instance', 'bookmark', 'openRight', 'unstarDut']);
|
||||
// Every contextValue `decorate` can produce must have a menu, or a row would
|
||||
// silently offer nothing.
|
||||
for (const kind of ['section', 'notice', 'module', 'instance']) {
|
||||
for (const suffix of ['', '.dut', '.dut.locked']) {
|
||||
if ((kind === 'section' || kind === 'notice') && suffix !== '') continue;
|
||||
assert(Array.isArray(table[`${kind}${suffix}`]), `no menu for ${kind}${suffix}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function aDutFromTheSettingsIsLockedAndSaysWhy() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, ['dut']);
|
||||
const decorated = decorate(openEverything(model, list).rows, ['dut'], ['dut']);
|
||||
const row = decorated.find((candidate) => candidate.label === 'dut');
|
||||
assert.equal(row.contextValue, 'module.dut.locked');
|
||||
assert.match(row.title, /lucisv\.hierarchy\.duts/, 'the tooltip names the setting');
|
||||
const [item] = menuTable()['module.dut.locked'];
|
||||
assert.equal(item.disabled, true);
|
||||
assert.equal(item.action, 'lockedDut');
|
||||
assert.equal(item.title, LOCKED.title);
|
||||
}
|
||||
|
||||
/** The pane with no DUT starred is the pane as it was: `sections()` is not on
|
||||
* the path at all, and the rows the view sends are `treeRows`' own. */
|
||||
function thePlainViewIsUntouched() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const open = new Set(treeRows(model, new Set(), '').rows.map((row) => row.id));
|
||||
const plain = treeRows(model, open, '');
|
||||
const decorated = decorate(plain.rows, [], []);
|
||||
const visible = ['id', 'kind', 'label', 'detail', 'depth', 'hasChildren', 'expanded',
|
||||
'warning', 'bookmarked'];
|
||||
for (let at = 0; at < plain.rows.length; at += 1) {
|
||||
for (const key of visible) {
|
||||
assert.deepEqual(decorated[at][key], plain.rows[at][key], `${key} changed on ${plain.rows[at].label}`);
|
||||
}
|
||||
assert.equal(decorated[at].contextValue, plain.rows[at].kind, 'nothing is a DUT');
|
||||
assert.equal(decorated[at].title, undefined);
|
||||
}
|
||||
assert.deepEqual(plain.rows.map((row) => row.label),
|
||||
['lonely', 'other_top', 'tb', 'u_dut (dut)']);
|
||||
}
|
||||
|
||||
/** The commands the menus and the pane's own rows fire have to exist, and the
|
||||
* view's title entries have to be gated on this view. */
|
||||
function packageJsonContributesTheCommandsMenusAndSetting() {
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
||||
const commands = manifest.contributes.commands.map((command) => command.command);
|
||||
for (const name of ['lucisv.hierarchy.starDut', 'lucisv.hierarchy.unstarDut',
|
||||
'lucisv.hierarchy.clearDuts']) {
|
||||
assert(commands.includes(name), `${name} is not contributed`);
|
||||
}
|
||||
const title = manifest.contributes.menus['view/title'];
|
||||
for (const name of ['lucisv.hierarchy.starDut', 'lucisv.hierarchy.unstarDut',
|
||||
'lucisv.hierarchy.clearDuts', 'lucisv.hierarchy.refresh',
|
||||
'lucisv.hierarchy.clearBookmark']) {
|
||||
const entry = title.find((item) => item.command === name);
|
||||
assert(entry, `${name} has no view/title entry`);
|
||||
assert.equal(entry.when, 'view == lucisv.hierarchy', `${name}'s when clause`);
|
||||
}
|
||||
const setting = manifest.contributes.configuration.properties['lucisv.hierarchy.duts'];
|
||||
assert.equal(setting.type, 'array');
|
||||
assert.equal(setting.items.type, 'string');
|
||||
assert.deepEqual(setting.default, []);
|
||||
// Every action the menu table can post must be one the view answers; the
|
||||
// view's own test covers the answering, this pins the vocabulary.
|
||||
const actions = new Set(Object.values(menuTable()).flat().map((item) => item.action));
|
||||
assert.deepEqual([...actions].sort(), ['bookmark', 'copyPath', 'definition', 'instance',
|
||||
'lockedDut', 'openRight', 'starDut', 'unstarDut']);
|
||||
}
|
||||
|
||||
/** The upward walk must not cost a pass over the design per opened row: the
|
||||
* reverse index is built once and reused. */
|
||||
function theReverseIndexIsBuiltOncePerSnapshot() {
|
||||
const model = buildHierarchy(fixture());
|
||||
const list = sections(model, ['dut']);
|
||||
assert(model.parentsByTarget instanceof Map, 'memoized on the model');
|
||||
const first = model.parentsByTarget;
|
||||
openEverything(model, list);
|
||||
sections(model, ['leaf1']);
|
||||
assert.equal(model.parentsByTarget, first, 'and never rebuilt for the same snapshot');
|
||||
}
|
||||
|
||||
for (const test of [
|
||||
noDutIsOneSectionAndThePlainRoots,
|
||||
oneDutIsThreeSectionsAndTwoAreFive,
|
||||
theDutSectionIsTheForwardSubtreeAndTheParentsSectionIsTheUpwardTree,
|
||||
othersHoldsEveryModuleOutsideEveryDut,
|
||||
aModuleUnderAnExcludedBenchIsReRootedInOthers,
|
||||
aModuleUnderTwoExcludedBenchesIsReRootedOnce,
|
||||
aModuleWithOneOrdinaryParentIsNotReRooted,
|
||||
twoDutsSharingABenchLeaveOthersCorrect,
|
||||
aCycleReachableOnlyThroughAnExcludedBenchStillHasARoot,
|
||||
aModuleBothBelowOneDutAndAboveAnotherIsInBothSections,
|
||||
theParentsWalkCutsACycle,
|
||||
aStarredNameTheSnapshotLacksKeepsItsSections,
|
||||
twoDeclarationsOfOneNameAreMarkedAmbiguous,
|
||||
sectionsAreCollapsedUntilOpenedAndOnlyTheDutOnesOpenByDefault,
|
||||
sectionRowsMatchTheShapeTheViewAlreadyRenders,
|
||||
aBookmarkIsPaintedWhereverItsPathIsShown,
|
||||
contextValuesAndMenusSayWhatEachRowOffers,
|
||||
aDutFromTheSettingsIsLockedAndSaysWhy,
|
||||
thePlainViewIsUntouched,
|
||||
packageJsonContributesTheCommandsMenusAndSetting,
|
||||
theReverseIndexIsBuiltOncePerSnapshot,
|
||||
]) test();
|
||||
|
||||
console.log('hierarchy sections: OK — three sections per DUT, five for two, the upward tree, cycles cut, missing names, others holding and re-rooting everything outside every DUT, menus, the setting lock, and the plain view untouched');
|
||||
+166
-15
@@ -8,11 +8,24 @@ const {
|
||||
searchTarget,
|
||||
treeRows,
|
||||
} = require('./hierarchyModel');
|
||||
const {
|
||||
OTHERS_ID,
|
||||
decorate,
|
||||
defaultOpenIds,
|
||||
menuTable,
|
||||
sectionPrefixes,
|
||||
sectionRows,
|
||||
sections,
|
||||
} = require('./hierarchySections');
|
||||
|
||||
const VIEW_ID = 'lucisv.hierarchy';
|
||||
const SNAPSHOT_METHOD = 'lucisv/moduleHierarchy';
|
||||
const CHANGED_METHOD = 'lucisv/moduleHierarchyChanged';
|
||||
const BOOKMARK_KEY = 'lucisv.hierarchy.bookmark';
|
||||
/** The starred DUTs of this workspace, in the order they were starred. */
|
||||
const DUTS_KEY = 'lucisv.hierarchy.duts';
|
||||
/** The same list as a setting, so a team can check theirs in. */
|
||||
const DUTS_SETTING = 'hierarchy.duts';
|
||||
const REFRESH_DEBOUNCE_MS = 100;
|
||||
|
||||
class HierarchyView {
|
||||
@@ -24,13 +37,18 @@ class HierarchyView {
|
||||
this.query = '';
|
||||
// Which rows the user has opened. Row ids are composed from URIs and
|
||||
// declaration positions, so they survive a refresh and what was open stays
|
||||
// open — nothing is expanded on the user's behalf (owner, 2026-08-29).
|
||||
// open — nothing is expanded on the user's behalf (owner, 2026-08-29)
|
||||
// except what the user asked for by bookmarking or by starring a DUT.
|
||||
this.expanded = new Set();
|
||||
this.nodes = new Map();
|
||||
this.request = 0;
|
||||
this.refreshTimer = undefined;
|
||||
this.bookmarkPath = context.workspaceState.get(BOOKMARK_KEY, '');
|
||||
this.lostBookmarkReported = false;
|
||||
// The DUTs this workspace starred, in starred order. The settings may name
|
||||
// more; `duts()` is the union the pane actually shows.
|
||||
this.starred = moduleNames(context.workspaceState.get(DUTS_KEY, []));
|
||||
this.seededFor = undefined;
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(VIEW_ID, this, {
|
||||
@@ -38,11 +56,32 @@ class HierarchyView {
|
||||
}),
|
||||
vscode.commands.registerCommand('lucisv.hierarchy.refresh', () => this.refresh()),
|
||||
vscode.commands.registerCommand('lucisv.hierarchy.clearBookmark', () => this.setBookmark('')),
|
||||
vscode.commands.registerCommand('lucisv.hierarchy.starDut', (name) => this.starDut(name)),
|
||||
vscode.commands.registerCommand('lucisv.hierarchy.unstarDut', (name) => this.unstarDut(name)),
|
||||
vscode.commands.registerCommand('lucisv.hierarchy.clearDuts', () => this.clearDuts()),
|
||||
vscode.workspace.onDidChangeConfiguration((event) => {
|
||||
if (!event.affectsConfiguration('lucisv.hierarchy.duts')) return;
|
||||
this.seededFor = undefined;
|
||||
this.render();
|
||||
}),
|
||||
client.onNotification(CHANGED_METHOD, () => this.scheduleRefresh()),
|
||||
{ dispose: () => clearTimeout(this.refreshTimer) },
|
||||
);
|
||||
}
|
||||
|
||||
/// The DUTs the settings name: a checked-in list the pane shows but will not
|
||||
/// edit, so its entries are locked against unstarring.
|
||||
lockedDuts() {
|
||||
return moduleNames(vscode.workspace.getConfiguration('lucisv').get(DUTS_SETTING, []));
|
||||
}
|
||||
|
||||
/// The effective list: the settings' DUTs first, then this workspace's own
|
||||
/// stars in the order they were made.
|
||||
duts() {
|
||||
const locked = this.lockedDuts();
|
||||
return [...locked, ...this.starred.filter((name) => !locked.includes(name))];
|
||||
}
|
||||
|
||||
resolveWebviewView(view) {
|
||||
this.view = view;
|
||||
const media = vscode.Uri.joinPath(this.context.extensionUri, 'media');
|
||||
@@ -108,21 +147,50 @@ class HierarchyView {
|
||||
/// on every keystroke is what froze the UI.
|
||||
render() {
|
||||
if (!this.model) return;
|
||||
const duts = this.duts();
|
||||
const locked = this.lockedDuts();
|
||||
const common = {
|
||||
type: 'render',
|
||||
revision: this.model.revision,
|
||||
complete: this.model.complete,
|
||||
query: this.query,
|
||||
empty: this.model.roots.length === 0,
|
||||
// One table per render rather than a rule per row: the renderer shows
|
||||
// exactly the items a row's `contextValue` names and decides nothing.
|
||||
menus: menuTable(),
|
||||
};
|
||||
if (this.query.trim() !== '') {
|
||||
const found = searchHierarchy(this.model, this.query);
|
||||
this.post({ ...common, mode: 'search', rows: found.rows, truncated: found.truncated, total: found.total });
|
||||
const rows = decorate(found.rows, duts, locked);
|
||||
this.post({ ...common, mode: 'search', rows, truncated: found.truncated, total: found.total });
|
||||
return;
|
||||
}
|
||||
const tree = treeRows(this.model, this.expanded, this.bookmarkPath);
|
||||
const tree = this.treeOrSections(duts);
|
||||
this.nodes = tree.nodes;
|
||||
this.post({ ...common, mode: 'tree', rows: tree.rows, truncated: 0, total: tree.rows.length });
|
||||
const rows = decorate(tree.rows, duts, locked);
|
||||
this.post({ ...common, mode: 'tree', rows, truncated: 0, total: rows.length });
|
||||
}
|
||||
|
||||
/// With no DUT starred the pane is the plain tree, unchanged and untouched.
|
||||
treeOrSections(duts) {
|
||||
const key = duts.join('\n');
|
||||
if (duts.length === 0) {
|
||||
// Recorded even here, so re-starring after a clear seeds again.
|
||||
this.seededFor = key;
|
||||
return treeRows(this.model, this.expanded, this.bookmarkPath);
|
||||
}
|
||||
const list = sections(this.model, duts);
|
||||
this.seedExpansion(list, key);
|
||||
return sectionRows(this.model, list, this.expanded, this.bookmarkPath);
|
||||
}
|
||||
|
||||
/// Open the new sections once, when the DUT list changes — not on every
|
||||
/// render, so a section the user closes stays closed.
|
||||
seedExpansion(list, key) {
|
||||
if (this.seededFor === key) return;
|
||||
this.seededFor = key;
|
||||
for (const id of defaultOpenIds(list)) this.expanded.add(id);
|
||||
this.expanded.delete(OTHERS_ID);
|
||||
}
|
||||
|
||||
async message(message) {
|
||||
@@ -153,15 +221,32 @@ class HierarchyView {
|
||||
return;
|
||||
}
|
||||
if (message.type !== 'context' || typeof message.action !== 'string') return;
|
||||
await this.contextAction(node, message.action);
|
||||
}
|
||||
|
||||
/// One row's menu item, chosen by the host's own menu table — so an action a
|
||||
/// row does not offer is one this never sees, and every one is re-checked
|
||||
/// here anyway.
|
||||
async contextAction(node, action) {
|
||||
// Starring is about the row's module — for an instance row, its type — so
|
||||
// it is the one action a module row offers as well.
|
||||
if (action === 'starDut') {
|
||||
await this.starDut(node.moduleName);
|
||||
return;
|
||||
}
|
||||
if (action === 'unstarDut') {
|
||||
await this.unstarDut(node.moduleName);
|
||||
return;
|
||||
}
|
||||
const actions = new Set(['copyPath', 'definition', 'instance', 'bookmark', 'openRight']);
|
||||
if (!actions.has(message.action) || node.kind !== 'instance') return;
|
||||
if (!actions.has(action) || node.kind !== 'instance') return;
|
||||
// A search hit is one row for an instance however many paths reach it, so
|
||||
// it has no one full path to copy or bookmark.
|
||||
if (!node.fullPath && (message.action === 'copyPath' || message.action === 'bookmark')) {
|
||||
if (!node.fullPath && (action === 'copyPath' || action === 'bookmark')) {
|
||||
vscode.window.showWarningMessage('Clear the search to copy or bookmark an instance path.');
|
||||
return;
|
||||
}
|
||||
switch (message.action) {
|
||||
switch (action) {
|
||||
case 'copyPath':
|
||||
await vscode.env.clipboard.writeText(node.fullPath);
|
||||
break;
|
||||
@@ -187,11 +272,73 @@ class HierarchyView {
|
||||
await this.context.workspaceState.update(BOOKMARK_KEY, path || undefined);
|
||||
// The one expansion the view performs for the user, and only because the
|
||||
// user asked for it by bookmarking: the direct ancestors of the marked row.
|
||||
// A section holds its own copy of that chain, behind the section's prefix.
|
||||
const chain = path && bookmarkChain(this.model, path);
|
||||
if (chain) for (const id of chain.slice(0, -1)) this.expanded.add(id);
|
||||
const prefixes = ['', ...sectionPrefixes(this.duts())];
|
||||
if (chain) {
|
||||
for (const id of chain.slice(0, -1)) {
|
||||
for (const prefix of prefixes) this.expanded.add(`${prefix}${id}`);
|
||||
}
|
||||
}
|
||||
this.render();
|
||||
}
|
||||
|
||||
/// Star a module as DUT. Called with a name from the pane's menu, and without
|
||||
/// one from the command palette, where the module is picked from the index.
|
||||
async starDut(name) {
|
||||
const chosen = name || await this.pickModule('Star a module as DUT', this.moduleNamesInIndex());
|
||||
if (!chosen) return;
|
||||
if (this.duts().includes(chosen)) {
|
||||
vscode.window.showInformationMessage(`${chosen} is already a DUT.`);
|
||||
return;
|
||||
}
|
||||
this.starred = [...this.starred, chosen];
|
||||
await this.context.workspaceState.update(DUTS_KEY, this.starred);
|
||||
this.render();
|
||||
}
|
||||
|
||||
async unstarDut(name) {
|
||||
const chosen = name || await this.pickModule('Unstar a DUT', this.starred);
|
||||
if (!chosen) return;
|
||||
if (this.lockedDuts().includes(chosen)) {
|
||||
vscode.window.showWarningMessage(
|
||||
`${chosen} comes from the lucisv.hierarchy.duts setting. Remove it there to unstar it.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!this.starred.includes(chosen)) return;
|
||||
this.starred = this.starred.filter((starred) => starred !== chosen);
|
||||
await this.context.workspaceState.update(DUTS_KEY, this.starred.length > 0 ? this.starred : undefined);
|
||||
this.render();
|
||||
}
|
||||
|
||||
/// Clear what this workspace starred. What the settings name stays, because
|
||||
/// only the settings file can take it away.
|
||||
async clearDuts() {
|
||||
this.starred = [];
|
||||
await this.context.workspaceState.update(DUTS_KEY, undefined);
|
||||
const locked = this.lockedDuts();
|
||||
if (locked.length > 0) {
|
||||
vscode.window.showInformationMessage(
|
||||
`Cleared the starred DUTs; ${locked.join(', ')} come from the lucisv.hierarchy.duts setting.`,
|
||||
);
|
||||
}
|
||||
this.render();
|
||||
}
|
||||
|
||||
moduleNamesInIndex() {
|
||||
if (!this.model) return [];
|
||||
return [...new Set(this.model.modules.map((module) => module.moduleName))].sort();
|
||||
}
|
||||
|
||||
async pickModule(placeHolder, choices) {
|
||||
if (choices.length === 0) {
|
||||
vscode.window.showWarningMessage('There is no module to choose: the hierarchy index is empty.');
|
||||
return undefined;
|
||||
}
|
||||
return vscode.window.showQuickPick(choices, { placeHolder });
|
||||
}
|
||||
|
||||
async showDefinition(node, beside) {
|
||||
let location;
|
||||
if (node.definitions.length === 0) {
|
||||
@@ -231,6 +378,13 @@ class HierarchyView {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stored or configured DUT list, made safe: non-strings, blanks and repeats
|
||||
/// are dropped, and the order the user chose is kept.
|
||||
function moduleNames(value) {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return [...new Set(value.filter((name) => typeof name === 'string' && name.trim() !== ''))];
|
||||
}
|
||||
|
||||
function asRange(range) {
|
||||
return new vscode.Range(
|
||||
range.start.line,
|
||||
@@ -261,13 +415,10 @@ function html(webview, media) {
|
||||
<div id="tree" role="tree" aria-label="Module instance hierarchy"></div>
|
||||
<div id="results" role="listbox" aria-label="Hierarchy search results" hidden></div>
|
||||
<div id="more" hidden></div>
|
||||
<div id="menu" role="menu" aria-label="Instance actions" hidden>
|
||||
<button role="menuitem" data-action="copyPath">Copy Full Path</button>
|
||||
<button role="menuitem" data-action="definition">Show Definition</button>
|
||||
<button role="menuitem" data-action="instance">Show Instance</button>
|
||||
<button role="menuitem" data-action="bookmark">Highlight / Bookmark</button>
|
||||
<button role="menuitem" data-action="openRight">Open on the Right</button>
|
||||
</div>
|
||||
<!-- Filled per row from the menu table the host sends: which items a row
|
||||
offers depends on whether its module is a DUT, and on where that DUT
|
||||
came from. -->
|
||||
<div id="menu" role="menu" aria-label="Row actions" hidden></div>
|
||||
<script nonce="${nonce}" src="${script}"></script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
@@ -7,10 +7,16 @@ const copied = [];
|
||||
const opened = [];
|
||||
const shown = [];
|
||||
const warned = [];
|
||||
const informed = [];
|
||||
const commands = new Map();
|
||||
/** What `lucisv.hierarchy.duts` is set to, as a checked-in setting would be. */
|
||||
let configuredDuts = [];
|
||||
let picked;
|
||||
let requests = 0;
|
||||
let provider;
|
||||
let receive;
|
||||
let changed;
|
||||
let configurationChanged;
|
||||
|
||||
class Range {
|
||||
constructor(startLine, startCharacter, endLine, endCharacter) {
|
||||
@@ -30,9 +36,16 @@ const vscode = {
|
||||
Range,
|
||||
ViewColumn: { Active: 1, Beside: 2 },
|
||||
env: { clipboard: { async writeText(value) { copied.push(value); } } },
|
||||
commands: { registerCommand() { return disposables(); } },
|
||||
commands: {
|
||||
registerCommand(id, handler) { commands.set(id, handler); return disposables(); },
|
||||
},
|
||||
workspace: {
|
||||
asRelativePath(uri) { return uri.fsPath; },
|
||||
getConfiguration(section) {
|
||||
assert.equal(section, 'lucisv');
|
||||
return { get(key, fallback) { return key === 'hierarchy.duts' ? configuredDuts : fallback; } };
|
||||
},
|
||||
onDidChangeConfiguration(handler) { configurationChanged = handler; return disposables(); },
|
||||
async openTextDocument(uri) {
|
||||
opened.push(uri.value);
|
||||
return {
|
||||
@@ -45,8 +58,9 @@ const vscode = {
|
||||
window: {
|
||||
registerWebviewViewProvider(_id, value) { provider = value; return disposables(); },
|
||||
async showTextDocument(document, options) { shown.push({ document, options }); },
|
||||
async showQuickPick(items) { return items[0]; },
|
||||
async showQuickPick(items) { picked = items; return items[0]; },
|
||||
showWarningMessage(text) { warned.push(text); },
|
||||
showInformationMessage(text) { informed.push(text); },
|
||||
},
|
||||
};
|
||||
|
||||
@@ -181,7 +195,136 @@ async function run() {
|
||||
assert(!webview.html.includes('id="preview"'), 'and the popover is gone from the markup');
|
||||
|
||||
assert.equal(typeof changed, 'function');
|
||||
console.log('hierarchy view: OK — collapsed rows, lazy opening, search list, navigation, menu, bookmark, and no preview');
|
||||
|
||||
// ---- DUT sections (TODO §56) -------------------------------------------
|
||||
// What the pane looks like with nothing starred, kept to compare against
|
||||
// after an unstar: starring must be perfectly reversible.
|
||||
const plainRows = rendered().rows.map((row) => ({ ...row }));
|
||||
assert(plainRows.every((row) => row.contextValue === row.kind), 'nothing is a DUT yet');
|
||||
assert.deepEqual(Object.keys(rendered().menus).sort(), [
|
||||
'instance', 'instance.dut', 'instance.dut.locked', 'module', 'module.dut',
|
||||
'module.dut.locked', 'notice', 'section',
|
||||
], 'the menu table travels with every render');
|
||||
|
||||
// Starring from the pane's own menu, on an instance row: the module starred
|
||||
// is the row's type.
|
||||
await receive({ type: 'context', action: 'starDut', id: instance.id });
|
||||
assert.deepEqual(state.get('lucisv.hierarchy.duts'), ['sub'], 'persisted in starred order');
|
||||
assert.deepEqual(rendered().rows.map((row) => [row.label, row.depth]), [
|
||||
['DUT: sub', 0],
|
||||
['sub', 1],
|
||||
['Parents of sub', 0],
|
||||
['sub', 1],
|
||||
['top', 2],
|
||||
['Other modules', 0],
|
||||
], 'three sections, the DUT ones opened one level, others closed');
|
||||
assert.equal(rendered().rows.find((row) => row.label === 'top').detail, 'via u');
|
||||
assert.equal(rendered().rows[1].contextValue, 'module.dut', 'the DUT row offers Unstar');
|
||||
assert.equal(rendered().rows.at(-1).contextValue, 'section');
|
||||
|
||||
// A section is an ordinary collapsible row: closing it builds none of its
|
||||
// tree, opening `others` shows what the exclusion left.
|
||||
await receive({ type: 'toggle', id: 'sec:dut:sub' });
|
||||
assert(!rendered().rows.some((row) => row.label === 'sub' && row.depth === 1
|
||||
&& row.id.startsWith('dut:')), 'a closed section shows nothing under it');
|
||||
await receive({ type: 'toggle', id: 'sec:dut:sub' });
|
||||
await receive({ type: 'toggle', id: 'sec:others' });
|
||||
assert.deepEqual(
|
||||
rendered().rows.filter((row) => row.depth === 1 && !row.id.startsWith('dut:')
|
||||
&& !row.id.startsWith('parents:')).map((row) => row.label),
|
||||
[], 'top is above the DUT, so the others section is empty',
|
||||
);
|
||||
|
||||
// A second DUT is two more sections, in starred order.
|
||||
await receive({ type: 'context', action: 'starDut', id: rendered().rows[1].id });
|
||||
assert.deepEqual(state.get('lucisv.hierarchy.duts'), ['sub']);
|
||||
assert.equal(informed.at(-1), 'sub is already a DUT.');
|
||||
await commands.get('lucisv.hierarchy.starDut')('top');
|
||||
assert.deepEqual(state.get('lucisv.hierarchy.duts'), ['sub', 'top']);
|
||||
assert.deepEqual(
|
||||
rendered().rows.filter((row) => row.kind === 'section').map((row) => row.label),
|
||||
['DUT: sub', 'Parents of sub', 'DUT: top', 'Parents of top', 'Other modules'],
|
||||
'two DUTs are five sections',
|
||||
);
|
||||
|
||||
// Unstarring from the menu, and clearing the rest from the title bar, put
|
||||
// the plain pane back exactly as it was.
|
||||
await receive({ type: 'context', action: 'unstarDut', id: rendered().rows[1].id });
|
||||
assert.deepEqual(state.get('lucisv.hierarchy.duts'), ['top']);
|
||||
await commands.get('lucisv.hierarchy.clearDuts')();
|
||||
assert.equal(state.get('lucisv.hierarchy.duts'), undefined);
|
||||
assert.deepEqual(rendered().rows, plainRows, 'the pane is byte-identical to before the star');
|
||||
|
||||
// The command palette route picks from the index. Starring the same module
|
||||
// again after a clear must open its sections again, not remember that it
|
||||
// once seeded them.
|
||||
await commands.get('lucisv.hierarchy.starDut')();
|
||||
assert.deepEqual(picked, ['sub', 'top'], 'every module name, sorted');
|
||||
assert.deepEqual(state.get('lucisv.hierarchy.duts'), ['sub']);
|
||||
assert.deepEqual(rendered().rows.map((row) => row.label), [
|
||||
'DUT: sub', 'sub', 'Parents of sub', 'sub', 'top', 'Other modules',
|
||||
], 'the sections are open again');
|
||||
await commands.get('lucisv.hierarchy.unstarDut')();
|
||||
assert.deepEqual(picked, ['sub'], 'only what this workspace starred');
|
||||
assert.equal(state.get('lucisv.hierarchy.duts'), undefined);
|
||||
|
||||
// The setting is the second way in: its DUTs come first, are locked, and the
|
||||
// pane refuses to unstar them.
|
||||
configuredDuts = ['top', ''];
|
||||
await commands.get('lucisv.hierarchy.starDut')('sub');
|
||||
configurationChanged({ affectsConfiguration: (key) => key === 'lucisv.hierarchy.duts' });
|
||||
assert.deepEqual(
|
||||
rendered().rows.filter((row) => row.kind === 'section').map((row) => row.label),
|
||||
['DUT: top', 'Parents of top', 'DUT: sub', 'Parents of sub', 'Other modules'],
|
||||
'the setting first, then the star; the blank entry is dropped',
|
||||
);
|
||||
const locked = rendered().rows.find((row) => row.label === 'top' && row.depth === 1);
|
||||
assert.equal(locked.contextValue, 'module.dut.locked');
|
||||
assert.match(locked.title, /lucisv\.hierarchy\.duts/);
|
||||
await receive({ type: 'context', action: 'unstarDut', id: locked.id });
|
||||
assert.match(warned.at(-1), /^top comes from the lucisv\.hierarchy\.duts setting/);
|
||||
assert.deepEqual(state.get('lucisv.hierarchy.duts'), ['sub'], 'and nothing changed');
|
||||
await commands.get('lucisv.hierarchy.clearDuts')();
|
||||
assert.match(informed.at(-1), /come from the lucisv\.hierarchy\.duts setting/);
|
||||
assert.deepEqual(
|
||||
rendered().rows.filter((row) => row.kind === 'section').map((row) => row.label),
|
||||
['DUT: top', 'Parents of top', 'Other modules'],
|
||||
'clearing takes the stars, not the setting',
|
||||
);
|
||||
|
||||
// A starred name the snapshot does not hold keeps its sections and says so.
|
||||
configuredDuts = [];
|
||||
await commands.get('lucisv.hierarchy.starDut')('renamed_away');
|
||||
assert.deepEqual(rendered().rows.map((row) => row.label), [
|
||||
'DUT: renamed_away',
|
||||
'renamed_away is not in the index',
|
||||
'Parents of renamed_away',
|
||||
'renamed_away is not in the index',
|
||||
'Other modules',
|
||||
]);
|
||||
await commands.get('lucisv.hierarchy.clearDuts')();
|
||||
|
||||
await persistenceSurvivesAReload();
|
||||
console.log('hierarchy view: OK — collapsed rows, lazy opening, search list, navigation, menu, bookmark, no preview, and DUT sections (star, unstar, clear, persistence, the setting lock)');
|
||||
}
|
||||
|
||||
/// A fresh view over the same `workspaceState`: what was starred is starred
|
||||
/// again, in the order it was starred, and the sections are open on arrival.
|
||||
async function persistenceSurvivesAReload() {
|
||||
state.set('lucisv.hierarchy.duts', ['sub', 'nope', 7, '']);
|
||||
new HierarchyView(context, client);
|
||||
const reposted = [];
|
||||
provider.resolveWebviewView({
|
||||
webview: { ...webview, postMessage(message) { reposted.push(message); } },
|
||||
onDidDispose() { return disposables(); },
|
||||
});
|
||||
await receive({ type: 'ready' });
|
||||
const render = reposted.findLast((message) => message.type === 'render');
|
||||
assert.deepEqual(render.rows.map((row) => row.label), [
|
||||
'DUT: sub', 'sub', 'Parents of sub', 'sub', 'top',
|
||||
'DUT: nope', 'nope is not in the index', 'Parents of nope', 'nope is not in the index',
|
||||
'Other modules',
|
||||
], 'both starred names come back, the number 7 and the blank do not');
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
|
||||
@@ -52,6 +52,17 @@ body {
|
||||
border-color: var(--vscode-charts-yellow, #cca700);
|
||||
}
|
||||
.row.warning .detail { color: var(--vscode-list-warningForeground, var(--vscode-editorWarning-foreground)); }
|
||||
/* A DUT section header: the pane's one structural row, so it reads as a
|
||||
heading rather than as another module. */
|
||||
.row.section {
|
||||
position: sticky;
|
||||
top: 38px;
|
||||
z-index: 2;
|
||||
background: var(--vscode-sideBarSectionHeader-background, var(--vscode-sideBar-background));
|
||||
font-weight: 700;
|
||||
}
|
||||
#menu button[disabled] { color: var(--vscode-disabledForeground, var(--vscode-descriptionForeground)); }
|
||||
#menu button[disabled]:hover { background: transparent; color: var(--vscode-disabledForeground, var(--vscode-descriptionForeground)); }
|
||||
.twisty { width: 12px; flex: 0 0 12px; text-align: center; }
|
||||
.icon { width: 14px; flex: 0 0 14px; color: var(--vscode-symbolIcon-moduleForeground, var(--vscode-foreground)); }
|
||||
.label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -15,7 +15,7 @@ const menu = document.getElementById('menu');
|
||||
/** Long enough that a fast typist sends one query, short enough to feel live. */
|
||||
const SEARCH_DEBOUNCE_MS = 60;
|
||||
|
||||
let payload = { mode: 'tree', rows: [], truncated: 0, query: '' };
|
||||
let payload = { mode: 'tree', rows: [], truncated: 0, query: '', menus: {} };
|
||||
let menuNode;
|
||||
let searchTimer;
|
||||
|
||||
@@ -87,6 +87,8 @@ function renderRow(row, searching) {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'row';
|
||||
button.type = 'button';
|
||||
if (row.kind === 'section') button.classList.add('section');
|
||||
if (row.title) button.title = row.title;
|
||||
button.setAttribute('role', searching ? 'option' : 'treeitem');
|
||||
button.setAttribute('aria-level', String(row.depth + 1));
|
||||
button.style.setProperty('--depth', row.depth);
|
||||
@@ -101,7 +103,10 @@ function renderRow(row, searching) {
|
||||
twisty.setAttribute('aria-hidden', 'true');
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'icon';
|
||||
icon.textContent = row.kind === 'module' ? '▣' : (row.detail === 'recursive' ? '↻' : '◇');
|
||||
// A section header and a "not in the index" notice bring their own glyph;
|
||||
// everything else is a module box or an instance diamond.
|
||||
icon.textContent = row.icon
|
||||
|| (row.kind === 'module' ? '▣' : (row.detail === 'recursive' ? '↻' : '◇'));
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
const label = document.createElement('span');
|
||||
label.className = 'label';
|
||||
@@ -112,7 +117,10 @@ function renderRow(row, searching) {
|
||||
button.append(twisty, icon, label, detail);
|
||||
|
||||
button.addEventListener('click', (event) => {
|
||||
if (row.hasChildren && event.detail === 1 && event.offsetX < 28 + row.depth * 12) {
|
||||
// A section header has nothing to navigate to, so the whole row opens it.
|
||||
if (row.kind === 'section') {
|
||||
vscode.postMessage({ type: 'toggle', id: row.id });
|
||||
} else if (row.hasChildren && event.detail === 1 && event.offsetX < 28 + row.depth * 12) {
|
||||
vscode.postMessage({ type: 'toggle', id: row.id });
|
||||
} else {
|
||||
vscode.postMessage({ type: 'activate', id: row.id });
|
||||
@@ -160,16 +168,32 @@ function firstVisibleRow() { return rows()[0]; }
|
||||
function nextRow(row) { const all = rows(); return all[all.indexOf(row) + 1]; }
|
||||
function previousRow(row) { const all = rows(); return all[all.indexOf(row) - 1]; }
|
||||
|
||||
// Which items a row offers is the host's decision, sent once per render as a
|
||||
// table keyed by `contextValue`: an instance row has the five it always had, a
|
||||
// module row has "Star as DUT", a starred one "Unstar DUT", and one the
|
||||
// settings name a single disabled item that says where it came from.
|
||||
function openMenu(event, row) {
|
||||
event.preventDefault();
|
||||
if (row.kind !== 'instance') return;
|
||||
const items = (payload.menus && payload.menus[row.contextValue]) || [];
|
||||
if (items.length === 0) return;
|
||||
menuNode = row;
|
||||
menu.replaceChildren(...items.map((item) => menuItem(item, row)));
|
||||
menu.hidden = false;
|
||||
menu.style.left = `${Math.min(event.clientX, innerWidth - 190)}px`;
|
||||
menu.style.top = `${Math.min(event.clientY, innerHeight - 180)}px`;
|
||||
menu.querySelector('[data-action="bookmark"]').textContent = row.bookmarked
|
||||
? 'Remove Highlight / Bookmark' : 'Highlight / Bookmark';
|
||||
menu.querySelector('button').focus();
|
||||
menu.style.top = `${Math.min(event.clientY, innerHeight - 180 - items.length * 4)}px`;
|
||||
const first = menu.querySelector('button:not([disabled])');
|
||||
if (first) first.focus();
|
||||
}
|
||||
|
||||
function menuItem(item, row) {
|
||||
const button = document.createElement('button');
|
||||
button.setAttribute('role', 'menuitem');
|
||||
button.dataset.action = item.action;
|
||||
button.textContent = item.action === 'bookmark' && row.bookmarked
|
||||
? 'Remove Highlight / Bookmark' : item.label;
|
||||
if (item.disabled) button.disabled = true;
|
||||
if (item.title) button.title = item.title;
|
||||
return button;
|
||||
}
|
||||
|
||||
menu.addEventListener('click', (event) => {
|
||||
@@ -178,9 +202,10 @@ menu.addEventListener('click', (event) => {
|
||||
closeMenu();
|
||||
});
|
||||
menu.addEventListener('keydown', (event) => {
|
||||
const items = [...menu.querySelectorAll('button')];
|
||||
const items = [...menu.querySelectorAll('button:not([disabled])')];
|
||||
const at = items.indexOf(document.activeElement);
|
||||
if (event.key === 'Escape') closeMenu();
|
||||
if (items.length === 0) return;
|
||||
if (event.key === 'ArrowDown') items[(at + 1) % items.length].focus();
|
||||
if (event.key === 'ArrowUp') items[(at - 1 + items.length) % items.length].focus();
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||
"version": "0.45.0",
|
||||
"version": "0.48.2",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
@@ -82,6 +82,24 @@
|
||||
"command": "lucisv.hierarchy.clearBookmark",
|
||||
"title": "Clear Hierarchy Bookmark",
|
||||
"icon": "$(clear-all)"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.hierarchy.starDut",
|
||||
"title": "Star Module as DUT",
|
||||
"category": "lucisv",
|
||||
"icon": "$(star-full)"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.hierarchy.unstarDut",
|
||||
"title": "Unstar DUT",
|
||||
"category": "lucisv",
|
||||
"icon": "$(star-empty)"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.hierarchy.clearDuts",
|
||||
"title": "Clear DUTs",
|
||||
"category": "lucisv",
|
||||
"icon": "$(star-empty)"
|
||||
}
|
||||
],
|
||||
"menus": {
|
||||
@@ -95,6 +113,21 @@
|
||||
"command": "lucisv.hierarchy.clearBookmark",
|
||||
"when": "view == lucisv.hierarchy",
|
||||
"group": "navigation@2"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.hierarchy.clearDuts",
|
||||
"when": "view == lucisv.hierarchy",
|
||||
"group": "navigation@3"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.hierarchy.starDut",
|
||||
"when": "view == lucisv.hierarchy",
|
||||
"group": "1_duts@1"
|
||||
},
|
||||
{
|
||||
"command": "lucisv.hierarchy.unstarDut",
|
||||
"when": "view == lucisv.hierarchy",
|
||||
"group": "1_duts@2"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -242,6 +275,15 @@
|
||||
"default": true,
|
||||
"markdownDescription": "Colour each nesting level of `begin`/`end` and `fork`/`join` a different colour, and a keyword whose counterpart is missing in an error colour. Every colour is a `lucisv.rainbow*` theme colour you can override in `workbench.colorCustomizations`. Takes effect immediately."
|
||||
},
|
||||
"lucisv.hierarchy.duts": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"default": [],
|
||||
"scope": "window",
|
||||
"markdownDescription": "Modules the Hierarchy pane treats as DUTs, by name. Each one splits the pane into two more sections — the DUT with its children, and an upward tree of everything that instantiates it — ahead of the \"Other modules\" section. This is the checked-in list a team shares (`.vscode/settings.json`); starring from the pane's own menu is the per-workspace way and the two are shown together. A DUT that comes from this setting is shown locked and cannot be unstarred from the pane."
|
||||
},
|
||||
"lucisv.inlineTemplates": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
@@ -1235,6 +1277,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 +1298,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 +1310,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."
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user