Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bd55acb98 | ||
|
|
c37b13de31 | ||
|
|
d8d1791c1c | ||
|
|
d10e57aa6e | ||
|
|
414d501847 | ||
|
|
4123905aa1 | ||
|
|
df4e71411f | ||
|
|
6759f0eea1 | ||
|
|
4c2dae323e | ||
|
|
a69a1cb528 | ||
|
|
e1679bebc5 | ||
|
|
94b0711efb | ||
|
|
449b874798 | ||
|
|
4d342367b9 | ||
|
|
a5ca0c9b10 | ||
|
|
acf20f7e62 | ||
|
|
e6eaf53c35 |
No files matched your search
@@ -7,3 +7,4 @@
|
||||
.DS_Store
|
||||
/.zcode
|
||||
/.claude
|
||||
__pycache__/
|
||||
+129
@@ -4,6 +4,135 @@ 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.50.0 — 2026-09-07
|
||||
|
||||
### The format cache key; performance take 4
|
||||
|
||||
- **`uvm-utils-indent` is part of the format cache key.** In 0.49.0 a
|
||||
clean verdict cached under one setting of `[format] uvm-utils-indent`
|
||||
survived a toggle of the option, so `format --check` could exit 0 where
|
||||
`--no-cache --check` would reformat (found by the repository audit,
|
||||
topo handshake 34). The entry carries the option, the store line has it
|
||||
as a fourth field, and a 0.49.0 store is dropped entry by entry and
|
||||
rebuilt — never trusted, never an error. Regression through the real
|
||||
CLI in both toggle directions.
|
||||
- **Performance take 4** (`docs/performance_take4.md`): 0.49.0 against
|
||||
0.43.0 on opentitan, both binaries driven by one client in one hour.
|
||||
0.44.0's `didOpen` fix confirmed in the release build — 14× on the
|
||||
42 192-line file, 3–7× on ordinary RTL; the CLI unchanged and its
|
||||
formatter verdicts byte-identical on all five trees; the findings filed
|
||||
for the next loop: the lazy code-action offer 2–3 ms dearer per cursor
|
||||
move (the extract and inline gates re-parse a buffer the server already
|
||||
holds), the hierarchical-tail rename at 751 ms, the Style lint class
|
||||
1.27× after `unused-import`, the index 14% bigger at codec 19. The
|
||||
measurement harness now lives in `tools/perf/` and runs from a clean
|
||||
checkout.
|
||||
|
||||
## 0.49.0 — 2026-09-06
|
||||
|
||||
### Inline module; the last coverage gaps
|
||||
|
||||
- **Inline module.** With the cursor on `S u_S (...)`, `S`'s body is
|
||||
copied into the instantiating module: ports replaced by the connected
|
||||
names or literals, parameters as `localparam`s with the override or
|
||||
default, internal names prefixed `u_S_` only where the file already
|
||||
spells one of them, comments and attributes carried verbatim, `.name`
|
||||
shorthand connections inside the body expanded when their signal is
|
||||
renamed. Refuses — with a sentence — a `.*` or positional list, an
|
||||
expression connection, an unconnected port, an output into a literal,
|
||||
any hierarchical reference to the instance, a `generate`, `initial`/
|
||||
`final`, macros, directives, interface/`inout`/unpacked ports, and a
|
||||
module declared in the same file. `refactor.inline` action,
|
||||
`lucisv.inlineModule`. Extract → inline round-trips byte-equal after
|
||||
formatting.
|
||||
- **The verifier learns a copy.** A copied region's comments and
|
||||
attributes may be written once per copy in the destination while the
|
||||
copied file must appear in no edit at all; attack tests through the
|
||||
production entry, re-attacked by QA.
|
||||
- **The last coverage gaps.** Six language shapes now parse and format:
|
||||
`->>` non-blocking event triggers (with delay or event control), stream
|
||||
`with [range]` slices, the LRM's other cast bases (`(W+1)'(x)`,
|
||||
`logic [3:0]'(x)`), drive strength on a net declaration (`wire (strong0,
|
||||
weak1) w = a;` — its comment slots also fix a pre-existing refusal on
|
||||
`assign /*c*/ (weak0, pull1) x = y;`), `let` at statement position, and
|
||||
`#(min:typ:max)` clocking skews. `randsequence … endsequence` is a real
|
||||
node — productions, weighted alternatives, `rand join`, `repeat`,
|
||||
`if`/`case`, code blocks — printed one production per line; it was a
|
||||
parse error before and `randsequence` is now a keyword. Comment slots
|
||||
added to `let`, stream concatenations and the clocking grammar: the
|
||||
formatter's gap fuzzer covers 499 gaps at zero failures.
|
||||
- **`[format] uvm-utils-indent`** (editor `lucisv.format.uvmUtilsIndent`),
|
||||
default off: indents the `uvm_field_*` lines between
|
||||
`uvm_object_utils_begin`/`uvm_component_utils_begin` and their `_end`.
|
||||
On over the corpus it changes 21 files, all idempotent, no comment
|
||||
lost. A short comment-free enum body already prints on one line, so no
|
||||
key was added for it; the behaviour is pinned.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -70,6 +70,13 @@ is in the decomposition-server README) and `vlog_parser/src/lexer.rs`
|
||||
thresholds: a dev adding to a file near 600 puts the code in a new
|
||||
module.
|
||||
|
||||
Re-measured 2026-09-07 at 0.49.0 (same rule, before `mod tests`): four
|
||||
files over 600 — `lucisv_server/src/state.rs` 958 (grew across §37–§49;
|
||||
a decomposition is filed as TODO §55: scope/widen, the document store,
|
||||
the source selectors are three sentences), `perf.rs` 900 (reasoned),
|
||||
`lexer.rs` 763, `vlog_formatter/src/format/stmt.rs` 604 (at the mark; the
|
||||
next statement arm goes in a new module) — and everything else under it.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -265,11 +265,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -278,7 +278,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.46.0"
|
||||
version = "0.50.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -86,10 +86,9 @@ run over an unchanged tree skips them: the summary says `N files from cache`,
|
||||
and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
|
||||
thread count, where parallelism has already taken the easy win).
|
||||
|
||||
An entry is keyed on **(content hash, `line-length`, `indent`, lucisv version)**
|
||||
per file, and only ever records the *already formatted* verdict — a file that
|
||||
would be reformatted, or that failed, is re-checked on every run, so
|
||||
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
|
||||
An entry is keyed on **(content hash, `line-length`, `indent`,
|
||||
`uvm-utils-indent`, lucisv version)** per file, and only ever records the *already formatted* verdict — a file that
|
||||
would be reformatted, or that failed, is re-checked on every run. The store is one
|
||||
text file in `.lucisv_cache/` (self-ignoring, like cargo's `target/`); deleting
|
||||
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
|
||||
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
|
||||
@@ -97,6 +96,10 @@ default is relative to the current directory). Content hashing is 64-bit
|
||||
FNV-1a and a lookup never crosses files; `docs/features/format-cache/README.md`
|
||||
states the collision posture, the semantics table and the concurrency story.
|
||||
|
||||
(In v0.49.0 only, `uvm-utils-indent` was missing from this key, so a cached
|
||||
clean verdict survived a toggle of the option — fixed in 0.50.0; a 0.49.0
|
||||
store is simply rebuilt.)
|
||||
|
||||
### Ignore files
|
||||
|
||||
While walking a directory, lucisv reads a `.gitignore` in every directory it
|
||||
@@ -170,9 +173,14 @@ error (exit 2) and nothing is processed. Details:
|
||||
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
|
||||
with a file that sets only `line-length` uses both). `exclude` is the
|
||||
exception: config patterns are *added* to `--exclude`, not replaced by it.
|
||||
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
|
||||
off by default, indents the `` `uvm_field_* `` macros written between
|
||||
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
|
||||
formatting choice lucisv leaves to the project, because it changes bytes
|
||||
in existing UVM code (21 of the 860 corpus files).
|
||||
|
||||
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
|
||||
supported subset (tables other than `[lint]` and `[lint.<rule>]`, multi-line
|
||||
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
|
||||
arrays, unsupported string escapes) is a hard error naming the file and
|
||||
line — exit 2, with nothing written. This is deliberate:
|
||||
a silently ignored `line_length` typo costs more than a strict parser does.
|
||||
@@ -287,6 +295,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 |
|
||||
@@ -462,7 +471,7 @@ of document layout from language rules:
|
||||
| `crates/vlog_formatter/src/format/` | `ruff_python_formatter` | Per-node formatting rules, one module per grammar domain (`item`, `module`, `instance`, `decl`, `stmt`, `expr`, `class`, `cover`, `sva`, …) |
|
||||
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
|
||||
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
|
||||
| `crates/vlog_refactor` | — | Verified rename, references, port refactors, instantiation plans |
|
||||
| `crates/vlog_refactor` | — | Verified rename/references, ports, imports, extract/inline module, instantiation plans |
|
||||
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
|
||||
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
|
||||
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
|
||||
@@ -474,7 +483,7 @@ Linting consumes the parser, semantics and `lucisv_core` (for the one
|
||||
refactoring consumes the parser and semantics. The CLI reaches
|
||||
semantics through the linter and has no refactoring dependency. The server
|
||||
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
|
||||
including the linter's formatter dependency used only by tests.
|
||||
including the linter’s and refactor’s formatter dependencies used only by tests.
|
||||
|
||||
Key ideas carried over from ruff/prettier:
|
||||
|
||||
@@ -614,12 +623,19 @@ into ranges. Full semantics, including what happens at a range boundary:
|
||||
|
||||
## Supported syntax
|
||||
|
||||
v0.49.0 adds real `randsequence` productions; nonblocking `->>` event
|
||||
triggers with optional timing; streaming `with [range]`; constant-expression
|
||||
and packed-type cast bases; net drive strengths; statement-level `let`; and
|
||||
min:typ:max clocking skews. The parser, formatter and AST consumers share these
|
||||
nodes. See [coverage gaps](docs/coverage_gaps.md) for the dated survey and
|
||||
remaining semantic limits.
|
||||
|
||||
Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
|
||||
|
||||
- Modules (ANSI and non-ANSI headers), packages, parameter ports,
|
||||
`import`, `timeunit`
|
||||
- Net/variable declarations (`wire`/`reg`/`logic`/`int`/... , signing,
|
||||
packed/unpacked dimensions, net delays), `parameter`/`localparam`,
|
||||
packed/unpacked dimensions, net delays and net drive strengths), `parameter`/`localparam`,
|
||||
`genvar`, `defparam`
|
||||
- `assign` (with delays), `always`/`always_comb`/`always_ff`/`always_latch`,
|
||||
`initial`/`final`
|
||||
@@ -851,8 +867,8 @@ See `docs/features/corpus-check/README.md` for the 820-file corpus baseline:
|
||||
bucket (26 files) and moved the parse rate from 94.1% to 97.1%; 24 of the
|
||||
26 files format, the other 2 advanced to a macro-items blocker and to the
|
||||
`new obj` shallow-copy expression. `randsequence` remained unsupported at
|
||||
this point; the other vendor/formal constructs listed here landed later in
|
||||
0.30.0
|
||||
this point; it shipped as real nodes in 0.49.0. The other vendor/formal
|
||||
constructs listed here landed in 0.30.0
|
||||
11. ~~A macro statement that ends its line followed by a symbol on the next
|
||||
one, the `new obj` shallow copy (IEEE 1800 §8.12), and a based number
|
||||
whose digits come from a macro (`` 32'h`DM_ADDR ``)~~ — **done**; see
|
||||
@@ -892,6 +908,25 @@ go-to-definition, references and document/workspace symbols — the full list,
|
||||
and what is deliberately *not* advertised yet, is in
|
||||
`docs/features/lucisv-server/README.md`.
|
||||
|
||||
The editor now offers these refactorings alongside rename and port propagation:
|
||||
|
||||
| Action | Behavior |
|
||||
|---|---|
|
||||
| Expand wildcard | Replace `.*` with declaration-order named connections; unmatched ports become `.p()` with a warning |
|
||||
| Convert ports to ANSI | Merge a legacy module header and its body port declarations, preserving comments and attributes |
|
||||
| Organize imports | Remove unused imports, merge exact duplicates and sort a top-of-scope run; uncertainty keeps the action conservative |
|
||||
| Extract module | Move selected whole module items into a named module, infer its interface, and insert the replacement instance; create a file when supported or append below the source module |
|
||||
| Inline module | Copy a separate-file module body into its instance site with simple named-connection substitution and collision-aware internal renaming |
|
||||
|
||||
The [language-tools reference](docs/site/src/content/docs/reference/language-tools.md)
|
||||
records commands and refusal limits. Inline-module has a known transitive
|
||||
source-selection gap; review hierarchical uses through wrapper modules before
|
||||
applying it (topology handshake 33).
|
||||
|
||||
In the VS Code hierarchy, **Star as DUT** groups a module’s children and
|
||||
parents into sections alongside Other Modules. Stars persist per workspace;
|
||||
`lucisv.hierarchy.duts` adds team-configured names, which are locked in the menu.
|
||||
|
||||
**VS Code needs no separate binary**: every release on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
|
||||
platform-specific `.vsix` with both binaries inside it — pick yours
|
||||
|
||||
@@ -710,8 +710,8 @@ 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.
|
||||
- [x] 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
|
||||
@@ -730,6 +730,35 @@ section only tracks the milestones.
|
||||
than moves — where a `(* ... *)` belongs in an ANSI port list, and whether
|
||||
the same one may be split across the ports a multi-name declaration
|
||||
declares, is a design question the merge rule does not answer.
|
||||
**Organize imports shipped 2026-09-05 (§52,
|
||||
`docs/features/organize-imports/README.md`)**: the imports nothing uses
|
||||
removed, exact duplicates merged and the run at a scope's top sorted, with a
|
||||
`source.organizeImports` code action, `lucisv.organizeImports`, and the same
|
||||
judgement as the `unused-import` lint rule. It leaves three things behind,
|
||||
added to this backlog: **a module header's `import`** (`module m import
|
||||
p::*;`), which is judged but never moved because it has no line of its own;
|
||||
**an unused import carrying a comment**, kept with a warning rather than
|
||||
deleted, because the comment would have to go with it; and — the one that
|
||||
decides how useful the feature is on real verification code — **a scope
|
||||
holding a macro call or a `` `include ``**, which lucisv refuses to judge at
|
||||
all: 32 of the corpus's 40 multi-import scopes and 33 of 33 OpenTitan UVM env
|
||||
packages.
|
||||
**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.
|
||||
**All five delivered in loop 2** (§50–§53 across 0.46.0–0.49.0); what each one deliberately refuses is listed under "Open items for loop 3" in the Loop 2 order section.
|
||||
|
||||
## 9. LSP 3.18 protocol audit (2026-08-26)
|
||||
|
||||
@@ -4612,9 +4641,46 @@ 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
|
||||
reached.
|
||||
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.
|
||||
|
||||
**Closed 2026-09-07.** Every section above shipped in the release named:
|
||||
0.44.0 (§45, §46), 0.45.0 (§47–§49), 0.46.0 (§50, §51), 0.47.0 (§52,
|
||||
§53.1), 0.48.0/0.48.2 (§56; 0.48.0's first packages were built a commit
|
||||
early and 0.48.1 never built — see the changelog), 0.49.0 (§53.2, §54).
|
||||
Loop 2's dev/QA/lead protocol ran in the main tree with no worktrees;
|
||||
its two release slips are recorded in CLAUDE.md's rules of thumb below
|
||||
(§57) and in the lead's memory.
|
||||
|
||||
**Open items for loop 3** (owner decides; nothing here is in flight):
|
||||
- §44 second finding ruled non-hot; §55 `state.rs` decomposition (958
|
||||
lines, three sentences) — a Fable refactor lane;
|
||||
- topo §2.9-31 DPI-export name binding (dpi-export request (b));
|
||||
- topo §2.9-32 the refactoring verifier and a same-file relocation of a
|
||||
never-dropped piece written as two edits (eq. 3 unreachable);
|
||||
- topo §2.9-33 `module_sources` lacks a transitive-instantiators rung
|
||||
(inline-module's hierarchical scan sees only the handed files);
|
||||
- inline module's deliberate refusals worth their own rounds: same-file
|
||||
`S`, unconnected outputs, any `generate`, prefixing past end labels;
|
||||
extract module's: attributes on absorbed declarations (§51 too), an
|
||||
`interface`'s non-ANSI header (§51), a `.*` inside a `bind` (§50);
|
||||
- `uvm-utils-indent` default (off; 21 corpus files change when on) —
|
||||
revisit after use;
|
||||
- organize imports on files with `` `include``s (refused by design —
|
||||
the preprocessor question, TODO §7's standing non-goal);
|
||||
- **perf take 4 (§58, 2026-09-07) filed:** the lazy `codeAction` offer
|
||||
costs 2–3 ms more at every cursor because `inline_site`/`extract_site`
|
||||
each re-parse the buffer the server already holds (take 4 §8.2 — the
|
||||
fix is §37.1's shape: gate on the document's own tree); §49's tail
|
||||
rename at 751 ms for two files vs 66 ms for one (§8.3 — look at
|
||||
rename's reference walk first, completion on the same surface is
|
||||
free); `check --select error,warning,style` 1.27× on `hw/ip` after
|
||||
`unused-import` (§8.4); two instance-head tails that do not resolve
|
||||
(`pwrmgr.sv` 178:10 in a macro argument, `pinmux.sv` 687:40; §8.5 —
|
||||
a ruling, not a fix); the index +14% at codec 19 (§8.6, watch).
|
||||
Sections after §46 are planned when reached.
|
||||
|
||||
## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22
|
||||
|
||||
@@ -4948,7 +5014,10 @@ scope/widen logic, the document store, and the source selectors
|
||||
owner decides where it goes in loop 2.
|
||||
|
||||
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
|
||||
count unchanged); CLAUDE.md's measurement line refreshed
|
||||
count unchanged); CLAUDE.md's measurement line refreshed —
|
||||
**deferred to loop 3 by the lead, 2026-09-07** (958 lines at 0.49.0;
|
||||
the measurement line already says so); a Fable refactor lane when
|
||||
the owner schedules it
|
||||
|
||||
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
|
||||
|
||||
@@ -5143,11 +5212,450 @@ so the editor squiggles what the action would delete.
|
||||
organized into scratch copies, counts, and every "unused" claim
|
||||
checked by grep for the package's members in the file.
|
||||
|
||||
- [ ] 52.1 engine: used/unused, sort, dedup, refusals
|
||||
- [ ] 52.2 `unused-import` rule + safe fix + toggle
|
||||
- [ ] 52.3 code action (`source.organizeImports`, lazy) + command
|
||||
- [ ] docs; §8 line annotated; README/site rows (lead)
|
||||
- [ ] Gates (guarded); byte-identity vs 0.46.0; corpus census
|
||||
- [ ] QA: every "unused" claim attacked (shadowing, nested scopes,
|
||||
- [x] 52.1 engine: used/unused, sort, dedup, refusals
|
||||
- [x] 52.2 `unused-import` rule + safe fix + toggle
|
||||
- [x] 52.3 code action (`source.organizeImports`, lazy) + command
|
||||
- [x] docs; §8 line annotated; README/site rows (lead)
|
||||
- [x] Gates (guarded); byte-identity vs 0.46.0; corpus census
|
||||
- [x] QA: every "unused" claim attacked (shadowing, nested scopes,
|
||||
re-exports, macros, directives, unknown packages); the verifier
|
||||
attack pair; opentitan UVM packages
|
||||
|
||||
## 53. Extract module and inline module (planned 2026-09-05) — the dearest §8 refactorings
|
||||
|
||||
One lane after §52 merges (two sub-lanes in sequence if the first alone
|
||||
takes a round), §36's protocol. Feature README:
|
||||
`docs/features/extract-inline-module/README.md`. Ships in 0.47.0 with §52.
|
||||
Both are lexical refactorings over a verified whole edit, like §50/§51:
|
||||
one plan through `vlog_refactor`'s splice and `check.rs` (`pieces_match`,
|
||||
`never_dropped`, the resolution check), with a refusal sentence for every
|
||||
shape lucisv cannot judge.
|
||||
|
||||
### 53.1 Extract module
|
||||
|
||||
Input: a selection covering **whole module items** (one or more
|
||||
contiguous `always`/`assign`/instantiation/declaration/generate items)
|
||||
inside module `M`, and a name `N` for the new module. Output: a new
|
||||
module `N` holding the items, with ports and parameters inferred, and the
|
||||
selection replaced by an instantiation `N u_N (...)` rendered by
|
||||
`instantiation_plan` over the new module's text (so the skeleton and the
|
||||
instantiation can never disagree).
|
||||
|
||||
- **Ports, from dataflow across the region boundary**, using the file's
|
||||
`Semantics` (symbols and references with spans): a name declared
|
||||
*outside* the region (in `M`, including its ports) and referenced
|
||||
*inside* becomes a port — `input` when only read inside, `output` when
|
||||
written inside (assign LHS, always LHS, an instantiation's output
|
||||
connection is unknown without the instantiated module's declaration —
|
||||
look it up through the index; refuse when unknown) and read or written
|
||||
outside, both → refuse ("`x` is driven on both sides of the selection").
|
||||
A name declared *inside* and referenced outside → refuse ("move the
|
||||
declaration of `x` out of the selection first"). The port's type is the
|
||||
declaration's own text in `M` (net/var kind, signing, packed dims —
|
||||
the §51 merge machinery renders it); an unpacked dim → refuse this
|
||||
round. A parameter of `M` referenced inside becomes a parameter of `N`
|
||||
with `M`'s default, passed through `#(.P(P))`. Imports of `M` used
|
||||
inside are copied into `N` (§52's judgement says which are used).
|
||||
- **The new module's home:** a new file `N.sv` beside `M`'s file when the
|
||||
client advertises `workspace.workspaceEdit.documentChanges` with
|
||||
`CreateFile` support (VS Code does); otherwise `N` is written below `M`
|
||||
in the same file. Say which happened in the action's warning list.
|
||||
- **Refusals** (each a sentence): the selection does not cover whole
|
||||
items; it contains a port declaration, a `parameter`/`localparam`
|
||||
declaration, a `genvar`, a `bind`, a macro call or conditional
|
||||
directive, a task/function used on both sides, a hierarchical
|
||||
reference crossing the boundary (`u_x.sig` in either direction — the
|
||||
§49 surface says whether the head is inside), an interface-typed name
|
||||
crossing, a name with an unpacked dimension crossing, an
|
||||
`initial`/`final` block (testbench code; refuse this round, say so), a
|
||||
`timescale`/`default_nettype` in force that `N.sv` would not inherit
|
||||
(a new file: copy the directive or refuse — refuse), `N` already
|
||||
declared in the workspace, `M` declared twice.
|
||||
- **Server:** code action `lucisv: extract selection into module…` under
|
||||
`refactor.extract` (lazy), whose resolve asks the client for the name
|
||||
through a command with a `showInputBox`-style flow: since LSP has no
|
||||
input prompt, the action carries a default name (`M_extracted`) and the
|
||||
VS Code extension wraps the command `lucisv.extractModule [uri, range,
|
||||
name]` with an input box (one function in `editors/vscode/extension.js`;
|
||||
other clients pass the name themselves). Say so in the docs.
|
||||
- Tests: a combinational region (inputs + one output); a sequential
|
||||
region (clk/rst become inputs, the register an output); a region using
|
||||
a parameter and an import; every refusal; the round trip `extract →
|
||||
inline` (53.2) returns the original file modulo layout (formats to
|
||||
the same text — pin as byte-equal after formatting both); corpus: five
|
||||
hand-picked regions in scratch copies, each result (both files) parses,
|
||||
formats, converges, and the whole design's reference counts match
|
||||
before/after (the census over the two files together).
|
||||
|
||||
### 53.2 Inline module
|
||||
|
||||
Input: the cursor on an instantiation `S u_S (...)` of a module `S`
|
||||
declared exactly once in the workspace. Output: the instantiation
|
||||
replaced by `S`'s items with `S`'s port names replaced by the connected
|
||||
names, `S`'s parameters by their override or default values as
|
||||
`localparam`s, and every internal name prefixed `u_S_` unless no name in
|
||||
`M` collides (then unprefixed — say which in the warning list); `S`'s
|
||||
imports copied into `M` if `M` lacks them.
|
||||
|
||||
- **Refusals:** a connection that is an expression rather than a plain
|
||||
name or literal ("connect `.a(x+1)` to a named wire first"); a `.*`
|
||||
("expand `.*` first" — §50); positional connections ("convert to named
|
||||
first"); an unconnected input; any hierarchical reference to `u_S` from
|
||||
anywhere in the workspace (the §49 hierarchical surface: `u_S.x` in any
|
||||
file → refuse, naming the file); `S` with a `generate` that declares
|
||||
names reachable hierarchically (`u_S.gen.x` — same rule); `S`
|
||||
declared twice or unknown; `S` with ports of interface type, with
|
||||
`inout` ports, with unpacked-array ports, or with an `initial`/`final`
|
||||
(refuse this round); a macro call or conditional directive in `S`;
|
||||
`S`'s `timescale` differing from `M`'s file; a name collision that
|
||||
prefixing cannot resolve (an escaped name).
|
||||
- **Server:** code action `lucisv: inline `S` here` under `refactor.inline`
|
||||
(lazy), command `lucisv.inlineModule [uri, position]`.
|
||||
- Tests: a two-port module inlined into its instantiator (round trip
|
||||
with 53.1); a parameterized module with an override; a name collision
|
||||
(prefixed); every refusal; the verifier's resolution check on the
|
||||
result; corpus: five instantiations of small `common_cells` modules
|
||||
inlined in scratch copies, each result parses, formats, converges, and
|
||||
a `lucisv check --select unused-signal,undriven-net` census over the
|
||||
result is unchanged in count from the original two files.
|
||||
|
||||
- [x] 53.1 extract: dataflow ports, parameters, imports, the new file,
|
||||
refusals, action + command + extension input box
|
||||
- [x] 53.2 inline: substitution, prefixing, refusals, action + command
|
||||
- [x] the extract → inline round trip pinned
|
||||
- [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
|
||||
- [x] 53.2 QA: the substitution attacked (every position a port name can
|
||||
appear in), the `.name` shorthand and `.*` inside `S`, the
|
||||
prefixing rule and its collisions, every refusal, the copy
|
||||
allowance's attack table re-attacked, the round trip, corpus and
|
||||
opentitan scratch trials — PASS, two MEDIUM findings (QA-2, QA-3),
|
||||
see the feature README's QA log
|
||||
|
||||
## 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.
|
||||
|
||||
- [x] 54.1 the six L6 shapes, each with cases + parity + fuzzers
|
||||
- [x] 54.2 `randsequence` as real nodes
|
||||
- [x] 54.3 the two cosmetics behind config keys, corpus impact measured
|
||||
— **one key, not two**: `[format] uvm-utils-indent` (21 corpus files
|
||||
when on); the enum one-lining was measured already-default and no
|
||||
key was shipped for it. Ruling in the feature README's work log.
|
||||
- [x] docs; coverage_gaps L3/L6/L10 struck; README/site config keys (lead)
|
||||
— strike text and the config-key rows are in the feature README
|
||||
under "Docs to apply at merge (lead)"
|
||||
- [x] Gates (guarded); byte-identity vs 0.47.0 (0 differing with the keys
|
||||
off); opentitan sweep unchanged — 4 143 tests green; corpus 814/820,
|
||||
the same six; byte-identity vs 0.48.1 0/860 differing; opentitan
|
||||
2 553 files, per-file outcomes identical
|
||||
- [x] 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
|
||||
- [x] docs (lead applies README/site) — applied 2026-09-06 (site editors
|
||||
paragraph, topo node; the extension README rows were the dev's)
|
||||
- [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
|
||||
|
||||
## 57. Final cleanup and closing release (owner's end goal, 2026-09-06)
|
||||
|
||||
After §53.2 and §54 merge and 0.49.0 ships, the last lane of loop 2 is the
|
||||
lead's own, no dev/QA:
|
||||
|
||||
- [x] **Tree:** `git status --porcelain` empty; `git worktree list` shows
|
||||
the main tree only; `git branch` shows `master` only; no local tag
|
||||
that is not on the server; no stray files in the tree
|
||||
(`corpus-check-results.tsv` is ignored — fine); the scratchpad and
|
||||
`~/.cache/lucisv-baselines/wip-*` snapshots deleted. — done
|
||||
2026-09-07 at 4c2dae3 (main tree only, `master` only, every local
|
||||
tag on the server, snapshots and scratch leftovers removed).
|
||||
- [x] **Remote:** `master` pushed and equal to local; every release tag
|
||||
on the server; every release with 8 assets; the published vsix of
|
||||
the final release unzipped and checked for the feature files of
|
||||
loop 2 (`hierarchySections.js`, `extract.js`, no `*_test.js`).
|
||||
— done 2026-09-07: v0.49.0 has 8 assets (run 270); the darwin-arm64
|
||||
vsix carries `hierarchySections.js` and `extract.js`, no `*_test.js`,
|
||||
version 0.49.0.
|
||||
- [x] **TODO.md:** every checkbox either ticked or annotated with a
|
||||
dated ruling (deferred to whom, or dropped why); the "Loop 2 order"
|
||||
section closed with what shipped in which release; §44/§55 and the
|
||||
topo §2.9 open rows (23 done; 29/30 done; 31 DPI export, 32 the
|
||||
verifier same-file relocation) restated in one "open items" list
|
||||
for loop 3. — done 2026-09-07: the only unticked lines left are
|
||||
§55 (deferred, annotated) and the §57 items that wait on the
|
||||
0.49.0 assets.
|
||||
- [x] **Docs:** `docs/topo.md` rows for every loop-2 lane present;
|
||||
`docs/coverage_gaps.md` struck where delivered; CLAUDE.md's
|
||||
measurement line refreshed (`state.rs` 957 lines → whatever §55
|
||||
leaves it; if §55 does not run, the number and the reason);
|
||||
`docs/manual-acceptance.md` rows through §56; the site rebuilt and
|
||||
committed. — done 2026-09-07 (CLAUDE.md re-measured at 0.49.0:
|
||||
state.rs 958 with §55 filed; topo rows for §36–§56; L3/L6/L9/L10
|
||||
struck; acceptance rows 15–17; site rebuilt in the §54 commit).
|
||||
- [x] **Memory:** the paused-state memory rewritten as a short current
|
||||
state (not a running log), with the release list and the open items.
|
||||
— done 2026-09-07.
|
||||
- [x] **Closing release:** if anything above changed a shipped file
|
||||
(docs count), a final release `0.49.x`/`0.50.0` cut from the clean
|
||||
tree, its assets verified, and the install line given to the owner.
|
||||
— **ruled 2026-09-07: 0.49.0 is the closing release.** The commits
|
||||
after it are TODO/CLAUDE.md/memory bookkeeping only — nothing that
|
||||
reaches a binary, the extension or the site — so no further tag.
|
||||
|
||||
## 58. Performance take 4 on opentitan (owner request 2026-09-07) — 0.49.0 vs 0.43.0 vs take 3
|
||||
|
||||
§40's protocol, one release later. Read-only measurement; a regression is
|
||||
filed with a reproduction, not fixed in this lane. Output:
|
||||
`docs/performance_take4.md`, the same table shapes as
|
||||
`docs/performance_take3.md` so every row is a before/after (take 3's
|
||||
0.43.0 column carried beside the new 0.49.0 column; 0.39.0 where take 3
|
||||
had it), plus a `docs/perf/README.md` entry. Tree:
|
||||
`/Users/guoliangchen/repo/opentitan` (never written; the three
|
||||
pre-existing modified files stay as they are, `git status --porcelain`
|
||||
checked after every phase). Every run under `tools/guard.sh -m 8 -t 1800`.
|
||||
No `cargo` command in any tree during a timed measurement.
|
||||
|
||||
Binaries: the 0.49.0 CLI is `~/.cache/lucisv-baselines/lucisv-0.49.0`
|
||||
(0.43.0 and 0.39.0 beside it); the 0.49.0 server is
|
||||
`target/release/lucisv-server` in the main tree (the tree's code is
|
||||
4c2dae3 = v0.49.0 — verify by sha or `--version` before use, rebuild
|
||||
once with `cargo build --release -p lucisv_server` only if it is stale,
|
||||
before any timing); the 0.43.0 server is built from the `v0.43.0` tag in a
|
||||
scratch `git worktree` under the scratchpad and the worktree removed after.
|
||||
|
||||
- **The harness is committed this time.** Take 2's client was lost and
|
||||
take 3's was reimplemented from prose; take 3's is gone too (the
|
||||
scratchpad is volatile). Take 4's client and drivers live in
|
||||
`tools/perf/` (`lspclient.py`, `bench.py`, `sweep.sh`,
|
||||
`sweeptable.py`, `outcomes.sh`; Python 3 standard library only, a
|
||||
short README saying how to run each phase). Take 5 reuses them.
|
||||
- **Server, the take-3 request table** (take 3 §2, every row): startup
|
||||
and scan per scope config and cache state (cold / warm), the `didOpen`
|
||||
widen at the default scope, `codeAction` at the take-3 cursors (lazy
|
||||
offer and eager, plus `codeAction/resolve` where an action is offered),
|
||||
`prepareRename` / `rename`, `completion`, `definition`, `hover`,
|
||||
`inlayHint`, `references`, `documentSymbol`, `workspaceSymbol`,
|
||||
`semanticTokens/full`, diagnostics publish, the queue-blocking analysis
|
||||
(take 3 §3), the transport baseline and the `--verbose` cross-check
|
||||
(take 3 §0).
|
||||
- **New rows for what 0.44–0.49 added**, each with the 0.43.0 column
|
||||
beside it where the request exists there:
|
||||
- the `didOpen` delay (§46) confirmed on the wire in the release build:
|
||||
`didOpen` → the request behind it for `aes.sv`, `aes_core.sv`,
|
||||
`spi_device.sv`, `pinmux_reg_top.sv` (the perf README's 2026-09-05
|
||||
table was taken with temporary timings — this is the release
|
||||
number);
|
||||
- `codeAction` at the new offer sites: a `.*` instance (expand
|
||||
wildcard), a non-ANSI module header (convert to ANSI), an `import`
|
||||
line (organize imports), a selection of a few module items (extract
|
||||
module), a separate-file instance with named connections (inline
|
||||
module) — the lazy offer and one `resolve` each; how many actions
|
||||
each cursor offers, so the reader knows what was paid for;
|
||||
- `rename` of a net reached through an instance tail (§49's
|
||||
hierarchical surface) and `completion` after `u_x.` on an instance
|
||||
head — pick real opentitan sites and name them;
|
||||
- `lucisv/moduleHierarchy` (the snapshot the DUT view consumes; the
|
||||
sections themselves are client-side and not measured here);
|
||||
- index store size on disk and the server's peak RSS after the
|
||||
workspace scan, 0.43.0 vs 0.49.0 (`FACTS_FORMAT` 18 → 19 added the
|
||||
hierarchical member table and the re-export group).
|
||||
- **CLI sweeps** as take 3 §7 over the same five trees: `format --check`
|
||||
(cold cache and warm), `check` (default rules; `--select
|
||||
error,warning,style`), wall time and peak RSS, 0.49.0 vs 0.43.0 vs
|
||||
0.39.0; failure counts per tree and every per-file outcome that changed
|
||||
since 0.43.0 (expected candidates: §54's grammar — `randsequence`,
|
||||
`->>`, casts, drive strengths, `let`, clocking skews — and §38's
|
||||
outcomes staying fixed; anything else is a finding). The formatter cache
|
||||
goes to a scratch `--cache-dir`; the index cache to a scratch
|
||||
`storagePath`.
|
||||
- **Method** as take 3 §9: three tries per row, first try and repeat
|
||||
range reported, machine state noted (load average before and after
|
||||
each phase; the machine runs a desktop session — say so).
|
||||
- **Findings:** any row slower than take 3 by more than noise is a filed
|
||||
item with a reproduction; anything faster is credited to the section
|
||||
that did it. The eager `codeAction` path is ruled a non-hot path
|
||||
(owner, 2026-09-05) — report it, do not re-file it.
|
||||
- Feature README: `docs/features/performance-take4/README.md` (Goal,
|
||||
Assumptions, Handshakes, Status, Work log, QA log, Review).
|
||||
|
||||
- [x] harness in `tools/perf/` with its README; runs from a clean checkout
|
||||
- [x] server table re-measured, 0.49.0 vs 0.43.0 vs take 3 — take 4 §2
|
||||
- [x] new rows: didOpen release numbers, the five refactoring offer sites,
|
||||
tail rename and instance-head completion, moduleHierarchy, index
|
||||
size and RSS
|
||||
- [x] CLI sweeps, three binaries, RSS included; outcome diff since 0.43.0
|
||||
- [x] `docs/performance_take4.md` + perf README entry
|
||||
- [x] opentitan status unchanged after every phase; no guard kill
|
||||
- [x] QA: a sample of at least eight rows re-run with the committed
|
||||
harness (both binaries) and checked against the document within its
|
||||
stated tolerance; the outcome diff re-derived; opentitan status;
|
||||
every number quoted in the document found in the raw logs
|
||||
|
||||
## 59. The format cache key omits `uvm-utils-indent` (topo §2.9-34, owner's audit 2026-09-07)
|
||||
|
||||
Filed by the repository analysis: `lucisv_core::cache::Entry` and
|
||||
`lucisv/src/main.rs::entry_for` key a verdict on content, `line-length`
|
||||
and `indent` (and the lucisv version), so toggling `[format]
|
||||
uvm-utils-indent` after a clean `--check` keeps the stale clean verdict
|
||||
(`--check` exits 0 while `--no-cache --check` exits 1). Runs after §58
|
||||
(no build during a timed measurement). Feature README:
|
||||
`docs/features/format-cache/README.md` (work log entry, Handshakes
|
||||
amended: the key now names the option).
|
||||
|
||||
- **The key.** `Entry` gains `uvm_utils_indent: bool`; `entry_for`
|
||||
fills it from `Config`; the store line carries it as a fifth field and
|
||||
a line without it (an older store) is dropped individually, like
|
||||
another version's entry. Equality and the codec round-trip tested in
|
||||
`cache.rs`.
|
||||
- **Regression** as the audit's probe, through the real CLI: a UVM class
|
||||
with `uvm_field_int`, cache a clean verdict with the option false,
|
||||
flip to true → `--check` exits 1; and the other direction.
|
||||
- README: the `--no-cache` workaround paragraph in `README.md` and the
|
||||
topo row 34 struck at merge (lead).
|
||||
|
||||
- [x] `Entry`/`entry_for`/store codec, tests
|
||||
- [x] CLI regression, both toggle directions
|
||||
- [x] format-cache README work log + Handshakes
|
||||
- [x] QA: attack the key (another option, another version, a store line
|
||||
with four fields); confirm the audit's probe passes on the fix and
|
||||
fails on 0.49.0
|
||||
@@ -106,6 +106,12 @@ impl Options {
|
||||
if let Some(n) = self.indent.or(file.indent) {
|
||||
config.indent_width = n;
|
||||
}
|
||||
// `[format]` has no CLI flag: these keys change how already-clean
|
||||
// files look, so the project's own config is the only place that
|
||||
// turns one on.
|
||||
if let Some(on) = file.format_uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
|
||||
+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() {
|
||||
|
||||
@@ -333,7 +333,12 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
|
||||
/// the key, not the config file that produced them, so identical settings
|
||||
/// from different `lucisv.toml` files share entries.
|
||||
fn entry_for(content: u64, config: &Config) -> Entry {
|
||||
Entry { content, line_length: config.max_width, indent: config.indent_width }
|
||||
Entry {
|
||||
content,
|
||||
line_length: config.max_width,
|
||||
indent: config.indent_width,
|
||||
uvm_utils_indent: config.uvm_utils_indent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds rayon's global pool. Worker stacks are sized for the parser's
|
||||
|
||||
@@ -1267,16 +1267,18 @@ impl TempDir {
|
||||
}
|
||||
}
|
||||
|
||||
/// One hand-written cache line, for the tests that forge entries.
|
||||
/// One hand-written cache line, for the tests that forge entries. The
|
||||
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
|
||||
fn cache_line(
|
||||
path: &str,
|
||||
content: &str,
|
||||
line_length: usize,
|
||||
indent: usize,
|
||||
uvm: bool,
|
||||
version: &str,
|
||||
) -> String {
|
||||
let hash = lucisv_core::cache::content_hash(content.as_bytes());
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{version}\t{path}\n")
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1363,7 +1365,8 @@ fn a_hit_skips_the_work_entirely() {
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 2, "without an entry this file is an error");
|
||||
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, VERSION)).unwrap();
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, false, VERSION))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "a hit does no work at all: {}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
@@ -1388,6 +1391,65 @@ fn a_config_file_change_invalidates_the_entry_too() {
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A UVM class whose layout depends on `[format] uvm-utils-indent`: with the
|
||||
/// option on, the `` `uvm_field_* `` macro gains a level. Written here as the
|
||||
/// formatter leaves it with the option *off*.
|
||||
const UVM_CLASS: &str = "class c extends uvm_object;\n `uvm_object_utils_begin(c)\n \
|
||||
`uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
|
||||
|
||||
#[test]
|
||||
fn changing_uvm_utils_indent_invalidates_the_entry() {
|
||||
let dir = TempDir::new("cache-uvm");
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
|
||||
let path = dir.write("a.sv", UVM_CLASS);
|
||||
let cache = dir.cache();
|
||||
|
||||
// Clean with the option off, and that verdict is cached.
|
||||
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
|
||||
let flat = dir.read("a.sv");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// Turning the option on must not hit the entry the option-off run left.
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "uvm-utils-indent is part of the key: {}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
|
||||
// Format under the option on, cache *that*, then flip back off.
|
||||
assert_eq!(code(&run_raw(&[&path, "--cache-dir", &cache])), 0);
|
||||
assert_ne!(dir.read("a.sv"), flat, "the option really does change the output");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
dir.write("lucisv.toml", "[format]\nuvm-utils-indent = false\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "and the other direction too: {}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_written_before_the_option_joined_the_key_is_rebuilt() {
|
||||
let dir = TempDir::new("cache-oldshape");
|
||||
let path = dir.write("a.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
|
||||
|
||||
// The five-field line lucisv wrote before `uvm-utils-indent` was in the
|
||||
// key. Not corruption: the line is dropped on its own and the run
|
||||
// rebuilds the store in the current shape.
|
||||
let hash = lucisv_core::cache::content_hash(FORMATTED.as_bytes());
|
||||
std::fs::write(dir.cache_file(), format!("{hash:016x}\t100\t2\t{VERSION}\t{path}\n")).unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "an older store is never an error: {}", stderr(&out));
|
||||
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
|
||||
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "the store was rebuilt: {}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_from_another_lucisv_version_is_ignored() {
|
||||
let dir = TempDir::new("cache-version");
|
||||
@@ -1397,13 +1459,14 @@ fn an_entry_from_another_lucisv_version_is_ignored() {
|
||||
|
||||
// A forged entry claiming this unformatted file is clean. With this
|
||||
// version's stamp it is believed…
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, VERSION)).unwrap();
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, VERSION))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "the forged entry proves entries are really read");
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// …and with any other version's stamp it is not.
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, "0.0.0-other"))
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, false, "0.0.0-other"))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "another version's entry must not be trusted: {}", stderr(&out));
|
||||
|
||||
@@ -32,6 +32,9 @@ pub struct Entry {
|
||||
pub line_length: usize,
|
||||
/// The `indent` that verdict was reached under.
|
||||
pub indent: usize,
|
||||
/// The `[format] uvm-utils-indent` that verdict was reached under: it
|
||||
/// changes the output of a UVM class, so it is part of the key.
|
||||
pub uvm_utils_indent: bool,
|
||||
}
|
||||
|
||||
/// The cache for one run: loaded once at startup, written once at exit.
|
||||
@@ -104,8 +107,8 @@ impl Cache {
|
||||
let entry = &self.entries[path];
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"{:016x}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent
|
||||
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
|
||||
);
|
||||
}
|
||||
text
|
||||
@@ -137,25 +140,49 @@ fn key(path: &Path) -> Option<&str> {
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The `(content, line-length, indent)` prefix every store line has ever
|
||||
/// begun with, or `None` when those three fields are not what lucisv writes.
|
||||
fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize, usize)> {
|
||||
Some((u64::from_str_radix(content, 16).ok()?, line_length.parse().ok()?, indent.parse().ok()?))
|
||||
}
|
||||
|
||||
/// Parses the store. `None` means "this file is not something lucisv wrote"
|
||||
/// — one malformed line discards the whole cache, because partial trust in
|
||||
/// a file already caught lying is not worth the branch. Entries from
|
||||
/// another lucisv version are dropped individually; that is staleness, not
|
||||
/// corruption.
|
||||
/// another lucisv version, and lines written in an older field layout, are
|
||||
/// dropped individually; that is staleness, not corruption.
|
||||
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
||||
let mut entries = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let mut fields = line.splitn(5, '\t');
|
||||
let content = u64::from_str_radix(fields.next()?, 16).ok()?;
|
||||
let line_length = fields.next()?.parse().ok()?;
|
||||
let indent = fields.next()?.parse().ok()?;
|
||||
let version = fields.next()?;
|
||||
let path = fields.next()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
entries.insert(path.to_string(), Entry { content, line_length, indent });
|
||||
let fields: Vec<&str> = line.splitn(6, '\t').collect();
|
||||
match fields[..] {
|
||||
[content, line_length, indent, uvm, version, path] => {
|
||||
let (content, line_length, indent) = prefix(content, line_length, indent)?;
|
||||
let uvm_utils_indent = uvm.parse().ok()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
entries.insert(
|
||||
path.to_string(),
|
||||
Entry { content, line_length, indent, uvm_utils_indent },
|
||||
);
|
||||
}
|
||||
}
|
||||
// A store written before `uvm-utils-indent` joined the key: a
|
||||
// well-formed line of that older shape says nothing about the
|
||||
// option, so it is dropped individually, exactly like another
|
||||
// version's entry. (The version field alone already makes such
|
||||
// a store miss; the codec stays self-describing anyway.)
|
||||
// Anything else on five fields is corruption and discards the
|
||||
// file like any other malformed line.
|
||||
[content, line_length, indent, _version, path] => {
|
||||
prefix(content, line_length, indent)?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(entries)
|
||||
@@ -201,7 +228,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn entry(content: u64) -> Entry {
|
||||
Entry { content, line_length: 100, indent: 2 }
|
||||
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -234,9 +261,53 @@ mod tests {
|
||||
assert!(!reloaded.is_clean(&file, entry(0xbeef)));
|
||||
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uvm_utils_indent_alone_is_a_different_entry() {
|
||||
let on = Entry { uvm_utils_indent: true, ..entry(0xdead) };
|
||||
assert_ne!(entry(0xdead), on, "the option is part of equality");
|
||||
|
||||
// …and it survives the round trip through the store, on its own.
|
||||
let dir = TempDir::new("uvm");
|
||||
let file = dir.file("a.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, on);
|
||||
cache.store();
|
||||
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
|
||||
|
||||
let reloaded = Cache::load(&dir.path);
|
||||
assert!(reloaded.is_clean(&file, on));
|
||||
assert!(!reloaded.is_clean(&file, entry(0xdead)), "the option must invalidate the entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_without_the_option_is_dropped_but_not_fatal() {
|
||||
// The five-field shape lucisv wrote before `uvm-utils-indent` joined
|
||||
// the key: stale, like another version's entry, never corruption.
|
||||
let dir = TempDir::new("oldshape");
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
mine.to_string_lossy()
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), text).unwrap();
|
||||
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&old, entry(1)), "a line without the option must not be trusted");
|
||||
assert!(cache.is_clean(&mine, entry(2)), "and it does not discard the rest of the file");
|
||||
|
||||
// And it is not carried forward.
|
||||
cache.store();
|
||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_sorted_and_carries_the_version() {
|
||||
let dir = TempDir::new("format");
|
||||
@@ -254,7 +325,7 @@ mod tests {
|
||||
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
||||
assert_eq!(
|
||||
lines[0],
|
||||
format!("{:016x}\t100\t2\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
@@ -277,12 +348,15 @@ mod tests {
|
||||
"0000000000000001\twide\t2\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\t\n",
|
||||
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
|
||||
"\0\0\0\n",
|
||||
] {
|
||||
let dir = TempDir::new("corrupt");
|
||||
let file = dir.file("a.sv");
|
||||
// A good line first: a bad one anywhere discards all of them.
|
||||
let good = format!("{:016x}\t100\t2\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
let good =
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
|
||||
@@ -295,7 +369,8 @@ mod tests {
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t0.0.0-not-this-one\t{}\n{:016x}\t100\t2\t{VERSION}\t{}\n",
|
||||
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
|
||||
@@ -30,6 +30,10 @@ pub struct FileConfig {
|
||||
/// directory, so every `FileConfig` a `Discovery` hands out carries a
|
||||
/// usable path. See `docs/features/filelist/README.md`.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// `[format] uvm-utils-indent`: indent the `` `uvm_field_* `` macro
|
||||
/// statements written between `` `uvm_*_utils_begin `` and
|
||||
/// `` `uvm_*_utils_end ``. Off for the same reason.
|
||||
pub format_uvm_utils_indent: Option<bool>,
|
||||
/// `[lint] select`: run exactly these rules, replacing the default set.
|
||||
/// The names are **not** validated here — this crate does not know the
|
||||
/// rule registry; `lucisv check` validates them the moment it resolves the
|
||||
@@ -104,6 +108,8 @@ enum Table {
|
||||
Top,
|
||||
/// `[lint]`: `select`, `ignore` and `waivers`.
|
||||
Lint,
|
||||
/// `[format]`: the layout keys that are off by default.
|
||||
Format,
|
||||
/// `[lint.<rule>]`: that rule's options.
|
||||
Rule(String),
|
||||
}
|
||||
@@ -122,6 +128,10 @@ fn parse_entry(
|
||||
*table = Table::Lint;
|
||||
return Ok(());
|
||||
}
|
||||
if line == "[format]" {
|
||||
*table = Table::Format;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) {
|
||||
if rule.is_empty() || rule.contains('.') || rule.contains(' ') {
|
||||
return Err(format!("`{line}` is not a rule table; write `[lint.<rule-name>]`"));
|
||||
@@ -130,7 +140,8 @@ fn parse_entry(
|
||||
return Ok(());
|
||||
}
|
||||
return Err(format!(
|
||||
"unknown table `{line}` (the tables are `[lint]` and `[lint.<rule-name>]`)"
|
||||
"unknown table `{line}` \
|
||||
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
|
||||
));
|
||||
}
|
||||
let (key, value) =
|
||||
@@ -141,6 +152,7 @@ fn parse_entry(
|
||||
return Err(format!("`{key}` has no value"));
|
||||
}
|
||||
match table {
|
||||
Table::Format => return parse_format_entry(key, value, config),
|
||||
Table::Lint => return parse_lint_entry(key, value, config),
|
||||
Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number),
|
||||
Table::Top => {}
|
||||
@@ -164,12 +176,43 @@ fn parse_entry(
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
uvm-utils-indent under `[format]`; \
|
||||
select, ignore, waivers under `[lint]`; and a rule's own options \
|
||||
under `[lint.<rule-name>]`)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[format]` table: a boolean that defaults to off, because
|
||||
/// it changes how already-clean files are laid out and a project has to opt
|
||||
/// in before anything of its moves.
|
||||
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
let slot = match key {
|
||||
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[format]` \
|
||||
(the only key is uvm-utils-indent)"
|
||||
))
|
||||
}
|
||||
};
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
*slot = Some(parse_bool(key, value)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `true` or `false`, and nothing else — a misspelling is a typo the user
|
||||
/// wants to hear about, not a silent `false`.
|
||||
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
|
||||
match value {
|
||||
"true" => Ok(true),
|
||||
"false" => Ok(false),
|
||||
_ => Err(format!("`{key}` expects `true` or `false`, found `{value}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[lint]` table.
|
||||
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if key == "waivers" {
|
||||
@@ -550,6 +593,65 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
);
|
||||
}
|
||||
|
||||
/// The `[format]` table: the layout keys that change how an already-clean
|
||||
/// file is laid out, and so are off unless a checked-in `lucisv.toml`
|
||||
/// turns them on (TODO §54.3).
|
||||
#[test]
|
||||
fn the_format_table_carries_uvm_utils_indent() {
|
||||
assert_eq!(ok("[format]\nuvm-utils-indent = true").format_uvm_utils_indent, Some(true));
|
||||
assert_eq!(ok("[format]\nuvm-utils-indent = false").format_uvm_utils_indent, Some(false));
|
||||
// Absent unless written — which is what makes the default off.
|
||||
assert_eq!(ok("indent = 4").format_uvm_utils_indent, None);
|
||||
assert_eq!(ok("[format]").format_uvm_utils_indent, None);
|
||||
// The formatter keys still work above the table, and nothing closes
|
||||
// the table but the next header.
|
||||
let mixed = parse(
|
||||
"indent = 4\n\n[format]\nuvm-utils-indent = true\n\n[lint]\nignore = [\"no-tabs\"]",
|
||||
)
|
||||
.expect("parses");
|
||||
assert_eq!(mixed.indent, Some(4));
|
||||
assert_eq!(mixed.format_uvm_utils_indent, Some(true));
|
||||
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
||||
}
|
||||
|
||||
/// Everything about the table's shape, the way the `[lint]` table's is
|
||||
/// pinned: an unknown key is named, a non-boolean value is refused, and a
|
||||
/// repeated key is an error rather than a last-one-wins.
|
||||
#[test]
|
||||
fn the_format_table_rejects_what_it_does_not_support() {
|
||||
assert!(err("[format]\nbogus = true").contains("unknown key `bogus` under `[format]`"));
|
||||
assert!(err("[format]\nuvm-utils-indent = \"yes\"")
|
||||
.contains("`uvm-utils-indent` expects `true` or `false`, found `\"yes\"`"));
|
||||
assert!(err("[format]\nuvm-utils-indent = 1").contains("expects `true` or `false`"));
|
||||
assert!(err("[format]\nuvm-utils-indent =").contains("has no value"));
|
||||
assert!(err("[format]\nuvm-utils-indent = true\nuvm-utils-indent = false")
|
||||
.contains("duplicate key `uvm-utils-indent`"));
|
||||
// A key before any table still belongs to the top level, and the
|
||||
// top-level unknown-key message names the table it does belong to.
|
||||
assert!(err("uvm-utils-indent = true").contains("unknown key `uvm-utils-indent`"));
|
||||
assert!(err("uvm-utils-indent = true").contains("`[format]`"));
|
||||
// `[format.<anything>]` is not a table this parser knows.
|
||||
assert!(err("[format.uvm]\nx = 1").contains("unknown table"));
|
||||
}
|
||||
|
||||
/// The same key in a real config file, so the message a user sees names
|
||||
/// the file and the line to edit — the ladder `[format]` sits at the top
|
||||
/// of (`lucisv.toml` outranks the editor setting).
|
||||
#[test]
|
||||
fn a_bad_format_key_names_the_file_and_line() {
|
||||
let tree = TempTree::new();
|
||||
let config = tree.write("lucisv.toml", "indent = 2\n\n[format]\nuvm-utils-indnet = true\n");
|
||||
let file = tree.write("x.sv", "");
|
||||
let message = Discovery::new(true).for_file(&file).expect_err("expected an error");
|
||||
assert!(message.starts_with(&format!("{}:4: ", config.display())), "{message}");
|
||||
assert!(message.contains("unknown key `uvm-utils-indnet` under `[format]`"), "{message}");
|
||||
// And the key spelled right loads through the same walk.
|
||||
let good = TempTree::new();
|
||||
good.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
|
||||
let sv = good.write("a/b/x.sv", "");
|
||||
assert_eq!(Discovery::new(true).for_file(&sv).unwrap().format_uvm_utils_indent, Some(true));
|
||||
}
|
||||
|
||||
/// The `[lint]` table: the off switch a round that turns rules on by
|
||||
/// default owes its users (topo §2.9-4).
|
||||
#[test]
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -224,6 +224,14 @@ fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingO
|
||||
if let Some(line_length) = file.line_length {
|
||||
config.max_width = line_length;
|
||||
}
|
||||
// The `[format]` keys follow the same ladder: the editor's own setting
|
||||
// first, then `lucisv.toml`, which outranks it.
|
||||
if let Some(on) = client.uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
if let Some(on) = file.format_uvm_utils_indent {
|
||||
config.uvm_utils_indent = on;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
@@ -508,6 +516,39 @@ mod tests {
|
||||
assert_eq!(settings.config.max_width, Config::default().max_width);
|
||||
}
|
||||
|
||||
/// The `[format]` keys climb the same ladder — with no rung 3, since the
|
||||
/// protocol has no option for them: `lucisv.toml` > `lucisv.format.*` >
|
||||
/// the built-in default, which is off (TODO §54.3).
|
||||
#[test]
|
||||
fn a_format_key_climbs_the_ladder_from_off() {
|
||||
let uvm = |on: Option<bool>| ClientSettings { uvm_utils_indent: on, ..Default::default() };
|
||||
// Rung 4: nobody asked, so the key never fires.
|
||||
let (ws, uri) = document("module m;\nendmodule\n");
|
||||
assert!(!settings_with(&ws, &uri, &none(), &options(2, true)).config.uvm_utils_indent);
|
||||
// Rung 2: the editor setting is the only thing that spoke.
|
||||
assert!(
|
||||
settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
|
||||
);
|
||||
// Rung 1: `lucisv.toml` outranks the editor, in both directions.
|
||||
let on = Tree::new("[format]\nuvm-utils-indent = true\n");
|
||||
let (ws, uri) = on.document("module m;\nendmodule\n");
|
||||
let settings = settings_with(&ws, &uri, &uvm(Some(false)), &options(2, true));
|
||||
assert_eq!(settings.problem, None);
|
||||
assert!(settings.config.uvm_utils_indent, "lucisv.toml wins");
|
||||
let off = Tree::new("[format]\nuvm-utils-indent = false\n");
|
||||
let (ws, uri) = off.document("module m;\nendmodule\n");
|
||||
assert!(
|
||||
!settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
|
||||
);
|
||||
// A config that names other keys is silent about this one, so the
|
||||
// editor setting still answers for it.
|
||||
let other = Tree::new("indent = 4\n");
|
||||
let (ws, uri) = other.document("module m;\nendmodule\n");
|
||||
let settings = settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true));
|
||||
assert_eq!(settings.config.indent_width, 4);
|
||||
assert!(settings.config.uvm_utils_indent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_key_climbs_the_ladder_independently() {
|
||||
// A `lucisv.toml` naming only `indent` must not also claim the width:
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Inline a module at the cursor, on the wire: `textDocument/codeAction` under
|
||||
//! LSP's own `refactor.inline`, and `workspace/executeCommand` for the editors
|
||||
//! that have no lightbulb.
|
||||
//!
|
||||
//! Protocol only. The edit is `vlog_refactor::inline_module`; this module
|
||||
//! decides which files that engine is handed, turns its answer into a
|
||||
//! `WorkspaceEdit` and its refusal into a request error.
|
||||
//!
|
||||
//! **The action carries a command, not an edit**, for the same reason the
|
||||
//! extraction's does — laziness rather than a prompt. Answering "what would
|
||||
//! inlining `S` here look like" means reading `S`'s file, every file that
|
||||
//! spells it, and analyzing all of them; a `textDocument/codeAction` arrives
|
||||
//! on every cursor move. So the offer is one parse of one buffer
|
||||
//! (`vlog_refactor::inline_site`) plus a `Command` naming [`INLINE_MODULE`],
|
||||
//! and the workspace is not touched until the user picks the action. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
|
||||
// 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, Position, Range, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Workspace;
|
||||
|
||||
/// Inline the module instantiated at a position: `[uri, position]`.
|
||||
pub const INLINE_MODULE: &str = "lucisv.inlineModule";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![INLINE_MODULE.to_string()]
|
||||
}
|
||||
|
||||
/// The kind LSP reserves for an inline, which is what an editor's "Refactor…"
|
||||
/// menu asks for by name.
|
||||
pub fn kind() -> CodeActionKind {
|
||||
CodeActionKind::REFACTOR_INLINE
|
||||
}
|
||||
|
||||
/// The action for the cursor, carrying the command that does the work.
|
||||
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 path for the engine's file set; nothing
|
||||
// is offered rather than offered and refused.
|
||||
return Vec::new();
|
||||
}
|
||||
let offset = doc.positions().offset(range.start);
|
||||
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else { return Vec::new() };
|
||||
let arguments = vec![
|
||||
serde_json::to_value(uri).unwrap_or(Value::Null),
|
||||
serde_json::to_value(range.start).unwrap_or(Value::Null),
|
||||
];
|
||||
let title = vlog_refactor::inline_title(&site.module);
|
||||
vec![CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: title.clone(),
|
||||
kind: Some(kind()),
|
||||
command: Some(Command {
|
||||
title,
|
||||
command: INLINE_MODULE.to_string(),
|
||||
arguments: Some(arguments),
|
||||
}),
|
||||
..Default::default()
|
||||
})]
|
||||
}
|
||||
|
||||
/// Run `lucisv.inlineModule`, or say why it cannot run.
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
arguments: &[Value],
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let uri: Uri = argument(arguments, 0, "a document URI")?;
|
||||
let position: Position = argument(arguments, 1, "a position")?;
|
||||
let doc =
|
||||
ws.document(&uri).ok_or_else(|| "lucisv can only inline in an open file.".to_string())?;
|
||||
let path = doc
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?;
|
||||
let offset = doc.positions().offset(position);
|
||||
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else {
|
||||
return Err(NOTHING.to_string());
|
||||
};
|
||||
// The engine reads the instantiated module's declaration and refuses over
|
||||
// any hierarchical path into the instance, so the file set is the two
|
||||
// units' own fan-out: the declaring file, and every file the index says
|
||||
// mentions either name.
|
||||
let files = ws.module_sources(&path, &site.units);
|
||||
let refactoring = vlog_refactor::inline_module(&files, &path, offset)?;
|
||||
Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
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!("{INLINE_MODULE} wants {what} as argument {}.", n + 1))
|
||||
}
|
||||
|
||||
const NOTHING: &str = "there is no module instantiation at this position to inline.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
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_inline_{}_{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) {
|
||||
fs::write(self.path.join(rel), text).expect("write");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
const SUB: &str = "\
|
||||
module sub (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
logic s; // the and
|
||||
assign s = a;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
sub u_sub (
|
||||
.a(x),
|
||||
.q(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn opened(tree: &Tree) -> (Workspace, Uri) {
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// The cursor on the `sub` of `sub u_sub (`.
|
||||
fn cursor() -> Range {
|
||||
let at = Position { line: 4, character: 4 };
|
||||
Range { start: at, end: at }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_on_an_instantiation_is_offered_the_action_with_its_command() {
|
||||
let tree = Tree::new("offer");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let actions = code_actions(&ws, &uri, cursor());
|
||||
let [CodeActionOrCommand::CodeAction(action)] = actions.as_slice() else {
|
||||
panic!("one action, got {actions:?}")
|
||||
};
|
||||
assert_eq!(action.title, "lucisv: inline `sub` here");
|
||||
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_INLINE));
|
||||
assert!(action.edit.is_none(), "the offer reads no workspace");
|
||||
let command = action.command.as_ref().expect("a command");
|
||||
assert_eq!(command.command, INLINE_MODULE);
|
||||
assert_eq!(command.arguments.as_ref().expect("arguments").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_on_anything_else_is_offered_nothing() {
|
||||
let tree = Tree::new("nothing");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let elsewhere = Range {
|
||||
start: Position { line: 1, character: 4 },
|
||||
end: Position { line: 1, character: 4 },
|
||||
};
|
||||
assert!(code_actions(&ws, &uri, elsewhere).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_replaces_the_instantiation_with_the_body() {
|
||||
let tree = Tree::new("run");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(cursor().start).expect("position"),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, &arguments).expect("inlines");
|
||||
let changes = edit.changes.as_ref().expect("changes");
|
||||
assert_eq!(changes.len(), 1, "only the file the cursor is in is edited");
|
||||
let written = &changes.get(&uri).expect("this file")[0].new_text;
|
||||
assert!(written.contains("assign s = x;"), "{written}");
|
||||
assert!(written.contains("// the and"), "{written}");
|
||||
assert!(warnings.iter().any(|w| w.contains("still declared where it was")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_says_why_when_there_is_nothing_to_inline() {
|
||||
let tree = Tree::new("refuse");
|
||||
let (ws, uri) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 1, character: 4 }).expect("position"),
|
||||
];
|
||||
assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_wants_both_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).expect_err("a refusal");
|
||||
assert!(message.contains("argument 2"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_asking_only_for_refactor_inline_is_answered() {
|
||||
let filter = [CodeActionKind::REFACTOR_INLINE];
|
||||
assert!(crate::code_action::wanted(Some(&filter), &kind()));
|
||||
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
|
||||
}
|
||||
}
|
||||
@@ -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,15 +13,18 @@ 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;
|
||||
mod inline;
|
||||
mod inline_module;
|
||||
mod instantiate;
|
||||
mod large;
|
||||
mod lens;
|
||||
@@ -59,11 +62,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 +131,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 +265,9 @@ fn capabilities() -> ServerCapabilities {
|
||||
CodeActionKind::QUICKFIX,
|
||||
CodeActionKind::new(code_action::FIX_ALL),
|
||||
CodeActionKind::new(ports::REFACTOR_PORTS),
|
||||
imports::kind(),
|
||||
extract::kind(),
|
||||
inline_module::kind(),
|
||||
]),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
// The quick fixes are complete when they are offered; the port
|
||||
@@ -397,10 +405,13 @@ 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(inline_module::commands());
|
||||
commands.extend(instantiate::commands());
|
||||
commands.extend(lens::commands());
|
||||
commands
|
||||
@@ -523,6 +534,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 +1216,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::{
|
||||
|
||||
@@ -349,6 +349,7 @@ pub fn execute(
|
||||
// its own `WorkspaceEdit`, but `server.rs` routes every non-lens
|
||||
// `workspace/executeCommand` through here — this is the one place an
|
||||
// edit-producing command is handed to `Server::deliver`.
|
||||
crate::imports::ORGANIZE_IMPORTS => return crate::imports::execute(ws, arguments),
|
||||
crate::instantiate::INSTANTIATE => {
|
||||
return crate::instantiate::execute(ws, arguments).map(|edit| (edit, Vec::new()))
|
||||
}
|
||||
|
||||
@@ -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, inline_module, lens, linked, lint, nav, pairs, ports,
|
||||
rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
impl Server {
|
||||
@@ -268,13 +268,44 @@ 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));
|
||||
}
|
||||
// Inlining the module instantiated under the cursor — the
|
||||
// mirror of the extraction, and lazy for the same reason: the
|
||||
// offer parses one buffer and the command reads the workspace.
|
||||
if code_action::wanted(only.as_deref(), &inline_module::kind()) {
|
||||
actions.extend(inline_module::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 +374,31 @@ 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)),
|
||||
};
|
||||
}
|
||||
if p.command == inline_module::INLINE_MODULE {
|
||||
return match inline_module::execute(&self.workspace, &p.arguments) {
|
||||
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.
|
||||
|
||||
@@ -106,6 +106,12 @@ pub struct ClientSettings {
|
||||
/// or relative to the workspace root. Empty means "unset", which is what
|
||||
/// the VS Code default is — see `docs/features/filelist/README.md`.
|
||||
pub filelist: Option<String>,
|
||||
/// `lucisv.format.uvmUtilsIndent`: whether the `` `uvm_field_* `` macros
|
||||
/// written between `` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` are
|
||||
/// indented one level. Unset means off, which is what the VS Code default
|
||||
/// declares — the key changes bytes in files that already format cleanly,
|
||||
/// so nothing turns it on for a user who did not ask.
|
||||
pub uvm_utils_indent: Option<bool>,
|
||||
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
|
||||
/// Unset means on, which is what the VS Code default declares — see
|
||||
/// `docs/features/inline-templates/README.md`.
|
||||
@@ -237,6 +243,7 @@ impl Default for ClientSettings {
|
||||
indent: None,
|
||||
exclude: Vec::new(),
|
||||
filelist: None,
|
||||
uvm_utils_indent: None,
|
||||
inline_templates: None,
|
||||
inline_instantiation: None,
|
||||
format_on_save: false,
|
||||
@@ -335,6 +342,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
|
||||
exclude: strings(lucisv.get("exclude")),
|
||||
filelist: path(lucisv.get("filelist")),
|
||||
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
|
||||
inline_templates: flag(lucisv.get("inlineTemplates")),
|
||||
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
|
||||
// Anything that is not `true` leaves the hook declining, wrong-typed
|
||||
|
||||
@@ -8529,3 +8529,105 @@ endmodule
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Two packages and a module importing both, for organize-imports.
|
||||
const IMPORTS_A: &str = "package a_pkg;\n typedef int a_t;\nendpackage\n";
|
||||
const IMPORTS_B: &str = "package b_pkg;\n typedef int b_t;\nendpackage\n";
|
||||
const IMPORTS_TOP: &str =
|
||||
"module top;\n import b_pkg::*;\n import a_pkg::*;\n a_t p;\n b_t q;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn organize_imports_is_offered_under_its_own_kind_and_runs_as_a_command() {
|
||||
// What only an e2e test can check: that `source.organizeImports` is
|
||||
// advertised and honoured as an `only` filter — which is exactly how an
|
||||
// editor's organize-on-save asks — and that the command reaches the
|
||||
// engine with its arguments intact.
|
||||
let dir = temp_dir("organize_imports");
|
||||
for (name, text) in [("a_pkg.sv", IMPORTS_A), ("b_pkg.sv", IMPORTS_B), ("top.sv", IMPORTS_TOP)]
|
||||
{
|
||||
std::fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let root = format!("file://{}", dir.display());
|
||||
let top_uri = format!("file://{}", dir.join("top.sv").display());
|
||||
|
||||
let open = |uri: &str, text: &str| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
open(&top_uri, IMPORTS_TOP),
|
||||
// The cursor on the first import, asking for organize-imports alone.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":1,"character":2}},"end":{{"line":1,"character":2}}}},"context":{{"diagnostics":[],"only":["source.organizeImports"]}}}}}}"#
|
||||
)),
|
||||
// The same cursor asking for quick fixes alone gets none of it.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":1,"character":2}},"end":{{"line":1,"character":2}}}},"context":{{"diagnostics":[],"only":["quickfix"]}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.organizeImports","arguments":["{top_uri}",{{"line":1,"character":2}}]}}}}"#
|
||||
)),
|
||||
// A cursor in the body has nothing to organize, and says so.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":5,"method":"workspace/executeCommand","params":{{"command":"lucisv.organizeImports","arguments":["{top_uri}",{{"line":3,"character":2}}]}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
|
||||
// 1. The kind and the command are advertised.
|
||||
let capabilities = &messages.iter().find(|m| m["id"] == 1).expect("initialize response")
|
||||
["result"]["capabilities"];
|
||||
let kinds = capabilities["codeActionProvider"]["codeActionKinds"]
|
||||
.as_array()
|
||||
.expect("the kinds are listed");
|
||||
assert!(kinds.iter().any(|k| k == "source.organizeImports"), "{kinds:#?}");
|
||||
let commands = capabilities["executeCommandProvider"]["commands"]
|
||||
.as_array()
|
||||
.expect("the commands are listed");
|
||||
assert!(commands.iter().any(|c| c == "lucisv.organizeImports"), "{commands:#?}");
|
||||
|
||||
// 2. `only: ["source.organizeImports"]` returns exactly this action.
|
||||
let offered = messages.iter().find(|m| m["id"] == 2).expect("codeAction response")["result"]
|
||||
.as_array()
|
||||
.expect("an array of actions")
|
||||
.clone();
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "source.organizeImports")
|
||||
.unwrap_or_else(|| panic!("no organize action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: organize imports (removes 0, sorts 2)");
|
||||
let edits = action["edit"]["changes"][&top_uri].as_array().expect("one file's edits");
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0]["newText"], " import a_pkg::*;\n import b_pkg::*;");
|
||||
|
||||
// 3. Asking for quick fixes alone does not compute it.
|
||||
let quick = messages.iter().find(|m| m["id"] == 3).expect("codeAction response")["result"]
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.clone();
|
||||
assert!(
|
||||
!quick.iter().any(|a| a["kind"] == "source.organizeImports"),
|
||||
"the `only` filter is honoured: {quick:#?}"
|
||||
);
|
||||
|
||||
// 4. The command applies the same edit...
|
||||
let ran = messages.iter().find(|m| m["id"] == 4).expect("executeCommand response");
|
||||
assert!(ran["error"].is_null(), "{ran:#?}");
|
||||
|
||||
// 5. ...and refuses elsewhere with a sentence rather than silence.
|
||||
let refused = messages.iter().find(|m| m["id"] == 5).expect("executeCommand response");
|
||||
let said = refused["error"]["message"].as_str().unwrap_or_default();
|
||||
assert!(said.contains("no import run to organize"), "{refused:#?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
|
||||
use super::comment::is_line_comment;
|
||||
use super::instance::drive_strength;
|
||||
use super::list::ListItem;
|
||||
use super::{name_doc, Fmt};
|
||||
|
||||
@@ -297,6 +298,11 @@ impl<'a> Fmt<'a> {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(net) = &d.net {
|
||||
docs.push(text(net.clone()));
|
||||
// `wire (strong0, weak1) #5 w;` — the strength stands between the
|
||||
// net keyword and the delay, and owns the gap in front of its `(`.
|
||||
if let Some(s) = &d.strength {
|
||||
docs.push(drive_strength(self, s));
|
||||
}
|
||||
self.net_delay(d, false, &mut docs);
|
||||
}
|
||||
self.qualifier_run(&d.qualifiers, &mut docs);
|
||||
|
||||
@@ -169,12 +169,16 @@ impl<'a> Fmt<'a> {
|
||||
text("}"),
|
||||
]),
|
||||
// `{<<8{v}}` — written tight, like a replication.
|
||||
ExprKind::Stream { dir, slice, inner } => {
|
||||
let mut docs = vec![text("{"), text(dir.clone())];
|
||||
ExprKind::Stream { dir, slice, inner, comments } => {
|
||||
let mut docs = vec![text("{")];
|
||||
self.slot_comments(&comments.after_open, &mut docs);
|
||||
docs.push(text(dir.clone()));
|
||||
if let Some(s) = slice {
|
||||
docs.push(self.expr(s));
|
||||
}
|
||||
self.slot_comments(&comments.before_inner, &mut docs);
|
||||
docs.push(self.expr_list("{", inner, "}"));
|
||||
self.slot_comments(&comments.before_close, &mut docs);
|
||||
docs.push(text("}"));
|
||||
concat(docs)
|
||||
}
|
||||
@@ -241,6 +245,17 @@ impl<'a> Fmt<'a> {
|
||||
ExprKind::With { base, arg, comments } => {
|
||||
concat(vec![self.with_head(base, comments), self.expr(arg)])
|
||||
}
|
||||
// `a with [0:3]` — the same head every postfix `with` has, then
|
||||
// the bracket printed through the slots a part select's uses.
|
||||
ExprKind::StreamWith { base, range } => {
|
||||
let mut docs = vec![self.with_head(base, &range.with_comments)];
|
||||
let rest = match (&range.op, &range.lsb) {
|
||||
(Some(op), Some(lsb)) => Some((op.as_str(), self.expr_compact(lsb))),
|
||||
_ => None,
|
||||
};
|
||||
docs.push(self.bracket_slots(&range.comments, self.expr_compact(&range.msb), rest));
|
||||
concat(docs)
|
||||
}
|
||||
ExprKind::WithConstraint { base, block, comments } => {
|
||||
let body = match &**block {
|
||||
ConstraintBody::Items(set) => self.with_constraint_block(set),
|
||||
|
||||
@@ -340,7 +340,7 @@ impl<'a> Fmt<'a> {
|
||||
pub(super) fn gate_instantiation(&self, g: &GateInstantiation) -> Doc {
|
||||
let mut docs = vec![text(g.gate.clone())];
|
||||
if let Some(s) = &g.strength {
|
||||
docs.push(text(format!(" {}", drive_strength(s))));
|
||||
docs.push(drive_strength(self, s));
|
||||
}
|
||||
if !g.delay.is_empty() {
|
||||
// The gap in front of the `#` is a space unless the source wrote
|
||||
@@ -439,10 +439,45 @@ fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write.
|
||||
pub(super) fn drive_strength(s: &DriveStrength) -> String {
|
||||
match &s.second {
|
||||
Some(second) => format!("({}, {})", s.first, second),
|
||||
None => format!("({})", s.first),
|
||||
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write —
|
||||
/// with the comments written in any of its five gaps back where they stood.
|
||||
///
|
||||
/// The gap in front of the `(` is the strength's own (`assign /*c*/ (weak0,
|
||||
/// pull1) x = y;`), so — exactly as a net delay's `before_hash` is — this
|
||||
/// prints the separator that precedes the `(` too: the comments when the
|
||||
/// source wrote any there, and a plain space when it did not. A caller emits
|
||||
/// nothing of its own in front of the call.
|
||||
pub(super) fn drive_strength(fmt: &Fmt<'_>, s: &DriveStrength) -> Doc {
|
||||
let c = &s.comments;
|
||||
if c.before_open.is_empty()
|
||||
&& c.after_open.is_empty()
|
||||
&& c.before_comma.is_empty()
|
||||
&& c.after_comma.is_empty()
|
||||
&& c.before_close.is_empty()
|
||||
{
|
||||
return match &s.second {
|
||||
Some(second) => text(format!(" ({}, {})", s.first, second)),
|
||||
None => text(format!(" ({})", s.first)),
|
||||
};
|
||||
}
|
||||
let mut docs = Vec::new();
|
||||
match c.before_open.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => fmt.inline_comments_spaced(&c.before_open, &mut docs),
|
||||
}
|
||||
docs.push(text("("));
|
||||
fmt.slot_comments(&c.after_open, &mut docs);
|
||||
docs.push(text(s.first.clone()));
|
||||
if let Some(second) = &s.second {
|
||||
fmt.slot_comments(&c.before_comma, &mut docs);
|
||||
docs.push(text(","));
|
||||
match c.after_comma.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => fmt.inline_comments_spaced(&c.after_comma, &mut docs),
|
||||
}
|
||||
docs.push(text(second.clone()));
|
||||
}
|
||||
fmt.slot_comments(&c.before_close, &mut docs);
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
@@ -66,23 +66,64 @@ impl<'a> Fmt<'a> {
|
||||
pub(super) fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
|
||||
let aligns = self.param_decl_aligns(items, depth);
|
||||
let mut docs = Vec::new();
|
||||
// The items between a `` `uvm_object_utils_begin `` and its `_end`,
|
||||
// one entry per `_begin` still open while `uvm-utils-indent` is on.
|
||||
// They are collected apart so each run can be indented at once — the
|
||||
// macros declare no block, so there is nothing else to indent them by
|
||||
// — and they are a stack so an `_end` closes the `_begin` it matches.
|
||||
let mut utils: Vec<Vec<Doc>> = Vec::new();
|
||||
// The last item that actually emitted something, which is what a
|
||||
// glued null item glues to.
|
||||
let mut prev: Option<&Item> = None;
|
||||
let mut emitted = false;
|
||||
for (item, align) in items.iter().zip(&aligns) {
|
||||
let item_docs = self.item_docs(item, align.as_ref(), depth);
|
||||
if item_docs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !docs.is_empty() && !prev.is_some_and(|p| self.glued_null_item(p, item)) {
|
||||
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
// The `_end` closes the level the innermost open `_begin` opened,
|
||||
// so it prints back in that `_begin`'s own column. An `_end` with
|
||||
// nothing open closes nothing and moves no indentation.
|
||||
if self.at_utils_macro(item, "_end") {
|
||||
if let Some(open) = utils.pop() {
|
||||
utils.last_mut().unwrap_or(&mut docs).push(indent(open));
|
||||
}
|
||||
}
|
||||
docs.extend(item_docs);
|
||||
let sink = utils.last_mut().unwrap_or(&mut docs);
|
||||
if emitted && !prev.is_some_and(|p| self.glued_null_item(p, item)) {
|
||||
sink.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
sink.extend(item_docs);
|
||||
prev = Some(item);
|
||||
emitted = true;
|
||||
if self.cfg.uvm_utils_indent && self.at_utils_macro(item, "_begin") {
|
||||
utils.push(Vec::new());
|
||||
}
|
||||
}
|
||||
// A `_begin` with no `_end` still prints everything it opened, one
|
||||
// level in: lucisv reproduces the file it was given, unbalanced
|
||||
// macros and all.
|
||||
while let Some(open) = utils.pop() {
|
||||
utils.last_mut().unwrap_or(&mut docs).push(indent(open));
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// True when `item` is a `` `uvm_object_utils_begin `` /
|
||||
/// `` `uvm_component_utils_begin `` macro (`suffix` = `"_begin"`) or the
|
||||
/// matching `_end`.
|
||||
///
|
||||
/// Exactly those four names, matched on the macro's own text: the
|
||||
/// `uvm-utils-indent` key is a targeted rule for one UVM idiom, not a
|
||||
/// general "indent between two macros" heuristic that would guess at
|
||||
/// anybody else's macros.
|
||||
fn at_utils_macro(&self, item: &Item, suffix: &str) -> bool {
|
||||
let ItemKind::MacroItem(m) = &item.kind else { return false };
|
||||
let name = m.raw.text.trim_start_matches('`');
|
||||
let name = name.split(['(', ' ', '\t']).next().unwrap_or("");
|
||||
matches!(name.strip_suffix(suffix), Some("uvm_object_utils" | "uvm_component_utils"))
|
||||
}
|
||||
|
||||
/// True when `item` is a null item (`;`) the source wrote on the line the
|
||||
/// item before it ended on, which is how it is printed back:
|
||||
/// `endgenerate;`, `end;`, `endmodule;`, `;;`.
|
||||
@@ -352,14 +393,16 @@ impl<'a> Fmt<'a> {
|
||||
// written after the keyword, and print there.
|
||||
let lead = a.assigns.first().map(|p| p.meta.leading.as_slice()).unwrap_or(&[]);
|
||||
let mut docs = vec![text("assign")];
|
||||
// A strength owns the gap in front of its `(` — including the space —
|
||||
// so it goes in before the separator the rest of the head needs.
|
||||
if let Some(s) = &a.strength {
|
||||
docs.push(drive_strength(self, s));
|
||||
}
|
||||
if lead.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(lead, &mut docs);
|
||||
}
|
||||
if let Some(s) = &a.strength {
|
||||
docs.push(text(format!("{} ", drive_strength(s))));
|
||||
}
|
||||
if let Some(delay) = &a.delay {
|
||||
docs.push(text("#"));
|
||||
self.slot_comments(&a.after_hash, &mut docs);
|
||||
|
||||
@@ -22,6 +22,7 @@ mod item;
|
||||
mod list;
|
||||
mod module;
|
||||
mod phrase;
|
||||
mod randsequence;
|
||||
mod routine;
|
||||
mod stmt;
|
||||
mod sva;
|
||||
@@ -38,11 +39,19 @@ use vlog_parser::ast::*;
|
||||
pub struct Config {
|
||||
pub max_width: usize,
|
||||
pub indent_width: usize,
|
||||
/// Indent the macro statements written between `` `uvm_object_utils_begin ``
|
||||
/// / `` `uvm_component_utils_begin `` and their `_end`, which are plain
|
||||
/// macro items with no block for the formatter to see.
|
||||
///
|
||||
/// **Off by default**: it changes the output of files that already format
|
||||
/// cleanly, so a project opts in through `[format] uvm-utils-indent` and
|
||||
/// nobody else moves a byte.
|
||||
pub uvm_utils_indent: bool,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config { max_width: 100, indent_width: 2 }
|
||||
Config { max_width: 100, indent_width: 2, uvm_utils_indent: false }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -316,25 +316,35 @@ impl<'a> Fmt<'a> {
|
||||
/// item per line — the body is a declaration list, not an expression, so
|
||||
/// there is nothing here worth collapsing onto the header's line.
|
||||
pub(super) fn clocking(&self, c: &ClockingDecl) -> Doc {
|
||||
let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" });
|
||||
if let Some(n) = &c.name {
|
||||
head.push(' ');
|
||||
head.push_str(&named(&n.text));
|
||||
let mut docs = vec![text(if c.is_default { "default clocking" } else { "clocking" })];
|
||||
match &c.name {
|
||||
Some(n) => {
|
||||
self.word_then("", &c.after_kw, &mut docs);
|
||||
docs.push(name_doc(&n.text));
|
||||
// The gap in front of the `@` is the event's; with no name the
|
||||
// keyword's own gap is that same gap and was printed already.
|
||||
match c.before_event.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&c.before_event, &mut docs),
|
||||
}
|
||||
}
|
||||
None => self.word_then("", &c.after_kw, &mut docs),
|
||||
}
|
||||
let mut docs = vec![text(head)];
|
||||
// `default clocking cb;` selects an existing block: no event, no body.
|
||||
let Some(event) = &c.event else {
|
||||
docs.push(text(";"));
|
||||
// Nothing follows the name, so the separator just written is not
|
||||
// wanted: the `;` goes straight after it.
|
||||
docs.pop();
|
||||
docs.push(self.semi(&c.before_semi));
|
||||
return concat(docs);
|
||||
};
|
||||
docs.push(text(" "));
|
||||
docs.push(self.sens_list(event));
|
||||
docs.push(text(";"));
|
||||
docs.push(self.semi(&c.before_semi));
|
||||
let mut body = Vec::new();
|
||||
for item in &c.items {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading_comments(&item.meta));
|
||||
body.push(concat(vec![self.clocking_item(&item.kind), text(";")]));
|
||||
body.push(concat(vec![self.clocking_item(&item.kind), self.semi(&item.before_semi)]));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
body.extend(self.dangling(&c.dangling));
|
||||
@@ -353,25 +363,24 @@ impl<'a> Fmt<'a> {
|
||||
fn clocking_item(&self, kind: &ClockingItemKind) -> Doc {
|
||||
match kind {
|
||||
ClockingItemKind::Default { input, output } => {
|
||||
let mut s = String::from("default");
|
||||
if let Some(skew) = input {
|
||||
s.push_str(" input ");
|
||||
s.push_str(skew);
|
||||
}
|
||||
if let Some(skew) = output {
|
||||
s.push_str(" output ");
|
||||
s.push_str(skew);
|
||||
}
|
||||
text(s)
|
||||
let mut docs = vec![text("default")];
|
||||
self.clocking_default(input.as_ref(), "input", &mut docs);
|
||||
self.clocking_default(output.as_ref(), "output", &mut docs);
|
||||
concat(docs)
|
||||
}
|
||||
ClockingItemKind::Signals { dir, skew, signals } => {
|
||||
let mut head = dir.clone();
|
||||
ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals } => {
|
||||
let mut docs = vec![text(dir.clone())];
|
||||
match after_dir.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(after_dir, &mut docs),
|
||||
}
|
||||
if let Some(skew) = skew {
|
||||
head.push(' ');
|
||||
head.push_str(skew);
|
||||
docs.push(self.clocking_skew(skew));
|
||||
match after_skew.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(after_skew, &mut docs),
|
||||
}
|
||||
}
|
||||
head.push(' ');
|
||||
let mut docs = vec![text(head)];
|
||||
for (i, sig) in signals.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
@@ -386,4 +395,56 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One half of a `default input #1step output #0;` item, or nothing at all
|
||||
/// when that half was not written. The gap in front of the direction
|
||||
/// keyword is the half's own, so this writes its own separator.
|
||||
fn clocking_default(&self, half: Option<&ClockingDefault>, dir: &str, docs: &mut Vec<Doc>) {
|
||||
let Some(half) = half else { return };
|
||||
match half.before_dir.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&half.before_dir, docs),
|
||||
}
|
||||
self.word_then(dir, &half.after_dir, docs);
|
||||
docs.push(self.clocking_skew(&half.skew));
|
||||
}
|
||||
|
||||
/// A clocking skew: an edge identifier and, when the source wrote one, the
|
||||
/// delay behind it — IEEE 1800 §14.3's `edge_identifier [delay_control]`.
|
||||
fn clocking_skew(&self, skew: &ClockingSkew) -> Doc {
|
||||
match skew {
|
||||
ClockingSkew::Edge { word, after_edge, delay } => {
|
||||
let mut docs = vec![text(word.clone())];
|
||||
if let Some(delay) = delay {
|
||||
match after_edge.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(after_edge, &mut docs),
|
||||
}
|
||||
docs.push(self.clocking_delay(delay));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
ClockingSkew::Delay(delay) => self.clocking_delay(delay),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `# …` half of a skew: the one-token spellings verbatim, the
|
||||
/// parenthesized `#( … )` through the expression printer so its comment
|
||||
/// slots print.
|
||||
fn clocking_delay(&self, delay: &ClockingDelay) -> Doc {
|
||||
match delay {
|
||||
ClockingDelay::Word { after_hash, word } => {
|
||||
let mut docs = vec![text("#")];
|
||||
self.slot_comments(after_hash, &mut docs);
|
||||
docs.push(text(word.clone()));
|
||||
concat(docs)
|
||||
}
|
||||
ClockingDelay::Paren { after_hash, expr } => {
|
||||
let mut docs = vec![text("#")];
|
||||
self.slot_comments(after_hash, &mut docs);
|
||||
docs.push(self.expr(expr));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! `randsequence` — laying out the production grammar of IEEE 1800 §18.17.
|
||||
//!
|
||||
//! One production per line, indented inside the `randsequence`/`endsequence`
|
||||
//! pair; a production's alternatives print after the `:` and, when the line
|
||||
//! does not fit, one per line with each `|` under that `:` — the shape the
|
||||
//! LRM's own examples are written in.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::{name_doc, Fmt};
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// `randsequence (main) … endsequence`.
|
||||
pub(super) fn rand_sequence(&self, r: &RandSequence) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
self.word_then("randsequence", &r.after_kw, &mut docs);
|
||||
docs.push(text("("));
|
||||
self.slot_comments(&r.after_open, &mut docs);
|
||||
if let Some(n) = &r.start {
|
||||
docs.push(name_doc(&n.text));
|
||||
}
|
||||
self.slot_comments(&r.before_close, &mut docs);
|
||||
docs.push(text(")"));
|
||||
let mut body = Vec::new();
|
||||
for p in &r.productions {
|
||||
body.push(if p.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading_comments(&p.meta));
|
||||
body.push(self.production(p));
|
||||
body.extend(self.trailing(&p.meta));
|
||||
}
|
||||
body.extend(self.dangling(&r.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("endsequence"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One production: its head, then the alternatives after the `:`.
|
||||
///
|
||||
/// The alternatives are one group: they stay on the head's line while they
|
||||
/// fit, and otherwise break one per line with the `|` starting each new
|
||||
/// one, aligned under the head's indent.
|
||||
fn production(&self, p: &Production) -> Doc {
|
||||
let mut head = Vec::new();
|
||||
if let Some(t) = self.data_type(p.ret_type.as_ref().unwrap_or(&DataType::default())) {
|
||||
head.push(t);
|
||||
head.push(text(" "));
|
||||
}
|
||||
head.push(name_doc(&p.name));
|
||||
if p.has_parens {
|
||||
head.push(self.tf_args(&p.args, &[]));
|
||||
}
|
||||
self.slot_comments(&p.before_colon, &mut head);
|
||||
head.push(text(if p.before_colon.is_empty() { " :" } else { ":" }));
|
||||
// One alternative rides on the head's line: it is the common shape,
|
||||
// and a code block inside it cuddles onto the `:` the way a `begin`
|
||||
// cuddles onto an `if`. Several break one per line, each `|` starting
|
||||
// its own, when they do not all fit.
|
||||
if let [only] = p.alternatives.as_slice() {
|
||||
self.after_bar(&only.after_bar, &mut head);
|
||||
head.push(self.alternative(only));
|
||||
return concat(vec![concat(head), self.semi(&p.before_semi)]);
|
||||
}
|
||||
let mut alts = Vec::new();
|
||||
for (i, alt) in p.alternatives.iter().enumerate() {
|
||||
// The comments written in front of the `|` print at the end of
|
||||
// the alternative before it, which is where the source put them;
|
||||
// a line comment among them forces the break the `|` needs.
|
||||
let broke = i > 0 && self.inline_comments(&alt.before_bar, &mut alts);
|
||||
if i > 0 {
|
||||
alts.push(if broke { Doc::HardLine } else { Doc::Line });
|
||||
alts.push(text("|"));
|
||||
self.after_bar(&alt.after_bar, &mut alts);
|
||||
} else if alt.after_bar.is_empty() {
|
||||
alts.push(Doc::Line);
|
||||
} else {
|
||||
// A comment here is the separator; the break opportunity it
|
||||
// replaces is not wanted on the first alternative, which has
|
||||
// no `|` of its own to start a line with.
|
||||
self.inline_comments_spaced(&alt.after_bar, &mut alts);
|
||||
}
|
||||
alts.push(self.alternative(alt));
|
||||
}
|
||||
head.push(indent(alts));
|
||||
concat(vec![group(head), self.semi(&p.before_semi)])
|
||||
}
|
||||
|
||||
/// The separator between the `:`/`|` an alternative follows and its first
|
||||
/// item: the comments written there, or a plain space.
|
||||
fn after_bar(&self, comments: &[Comment], docs: &mut Vec<Doc>) {
|
||||
match comments.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(comments, docs),
|
||||
}
|
||||
}
|
||||
|
||||
/// One `|`-separated right-hand side, with its `:= weight` when it has
|
||||
/// one. The separator in front of it is the caller's, since only the
|
||||
/// caller knows whether a `|` or a line break stands there.
|
||||
fn alternative(&self, a: &Alternative) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
for (i, item) in a.items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.prod_item(item));
|
||||
}
|
||||
if let Some(w) = &a.weight {
|
||||
self.slot_comments(&a.before_weight, &mut docs);
|
||||
docs.push(text(if a.before_weight.is_empty() { " :=" } else { ":=" }));
|
||||
self.word_then("", &w.after_op, &mut docs);
|
||||
docs.push(self.expr(&w.expr));
|
||||
if let Some(block) = &w.block {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.code_block(block));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One item of an alternative — a reference, a code block, or one of the
|
||||
/// four control shapes.
|
||||
fn prod_item(&self, item: &ProdItem) -> Doc {
|
||||
match item {
|
||||
ProdItem::Ref(r) => self.prod_ref(r),
|
||||
ProdItem::Block(b) => self.code_block(b),
|
||||
ProdItem::If { after_kw, cond, then, before_else, after_else, els } => {
|
||||
let mut docs = vec![text("if")];
|
||||
self.word_then("", after_kw, &mut docs);
|
||||
docs.push(self.parens(cond));
|
||||
docs.push(text(" "));
|
||||
docs.push(self.prod_item(then));
|
||||
if let Some(e) = els {
|
||||
self.word_then("", before_else, &mut docs);
|
||||
docs.push(text("else"));
|
||||
self.word_then("", after_else, &mut docs);
|
||||
docs.push(self.prod_item(e));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
ProdItem::Repeat { after_kw, count, body } => {
|
||||
let mut docs = vec![text("repeat")];
|
||||
self.word_then("", after_kw, &mut docs);
|
||||
docs.push(self.parens(count));
|
||||
docs.push(text(" "));
|
||||
docs.push(self.prod_item(body));
|
||||
concat(docs)
|
||||
}
|
||||
ProdItem::Case { after_kw, expr, items, dangling } => {
|
||||
let mut docs = vec![text("case")];
|
||||
self.word_then("", after_kw, &mut docs);
|
||||
docs.push(self.parens(expr));
|
||||
let mut body = Vec::new();
|
||||
for arm in items {
|
||||
body.push(if arm.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading_comments(&arm.meta));
|
||||
body.push(self.prod_case_item(arm));
|
||||
body.extend(self.trailing(&arm.meta));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("endcase"));
|
||||
concat(docs)
|
||||
}
|
||||
ProdItem::RandJoin { after_rand, weight, items } => {
|
||||
let mut docs = vec![text("rand")];
|
||||
self.word_then("", after_rand, &mut docs);
|
||||
docs.push(text("join"));
|
||||
if let Some(w) = weight {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.parens(w));
|
||||
}
|
||||
for item in items {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.prod_item(item));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One arm of an `rs_case`: `labels : item;` or `default : item;`.
|
||||
///
|
||||
/// The labels and their `:` are printed by the same helper a `case`
|
||||
/// statement's arm uses — including the `default` whose `:` IEEE 1800
|
||||
/// leaves optional — because they are the same tokens with the same
|
||||
/// comment slots; only the body is a production item rather than a
|
||||
/// statement.
|
||||
fn prod_case_item(&self, arm: &ProdCaseItem) -> Doc {
|
||||
let mut docs = vec![self.case_labels(&arm.labels, &arm.before_colon, arm.span)];
|
||||
self.word_then("", &arm.after_colon, &mut docs);
|
||||
docs.push(self.prod_item(&arm.item));
|
||||
docs.push(self.semi(&arm.before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// `name` or `name(a, b)`.
|
||||
fn prod_ref(&self, r: &ProdRef) -> Doc {
|
||||
let mut docs = vec![name_doc(&r.name)];
|
||||
if r.has_parens {
|
||||
self.slot_comments(&r.before_args, &mut docs);
|
||||
docs.push(self.expr_list("(", &r.args, ")"));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// An `rs_code_block`: `{ statements }`, laid out as a `begin`/`end` body
|
||||
/// is — one statement per line, indented, the braces on their own lines
|
||||
/// when the block holds anything at all.
|
||||
fn code_block(&self, b: &CodeBlock) -> Doc {
|
||||
if b.stmts.is_empty() && b.dangling.is_empty() {
|
||||
return text("{}");
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.stmts.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.stmt_seq(&b.stmts));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
concat(vec![text("{"), indent(body), Doc::HardLine, text("}")])
|
||||
}
|
||||
}
|
||||
@@ -245,13 +245,24 @@ impl<'a> Fmt<'a> {
|
||||
/// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an
|
||||
/// optional port list laid out like a function's, and one expression.
|
||||
pub(super) fn let_decl(&self, l: &LetDecl) -> Doc {
|
||||
let mut docs = vec![text(format!("let {}", named(&l.name)))];
|
||||
let mut docs = vec![text("let")];
|
||||
self.word_then("", &l.after_kw, &mut docs);
|
||||
docs.push(name_doc(&l.name));
|
||||
if l.has_parens {
|
||||
docs.push(self.tf_args(&l.ports, &[]));
|
||||
}
|
||||
docs.push(text(" ="));
|
||||
docs.push(self.assign_rhs(self.expr(&l.value)));
|
||||
concat(vec![group(docs), text(";")])
|
||||
// The `=` and its two sides are laid out the way a declarator's
|
||||
// initializer is: a comment on either side stays on that side of the
|
||||
// sign, and only a clean `=` keeps the breakable right-hand side.
|
||||
self.slot_comments(&l.eq_comments.before, &mut docs);
|
||||
docs.push(text(if l.eq_comments.before.is_empty() { " =" } else { "=" }));
|
||||
if l.eq_comments.after.is_empty() {
|
||||
docs.push(self.assign_rhs(self.expr(&l.value)));
|
||||
} else {
|
||||
self.inline_comments_spaced(&l.eq_comments.after, &mut docs);
|
||||
docs.push(self.expr(&l.value));
|
||||
}
|
||||
concat(vec![group(docs), self.semi(&l.before_semi)])
|
||||
}
|
||||
|
||||
/// `export "DPI-C" function f;` / `export pkg::*;` — one line either way;
|
||||
|
||||
@@ -460,12 +460,27 @@ impl<'a> Fmt<'a> {
|
||||
None => concat(vec![text("wait "), self.parens(cond), self.semi(before_semi)]),
|
||||
},
|
||||
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), self.semi(before_semi)]),
|
||||
StmtKind::EventTrigger(e) => {
|
||||
concat(vec![text("-> "), self.expr(e), self.semi(before_semi)])
|
||||
StmtKind::EventTrigger(t) => {
|
||||
let mut docs = Vec::new();
|
||||
self.word_then(&t.arrow, &t.after_arrow, &mut docs);
|
||||
if let Some(tc) = &t.timing {
|
||||
docs.push(self.timing_control(tc));
|
||||
if t.before_event.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&t.before_event, &mut docs);
|
||||
}
|
||||
}
|
||||
docs.push(self.expr(&t.expr));
|
||||
docs.push(self.semi(before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), self.semi(before_semi)]),
|
||||
// The item form prints its own `;`.
|
||||
StmtKind::Typedef(t) => self.typedef(t),
|
||||
StmtKind::Let(l) => self.let_decl(l),
|
||||
// `randsequence` closes itself with `endsequence`; no `;`.
|
||||
StmtKind::RandSequence(r) => self.rand_sequence(r),
|
||||
StmtKind::ParamDecl(d) => {
|
||||
concat(vec![self.param_decl(d, None), self.semi(before_semi)])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
# TODO §54.1 — the six small language shapes coverage gap L6 left open.
|
||||
# None of them occurs in the corpus or in opentitan, so these hand-written
|
||||
# cases and the gap fuzzers are the whole acceptance.
|
||||
# docs/features/coverage-gaps-l/README.md
|
||||
#
|
||||
# 1. `->>`, the non-blocking event trigger (IEEE 1800 §15.5.2), with and
|
||||
# without a delay or event control of its own. `->` is untouched.
|
||||
module m;
|
||||
event e;
|
||||
initial begin
|
||||
-> e;
|
||||
->> e;
|
||||
->> #5 e;
|
||||
->> @(posedge clk) e;
|
||||
->> @(a or b) e;
|
||||
->> #(1:2:3) e;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
event e;
|
||||
initial begin
|
||||
-> e;
|
||||
->> e;
|
||||
->> #5 e;
|
||||
->> @(posedge clk) e;
|
||||
->> @(a or b) e;
|
||||
->> #(1:2:3) e;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# `->>` with a comment in each of its two gaps: after the arrow, and
|
||||
# between the timing control and the event.
|
||||
module m;
|
||||
initial begin
|
||||
->> /*a*/ #5 /*b*/ e;
|
||||
->> /*c*/ e;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
->> /*a*/ #5 /*b*/ e;
|
||||
->> /*c*/ e;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# 2. A stream expression's `with [range]` (IEEE 1800 §11.4.14) — the third
|
||||
# postfix spelling of `with`, told from the other two by its `[`.
|
||||
module m;
|
||||
initial begin
|
||||
a = {<<{b with [0:3]}};
|
||||
c = {>>{d with [i+:4]}};
|
||||
f = {<<{g with [i-:4]}};
|
||||
h = {<<{j with [i]}};
|
||||
k = {<<byte{l with [0 : 3]}};
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
a = {<<{b with [0:3]}};
|
||||
c = {>>{d with [i+:4]}};
|
||||
f = {<<{g with [i-:4]}};
|
||||
h = {<<{j with [i]}};
|
||||
k = {<<byte{l with [0:3]}};
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# The stream range's five comment slots: either side of the `with`, just
|
||||
# inside the `[`, either side of the `:`, and before the `]`.
|
||||
module m;
|
||||
initial a = {<<{b /*a*/ with /*b*/ [ /*c*/ 0 /*d*/ : /*e*/ 3 /*f*/ ]}};
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial a = {<<{b /*a*/ with /*b*/ [ /*c*/ 0 /*d*/ : /*e*/ 3 /*f*/ ]}};
|
||||
endmodule
|
||||
====
|
||||
# The other two `with` spellings still parse as what they always were: a
|
||||
# `(` is an array method's iterator argument, a `{` a constraint block.
|
||||
module m;
|
||||
initial begin
|
||||
x = q.find(v) with (v > 3);
|
||||
obj.randomize() with {a < 5;};
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
x = q.find(v) with (v > 3);
|
||||
obj.randomize() with {a < 5;};
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# 3. The cast bases IEEE 1800 §6.24.1 allows besides a name and a system
|
||||
# call: a parenthesised width, a sized literal, and a type with packed
|
||||
# dimensions on it.
|
||||
module m;
|
||||
initial begin
|
||||
x = (W+1)'(y);
|
||||
z = 4'(y);
|
||||
q = logic [3:0]'(y);
|
||||
r = bit signed [7:0]'(y);
|
||||
s = $clog2(N)'(y);
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
x = (W + 1)'(y);
|
||||
z = 4'(y);
|
||||
q = logic [3:0]'(y);
|
||||
r = bit signed [7:0]'(y);
|
||||
s = $clog2(N)'(y);
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# 4. Drive strength on a net declaration (IEEE 1800 §6.6), the position
|
||||
# `ContAssign` has always read one in.
|
||||
module m;
|
||||
wire (strong0, weak1) w = a;
|
||||
wire (supply0, supply1) [7:0] v;
|
||||
wire (pull1, highz0) #5 d = e;
|
||||
tri (weak1, weak0) t;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire (strong0, weak1) w = a;
|
||||
wire (supply0, supply1) [7:0] v;
|
||||
wire (pull1, highz0) #5 d = e;
|
||||
tri (weak1, weak0) t;
|
||||
endmodule
|
||||
====
|
||||
# The strength's five comment slots, on a net declaration and on the
|
||||
# continuous assignment and the gate that already wrote one.
|
||||
module m;
|
||||
wire /*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ ) w = a;
|
||||
assign /*f*/ (weak0, pull1) x = y;
|
||||
pullup /*g*/ ( /*h*/ weak1 /*i*/ ) p1 (n1);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire /*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ ) w = a;
|
||||
assign /*f*/ (weak0, pull1) x = y;
|
||||
pullup /*g*/ ( /*h*/ weak1 /*i*/ ) p1 (n1);
|
||||
endmodule
|
||||
====
|
||||
# A `(` after a net keyword that is not a strength is still not one: an
|
||||
# implicitly-typed net whose value is parenthesised keeps its old parse.
|
||||
module m;
|
||||
wire w = (a & b);
|
||||
assign (x) = y;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire w = (a & b);
|
||||
assign (x) = y;
|
||||
endmodule
|
||||
====
|
||||
# 5. `let` at statement position (IEEE 1800 §11.13) — the item-level
|
||||
# grammar and the item-level layout, among a block's declarations.
|
||||
module m;
|
||||
initial begin
|
||||
let sum = a + b;
|
||||
let max(p, q) = (p > q) ? p : q;
|
||||
x = sum + max(1, 2);
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
let sum = a + b;
|
||||
let max(p, q) = (p > q) ? p : q;
|
||||
x = sum + max(1, 2);
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# 6. The `#(min:typ:max)` clocking skew (IEEE 1800 §14.3), on a `default`
|
||||
# item and on a direction group, beside the one-token spellings.
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input #(1:2:3) output #(2:3:4);
|
||||
input #(1:2:3) sig;
|
||||
output #(5) other;
|
||||
input #1step a, b;
|
||||
output negedge c;
|
||||
endclocking
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input #(1:2:3) output #(2:3:4);
|
||||
input #(1:2:3) sig;
|
||||
output #(5) other;
|
||||
input #1step a, b;
|
||||
output negedge c;
|
||||
endclocking
|
||||
endmodule
|
||||
====
|
||||
# The parenthesised skew's comment slots are the delay grammar's own:
|
||||
# after the `#`, inside the parens and around each `:`.
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input # /*a*/ (1 /*c*/ : /*d*/ 2 /*e*/ : /*f*/ 3 /*g*/) output #(1:2:3);
|
||||
endclocking
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input # /*a*/ (1 /*c*/ : /*d*/ 2 /*e*/ : /*f*/ 3 /*g*/) output #(1:2:3);
|
||||
endclocking
|
||||
endmodule
|
||||
====
|
||||
# A comment written just inside the delay's `(` breaks the parens the way it
|
||||
# does on a net delay (`wire # /*a*/ ( /*b*/ 1:2:3) a;`) — pre-existing
|
||||
# layout the skew inherits by going through the same grammar.
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input # /*a*/ ( /*b*/ 1:2:3);
|
||||
endclocking
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input # /*a*/ (
|
||||
/*b*/
|
||||
1:2:3
|
||||
);
|
||||
endclocking
|
||||
endmodule
|
||||
====
|
||||
# The other half of §14.3's `clocking_skew ::= edge_identifier
|
||||
# [ delay_control ] | delay_control`: an edge that carries a delay of its
|
||||
# own, in both spellings, on a `default` item and on a direction group.
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input negedge #(1:2:3) output posedge #5;
|
||||
input negedge #(1:2:3) sig;
|
||||
output posedge #5 other;
|
||||
input posedge #1step a, b;
|
||||
input edge c;
|
||||
endclocking
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input negedge #(1:2:3) output posedge #5;
|
||||
input negedge #(1:2:3) sig;
|
||||
output posedge #5 other;
|
||||
input posedge #1step a, b;
|
||||
input edge c;
|
||||
endclocking
|
||||
endmodule
|
||||
====
|
||||
# The gap between the edge and the `#` is the skew's own slot; the gap
|
||||
# after a bare edge still belongs to what follows it.
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input negedge /*a*/ #2 output /*b*/ posedge /*c*/ #(1:2:3);
|
||||
input edge /*d*/ sig;
|
||||
endclocking
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
clocking cb @(posedge clk);
|
||||
default input negedge /*a*/ #2 output /*b*/ posedge /*c*/ #(1:2:3);
|
||||
input edge /*d*/ sig;
|
||||
endclocking
|
||||
endmodule
|
||||
@@ -0,0 +1,257 @@
|
||||
# TODO §54.2 — `randsequence` (IEEE 1800 §18.17) as real nodes: a production
|
||||
# list with weighted alternatives, not an opaque leaf. Zero occurrences in the
|
||||
# corpus and in opentitan, so the LRM's own examples are the cases.
|
||||
# docs/features/coverage-gaps-l/README.md
|
||||
#
|
||||
# §18.17's opening example: a start production and three plain ones.
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (main)
|
||||
main : first second done;
|
||||
first : add | dec;
|
||||
second : pop | push;
|
||||
done : {$display("done");};
|
||||
add : {$display("add");};
|
||||
dec : {$display("dec");};
|
||||
pop : {$display("pop");};
|
||||
push : {$display("push");};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (main)
|
||||
main : first second done;
|
||||
first : add | dec;
|
||||
second : pop | push;
|
||||
done : {
|
||||
$display("done");
|
||||
};
|
||||
add : {
|
||||
$display("add");
|
||||
};
|
||||
dec : {
|
||||
$display("dec");
|
||||
};
|
||||
pop : {
|
||||
$display("pop");
|
||||
};
|
||||
push : {
|
||||
$display("push");
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# Weighted alternatives (§18.17.2): `:= weight`, with and without the code
|
||||
# block that runs when the alternative is chosen. Alternatives that fit stay
|
||||
# on the production's line; the case after this one is the same list too wide
|
||||
# for one, broken one per line with each `|` under the `:`.
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (top)
|
||||
top : a := 3 | b := 2 | c := 1;
|
||||
a : add;
|
||||
b : dec := 5 {$display("chosen");};
|
||||
c : add;
|
||||
add : {x = x + 1;};
|
||||
dec : {x = x - 1;};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (top)
|
||||
top : a := 3 | b := 2 | c := 1;
|
||||
a : add;
|
||||
b : dec := 5 {
|
||||
$display("chosen");
|
||||
};
|
||||
c : add;
|
||||
add : {
|
||||
x = x + 1;
|
||||
};
|
||||
dec : {
|
||||
x = x - 1;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# The three control shapes an alternative's items may take (§18.17.3–4) and
|
||||
# the interleaving `rand join` (§18.17.6).
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (main)
|
||||
main : gen loop sel mix;
|
||||
gen : if (cond) add else dec;
|
||||
loop : repeat (3) add;
|
||||
sel : case (mode) 0, 1 : add; 2 : dec; default : add; endcase;
|
||||
mix : rand join add dec;
|
||||
bias : rand join (0.5) add dec;
|
||||
add : {x++;};
|
||||
dec : {x--;};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (main)
|
||||
main : gen loop sel mix;
|
||||
gen : if (cond) add else dec;
|
||||
loop : repeat (3) add;
|
||||
sel : case (mode)
|
||||
0, 1: add;
|
||||
2: dec;
|
||||
default: add;
|
||||
endcase;
|
||||
mix : rand join add dec;
|
||||
bias : rand join (0.5) add dec;
|
||||
add : {
|
||||
x++;
|
||||
};
|
||||
dec : {
|
||||
x--;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# A production with a return type and formal arguments (§18.17.5), and a
|
||||
# reference that passes arguments to one.
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (main)
|
||||
main : bump(3) use_it;
|
||||
void bump(int step) : {
|
||||
total = total + step;
|
||||
};
|
||||
int use_it : {
|
||||
return total;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (main)
|
||||
main : bump(3) use_it;
|
||||
void bump(int step) : {
|
||||
total = total + step;
|
||||
};
|
||||
int use_it : {
|
||||
return total;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# `break` and `return` inside a production's code block are the ordinary
|
||||
# statements they are, and `randsequence ()` may name no start production.
|
||||
module m;
|
||||
initial begin
|
||||
randsequence ()
|
||||
main : {
|
||||
if (done) break;
|
||||
return;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
randsequence ()
|
||||
main : {
|
||||
if (done) break;
|
||||
return;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# Every gap of the grammar takes a comment and prints it back where it was
|
||||
# written: around the `(main)`, around the `:`, the `|` and the `:=`, and
|
||||
# inside a code block and a case arm.
|
||||
module m;
|
||||
initial begin
|
||||
randsequence /*a*/ ( /*b*/ main /*c*/ )
|
||||
// above the production
|
||||
main /*d*/ : /*e*/ first /*f*/ | /*g*/ second /*h*/ := /*i*/ 3 /*j*/ ; // after it
|
||||
first : {
|
||||
/*k*/
|
||||
x = 1; /*l*/
|
||||
};
|
||||
second : if /*m*/ (c) first /*n*/ else /*o*/ first;
|
||||
third : case /*p*/ (x)
|
||||
1 /*q*/: /*r*/ first /*s*/ ;
|
||||
default first;
|
||||
endcase;
|
||||
fourth : rand /*t*/ join (2) first second;
|
||||
// before endsequence
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
randsequence /*a*/ ( /*b*/ main /*c*/ )
|
||||
// above the production
|
||||
main /*d*/ : /*e*/ first /*f*/ | /*g*/ second /*h*/ := /*i*/ 3 /*j*/ ; // after it
|
||||
first : {
|
||||
/*k*/
|
||||
x = 1; /*l*/
|
||||
};
|
||||
second : if /*m*/ (c) first /*n*/ else /*o*/ first;
|
||||
third : case /*p*/ (x)
|
||||
1 /*q*/: /*r*/ first /*s*/ ;
|
||||
default first;
|
||||
endcase;
|
||||
fourth : rand /*t*/ join (2) first second;
|
||||
// before endsequence
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# The same production with alternatives too wide for one line: one per line,
|
||||
# each `|` starting its own, indented under the production's head.
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (top)
|
||||
top : first_alternative_name := 3 | second_alternative_name := 2 | third_alternative_name := 1;
|
||||
first_alternative_name : {
|
||||
x = 1;
|
||||
};
|
||||
second_alternative_name : {
|
||||
x = 2;
|
||||
};
|
||||
third_alternative_name : {
|
||||
x = 3;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
randsequence (top)
|
||||
top :
|
||||
first_alternative_name := 3
|
||||
| second_alternative_name := 2
|
||||
| third_alternative_name := 1;
|
||||
first_alternative_name : {
|
||||
x = 1;
|
||||
};
|
||||
second_alternative_name : {
|
||||
x = 2;
|
||||
};
|
||||
third_alternative_name : {
|
||||
x = 3;
|
||||
};
|
||||
endsequence
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,240 @@
|
||||
//! The `[format]` config keys — the layout choices that are off unless a
|
||||
//! project turns them on (TODO §54.3).
|
||||
//!
|
||||
//! Every one of them changes the output of files that already format cleanly,
|
||||
//! so each test asserts both directions: the shipped default leaves the file
|
||||
//! exactly as it was, and the key on produces the asked-for layout and is
|
||||
//! still idempotent.
|
||||
|
||||
use vlog_formatter::{format_source, Config};
|
||||
|
||||
/// A class body written the way UVM's own examples write one.
|
||||
const UVM_CLASS: &str = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_field_string(b, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
function new(string name = \"c\");
|
||||
super.new(name);
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
|
||||
/// The same body with the field macros indented one level.
|
||||
const UVM_CLASS_INDENTED: &str = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_field_string(b, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
function new(string name = \"c\");
|
||||
super.new(name);
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
|
||||
fn on() -> Config {
|
||||
Config { uvm_utils_indent: true, ..Config::default() }
|
||||
}
|
||||
|
||||
fn format(src: &str, config: &Config) -> String {
|
||||
format_source(src, config).expect("formats")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shipped_default_leaves_uvm_utils_macros_where_they_stand() {
|
||||
assert_eq!(format(UVM_CLASS, &Config::default()), UVM_CLASS);
|
||||
// And it un-indents a file that was written indented, which is exactly
|
||||
// why the key exists: without it there is no way to keep that shape.
|
||||
assert_eq!(format(UVM_CLASS_INDENTED, &Config::default()), UVM_CLASS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uvm_utils_indent_indents_the_run_between_begin_and_end() {
|
||||
assert_eq!(format(UVM_CLASS, &on()), UVM_CLASS_INDENTED);
|
||||
assert_eq!(format(UVM_CLASS_INDENTED, &on()), UVM_CLASS_INDENTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uvm_utils_indent_is_idempotent() {
|
||||
let once = format(UVM_CLASS, &on());
|
||||
assert_eq!(format(&once, &on()), once);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_component_spelling_opens_the_same_level() {
|
||||
let src = "\
|
||||
class c extends uvm_component;
|
||||
`uvm_component_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_component_utils_end
|
||||
endclass
|
||||
";
|
||||
let want = "\
|
||||
class c extends uvm_component;
|
||||
`uvm_component_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_component_utils_end
|
||||
endclass
|
||||
";
|
||||
assert_eq!(format(src, &on()), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_those_four_macro_names_open_a_level() {
|
||||
// A macro pair that merely *looks* like the idiom is not it: the rule is
|
||||
// four names, not a heuristic about `_begin`/`_end`.
|
||||
let src = "\
|
||||
class c;
|
||||
`my_utils_begin(c)
|
||||
`my_field(a)
|
||||
`my_utils_end
|
||||
endclass
|
||||
";
|
||||
assert_eq!(format(src, &on()), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_inside_the_run_are_indented_with_it_and_never_dropped() {
|
||||
let src = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
// why this field matters
|
||||
`uvm_field_int(a, UVM_DEFAULT) // trailing
|
||||
`uvm_object_utils_end
|
||||
endclass
|
||||
";
|
||||
let want = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
// why this field matters
|
||||
`uvm_field_int(a, UVM_DEFAULT) // trailing
|
||||
`uvm_object_utils_end
|
||||
endclass
|
||||
";
|
||||
assert_eq!(format(src, &on()), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_with_no_end_still_prints_everything_it_opened() {
|
||||
// lucisv reproduces the file it was given, unbalanced macros included.
|
||||
let src = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
endclass
|
||||
";
|
||||
let want = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
endclass
|
||||
";
|
||||
assert_eq!(format(src, &on()), want);
|
||||
assert_eq!(format(&format(src, &on()), &on()), want);
|
||||
}
|
||||
|
||||
/// The other half of coverage gap L10: an enum body one-lined when it is
|
||||
/// short. **This already is the default** — measured 2026-09-06, over every
|
||||
/// shape the gap names — so no config key was added for it. The test pins the
|
||||
/// behaviour so nothing takes it away.
|
||||
#[test]
|
||||
fn a_short_enum_body_is_already_one_lined_by_default() {
|
||||
let broken = "\
|
||||
package p;
|
||||
typedef enum {
|
||||
A,
|
||||
B,
|
||||
C
|
||||
} e_t;
|
||||
typedef enum logic [1:0] {
|
||||
X = 0,
|
||||
Y,
|
||||
Z
|
||||
} s_e;
|
||||
enum {
|
||||
IDLE,
|
||||
BUSY
|
||||
} state;
|
||||
endpackage
|
||||
";
|
||||
let want = "\
|
||||
package p;
|
||||
typedef enum {A, B, C} e_t;
|
||||
typedef enum logic [1:0] {X = 0, Y, Z} s_e;
|
||||
enum {IDLE, BUSY} state;
|
||||
endpackage
|
||||
";
|
||||
assert_eq!(format(broken, &Config::default()), want);
|
||||
}
|
||||
|
||||
/// And a body with a comment in it still breaks, which is the condition the
|
||||
/// gap named: one-lining it would put a `//` in front of the `}`.
|
||||
#[test]
|
||||
fn an_enum_body_with_a_comment_still_breaks_one_member_per_line() {
|
||||
let src = "\
|
||||
package p;
|
||||
typedef enum {
|
||||
A, // first
|
||||
B
|
||||
} e_t;
|
||||
endpackage
|
||||
";
|
||||
assert_eq!(format(src, &Config::default()), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_begin_opens_a_level_of_its_own_and_its_end_closes_that_one() {
|
||||
// Real UVM code never nests these macros, but the rule tracks a stack all
|
||||
// the same: the first `_end` closes the `_begin` it matches, not the run.
|
||||
let src = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_object_utils_begin(d)
|
||||
`uvm_field_int(b, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
`uvm_field_int(e, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
`uvm_field_int(f, UVM_DEFAULT)
|
||||
endclass
|
||||
";
|
||||
let want = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_object_utils_begin(d)
|
||||
`uvm_field_int(b, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
`uvm_field_int(e, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
`uvm_field_int(f, UVM_DEFAULT)
|
||||
endclass
|
||||
";
|
||||
assert_eq!(format(src, &on()), want);
|
||||
assert_eq!(format(want, &on()), want, "idempotent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_with_no_begin_open_changes_no_indentation() {
|
||||
// Nothing to close, so nothing moves — the file comes back as written.
|
||||
let src = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_end
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
endclass
|
||||
";
|
||||
assert_eq!(format(src, &on()), src);
|
||||
// And an unmatched `_end` after a closed pair closes nothing either.
|
||||
let after = "\
|
||||
class c extends uvm_object;
|
||||
`uvm_object_utils_begin(c)
|
||||
`uvm_field_int(a, UVM_DEFAULT)
|
||||
`uvm_object_utils_end
|
||||
`uvm_object_utils_end
|
||||
`uvm_field_int(b, UVM_DEFAULT)
|
||||
endclass
|
||||
";
|
||||
assert_eq!(format(after, &on()), after);
|
||||
}
|
||||
@@ -260,6 +260,136 @@ fn reindented_string_inside_a_with_block_is_rejected() {
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The shapes TODO §54 added — masked-corruption attack pairs
|
||||
//
|
||||
// `verify.rs` was not touched by this round and no normalization was
|
||||
// widened (CLAUDE.md invariant 4 asks for these anyway): each pair is a
|
||||
// plausible way a new printer could have lost or rewritten something, and
|
||||
// each must be refused. They are `(input, corrupted output)` pairs handed
|
||||
// straight to the safety net, so they hold whether or not the formatter
|
||||
// would ever produce that output.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_event_trigger_arrow_rewritten_as_the_other_one_is_rejected() {
|
||||
// `->` and `->>` are different statements — blocking and non-blocking —
|
||||
// so normalizing one into the other changes the design.
|
||||
expect_divergence(
|
||||
"module m;\n initial -> e;\nendmodule\n",
|
||||
"module m;\n initial ->> e;\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n initial ->> e;\nendmodule\n",
|
||||
"module m;\n initial -> e;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_event_trigger_timing_control_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n initial ->> #5 e;\nendmodule\n",
|
||||
"module m;\n initial ->> e;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_range_turned_into_an_index_is_rejected() {
|
||||
// `a with [0:3]` and `a with [0]` select different bits.
|
||||
expect_divergence(
|
||||
"module m;\n initial q = {<<{a with [0:3]}};\nendmodule\n",
|
||||
"module m;\n initial q = {<<{a with [0]}};\nendmodule\n",
|
||||
);
|
||||
// And a part-select operator swapped for another one.
|
||||
expect_divergence(
|
||||
"module m;\n initial q = {<<{a with [i+:4]}};\nendmodule\n",
|
||||
"module m;\n initial q = {<<{a with [i-:4]}};\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_or_reordered_drive_strength_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n wire (strong0, weak1) w = a;\nendmodule\n",
|
||||
"module m;\n wire w = a;\nendmodule\n",
|
||||
);
|
||||
// The two keywords may be written in either order and mean different
|
||||
// things; a printer that sorted them would be corrupting the design.
|
||||
expect_divergence(
|
||||
"module m;\n wire (strong0, weak1) w = a;\nendmodule\n",
|
||||
"module m;\n wire (weak1, strong0) w = a;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_skew_rewritten_into_a_bare_delay_is_rejected() {
|
||||
// `#(1:2:3)` is three values; `#1` is one.
|
||||
expect_divergence(
|
||||
"module m;\n clocking cb @(posedge clk);\n input #(1:2:3) sig;\n endclocking\nendmodule\n",
|
||||
"module m;\n clocking cb @(posedge clk);\n input #1 sig;\n endclocking\nendmodule\n",
|
||||
);
|
||||
// An edge and the delay behind it are one skew (§14.3): losing either
|
||||
// half changes when the signal is sampled.
|
||||
expect_divergence(
|
||||
"module m;\n clocking cb @(posedge clk);\n input negedge #5 sig;\n endclocking\nendmodule\n",
|
||||
"module m;\n clocking cb @(posedge clk);\n input negedge sig;\n endclocking\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n clocking cb @(posedge clk);\n input negedge #5 sig;\n endclocking\nendmodule\n",
|
||||
"module m;\n clocking cb @(posedge clk);\n input #5 sig;\n endclocking\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_randsequence_production_is_rejected() {
|
||||
let input = "module m;\n initial begin\n randsequence (main)\n main : a b;\n a : {x = 1;};\n b : {x = 2;};\n endsequence\n end\nendmodule\n";
|
||||
let output = "module m;\n initial begin\n randsequence (main)\n main : a b;\n a : {x = 1;};\n endsequence\n end\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reordered_randsequence_alternative_is_rejected() {
|
||||
// The order of the alternatives is what `:=` weights are relative to.
|
||||
let input = "module m;\n initial begin\n randsequence (main)\n main : a := 3 | b := 1;\n endsequence\n end\nendmodule\n";
|
||||
let output = "module m;\n initial begin\n randsequence (main)\n main : b := 1 | a := 3;\n endsequence\n end\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_randsequence_bar_turned_into_a_juxtaposition_is_rejected() {
|
||||
// `a | b` picks one; `a b` runs both. One token apart, opposite meanings.
|
||||
let input = "module m;\n initial begin\n randsequence (main)\n main : a | b;\n endsequence\n end\nendmodule\n";
|
||||
let output = "module m;\n initial begin\n randsequence (main)\n main : a b;\n endsequence\n end\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_randsequence_weight_is_rejected() {
|
||||
let input = "module m;\n initial begin\n randsequence (main)\n main : a := 3 | b;\n endsequence\n end\nendmodule\n";
|
||||
let output = "module m;\n initial begin\n randsequence (main)\n main : a | b;\n endsequence\n end\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_let_statement_losing_its_ports_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n initial begin\n let f(a) = a + 1;\n end\nendmodule\n",
|
||||
"module m;\n initial begin\n let f = a + 1;\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uvm_utils_indentation_is_whitespace_the_net_ignores_and_a_dropped_macro_is_not() {
|
||||
// The `uvm-utils-indent` key only ever moves leading whitespace, which is
|
||||
// exactly what the net is allowed to forgive...
|
||||
let flat = "class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
|
||||
let indented = "class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
|
||||
verify_equivalence(flat, indented).expect("indentation alone is not a divergence");
|
||||
// ...and losing one of the macros it indents is not.
|
||||
let dropped = "class c;\n `uvm_object_utils_begin(c)\n `uvm_object_utils_end\nendclass\n";
|
||||
expect_divergence(flat, dropped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_output_is_rejected() {
|
||||
let input = "module m;\n wire x;\nendmodule\n";
|
||||
@@ -1151,7 +1281,7 @@ fn a_dropped_method_qualifier_is_rejected() {
|
||||
|
||||
/// Format `src` at `width`, then format that again, and return both.
|
||||
fn twice(src: &str, width: usize, indent: usize) -> (String, String) {
|
||||
let config = Config { max_width: width, indent_width: indent };
|
||||
let config = Config { max_width: width, indent_width: indent, ..Config::default() };
|
||||
let once = format_source(src, &config).expect("first pass");
|
||||
let again = format_source(&once, &config).expect("second pass");
|
||||
(once, again)
|
||||
@@ -2360,6 +2490,12 @@ const RTL_FIXTURES: &[&str] = &[
|
||||
// owner until this round — `MinTypMaxComments`, `DelayValue`, and the
|
||||
// gate's own `before_hash`/`after_hash`/`before_args`/`before_semi`.
|
||||
"module m;\n wire #(1:2:3) a;\n assign #(1:2:3) z = a;\n and #(2, 3) g1 (y, a, b);\nendmodule\n",
|
||||
// The six shapes of TODO §54.1. Each opened a gap the parser had no slot
|
||||
// for — the arrow of `->>`, the `with [ … ]` bracket, the five of a drive
|
||||
// strength, the `let` head, and the parenthesized clocking skew — and
|
||||
// this is what says every one of them found an owner.
|
||||
"module m;\n wire (strong0, weak1) w = a;\n initial begin\n ->> #5 e;\n q = {<<{a with [i+:4]}};\n let sum = a + b;\n end\nendmodule\n",
|
||||
"module m;\n clocking cb @(posedge clk);\n default input #(1:2:3) output #2;\n input #(5) sig;\n output negedge #5 o;\n endclocking\nendmodule\n",
|
||||
];
|
||||
|
||||
#[test]
|
||||
@@ -2368,8 +2504,23 @@ fn a_comment_in_every_rtl_gap_still_formats() {
|
||||
}
|
||||
|
||||
/// Inter-token gaps across [`RTL_FIXTURES`]. 374 before TODO §45.4 added the
|
||||
/// delay-list fixture, whose 45 gaps brought the total here.
|
||||
const EXPECTED_RTL_GAPS: usize = 419;
|
||||
/// delay-list fixture, whose 45 gaps took it to 419; TODO §54.1's two
|
||||
/// fixtures — the six L6 shapes and a clocking block — brought the 80 that
|
||||
/// take it here. Nineteen of those 80 failed when the fixtures were written,
|
||||
/// none of them because of the new shapes: the `let` head, the two brace
|
||||
/// pairs of a streaming concatenation and the whole clocking grammar had no
|
||||
/// comment slots at all, and fail identically on a tree without this round
|
||||
/// (`let /*C*/ sum = a + b;` as an item, `{ /*C*/ <<{a}}`,
|
||||
/// `clocking /*C*/ cb`). All nineteen have owners now — `LetDecl`'s
|
||||
/// `after_kw`/`eq_comments`/`before_semi`, `StreamComments`,
|
||||
/// `ClockingDecl`'s `after_kw`/`before_event`/`before_semi`,
|
||||
/// `ClockingDefault`, `ClockingItem::before_semi` and the skew's own
|
||||
/// `after_hash`. The rework of §54.1 added `output negedge #5 o;` to the
|
||||
/// clocking fixture — the LRM's `edge_identifier [delay_control]`, which the
|
||||
/// round's first pass could not parse — for the 6 that take it to 505, none of
|
||||
/// them failing: the gap between the edge and its `#` is
|
||||
/// `ClockingSkew::Edge::after_edge`.
|
||||
const EXPECTED_RTL_GAPS: usize = 505;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Vendor and formal collateral — `vendor-formal-grammar`
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -86,7 +86,8 @@ pub(crate) fn walk_exprs(file: &SourceFile, f: &mut dyn FnMut(&Expr)) {
|
||||
root(expr);
|
||||
}
|
||||
}
|
||||
StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => root(expr),
|
||||
StmtKind::ExprStmt(expr) => root(expr),
|
||||
StmtKind::EventTrigger(t) => root(&t.expr),
|
||||
StmtKind::If { cond, .. } => root(cond),
|
||||
StmtKind::Case { expr, items, .. } => {
|
||||
root(expr);
|
||||
@@ -244,6 +245,14 @@ fn descend(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
|
||||
}
|
||||
ExprKind::InsideMacro { lhs, .. } => descend(lhs, f),
|
||||
ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => descend(base, f),
|
||||
// The stream range's operands are reads like any index's.
|
||||
ExprKind::StreamWith { base, range } => {
|
||||
descend(base, f);
|
||||
descend(&range.msb, f);
|
||||
if let Some(lsb) = &range.lsb {
|
||||
descend(lsb, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Dist { expr: inner, .. } => descend(inner, f),
|
||||
ExprKind::NamedArg { value, .. } => descend(value, f),
|
||||
ExprKind::AssignPattern(items) => {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -466,8 +466,8 @@ impl Scanner {
|
||||
None => self.unknown.push(expr.span),
|
||||
},
|
||||
// `-> ev;` is what drives a named event.
|
||||
StmtKind::EventTrigger(expr) => {
|
||||
self.write(expr, DriverKind::Trigger, block, in_generate)
|
||||
StmtKind::EventTrigger(t) => {
|
||||
self.write(&t.expr, DriverKind::Trigger, block, in_generate)
|
||||
}
|
||||
StmtKind::MacroStmt(_)
|
||||
| StmtKind::Directive(_)
|
||||
|
||||
@@ -340,6 +340,12 @@ pub struct NetDelay {
|
||||
pub struct DataDecl {
|
||||
/// Net type (`wire`, `tri`, ...) if any.
|
||||
pub net: Option<String>,
|
||||
/// Drive strength: the `(strong0, weak1)` of
|
||||
/// `wire (strong0, weak1) w = a;` (IEEE 1800 §6.6), read only after a net
|
||||
/// keyword — the one position the grammar allows it. Carried the way
|
||||
/// [`ContAssign::strength`] is, and printed between the net keyword and
|
||||
/// the delay, where the source wrote it.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in
|
||||
/// `wire [31:0] #0.1 x = y;`.
|
||||
pub delay: Option<NetDelay>,
|
||||
@@ -477,6 +483,8 @@ pub struct TaskDecl {
|
||||
/// growing a near-identical node of their own.
|
||||
#[derive(Debug)]
|
||||
pub struct LetDecl {
|
||||
/// Comments written between the `let` keyword and the name.
|
||||
pub after_kw: Vec<Comment>,
|
||||
pub name: String,
|
||||
/// Byte range of `name`.
|
||||
pub name_span: TextRange,
|
||||
@@ -484,7 +492,12 @@ pub struct LetDecl {
|
||||
/// written when this is true and [`LetDecl::ports`] is empty.
|
||||
pub has_parens: bool,
|
||||
pub ports: Vec<ListElem<TfArg>>,
|
||||
/// Comments written on either side of the `=`, each kept on its own side
|
||||
/// of it the way a declarator's `eq_comments` are.
|
||||
pub eq_comments: Box<BinaryComments>,
|
||||
pub value: Expr,
|
||||
/// Comments written between the value and the `;`.
|
||||
pub before_semi: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -119,6 +119,18 @@ pub enum ExprKind {
|
||||
/// The stream expressions, carrying their comments the way a
|
||||
/// concatenation's elements do.
|
||||
inner: Vec<ExprItem>,
|
||||
/// The three gaps the two nested brace pairs open. Boxed to keep
|
||||
/// `Expr` small, as for `TernaryComments`.
|
||||
comments: Box<StreamComments>,
|
||||
},
|
||||
/// `expr with [ range ]` — a stream expression's array range
|
||||
/// (IEEE 1800 §11.4.14): `{<< {a with [0:3]}}`, `{>> {a with [i+:4]}}`,
|
||||
/// `{<< {a with [i]}}`. The only `with` whose argument is a bracket
|
||||
/// rather than a `(` or a `{`, which is what tells it from an array
|
||||
/// method's iterator argument and from a `randomize` constraint block.
|
||||
StreamWith {
|
||||
base: Box<Expr>,
|
||||
range: Box<StreamRange>,
|
||||
},
|
||||
Paren {
|
||||
inner: Box<Expr>,
|
||||
@@ -451,6 +463,45 @@ pub struct WithComments {
|
||||
pub after_kw: Vec<Comment>,
|
||||
}
|
||||
|
||||
/// The gaps of a streaming concatenation's own brackets:
|
||||
/// `{ /*a*/ << byte /*b*/ { x } /*c*/ }`. The elements inside carry their own
|
||||
/// comments the way a concatenation's do; these three are what the nesting of
|
||||
/// the two brace pairs leaves over.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct StreamComments {
|
||||
/// Between the outer `{` and the `<<` or `>>`.
|
||||
pub after_open: Vec<Comment>,
|
||||
/// Between the direction (or the slice size) and the inner `{`.
|
||||
pub before_inner: Vec<Comment>,
|
||||
/// Between the inner `}` and the outer `}`.
|
||||
pub before_close: Vec<Comment>,
|
||||
}
|
||||
|
||||
/// The `with [ … ]` bracket of a stream expression: one index (`[i]`) or a
|
||||
/// range in any of the three spellings a part select takes (`[m:l]`,
|
||||
/// `[i+:n]`, `[i-:n]`).
|
||||
///
|
||||
/// It is not an [`ExprKind::Range`] because that node wraps a *base* — here
|
||||
/// the base stands on the `with`'s left, outside the bracket — but it keeps
|
||||
/// exactly the same comment slots, so the printer lays both out through one
|
||||
/// function.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StreamRange {
|
||||
/// Comments written on either side of the `with` keyword.
|
||||
pub with_comments: WithComments,
|
||||
/// The single index, or the range's first operand.
|
||||
pub msb: Expr,
|
||||
/// `:`, `+:` or `-:`; `None` for the single-index spelling.
|
||||
pub op: Option<String>,
|
||||
/// The range's second operand; `None` for the single-index spelling.
|
||||
pub lsb: Option<Expr>,
|
||||
/// `[ /*a*/ m /*b*/ : /*c*/ l /*d*/ ]` — the slots
|
||||
/// [`SegmentComments`] names. `before_open` is always empty here: what
|
||||
/// was written between the `with` and the `[` belongs to the keyword, so
|
||||
/// it goes in `with_comments.after_kw`.
|
||||
pub comments: SegmentComments,
|
||||
}
|
||||
|
||||
impl TernaryComments {
|
||||
/// True when nothing was written inside the `? :` — the common case, laid
|
||||
/// out without any comment handling.
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
//! | `expr` | [`Expr`], [`ExprKind`], the expression comment slots |
|
||||
//! | `class`, `covergroup` | classes and constraints; covergroups |
|
||||
//! | `sva` | assertions, `property`/`sequence`, the property-expression tree |
|
||||
//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) |
|
||||
|
||||
use crate::span::TextRange;
|
||||
use crate::token::Comment;
|
||||
@@ -42,6 +43,7 @@ mod covergroup;
|
||||
mod decl;
|
||||
mod expr;
|
||||
mod module;
|
||||
mod randsequence;
|
||||
mod stmt;
|
||||
mod sva;
|
||||
|
||||
@@ -50,6 +52,7 @@ pub use covergroup::*;
|
||||
pub use decl::*;
|
||||
pub use expr::*;
|
||||
pub use module::*;
|
||||
pub use randsequence::*;
|
||||
pub use stmt::*;
|
||||
pub use sva::*;
|
||||
|
||||
|
||||
@@ -183,6 +183,24 @@ pub struct DriveStrength {
|
||||
/// `None` for the single-strength spelling `pullup (weak1) p (x);`
|
||||
/// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes.
|
||||
pub second: Option<String>,
|
||||
/// Boxed: five comment vectors dwarf the two strength words, and a
|
||||
/// [`DataDecl`] carrying one of these is what `ast::size_pins` measures.
|
||||
pub comments: Box<DriveStrengthComments>,
|
||||
}
|
||||
|
||||
/// The five gaps of `/*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ )`.
|
||||
///
|
||||
/// `before_open` is the gap in front of the `(` — the strength owns it because
|
||||
/// the three constructs that write one (`assign`, a gate, a net declaration)
|
||||
/// all have something of their own directly in front of it.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DriveStrengthComments {
|
||||
pub before_open: Vec<Comment>,
|
||||
pub after_open: Vec<Comment>,
|
||||
/// Empty for the single-strength spelling, which has no `,`.
|
||||
pub before_comma: Vec<Comment>,
|
||||
pub after_comma: Vec<Comment>,
|
||||
pub before_close: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -549,8 +567,16 @@ pub struct ModportPort {
|
||||
pub struct ClockingDecl {
|
||||
/// True when the declaration was written `default clocking ...`.
|
||||
pub is_default: bool,
|
||||
/// Comments written between the `clocking` keyword and whatever follows
|
||||
/// it — the name, or the `@` of an anonymous block.
|
||||
pub after_kw: Vec<Comment>,
|
||||
/// `None` for the anonymous `default clocking @(posedge clk);` form.
|
||||
pub name: Option<Name>,
|
||||
/// Comments written between the name and the `@` of the clocking event.
|
||||
/// Empty when no name or no event was written.
|
||||
pub before_event: Vec<Comment>,
|
||||
/// Comments written between the header's last token and its `;`.
|
||||
pub before_semi: Vec<Comment>,
|
||||
/// The `@( ... )` clocking event. `None` for `default clocking cb;`, which
|
||||
/// selects an existing clocking block and has no body.
|
||||
pub event: Option<SensList>,
|
||||
@@ -572,6 +598,8 @@ pub struct ClockingDecl {
|
||||
pub struct ClockingItem {
|
||||
pub meta: Meta,
|
||||
pub kind: ClockingItemKind,
|
||||
/// Comments written between the item's last token and its `;`.
|
||||
pub before_semi: Vec<Comment>,
|
||||
/// Code extent of the item, its `;` excluded.
|
||||
pub span: TextRange,
|
||||
}
|
||||
@@ -579,10 +607,73 @@ pub struct ClockingItem {
|
||||
#[derive(Debug)]
|
||||
pub enum ClockingItemKind {
|
||||
/// `default input #1step output #0;` — at least one half is written.
|
||||
Default { input: Option<String>, output: Option<String> },
|
||||
Default { input: Option<ClockingDefault>, output: Option<ClockingDefault> },
|
||||
/// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay
|
||||
/// or edge as written (`#2`, `negedge`), or `None` when omitted.
|
||||
Signals { dir: String, skew: Option<String>, signals: Vec<ClockingSignal> },
|
||||
Signals {
|
||||
dir: String,
|
||||
/// Comments written between the direction keyword and the skew — or,
|
||||
/// when no skew was written, between it and the first signal name.
|
||||
after_dir: Vec<Comment>,
|
||||
skew: Option<ClockingSkew>,
|
||||
/// Comments written between that skew and the first signal name.
|
||||
/// Empty when no skew was written.
|
||||
after_skew: Vec<Comment>,
|
||||
signals: Vec<ClockingSignal>,
|
||||
},
|
||||
}
|
||||
|
||||
/// One half of a `default input #1step output #0;` item: a direction keyword
|
||||
/// and the skew that follows it.
|
||||
#[derive(Debug)]
|
||||
pub struct ClockingDefault {
|
||||
/// Comments written between whatever precedes the direction keyword — the
|
||||
/// `default`, or the other half's skew — and the keyword itself.
|
||||
pub before_dir: Vec<Comment>,
|
||||
/// Comments written between the direction keyword and the skew.
|
||||
pub after_dir: Vec<Comment>,
|
||||
pub skew: ClockingSkew,
|
||||
}
|
||||
|
||||
/// The skew of a clocking item — IEEE 1800 §14.3's
|
||||
/// `clocking_skew ::= edge_identifier [ delay_control ] | delay_control`.
|
||||
#[derive(Debug)]
|
||||
pub enum ClockingSkew {
|
||||
/// `posedge`, `negedge`, `edge`, each of which may carry a delay of its
|
||||
/// own (`input negedge #(1:2:3) sig;`).
|
||||
Edge {
|
||||
/// The edge keyword as written.
|
||||
word: String,
|
||||
/// Comments written between that keyword and the `#` behind it. Empty
|
||||
/// when no delay was written — the gap is then the caller's own slot
|
||||
/// before the signal name or the other `default` half.
|
||||
after_edge: Vec<Comment>,
|
||||
delay: Option<ClockingDelay>,
|
||||
},
|
||||
/// A skew that is a `delay_control` alone: `#2`, `#(1:2:3)`.
|
||||
Delay(ClockingDelay),
|
||||
}
|
||||
|
||||
/// The `# …` half of a clocking skew — IEEE 1800 §14.3's `delay_control`,
|
||||
/// written alone or behind an edge identifier.
|
||||
#[derive(Debug)]
|
||||
pub enum ClockingDelay {
|
||||
/// `#2`, `#1step` — the one token written after the `#`, kept exactly as
|
||||
/// written: it is a delay, never something lucisv re-lays out.
|
||||
Word {
|
||||
/// Comments written between the `#` and that token.
|
||||
after_hash: Vec<Comment>,
|
||||
word: String,
|
||||
},
|
||||
/// The parenthesized spelling `#(1:2:3)`, `#(5)` — the same delay
|
||||
/// expression a net declaration writes, so it arrives with the comment
|
||||
/// slots [`ExprKind::MinTypMax`] and [`ExprKind::Paren`] already have.
|
||||
Paren {
|
||||
/// Comments written between the `#` and the `(`.
|
||||
after_hash: Vec<Comment>,
|
||||
/// The parenthesized delay, `(` and `)` included.
|
||||
expr: Expr,
|
||||
},
|
||||
}
|
||||
|
||||
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
//! `randsequence` — the production grammar of IEEE 1800 §18.17.
|
||||
//!
|
||||
//! A `randsequence` statement is a little grammar of its own written inside a
|
||||
//! procedural block: a list of *productions*, each a name with optional
|
||||
//! arguments and return type, each defining one or more weighted
|
||||
//! *alternatives*, each alternative a run of *items* — a reference to another
|
||||
//! production, a code block of ordinary statements, or one of the three
|
||||
//! control shapes (`if`/`else`, `repeat`, `case`).
|
||||
//!
|
||||
//! Every node here carries the comment slots its own tokens open, for the
|
||||
//! reason the rest of the AST does: a comment written between two tokens must
|
||||
//! print back between those same two tokens or `verify.rs` refuses the file.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `randsequence (main) … endsequence` (IEEE 1800 §18.17).
|
||||
#[derive(Debug)]
|
||||
pub struct RandSequence {
|
||||
/// Comments written between the keyword and its `(`.
|
||||
pub after_kw: Vec<Comment>,
|
||||
/// Comments written just inside the `(`.
|
||||
pub after_open: Vec<Comment>,
|
||||
/// The starting production, `None` for the empty `randsequence ()`.
|
||||
pub start: Option<Name>,
|
||||
/// Comments written between that name and the `)`.
|
||||
pub before_close: Vec<Comment>,
|
||||
pub productions: Vec<Production>,
|
||||
/// Comments written after the last production and before `endsequence`.
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
/// One production: `[type] name [(ports)] : alternative { | alternative } ;`.
|
||||
#[derive(Debug)]
|
||||
pub struct Production {
|
||||
pub meta: Meta,
|
||||
/// The production's return type, `None` when it declares none (or wrote
|
||||
/// `void`, which is kept here as an ordinary type name).
|
||||
pub ret_type: Option<DataType>,
|
||||
pub name: String,
|
||||
/// Byte range of `name`.
|
||||
pub name_span: TextRange,
|
||||
/// True when the production wrote a `( … )` port list, even an empty one.
|
||||
pub has_parens: bool,
|
||||
/// The formal arguments, read as a subroutine's are (§18.17.5).
|
||||
pub args: Vec<ListElem<TfArg>>,
|
||||
/// Comments written between the head and the `:`.
|
||||
pub before_colon: Vec<Comment>,
|
||||
/// At least one; the `|`-separated right-hand sides.
|
||||
pub alternatives: Vec<Alternative>,
|
||||
/// Comments written between the last alternative and the `;`.
|
||||
pub before_semi: Vec<Comment>,
|
||||
/// Code extent of the production, its `;` excluded.
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
/// One `|`-separated right-hand side of a production, with the optional
|
||||
/// `:= weight` that biases it.
|
||||
#[derive(Debug)]
|
||||
pub struct Alternative {
|
||||
/// Comments written between the previous alternative and the `|` that
|
||||
/// starts this one. Always empty on the first alternative, whose left
|
||||
/// neighbour is the production's `:`.
|
||||
pub before_bar: Vec<Comment>,
|
||||
/// Comments written between the `:` (or the `|`) and the first item.
|
||||
pub after_bar: Vec<Comment>,
|
||||
pub items: Vec<ProdItem>,
|
||||
/// Comments written between the last item and the `:=`.
|
||||
pub before_weight: Vec<Comment>,
|
||||
/// The `:= expr` weight (§18.17.2), `None` when unweighted.
|
||||
pub weight: Option<Weight>,
|
||||
}
|
||||
|
||||
/// The `:= weight [code block]` of a weighted alternative.
|
||||
#[derive(Debug)]
|
||||
pub struct Weight {
|
||||
/// Comments written between the `:=` and the weight expression.
|
||||
pub after_op: Vec<Comment>,
|
||||
pub expr: Expr,
|
||||
/// The optional code block run when the alternative is chosen.
|
||||
pub block: Option<Box<CodeBlock>>,
|
||||
}
|
||||
|
||||
/// One item of an alternative's right-hand side — §18.17's `rs_prod`.
|
||||
#[derive(Debug)]
|
||||
pub enum ProdItem {
|
||||
/// `name`, or `name(args)` — a reference to another production.
|
||||
Ref(ProdRef),
|
||||
/// `{ … }` — ordinary statements, laid out as a `begin`/`end` body is.
|
||||
Block(Box<CodeBlock>),
|
||||
/// `if (expr) item [else item]`.
|
||||
If {
|
||||
/// Comments written between the `if` and its `(`.
|
||||
after_kw: Vec<Comment>,
|
||||
cond: Expr,
|
||||
then: Box<ProdItem>,
|
||||
/// Comments written between the `then` item and the `else`.
|
||||
before_else: Vec<Comment>,
|
||||
/// Comments written between the `else` and its item.
|
||||
after_else: Vec<Comment>,
|
||||
els: Option<Box<ProdItem>>,
|
||||
},
|
||||
/// `repeat (expr) item`.
|
||||
Repeat {
|
||||
/// Comments written between the `repeat` and its `(`.
|
||||
after_kw: Vec<Comment>,
|
||||
count: Expr,
|
||||
body: Box<ProdItem>,
|
||||
},
|
||||
/// `case (expr) … endcase`, whose arms take production items rather than
|
||||
/// statements.
|
||||
Case {
|
||||
/// Comments written between the `case` and its `(`.
|
||||
after_kw: Vec<Comment>,
|
||||
expr: Expr,
|
||||
items: Vec<ProdCaseItem>,
|
||||
/// Comments written after the last arm and before `endcase`.
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
/// `rand join [(expr)] item item { item }` (§18.17.6).
|
||||
RandJoin {
|
||||
/// Comments written between the `rand` and the `join`.
|
||||
after_rand: Vec<Comment>,
|
||||
/// The `( expr )` bias, `None` when omitted.
|
||||
weight: Option<Expr>,
|
||||
items: Vec<ProdItem>,
|
||||
},
|
||||
}
|
||||
|
||||
/// A reference to another production: `name` or `name(a, b)`.
|
||||
#[derive(Debug)]
|
||||
pub struct ProdRef {
|
||||
pub name: String,
|
||||
/// Byte range of `name`.
|
||||
pub name_span: TextRange,
|
||||
/// True when a `( … )` argument list was written, even an empty one.
|
||||
pub has_parens: bool,
|
||||
/// Comments written between the name and that `(`.
|
||||
pub before_args: Vec<Comment>,
|
||||
pub args: Vec<ExprItem>,
|
||||
}
|
||||
|
||||
/// One arm of an `rs_case`: `expr, expr : item;` or `default [:] item;`.
|
||||
#[derive(Debug)]
|
||||
pub struct ProdCaseItem {
|
||||
pub meta: Meta,
|
||||
/// Empty for the `default` arm.
|
||||
pub labels: Vec<ExprItem>,
|
||||
/// True when the arm was written `default`.
|
||||
pub is_default: bool,
|
||||
/// Comments written between the labels (or the `default`) and the `:`.
|
||||
pub before_colon: Vec<Comment>,
|
||||
/// Comments written between the `:` and the item. A `default` arm may
|
||||
/// write no `:` at all, and then this is the gap after the keyword.
|
||||
pub after_colon: Vec<Comment>,
|
||||
pub item: ProdItem,
|
||||
/// Comments written between the item and the arm's `;`.
|
||||
pub before_semi: Vec<Comment>,
|
||||
/// Code extent of the arm, its `;` excluded.
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
/// An `rs_code_block`: `{ declarations statements }`. The braces are the
|
||||
/// block's own, and what stands between them is the statement grammar.
|
||||
///
|
||||
/// There is no slot for the gap just inside the `{`: it belongs to the first
|
||||
/// statement's leading comments, exactly as a `begin`/`end` block's does, and
|
||||
/// to `dangling` when the block holds no statement at all.
|
||||
#[derive(Debug)]
|
||||
pub struct CodeBlock {
|
||||
pub stmts: Vec<Stmt>,
|
||||
/// Comments written after the last statement and before the `}`.
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
@@ -253,9 +253,25 @@ pub enum StmtKind {
|
||||
stmt: Option<Box<Stmt>>,
|
||||
},
|
||||
ExprStmt(Expr),
|
||||
/// `-> event_name;`
|
||||
EventTrigger(Expr),
|
||||
/// `-> ev;` and the non-blocking `->> ev;` (IEEE 1800 §15.5.2), which may
|
||||
/// carry a delay or event control of its own: `->> #5 ev;`,
|
||||
/// `->> @(posedge clk) ev;`.
|
||||
///
|
||||
/// Boxed because the timing control is the size of a whole sensitivity
|
||||
/// list and this is one of the smallest statements there is; see
|
||||
/// `ast::size_pins`.
|
||||
EventTrigger(Box<EventTrigger>),
|
||||
VarDecl(DataDecl),
|
||||
/// A block-scoped `let` (IEEE 1800 §11.13): `let sum = a + b;` written
|
||||
/// among a `begin`/`end`'s declarations. Same grammar and same layout as
|
||||
/// the item-level one, so it carries the item's node; boxed because a
|
||||
/// `let` is rare and its node is wider than the statement kinds that are
|
||||
/// not (see `ast::size_pins`).
|
||||
Let(Box<LetDecl>),
|
||||
/// `randsequence (main) … endsequence` (IEEE 1800 §18.17) — a production
|
||||
/// grammar of its own, modelled in `ast::randsequence`. Boxed: a
|
||||
/// production list is wide and a `randsequence` is rare.
|
||||
RandSequence(Box<RandSequence>),
|
||||
ParamDecl(ParamDecl),
|
||||
/// Old-style task/function port declaration: `input [7:0] a;`
|
||||
PortDecl(PortDecl),
|
||||
@@ -341,6 +357,27 @@ impl StmtKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// An event trigger: `-> ev;` or the non-blocking `->> ev;`.
|
||||
///
|
||||
/// Only the non-blocking spelling may write a delay or an event control
|
||||
/// between the arrow and the event (IEEE 1800 §15.5.2), but the node carries
|
||||
/// one either way — lucisv reproduces what was written and is not a legality
|
||||
/// checker.
|
||||
#[derive(Debug)]
|
||||
pub struct EventTrigger {
|
||||
/// `->` or `->>`, as written.
|
||||
pub arrow: String,
|
||||
/// Comments written between the arrow and whatever follows it
|
||||
/// (`->> /*c*/ #5 ev;`).
|
||||
pub after_arrow: Vec<Comment>,
|
||||
/// The `#5` or `@(posedge clk)` of `->> #5 ev;`.
|
||||
pub timing: Option<TimingControl>,
|
||||
/// Comments written between that timing control and the event name.
|
||||
/// Empty when no timing control was written.
|
||||
pub before_event: Vec<Comment>,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TimingControl {
|
||||
/// `#expr`
|
||||
|
||||
@@ -52,9 +52,9 @@ struct RawLexer<'a> {
|
||||
|
||||
/// Multi-character operators, longest first so greedy matching works.
|
||||
const OPERATORS: &[&str] = &[
|
||||
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "**", "==",
|
||||
"!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=",
|
||||
"%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
|
||||
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "->>", "**",
|
||||
"==", "!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=",
|
||||
"/=", "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
|
||||
];
|
||||
|
||||
const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
|
||||
|
||||
@@ -260,6 +260,10 @@ impl<'a> Parser<'a> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// `wire (strong0, weak1) w = a;` — IEEE 1800 §6.6 writes the strength
|
||||
// directly after the net keyword and nowhere else, so a `(` here is
|
||||
// only read as one when a net keyword was actually written.
|
||||
let strength = if net.is_some() { self.parse_opt_drive_strength()? } else { None };
|
||||
let before = self.parse_net_delay(net.is_some(), false)?;
|
||||
// A declaration reaches here with its `virtual` already in
|
||||
// `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot
|
||||
@@ -285,7 +289,7 @@ impl<'a> Parser<'a> {
|
||||
};
|
||||
let declarators = self.parse_declarators()?;
|
||||
self.expect_sym(";")?;
|
||||
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
|
||||
Ok(DataDecl { net, strength, delay, qualifiers, ty, declarators })
|
||||
}
|
||||
|
||||
/// The net delay at the cursor, if one is written there: `#5`, `#0.1`,
|
||||
|
||||
@@ -265,14 +265,16 @@ impl<'a> Parser<'a> {
|
||||
|| (t.is_sym("'{") && self.is_cast_base(base))
|
||||
|| t.is_sym("++")
|
||||
|| t.is_sym("--")
|
||||
// `with ( ... )` (an array method's iterator argument) and
|
||||
// `with { ... }` (a `randomize` constraint block) are the two
|
||||
// postfix spellings of `with`; the delimiter tells them apart and
|
||||
// demanding one keeps the `with [range]` of a stream expression,
|
||||
// which lucisv does not model, out of this path.
|
||||
// `with ( ... )` (an array method's iterator argument),
|
||||
// `with { ... }` (a `randomize` constraint block) and
|
||||
// `with [ ... ]` (a stream expression's array range,
|
||||
// IEEE 1800 §11.4.14) are the three postfix spellings of `with`;
|
||||
// the delimiter after the keyword is what tells them apart.
|
||||
|| (t.is_kw("with")
|
||||
&& !self.no_with
|
||||
&& (self.nth(1).is_sym("(") || self.nth(1).is_sym("{")))
|
||||
&& (self.nth(1).is_sym("(")
|
||||
|| self.nth(1).is_sym("{")
|
||||
|| self.nth(1).is_sym("[")))
|
||||
}
|
||||
|
||||
/// True when the `[` at the cursor opens a transition or consecutive
|
||||
@@ -363,6 +365,35 @@ impl<'a> Parser<'a> {
|
||||
))
|
||||
}
|
||||
|
||||
/// The `[ … ]` of a stream expression's `with` (IEEE 1800 §11.4.14), the
|
||||
/// `with` already consumed: one index or a range in any of the three
|
||||
/// spellings a part select takes.
|
||||
///
|
||||
/// `with_comments` arrives holding what was written in front of the
|
||||
/// keyword; the gap after it is that same node's `after_kw`, so the two
|
||||
/// halves of `a /*x*/ with /*y*/ [i]` keep their own sides of the word and
|
||||
/// the printer lays the head out through the one function all three
|
||||
/// postfix `with` forms share.
|
||||
fn parse_stream_range(&mut self, mut with_comments: WithComments) -> PResult<StreamRange> {
|
||||
with_comments.after_kw = self.take_before_open("[");
|
||||
let mut comments = SegmentComments::default();
|
||||
self.expect_sym("[")?;
|
||||
comments.after_open = self.take_gap();
|
||||
let msb = self.parse_expr()?;
|
||||
let t = self.cur();
|
||||
let (op, lsb) = if t.is_sym(":") || t.is_sym("+:") || t.is_sym("-:") {
|
||||
comments.before_op = self.take_gap();
|
||||
let op = self.bump().text;
|
||||
comments.after_op = self.take_gap();
|
||||
(Some(op), Some(self.parse_expr()?))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
comments.before_close = self.gap_before("]");
|
||||
self.expect_sym("]")?;
|
||||
Ok(StreamRange { with_comments, msb, op, lsb, comments })
|
||||
}
|
||||
|
||||
fn parse_postfix_inner(&mut self) -> PResult<Expr> {
|
||||
let mut expr = self.parse_primary()?;
|
||||
while self.at_postfix_segment(&expr) {
|
||||
@@ -430,6 +461,13 @@ impl<'a> Parser<'a> {
|
||||
comments: Box::new(comments),
|
||||
},
|
||||
);
|
||||
} else if self.nth(1).is_sym("[") {
|
||||
self.bump(); // with
|
||||
let range = self.parse_stream_range(comments)?;
|
||||
expr = self.expr_at(
|
||||
start,
|
||||
ExprKind::StreamWith { base: Box::new(expr), range: Box::new(range) },
|
||||
);
|
||||
} else {
|
||||
self.bump(); // with
|
||||
comments.after_kw = self.take_before_open("(");
|
||||
|
||||
@@ -76,22 +76,32 @@ impl<'a> Parser<'a> {
|
||||
/// strength when a strength keyword follows it, so a parenthesized
|
||||
/// left-hand side — and a gate whose first argument is an expression — is
|
||||
/// untouched.
|
||||
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
|
||||
pub(super) fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
|
||||
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut comments =
|
||||
Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() });
|
||||
self.bump(); // (
|
||||
comments.after_open = self.take_gap();
|
||||
let first = self.bump().text;
|
||||
// The gap after the first strength ends either at the `,` or at the
|
||||
// `)`, and it is that token which says which slot it belongs in.
|
||||
let gap = self.take_gap();
|
||||
if self.eat_sym(")") {
|
||||
return Ok(Some(DriveStrength { first, second: None }));
|
||||
comments.before_close = gap;
|
||||
return Ok(Some(DriveStrength { first, second: None, comments }));
|
||||
}
|
||||
comments.before_comma = gap;
|
||||
self.expect_sym(",")?;
|
||||
comments.after_comma = self.take_gap();
|
||||
if !is_drive_strength(self.cur()) {
|
||||
return self.error("expected a drive strength");
|
||||
}
|
||||
let second = Some(self.bump().text);
|
||||
comments.before_close = self.gap_before(")");
|
||||
self.expect_sym(")")?;
|
||||
Ok(Some(DriveStrength { first, second }))
|
||||
Ok(Some(DriveStrength { first, second, comments }))
|
||||
}
|
||||
|
||||
/// The value after a `#`: a bare primary, or a parenthesized delay —
|
||||
|
||||
@@ -238,6 +238,13 @@ impl<'a> Parser<'a> {
|
||||
// A package import standing among a block's declarations
|
||||
// (IEEE 1800 §13.4.2): the same statement the item level takes.
|
||||
"import" => Ok(StmtKind::Import(self.parse_import_list()?)),
|
||||
// A block-scoped `let` (IEEE 1800 §11.13). `parse_let` reads the
|
||||
// `;` itself, which is why `takes_semi()` says this kind takes
|
||||
// none — exactly as the item-level spelling works.
|
||||
"let" => Ok(StmtKind::Let(Box::new(self.parse_let()?))),
|
||||
// `randsequence` reads its own `endsequence`, so like a block it
|
||||
// takes no `;` of its own (`takes_semi()` says so).
|
||||
"randsequence" => Ok(StmtKind::RandSequence(Box::new(self.parse_randsequence()?))),
|
||||
// A block-scoped type (IEEE 1800 §6.18), e.g.
|
||||
// `spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577`. Same
|
||||
// grammar and same layout as the item-level `typedef`.
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
//! | `expr`, `primary` | the operator grammar; its leaves and argument lists |
|
||||
//! | `class`, `covergroup` | classes with their constraints; covergroups |
|
||||
//! | `assertion`, `sva` | concurrent assertions and SVA declarations; the property grammar |
|
||||
//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) |
|
||||
//! | `directive` | `` `ifdef `` tracking, list directives, macros, fragment mode |
|
||||
//! | `split` | conditional-directive split recovery |
|
||||
//! | `verbatim` | vendor/formal blocks kept as bytes, and the capture helpers |
|
||||
@@ -59,6 +60,7 @@ mod item;
|
||||
mod keyword_stmt;
|
||||
mod module;
|
||||
mod primary;
|
||||
mod randsequence;
|
||||
mod recover;
|
||||
mod recover_list;
|
||||
mod split;
|
||||
|
||||
@@ -217,15 +217,21 @@ impl<'a> Parser<'a> {
|
||||
/// `default` keyword, when written, has already been consumed.
|
||||
pub(super) fn parse_clocking(&mut self, is_default: bool) -> PResult<ClockingDecl> {
|
||||
self.expect_kw("clocking")?;
|
||||
let after_kw = self.take_gap();
|
||||
let name =
|
||||
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
|
||||
let before_event = if self.cur().is_sym("@") { self.take_gap() } else { Vec::new() };
|
||||
// `default clocking cb;` selects an existing block and has no body.
|
||||
let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None };
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
if event.is_none() {
|
||||
return Ok(ClockingDecl {
|
||||
is_default,
|
||||
after_kw,
|
||||
name,
|
||||
before_event,
|
||||
before_semi,
|
||||
event,
|
||||
items: Vec::new(),
|
||||
dangling: Vec::new(),
|
||||
@@ -245,7 +251,10 @@ impl<'a> Parser<'a> {
|
||||
let (end_label, end_label_span) = split_label(end_name);
|
||||
Ok(ClockingDecl {
|
||||
is_default,
|
||||
after_kw,
|
||||
name,
|
||||
before_event,
|
||||
before_semi,
|
||||
event,
|
||||
items,
|
||||
dangling,
|
||||
@@ -262,9 +271,8 @@ impl<'a> Parser<'a> {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let kind = if self.eat_kw("default") {
|
||||
let input = if self.eat_kw("input") { Some(self.parse_clocking_skew()?) } else { None };
|
||||
let output =
|
||||
if self.eat_kw("output") { Some(self.parse_clocking_skew()?) } else { None };
|
||||
let input = self.parse_clocking_default("input")?;
|
||||
let output = self.parse_clocking_default("output")?;
|
||||
if input.is_none() && output.is_none() {
|
||||
return self.error("expected `input` or `output` after `default`");
|
||||
}
|
||||
@@ -275,20 +283,28 @@ impl<'a> Parser<'a> {
|
||||
return self.error("expected a clocking item");
|
||||
}
|
||||
let dir = self.bump().text;
|
||||
let skew =
|
||||
if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None };
|
||||
let after_dir = self.take_gap();
|
||||
let mut after_skew = Vec::new();
|
||||
let skew = if self.at_clocking_skew() {
|
||||
let skew = self.parse_clocking_skew()?;
|
||||
after_skew = self.take_gap();
|
||||
Some(skew)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut signals = vec![self.parse_clocking_signal()?];
|
||||
while self.eat_sym(",") {
|
||||
signals.push(self.parse_clocking_signal()?);
|
||||
}
|
||||
ClockingItemKind::Signals { dir, skew, signals }
|
||||
ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals }
|
||||
};
|
||||
let span = self.span_from(start);
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
if meta.trailing.is_none() {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
Ok(ClockingItem { meta, kind, span })
|
||||
Ok(ClockingItem { meta, kind, before_semi, span })
|
||||
}
|
||||
|
||||
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
|
||||
@@ -301,6 +317,21 @@ impl<'a> Parser<'a> {
|
||||
Ok(ClockingSignal { name, value })
|
||||
}
|
||||
|
||||
/// One half of a `default input #1step output #0;` item: the direction
|
||||
/// keyword `dir` and its skew, or `None` when this half was not written.
|
||||
///
|
||||
/// The gap in front of the keyword is the half's own, so the two halves
|
||||
/// keep their own sides of the word that separates them.
|
||||
fn parse_clocking_default(&mut self, dir: &str) -> PResult<Option<ClockingDefault>> {
|
||||
if !self.cur().is_kw(dir) {
|
||||
return Ok(None);
|
||||
}
|
||||
let before_dir = self.take_gap();
|
||||
self.bump();
|
||||
let after_dir = self.take_gap();
|
||||
Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? }))
|
||||
}
|
||||
|
||||
/// True when the cursor is on a clocking skew rather than on the first
|
||||
/// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`.
|
||||
fn at_clocking_skew(&self) -> bool {
|
||||
@@ -308,25 +339,47 @@ impl<'a> Parser<'a> {
|
||||
t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge")
|
||||
}
|
||||
|
||||
/// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text —
|
||||
/// it is a delay or an edge, never something lucisv re-lays out — so the
|
||||
/// printer writes back exactly what the source said. The `#(min:typ:max)`
|
||||
/// spelling is not supported; see the feature README's Assumptions.
|
||||
fn parse_clocking_skew(&mut self) -> PResult<String> {
|
||||
if self.eat_sym("#") {
|
||||
let t = self.cur();
|
||||
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
|
||||
return self.error("expected a clocking skew delay");
|
||||
}
|
||||
return Ok(format!("#{}", self.bump().text));
|
||||
/// A clocking skew, as written: `#2`, `#1step`, the parenthesized
|
||||
/// `#(1:2:3)`, an edge identifier, or — IEEE 1800 §14.3's first
|
||||
/// alternative — an edge identifier with a delay behind it
|
||||
/// (`negedge #(1:2:3)`).
|
||||
fn parse_clocking_skew(&mut self) -> PResult<ClockingSkew> {
|
||||
if self.cur().is_sym("#") {
|
||||
return Ok(ClockingSkew::Delay(self.parse_clocking_delay()?));
|
||||
}
|
||||
let t = self.cur();
|
||||
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
|
||||
return Ok(self.bump().text);
|
||||
let word = self.bump().text;
|
||||
// Only a gap that really is in front of a `#` is the edge's own;
|
||||
// otherwise it belongs to the caller's slot before the name.
|
||||
let after_edge = self.gap_before("#");
|
||||
let delay =
|
||||
if self.cur().is_sym("#") { Some(self.parse_clocking_delay()?) } else { None };
|
||||
return Ok(ClockingSkew::Edge { word, after_edge, delay });
|
||||
}
|
||||
self.error("expected a clocking skew")
|
||||
}
|
||||
|
||||
/// The `# …` half of a clocking skew.
|
||||
///
|
||||
/// The one-token spellings are kept as text — a delay is never something
|
||||
/// lucisv re-lays out — so the printer writes back exactly what the source
|
||||
/// said. The parenthesized one goes through the delay-value grammar every
|
||||
/// other `#( … )` uses, which is what gives its `:` and its parens their
|
||||
/// comment slots.
|
||||
fn parse_clocking_delay(&mut self) -> PResult<ClockingDelay> {
|
||||
self.expect_sym("#")?;
|
||||
let after_hash = self.take_gap();
|
||||
if self.cur().is_sym("(") {
|
||||
return Ok(ClockingDelay::Paren { after_hash, expr: self.parse_delay_value()? });
|
||||
}
|
||||
let t = self.cur();
|
||||
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
|
||||
return self.error("expected a clocking skew delay");
|
||||
}
|
||||
Ok(ClockingDelay::Word { after_hash, word: self.bump().text })
|
||||
}
|
||||
|
||||
/// A `#( parameter ... )` port list, shared by module and class headers.
|
||||
/// `ports` is `None` when no `#(` was written at the cursor at all.
|
||||
pub(super) fn parse_param_port_list(&mut self) -> PResult<ParamPortList> {
|
||||
|
||||
@@ -146,20 +146,25 @@ impl<'a> Parser<'a> {
|
||||
/// its `<<` or `>>`: IEEE 1800 §11.4.14
|
||||
/// `{ (<<|>>) [slice_size] { stream_expression {, stream_expression} } }`.
|
||||
///
|
||||
/// The `with [range]` form of a stream expression is not supported; a
|
||||
/// file using it keeps its old "expected expression" error.
|
||||
/// A stream expression's `with [range]` is read by `parse_postfix_inner`,
|
||||
/// as the postfix segment it is; the elements here are ordinary
|
||||
/// expressions either way.
|
||||
fn parse_stream_concat(&mut self, start: u32) -> PResult<Expr> {
|
||||
let mut comments =
|
||||
Box::new(StreamComments { after_open: self.take_gap(), ..Default::default() });
|
||||
let dir = self.bump().text;
|
||||
// The slice size is optional and is a constant expression or a type
|
||||
// (`{<< byte {x}}`); a `{` here means it was omitted.
|
||||
let slice =
|
||||
if self.cur().is_sym("{") { None } else { Some(Box::new(self.parse_expr_or_type()?)) };
|
||||
comments.before_inner = self.take_before_open("{");
|
||||
self.expect_sym("{")?;
|
||||
let first = self.parse_expr_item()?;
|
||||
let inner = self.parse_expr_list(first, "}")?;
|
||||
self.expect_sym("}")?;
|
||||
comments.before_close = self.gap_before("}");
|
||||
self.expect_sym("}")?;
|
||||
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner }))
|
||||
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner, comments }))
|
||||
}
|
||||
|
||||
/// True when `e` may stand left of a cast's `'` — the `constant_primary`
|
||||
@@ -180,6 +185,14 @@ impl<'a> Parser<'a> {
|
||||
| ExprKind::Scope { .. }
|
||||
| ExprKind::Member { .. }
|
||||
| ExprKind::Paren { .. } => true,
|
||||
// A data type with dimensions on it — `logic [3:0]'(x)`,
|
||||
// `bit signed [7:0]'(y)`. A bare `int'(x)` never reaches here
|
||||
// (`parse_primary` takes the keyword-and-tick shape itself); this
|
||||
// is the spelling whose `[3:0]` sent it down `parse_type_expr`
|
||||
// instead. IEEE 1800 §6.24.1's `casting_type` names only
|
||||
// `simple_type`, but every tool in use accepts the packed
|
||||
// dimensions and lucisv is not a legality checker.
|
||||
ExprKind::Type(_) => true,
|
||||
ExprKind::Call { callee, .. } => {
|
||||
matches!(&callee.kind, ExprKind::Ident(n) if n.starts_with('$'))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! `randsequence` — the production grammar of IEEE 1800 §18.17.
|
||||
//!
|
||||
//! One file for one sub-grammar, the way the SVA and covergroup grammars each
|
||||
//! have their own: a `randsequence` body is a production list, not a
|
||||
//! statement list, and nothing outside it reads these productions.
|
||||
//!
|
||||
//! The nesting between an alternative's items and the control shapes that
|
||||
//! wrap them is real recursion, so `parse_prod_item` brackets itself with
|
||||
//! [`Parser::enter`] / [`Parser::leave`] the way every other recursive
|
||||
//! production does.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// `randsequence ( [name] ) production { production } endsequence`
|
||||
/// (IEEE 1800 §18.17), the cursor on the keyword.
|
||||
pub(super) fn parse_randsequence(&mut self) -> PResult<RandSequence> {
|
||||
self.expect_kw("randsequence")?;
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let after_open = self.take_gap();
|
||||
let start =
|
||||
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
|
||||
let before_close = self.gap_before(")");
|
||||
self.expect_sym(")")?;
|
||||
let mut productions = Vec::new();
|
||||
while !self.at_body_end("endsequence") {
|
||||
productions.push(self.parse_production()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_closer("endsequence")?;
|
||||
Ok(RandSequence { after_kw, after_open, start, before_close, productions, dangling })
|
||||
}
|
||||
|
||||
/// One production: `[data_type] name [( ports )] : alternatives ;`.
|
||||
///
|
||||
/// The optional return type is told from the name by what follows the
|
||||
/// identifier: a production's name is the last identifier before the `(`,
|
||||
/// the `:` or another identifier, so a second identifier means the first
|
||||
/// one was the type.
|
||||
fn parse_production(&mut self) -> PResult<Production> {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let ret_type = self.parse_opt_production_type()?;
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
let has_parens = self.cur().is_sym("(");
|
||||
let args = self.parse_tf_ports(false)?.args;
|
||||
let before_colon = self.gap_before(":");
|
||||
self.expect_sym(":")?;
|
||||
let mut alternatives = vec![self.parse_alternative(Vec::new())?];
|
||||
while self.cur().is_sym("|") {
|
||||
// The gap in front of the `|` belongs to the alternative it opens,
|
||||
// so it prints on the bar's own side of the previous one.
|
||||
let before_bar = self.take_gap();
|
||||
self.bump();
|
||||
alternatives.push(self.parse_alternative(before_bar)?);
|
||||
}
|
||||
let span = self.span_from(start);
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
if meta.trailing.is_none() {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
Ok(Production {
|
||||
meta,
|
||||
ret_type,
|
||||
name,
|
||||
name_span,
|
||||
has_parens,
|
||||
args,
|
||||
before_colon,
|
||||
alternatives,
|
||||
before_semi,
|
||||
span,
|
||||
})
|
||||
}
|
||||
|
||||
/// The production's return type, when it wrote one. `void` is a keyword
|
||||
/// rather than an identifier, so it is read here too and kept as the type
|
||||
/// name it is written as.
|
||||
fn parse_opt_production_type(&mut self) -> PResult<Option<DataType>> {
|
||||
let t = self.cur();
|
||||
let typed = if t.is_kw("void") {
|
||||
true
|
||||
} else if t.kind == TokenKind::Keyword {
|
||||
// `int name : …`, `bit [3:0] name : …` — a type keyword can only
|
||||
// be the type, never the production's own name.
|
||||
TYPE_KEYWORDS.contains(&t.text.as_str())
|
||||
} else {
|
||||
// Two identifiers in a row: the first is a user-defined type.
|
||||
t.kind == TokenKind::Ident && self.nth(1).kind == TokenKind::Ident
|
||||
};
|
||||
if !typed {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(self.parse_opt_data_type()?))
|
||||
}
|
||||
|
||||
/// One `|`-separated right-hand side, with its optional `:= weight`.
|
||||
fn parse_alternative(&mut self, before_bar: Vec<Comment>) -> PResult<Alternative> {
|
||||
let after_bar = self.take_gap();
|
||||
let mut items = vec![self.parse_prod_item()?];
|
||||
while self.at_prod_item() {
|
||||
items.push(self.parse_prod_item()?);
|
||||
}
|
||||
let mut before_weight = Vec::new();
|
||||
let mut weight = None;
|
||||
if self.at_weight_op() {
|
||||
before_weight = self.take_gap();
|
||||
self.bump(); // :
|
||||
self.bump(); // =
|
||||
weight = Some(self.parse_weight()?);
|
||||
}
|
||||
Ok(Alternative { before_bar, after_bar, items, before_weight, weight })
|
||||
}
|
||||
|
||||
/// True when the cursor is on the `:=` of a weight. The lexer has no `:=`
|
||||
/// token — it is a `:` and an `=` written adjacently, the same two tokens
|
||||
/// a `dist` weight is read from — so adjacency is checked by span and
|
||||
/// `a : = 5` written with a space is not one.
|
||||
fn at_weight_op(&self) -> bool {
|
||||
self.cur().is_sym(":")
|
||||
&& self.nth(1).is_sym("=")
|
||||
&& self.nth(1).span.start == self.cur().span.end
|
||||
}
|
||||
|
||||
/// The `:= expr [ { code } ]` of a weighted alternative (§18.17.2).
|
||||
///
|
||||
/// §18.17.2's `weight_specification` is a number, a scoped name or a
|
||||
/// *parenthesized* expression — never a bare operator expression — and
|
||||
/// that is what keeps `a := 3 | b := 2` readable: an unparenthesized `|`
|
||||
/// separates the alternatives, it does not or two weights together. So
|
||||
/// the weight is read as a postfix expression and stops there.
|
||||
fn parse_weight(&mut self) -> PResult<Weight> {
|
||||
let after_op = self.take_gap();
|
||||
let expr = self.parse_postfix()?;
|
||||
let block =
|
||||
if self.cur().is_sym("{") { Some(Box::new(self.parse_rs_code_block()?)) } else { None };
|
||||
Ok(Weight { after_op, expr, block })
|
||||
}
|
||||
|
||||
/// True when the cursor opens another item of the alternative rather than
|
||||
/// ending it. An alternative ends at `|`, `:=`, `;`, or the `}` / `endcase`
|
||||
/// of whatever encloses it.
|
||||
fn at_prod_item(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.kind == TokenKind::Ident
|
||||
|| t.is_sym("{")
|
||||
|| t.is_kw("if")
|
||||
|| t.is_kw("repeat")
|
||||
|| t.is_kw("case")
|
||||
|| t.is_kw("rand")
|
||||
}
|
||||
|
||||
/// One `rs_prod`: a production reference, a code block, or one of the four
|
||||
/// control shapes.
|
||||
fn parse_prod_item(&mut self) -> PResult<ProdItem> {
|
||||
self.enter()?;
|
||||
let item = self.parse_prod_item_inner();
|
||||
self.leave();
|
||||
item
|
||||
}
|
||||
|
||||
fn parse_prod_item_inner(&mut self) -> PResult<ProdItem> {
|
||||
let t = self.cur();
|
||||
if t.is_sym("{") {
|
||||
return Ok(ProdItem::Block(Box::new(self.parse_rs_code_block()?)));
|
||||
}
|
||||
if t.is_kw("if") {
|
||||
return self.parse_rs_if();
|
||||
}
|
||||
if t.is_kw("repeat") {
|
||||
self.bump();
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let count = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
let body = Box::new(self.parse_prod_item()?);
|
||||
return Ok(ProdItem::Repeat { after_kw, count, body });
|
||||
}
|
||||
if t.is_kw("case") {
|
||||
return self.parse_rs_case();
|
||||
}
|
||||
if t.is_kw("rand") {
|
||||
return self.parse_rand_join();
|
||||
}
|
||||
Ok(ProdItem::Ref(self.parse_prod_ref()?))
|
||||
}
|
||||
|
||||
/// `if ( expr ) item [ else item ]` — the arms are production items, not
|
||||
/// statements, so this is not `parse_if_stmt`.
|
||||
fn parse_rs_if(&mut self) -> PResult<ProdItem> {
|
||||
self.expect_kw("if")?;
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let cond = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
let then = Box::new(self.parse_prod_item()?);
|
||||
// Whatever was written in the gap before `else` stays on the
|
||||
// keyword's left, as an `if` statement's does.
|
||||
let mut before_else = Vec::new();
|
||||
if self.cur().is_kw("else") {
|
||||
before_else = self.take_dangling();
|
||||
}
|
||||
let (after_else, els) = if self.eat_kw("else") {
|
||||
(self.take_gap(), Some(Box::new(self.parse_prod_item()?)))
|
||||
} else {
|
||||
(Vec::new(), None)
|
||||
};
|
||||
Ok(ProdItem::If { after_kw, cond, then, before_else, after_else, els })
|
||||
}
|
||||
|
||||
/// `case ( expr ) arm { arm } endcase`, whose arms take production items.
|
||||
fn parse_rs_case(&mut self) -> PResult<ProdItem> {
|
||||
self.expect_kw("case")?;
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let expr = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
let mut items = Vec::new();
|
||||
while !self.at_body_end("endcase") {
|
||||
items.push(self.parse_rs_case_item()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_closer("endcase")?;
|
||||
Ok(ProdItem::Case { after_kw, expr, items, dangling })
|
||||
}
|
||||
|
||||
/// One arm: `expr {, expr} : item ;` or `default [:] item ;`.
|
||||
fn parse_rs_case_item(&mut self) -> PResult<ProdCaseItem> {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let mut labels = Vec::new();
|
||||
let is_default = self.eat_kw("default");
|
||||
if !is_default {
|
||||
let first = self.parse_expr_item()?;
|
||||
labels = self.parse_expr_list(first, ":")?;
|
||||
}
|
||||
let before_colon = self.gap_before(":");
|
||||
// A `default` arm may write no `:` at all (§18.17.4).
|
||||
let has_colon = self.cur().is_sym(":");
|
||||
if has_colon {
|
||||
self.bump();
|
||||
} else if !is_default {
|
||||
return self.error("expected `:` in a randsequence case arm");
|
||||
}
|
||||
let after_colon = self.take_gap();
|
||||
let item = self.parse_prod_item()?;
|
||||
let span = self.span_from(start);
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
if meta.trailing.is_none() {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
Ok(ProdCaseItem {
|
||||
meta,
|
||||
labels,
|
||||
is_default,
|
||||
before_colon,
|
||||
after_colon,
|
||||
item,
|
||||
before_semi,
|
||||
span,
|
||||
})
|
||||
}
|
||||
|
||||
/// `rand join [ ( expr ) ] item item { item }` (§18.17.6): the items are
|
||||
/// interleaved rather than run in order, and there are at least two.
|
||||
fn parse_rand_join(&mut self) -> PResult<ProdItem> {
|
||||
self.expect_kw("rand")?;
|
||||
let after_rand = self.take_gap();
|
||||
self.expect_kw("join")?;
|
||||
let weight = if self.cur().is_sym("(") {
|
||||
self.bump();
|
||||
let e = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
Some(e)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut items = vec![self.parse_prod_item()?];
|
||||
while self.at_prod_item() {
|
||||
items.push(self.parse_prod_item()?);
|
||||
}
|
||||
Ok(ProdItem::RandJoin { after_rand, weight, items })
|
||||
}
|
||||
|
||||
/// A production reference: `name` or `name(a, b)`.
|
||||
fn parse_prod_ref(&mut self) -> PResult<ProdRef> {
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
let before_args = self.take_before_open("(");
|
||||
let has_parens = self.cur().is_sym("(");
|
||||
let mut args = Vec::new();
|
||||
if has_parens {
|
||||
self.bump();
|
||||
if !self.cur().is_sym(")") {
|
||||
let first = self.parse_expr_item()?;
|
||||
args = self.parse_expr_list(first, ")")?;
|
||||
}
|
||||
self.expect_sym(")")?;
|
||||
}
|
||||
Ok(ProdRef { name, name_span, has_parens, before_args, args })
|
||||
}
|
||||
|
||||
/// An `rs_code_block`: `{ … }` around ordinary statements.
|
||||
fn parse_rs_code_block(&mut self) -> PResult<CodeBlock> {
|
||||
self.expect_sym("{")?;
|
||||
let mut stmts = Vec::new();
|
||||
while !self.cur().is_sym("}") && !self.at_eof() {
|
||||
stmts.push(self.stmt_or_recover()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_sym("}")?;
|
||||
Ok(CodeBlock { stmts, dangling })
|
||||
}
|
||||
}
|
||||
@@ -144,11 +144,8 @@ impl<'a> Parser<'a> {
|
||||
let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) };
|
||||
return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt });
|
||||
}
|
||||
if t.is_sym("->") {
|
||||
self.bump();
|
||||
let e = self.parse_unary()?;
|
||||
self.expect_stmt_semi()?;
|
||||
return Ok(StmtKind::EventTrigger(e));
|
||||
if t.is_sym("->") || t.is_sym("->>") {
|
||||
return self.parse_event_trigger();
|
||||
}
|
||||
if t.kind == TokenKind::Keyword {
|
||||
return self.parse_keyword_stmt();
|
||||
@@ -157,6 +154,42 @@ impl<'a> Parser<'a> {
|
||||
self.parse_assign_or_expr_stmt()
|
||||
}
|
||||
|
||||
/// `-> ev;` and `->> [delay_or_event_control] ev;` (IEEE 1800 §15.5.2).
|
||||
///
|
||||
/// The arrow is kept as written: `->` and `->>` are different statements
|
||||
/// (blocking and non-blocking), so rewriting one as the other would
|
||||
/// change the design. Only `->>` may carry the timing control, but it is
|
||||
/// read for both spellings — the parser reproduces what stands there and
|
||||
/// leaves legality to the tools that check it.
|
||||
fn parse_event_trigger(&mut self) -> PResult<StmtKind> {
|
||||
let arrow = self.bump().text;
|
||||
let after_arrow = self.take_gap();
|
||||
let timing = self.parse_opt_timing_control()?;
|
||||
let before_event = if timing.is_some() { self.take_gap() } else { Vec::new() };
|
||||
let expr = self.parse_unary()?;
|
||||
self.expect_stmt_semi()?;
|
||||
Ok(StmtKind::EventTrigger(Box::new(EventTrigger {
|
||||
arrow,
|
||||
after_arrow,
|
||||
timing,
|
||||
before_event,
|
||||
expr,
|
||||
})))
|
||||
}
|
||||
|
||||
/// The `#delay` or `@(event)` written at the cursor, if one is.
|
||||
fn parse_opt_timing_control(&mut self) -> PResult<Option<TimingControl>> {
|
||||
if self.eat_sym("#") {
|
||||
let after_hash = self.take_gap();
|
||||
let expr = self.parse_delay_value()?;
|
||||
return Ok(Some(TimingControl::Delay { after_hash, expr }));
|
||||
}
|
||||
if self.eat_sym("@") {
|
||||
return Ok(Some(TimingControl::Event(self.parse_sens_list()?)));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn parse_if_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
|
||||
self.expect_kw("if")?;
|
||||
let after_kw = self.take_before_open("(");
|
||||
|
||||
@@ -226,13 +226,17 @@ fn only_a_brace_after_the_first_element_makes_an_assignment_pattern_a_replicatio
|
||||
fn a_streaming_concatenation_keeps_its_direction_and_optional_slice_size() {
|
||||
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2_pkg.sv:123.
|
||||
with_assign_rhs("module m;\n assign y = {<<8{v}};\nendmodule\n", |e| {
|
||||
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
|
||||
let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else {
|
||||
panic!("expected a stream")
|
||||
};
|
||||
assert_eq!(dir, "<<");
|
||||
assert!(matches!(slice.as_deref().map(|s| &s.kind), Some(ExprKind::Number(_))));
|
||||
assert_eq!(inner.len(), 1);
|
||||
});
|
||||
with_assign_rhs("module m;\n assign y = {>>{a, b}};\nendmodule\n", |e| {
|
||||
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
|
||||
let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else {
|
||||
panic!("expected a stream")
|
||||
};
|
||||
assert_eq!(dir, ">>");
|
||||
assert!(slice.is_none(), "no slice size was written");
|
||||
assert_eq!(inner.len(), 2);
|
||||
@@ -287,10 +291,28 @@ fn an_argument_carries_its_own_comments_and_the_call_carries_none() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() {
|
||||
// The stream expression's `with [range]` is still unsupported, and
|
||||
// still fails where it always did rather than being mis-read.
|
||||
assert!(parse_err("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n").contains("with"));
|
||||
fn a_with_that_opens_a_bracket_is_a_stream_range() {
|
||||
// The third postfix spelling of `with` (TODO §54.1): `[` after the
|
||||
// keyword is a stream expression's array range, not an array method's
|
||||
// iterator argument and not a `randomize` constraint block.
|
||||
let f = parse_ok("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n");
|
||||
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
|
||||
panic!("expected an initial block")
|
||||
};
|
||||
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
|
||||
let ExprKind::Stream { inner, .. } = &rhs.kind else { panic!("expected a stream") };
|
||||
let ExprKind::StreamWith { range, .. } = &inner[0].expr.kind else {
|
||||
panic!("expected a stream range, got {:?}", inner[0].expr.kind)
|
||||
};
|
||||
assert_eq!(range.op.as_deref(), Some(":"));
|
||||
assert!(range.lsb.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_with_that_opens_none_of_the_three_delimiters_is_not_a_postfix_segment() {
|
||||
// A bare `with name` is no postfix segment at all, and still fails where
|
||||
// it always did rather than being mis-read.
|
||||
assert!(parse_err("module m;\n initial x = a with b;\nendmodule\n").contains("with"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -338,18 +338,93 @@ fn a_clocking_block_parses_its_items() {
|
||||
assert_eq!(c.items.len(), 3);
|
||||
assert!(matches!(
|
||||
&c.items[0].kind,
|
||||
ClockingItemKind::Default { input: Some(i), output: Some(o) } if i == "#2" && o == "#4"
|
||||
ClockingItemKind::Default {
|
||||
input: Some(ClockingDefault {
|
||||
skew: ClockingSkew::Delay(ClockingDelay::Word { word: i, .. }), ..
|
||||
}),
|
||||
output: Some(ClockingDefault {
|
||||
skew: ClockingSkew::Delay(ClockingDelay::Word { word: o, .. }), ..
|
||||
}),
|
||||
} if i == "2" && o == "4"
|
||||
));
|
||||
assert!(matches!(
|
||||
&c.items[1].kind,
|
||||
ClockingItemKind::Signals { dir, skew: None, signals } if dir == "input" && signals.len() == 2
|
||||
ClockingItemKind::Signals { dir, skew: None, signals, .. }
|
||||
if dir == "input" && signals.len() == 2
|
||||
));
|
||||
assert!(matches!(
|
||||
&c.items[2].kind,
|
||||
ClockingItemKind::Signals { dir, skew: Some(s), .. } if dir == "output" && s == "negedge"
|
||||
ClockingItemKind::Signals {
|
||||
dir,
|
||||
skew: Some(ClockingSkew::Edge { word: s, delay: None, .. }),
|
||||
..
|
||||
} if dir == "output" && s == "negedge"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_skew_reads_a_delay_behind_its_edge() {
|
||||
// IEEE 1800-2017 14.3: `clocking_skew ::= edge_identifier [ delay_control ]
|
||||
// | delay_control`. The edge and the delay are one skew, not two.
|
||||
let f = parse_ok(
|
||||
"module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input posedge #1step a;\n input edge b;\n endclocking\nendmodule\n",
|
||||
);
|
||||
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
|
||||
let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") };
|
||||
assert!(matches!(
|
||||
&c.items[0].kind,
|
||||
ClockingItemKind::Default {
|
||||
input: Some(ClockingDefault {
|
||||
skew: ClockingSkew::Edge {
|
||||
word: i,
|
||||
delay: Some(ClockingDelay::Paren { .. }),
|
||||
..
|
||||
},
|
||||
..
|
||||
}),
|
||||
output: Some(ClockingDefault {
|
||||
skew: ClockingSkew::Edge {
|
||||
word: o,
|
||||
delay: Some(ClockingDelay::Word { word: d, .. }),
|
||||
..
|
||||
},
|
||||
..
|
||||
}),
|
||||
} if i == "negedge" && o == "posedge" && d == "5"
|
||||
));
|
||||
assert!(matches!(
|
||||
&c.items[1].kind,
|
||||
ClockingItemKind::Signals {
|
||||
skew: Some(ClockingSkew::Edge { delay: Some(ClockingDelay::Word { word, .. }), .. }),
|
||||
..
|
||||
} if word == "1step"
|
||||
));
|
||||
assert!(matches!(
|
||||
&c.items[2].kind,
|
||||
ClockingItemKind::Signals { skew: Some(ClockingSkew::Edge { word, delay: None, .. }), .. }
|
||||
if word == "edge"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode() {
|
||||
// Strict/tolerant parity: the shape is grammar, not recovery, so the
|
||||
// tolerant parser reads it with no diagnostic of its own.
|
||||
let src = "module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input edge /*c*/ #2 a;\n endclocking\nendmodule\n";
|
||||
let (f, diags) = parse_tolerant(tokenize(src).expect("lex error"), src);
|
||||
assert!(diags.is_empty(), "tolerant mode recovered from a legal skew: {diags:?}");
|
||||
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
|
||||
let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") };
|
||||
let ClockingItemKind::Signals {
|
||||
skew: Some(ClockingSkew::Edge { after_edge, delay, .. }), ..
|
||||
} = &c.items[1].kind
|
||||
else {
|
||||
panic!("expected an edge skew with a delay")
|
||||
};
|
||||
assert_eq!(texts(after_edge), ["/*c*/"], "the gap in front of the `#` is the edge's own");
|
||||
assert!(matches!(delay, Some(ClockingDelay::Word { word, .. }) if word == "2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_clocking_may_be_anonymous_or_body_less() {
|
||||
// corpus/ibex/dv/formal/check/top.sv:143, and IEEE 1800-2017 14.12.
|
||||
|
||||
@@ -134,13 +134,27 @@ impl<'a> Parser<'a> {
|
||||
/// writes no parens at all, which is what `has_parens` records.
|
||||
pub(super) fn parse_let(&mut self) -> PResult<LetDecl> {
|
||||
self.expect_kw("let")?;
|
||||
let after_kw = self.take_gap();
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
let has_parens = self.cur().is_sym("(");
|
||||
let ports = self.parse_tf_ports(false)?.args;
|
||||
let mut eq_comments = Box::new(BinaryComments::default());
|
||||
eq_comments.before = self.gap_before("=");
|
||||
self.expect_sym("=")?;
|
||||
eq_comments.after = self.take_gap();
|
||||
let value = self.parse_expr()?;
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
Ok(LetDecl { name, name_span, has_parens, ports, value })
|
||||
Ok(LetDecl {
|
||||
after_kw,
|
||||
name,
|
||||
name_span,
|
||||
has_parens,
|
||||
ports,
|
||||
eq_comments,
|
||||
value,
|
||||
before_semi,
|
||||
})
|
||||
}
|
||||
|
||||
/// The header a subroutine declaration and a `modport` method prototype
|
||||
|
||||
@@ -257,6 +257,7 @@ keywords![
|
||||
"pure",
|
||||
"extern",
|
||||
"rand",
|
||||
"randsequence",
|
||||
"randc",
|
||||
"local",
|
||||
"protected",
|
||||
|
||||
@@ -980,9 +980,36 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
|
||||
check_stmt(src, s, here);
|
||||
}
|
||||
}
|
||||
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here),
|
||||
StmtKind::ExprStmt(e) => check_expr(src, e, here),
|
||||
StmtKind::EventTrigger(t) => check_expr(src, &t.expr, here),
|
||||
StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here),
|
||||
StmtKind::Typedef(t) => check_typedef(src, t, here),
|
||||
StmtKind::RandSequence(r) => {
|
||||
for p in &r.productions {
|
||||
assert_inside(src, "production", p.span, here);
|
||||
check_name(src, "production name", &p.name, p.name_span, p.span);
|
||||
check_list(src, "production port", &p.args, p.span, |a| {
|
||||
assert_inside(src, "production port", a.span, p.span);
|
||||
check_name(src, "production port name", &a.name, a.name_span, a.span);
|
||||
});
|
||||
for alt in &p.alternatives {
|
||||
for item in &alt.items {
|
||||
check_prod_item(src, item, p.span);
|
||||
}
|
||||
if let Some(w) = &alt.weight {
|
||||
check_expr(src, &w.expr, p.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Let(l) => {
|
||||
check_name(src, "let name", &l.name, l.name_span, here);
|
||||
check_list(src, "let port", &l.ports, here, |a| {
|
||||
assert_inside(src, "let port", a.span, here);
|
||||
check_name(src, "let port name", &a.name, a.name_span, a.span);
|
||||
});
|
||||
check_expr(src, &l.value, here);
|
||||
}
|
||||
StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
StmtKind::Return { expr, .. } => check_opt_expr(src, expr.as_ref(), here),
|
||||
@@ -1126,6 +1153,50 @@ fn check_match_items(src: &str, items: &[MatchItem], parent: TextRange) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every span a `randsequence` item and the items nested in it carry.
|
||||
fn check_prod_item(src: &str, item: &ProdItem, parent: TextRange) {
|
||||
match item {
|
||||
ProdItem::Ref(r) => {
|
||||
check_name(src, "production reference", &r.name, r.name_span, parent);
|
||||
for a in &r.args {
|
||||
check_expr(src, &a.expr, parent);
|
||||
}
|
||||
}
|
||||
ProdItem::Block(b) => {
|
||||
for s in &b.stmts {
|
||||
check_stmt(src, s, parent);
|
||||
}
|
||||
}
|
||||
ProdItem::If { cond, then, els, .. } => {
|
||||
check_expr(src, cond, parent);
|
||||
check_prod_item(src, then, parent);
|
||||
if let Some(e) = els {
|
||||
check_prod_item(src, e, parent);
|
||||
}
|
||||
}
|
||||
ProdItem::Repeat { count, body, .. } => {
|
||||
check_expr(src, count, parent);
|
||||
check_prod_item(src, body, parent);
|
||||
}
|
||||
ProdItem::Case { expr, items, .. } => {
|
||||
check_expr(src, expr, parent);
|
||||
for arm in items {
|
||||
assert_inside(src, "randsequence case arm", arm.span, parent);
|
||||
for l in &arm.labels {
|
||||
check_expr(src, &l.expr, arm.span);
|
||||
}
|
||||
check_prod_item(src, &arm.item, arm.span);
|
||||
}
|
||||
}
|
||||
ProdItem::RandJoin { weight, items, .. } => {
|
||||
check_opt_expr(src, weight.as_ref(), parent);
|
||||
for i in items {
|
||||
check_prod_item(src, i, parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_opt_expr(src: &str, e: Option<&Expr>, parent: TextRange) {
|
||||
if let Some(e) = e {
|
||||
check_expr(src, e, parent);
|
||||
@@ -1148,6 +1219,11 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
|
||||
check_expr(src, base, here);
|
||||
check_expr(src, arg, here);
|
||||
}
|
||||
ExprKind::StreamWith { base, range } => {
|
||||
check_expr(src, base, here);
|
||||
check_expr(src, &range.msb, here);
|
||||
check_opt_expr(src, range.lsb.as_ref(), here);
|
||||
}
|
||||
ExprKind::WithConstraint { base, block, .. } => {
|
||||
check_expr(src, base, here);
|
||||
match &**block {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,929 @@
|
||||
//! 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;
|
||||
|
||||
use super::{Moving, Origin};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// 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 as one
|
||||
/// it *edits* at all: a source's own region, or the empty range that says
|
||||
/// "this one only receives". A file the move does not name — and a file it
|
||||
/// only copies out of, which it does not edit — has none, and keeps the
|
||||
/// per-file contract.
|
||||
pub(super) fn region_of(moving: &[Moving], i: usize) -> Option<TextRange> {
|
||||
moving
|
||||
.iter()
|
||||
.find(|moving| moving.file == i && moving.origin == Origin::Moved)
|
||||
.map(|moving| moving.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, a **copy** keeps
|
||||
/// them and lends them out, 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>,
|
||||
/// The files a move only copies out of: what a refusal calls each one, and
|
||||
/// the never-dropped pieces its region holds. They have no ledger — a copy
|
||||
/// is not edited, and [`super::verify_move`] refuses one that is.
|
||||
copied: Vec<(String, Tally)>,
|
||||
}
|
||||
|
||||
/// 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),
|
||||
});
|
||||
}
|
||||
|
||||
/// Take the pieces a move **copies** out of a file it does not edit: what
|
||||
/// that file's region holds, once, which is what the destinations between
|
||||
/// them may write.
|
||||
pub(super) fn copy(
|
||||
&mut self,
|
||||
where_: &str,
|
||||
text: &str,
|
||||
region: TextRange,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let Some(pieces) = pieces(text) else {
|
||||
return Err(format!(
|
||||
"{where_} does not lex, so {what} cannot say what it would copy out of it; no edits were made."
|
||||
));
|
||||
};
|
||||
let mut tally = Tally::new();
|
||||
tally_into(
|
||||
&mut tally,
|
||||
pieces.iter().filter(|(span, _)| within(region, *span)).map(|(_, piece)| piece),
|
||||
);
|
||||
self.copied.push((where_.to_string(), tally));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
for (_, tally) in &self.copied {
|
||||
for (key, n) in tally {
|
||||
*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> {
|
||||
let named = self.files.iter().filter(move |f| f.receives == receives);
|
||||
let copies = self.copied.iter().filter(|_| !receives);
|
||||
named.map(|f| f.where_.clone()).chain(copies.map(|(name, _)| name.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 carry 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}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,665 @@
|
||||
//! 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(t) => self.write(&t.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) => f(expr),
|
||||
StmtKind::EventTrigger(t) => f(&t.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,514 @@
|
||||
//! 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<check::Moving> = 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![
|
||||
check::Moving::source(here, region.span),
|
||||
check::Moving::destination(there),
|
||||
];
|
||||
}
|
||||
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(|moving| moving.file);
|
||||
|
||||
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
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Inline a module: replace `S u_S (...)` with what `S` is made of.
|
||||
//!
|
||||
//! The mirror of [`crate::extract_module`], and the mirror only up to a point.
|
||||
//! An extraction *moves* text out of one file and into another; an inline
|
||||
//! **copies** — `S`'s declaration is left exactly where it is, because
|
||||
//! everything else in the workspace still instantiates it — and deletes only
|
||||
//! the instantiation. So the file the user is in loses one item and gains
|
||||
//! `S`'s, with `S`'s port names replaced by the names connected to them and
|
||||
//! `S`'s parameters written out as `localparam`s.
|
||||
//!
|
||||
//! Three files, one question each:
|
||||
//!
|
||||
//! * `site` — *what is the cursor on?* The module `M`, the instantiation, and
|
||||
//! the connection shapes lucisv will not read a substitution out of.
|
||||
//! * `source` — *what is `S` made of?* Its ports, its parameters, the bytes of
|
||||
//! its body, and the constructs that do not mean the same thing copied into
|
||||
//! another module.
|
||||
//! * `render` — *what does lucisv write?* The substitution, the prefixing rule
|
||||
//! and the text.
|
||||
//!
|
||||
//! This file is the plan: the entry points, the workspace-wide refusals (a
|
||||
//! second declaration of `S`, a hierarchical reference to `u_S` from anywhere,
|
||||
//! a `timescale` that differs), the edit, and the verification. The
|
||||
//! verification is one [`check::verify_move`] naming `S`'s file as a file the
|
||||
//! edit **copies** out of ([`check::Moving::copy`]): the comments arriving in
|
||||
//! `M` are copies of pieces of a file that is not being edited, and that —
|
||||
//! bounded to `S`'s body and to one copy — is the whole of what the
|
||||
//! never-dropped ledger is asked to forgive. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
|
||||
mod render;
|
||||
mod site;
|
||||
mod source;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
|
||||
use crate::instantiate::module_definition;
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
use site::Site;
|
||||
use source::Source;
|
||||
|
||||
/// What the cheap gate found: an instantiation the cursor is on, and the units
|
||||
/// whose files the engine needs read.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct InlineSite {
|
||||
/// The module being instantiated — the one that would be inlined.
|
||||
pub module: String,
|
||||
/// The instance's own name.
|
||||
pub instance: String,
|
||||
/// Every unit whose declaration the engine will look up: the instantiated
|
||||
/// module and the module the cursor is in.
|
||||
pub units: Vec<String>,
|
||||
}
|
||||
|
||||
/// Whether the cursor is on an instantiation lucisv could inline, 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 [`crate::extract_site`] strikes, and for the same reason (a
|
||||
/// `textDocument/codeAction` arrives on every cursor move). `None` where there
|
||||
/// is no instantiation under the cursor, and `None` too where the
|
||||
/// instantiation's own shape already refuses — a `.*`, a positional list, an
|
||||
/// expression where a name belongs — since those are answerable without
|
||||
/// reading a single other file and an action that would only refuse is one
|
||||
/// nobody wants offered. Every refusal that needs `S`'s declaration is a
|
||||
/// sentence from the command instead.
|
||||
pub fn inline_site(text: &str, offset: u32) -> Option<InlineSite> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let site = Site::read(&tree, text, offset)?.ok()?;
|
||||
Some(InlineSite {
|
||||
units: vec![site.target.clone(), site.module.name.clone()],
|
||||
module: site.target.clone(),
|
||||
instance: site.instance.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The lightbulb's text, written here so every front end says the same thing.
|
||||
pub fn inline_title(module: &str) -> String {
|
||||
format!("lucisv: inline `{module}` here")
|
||||
}
|
||||
|
||||
/// Replace the instantiation under `offset` with the body of the module it
|
||||
/// instantiates.
|
||||
pub fn inline_module(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
let mut scope = Scope::build(files);
|
||||
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 = parsed(text, file)?;
|
||||
let Some(found) = Site::read(&tree, text, offset) else { return Err(NOTHING.to_string()) };
|
||||
let site = found?;
|
||||
|
||||
if let Some(attribute) = attribute_in(text, site.span) {
|
||||
return Err(format!(
|
||||
"the instantiation carries the attribute `{attribute}`, which says something about that instance and has nothing left to say once there is no instance; no edits were made."
|
||||
));
|
||||
}
|
||||
let there = declaring_file(&scope, here, &site)?;
|
||||
let Some(source_text) = scope.text(there) else { return Err(abandoned(&site)) };
|
||||
let source_path = scope.path(there).unwrap_or(Path::new("?")).to_path_buf();
|
||||
let source_tree = parsed(source_text, &source_path)?;
|
||||
let source = Source::read(&source_tree, source_text, scope.index(), &site.target)?;
|
||||
same_timescale(text, source_text, &site.target)?;
|
||||
no_hierarchy(&scope, &site)?;
|
||||
|
||||
let inlined = plan(&mut scope, here, there, &site, &source)?;
|
||||
let edits = vec![(here, vec![TextEdit { range: site.span, new_text: inlined.text.clone() }])];
|
||||
let what = format!("inlining `{}` into `{}`", site.target, site.module.name);
|
||||
let moving = [check::Moving::destination(here), check::Moving::copy(there, source.body)];
|
||||
check::verify_move(&mut scope, &edits, &[&site.module.name], &what, &moving)?;
|
||||
|
||||
Ok(RefactorEdit {
|
||||
edits: vec![(file.to_path_buf(), edits.into_iter().flat_map(|(_, e)| e).collect())],
|
||||
warnings: warnings(&site, &inlined),
|
||||
created: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Everything the substitution needs from both files, and the text it writes.
|
||||
fn plan(
|
||||
scope: &mut Scope<'_>,
|
||||
here: usize,
|
||||
there: usize,
|
||||
site: &Site<'_>,
|
||||
source: &Source,
|
||||
) -> Result<render::Inlined, String> {
|
||||
let taken: Vec<String> = {
|
||||
let Some(analysis) = scope.analysis(here) else { return Err(abandoned(site)) };
|
||||
analysis.semantics.symbols().iter().map(|symbol| symbol.name.clone()).collect()
|
||||
};
|
||||
let (Some(text), Some(source_text)) = (scope.text(here), scope.text(there)) else {
|
||||
return Err(abandoned(site));
|
||||
};
|
||||
let Some(analysis) = scope.analysis(there) else { return Err(abandoned(site)) };
|
||||
let carried = comments_in(text, site.span);
|
||||
let held = held_imports(text, site.module_span);
|
||||
render::inline(&render::Inputs {
|
||||
text: source_text,
|
||||
semantics: &analysis.semantics,
|
||||
source,
|
||||
site,
|
||||
taken: &taken,
|
||||
carried: &carried,
|
||||
held: &held,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the user is told about an inline that went through.
|
||||
fn warnings(site: &Site<'_>, inlined: &render::Inlined) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
match inlined.prefixed.split_first() {
|
||||
None => out.push(format!(
|
||||
"`{}` declares no name `{}` already spells, so its body was copied under its own names.",
|
||||
site.target, site.module.name
|
||||
)),
|
||||
Some((first, rest)) => out.push(format!(
|
||||
"`{}` already spells {}, so every name `{}` declares was written with `{}_` in front of it.",
|
||||
site.module.name,
|
||||
match rest.is_empty() {
|
||||
true => format!("`{first}`"),
|
||||
false => format!("`{first}` and {} more of `{}`'s names", rest.len(), site.target),
|
||||
},
|
||||
site.target,
|
||||
site.instance
|
||||
)),
|
||||
}
|
||||
for import in &inlined.imports {
|
||||
out.push(format!(
|
||||
"`{}` needs `{import}`, which `{}` did not write, so it was copied in above the body.",
|
||||
site.target, site.module.name
|
||||
));
|
||||
}
|
||||
out.push(format!(
|
||||
"`{}` is still declared where it was; nothing else that instantiates it was touched.",
|
||||
site.target
|
||||
));
|
||||
out
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the workspace-wide questions
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The one file that declares `S`, and the refusals for none and for two.
|
||||
///
|
||||
/// `S` is looked up exactly the way an instantiation skeleton looks it up, so
|
||||
/// "lucisv indexes no module named `S`" is one sentence in the codebase and
|
||||
/// not two. The one thing added here is that `S` may not live in `M`'s own
|
||||
/// file: the verifier's copy allowance is bound to a file the edit does *not*
|
||||
/// touch, and lucisv would rather refuse than widen it.
|
||||
fn declaring_file(scope: &Scope<'_>, here: usize, site: &Site<'_>) -> Result<usize, String> {
|
||||
let path = module_definition(scope.index(), &site.target)?;
|
||||
let Some(there) = scope.index_of(path) else {
|
||||
return Err(format!(
|
||||
"`{}` is declared in {}, which is not one of the files lucisv was given.",
|
||||
site.target,
|
||||
display(path)
|
||||
));
|
||||
};
|
||||
match there == here {
|
||||
true => Err(format!(
|
||||
"`{}` is declared in the same file it is instantiated in, and lucisv inlines a module written in a file of its own this round; no edits were made.",
|
||||
site.target
|
||||
)),
|
||||
false => Ok(there),
|
||||
}
|
||||
}
|
||||
|
||||
/// A `timescale` in force where `S` is written is not one `M`'s file inherits,
|
||||
/// and silently changing what a delay means is a change to what the design
|
||||
/// does.
|
||||
fn same_timescale(here: &str, there: &str, target: &str) -> Result<(), String> {
|
||||
let (mine, theirs) = (timescale(here), timescale(there));
|
||||
match mine == theirs {
|
||||
true => Ok(()),
|
||||
false => Err(format!(
|
||||
"`{target}` is compiled under `{}` and the file it would be inlined into under `{}`, and a `timescale` changes what every delay in the body means; no edits were made.",
|
||||
theirs.as_deref().unwrap_or("no `timescale"),
|
||||
mine.as_deref().unwrap_or("no `timescale")
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `` `timescale`` a file writes, whitespace collapsed.
|
||||
fn timescale(text: &str) -> Option<String> {
|
||||
let mut out = None;
|
||||
for line in text.lines().map(str::trim) {
|
||||
if line.starts_with("`timescale") {
|
||||
out = Some(line.split_whitespace().collect::<Vec<_>>().join(" "));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether anything in the workspace reaches into `u_S` through the design
|
||||
/// hierarchy — `u_S.state` in a testbench, `top.u_m.u_S.q` in an assertion.
|
||||
///
|
||||
/// Such a path names a scope that inlining dissolves, and no edit lucisv makes
|
||||
/// in `M` could keep it working. The test is lexical on purpose and errs
|
||||
/// towards refusing: an identifier spelling the instance's name with a `.` on
|
||||
/// either side of it, in any file the caller handed over. §49's hierarchical
|
||||
/// surface is what makes such a path resolvable at all; this is what says
|
||||
/// lucisv will not break one it can see.
|
||||
fn no_hierarchy(scope: &Scope<'_>, site: &Site<'_>) -> Result<(), String> {
|
||||
for i in 0..scope.len() {
|
||||
let (Some(text), Some(path)) = (scope.text(i), scope.path(i)) else { continue };
|
||||
if !contains_word(text, &site.instance) {
|
||||
continue;
|
||||
}
|
||||
let Ok(tokens) = tokenize(text) else { continue };
|
||||
for (n, token) in tokens.iter().enumerate() {
|
||||
if token.kind != TokenKind::Ident || token.text != site.instance {
|
||||
continue;
|
||||
}
|
||||
let spells = |at: usize, what: &str| {
|
||||
tokens.get(at).is_some_and(|t: &vlog_parser::token::Token| t.text == what)
|
||||
};
|
||||
// A `.` on either side is a path walking through the instance; a
|
||||
// `bind` in front of it names the instance as a scope of its own,
|
||||
// which is the same scope and disappears the same way.
|
||||
let named =
|
||||
spells(n + 1, ".") || (n > 0 && (spells(n - 1, ".") || spells(n - 1, "bind")));
|
||||
if named {
|
||||
return Err(format!(
|
||||
"`{}` is named as a scope of the design hierarchy in {}, and inlining it dissolves the scope that path walks through; no edits were made.",
|
||||
site.instance,
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// odds and ends
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn parsed(text: &str, path: &Path) -> Result<vlog_parser::ast::SourceFile, String> {
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
match diagnostics.first() {
|
||||
None => Ok(tree),
|
||||
Some(problem) => Err(format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not inline through it.",
|
||||
display(path),
|
||||
problem.message,
|
||||
problem.line
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The comments written inside the bytes the inline deletes — the notes on the
|
||||
/// connection list — which are written back above the body that replaces them.
|
||||
/// An attribute is refused rather than moved: `(* keep *)` on an instantiation
|
||||
/// says something about *that instance*, and there is no instance left.
|
||||
fn comments_in(text: &str, span: TextRange) -> Vec<String> {
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for token in &tokens {
|
||||
for comment in token.leading.iter().chain(token.trailing.as_ref()) {
|
||||
if span.start <= comment.span.start && comment.span.end <= span.end {
|
||||
out.push(comment.text.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the deleted bytes carry an attribute instance, which lucisv will
|
||||
/// not re-attach to anything.
|
||||
fn attribute_in(text: &str, span: TextRange) -> Option<String> {
|
||||
let tokens = tokenize(text).ok()?;
|
||||
tokens
|
||||
.iter()
|
||||
.find(|token| {
|
||||
token.kind == TokenKind::Attribute
|
||||
&& span.start <= token.span.start
|
||||
&& token.span.end <= span.end
|
||||
})
|
||||
.map(|token| token.text.clone())
|
||||
}
|
||||
|
||||
/// The package paths `M` already imports — its header's and its body's — in
|
||||
/// the same spelling [`source`] gives `S`'s, so the comparison is per path
|
||||
/// rather than per statement.
|
||||
fn held_imports(text: &str, module: TextRange) -> Vec<String> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let mut out = Vec::new();
|
||||
for item in &tree.items {
|
||||
let vlog_parser::ast::ItemKind::Module(declared) = &item.kind else { continue };
|
||||
if item.span != module {
|
||||
continue;
|
||||
}
|
||||
for import in &declared.imports {
|
||||
out.extend(import.paths.iter().map(|path| path.text()));
|
||||
}
|
||||
for item in &declared.items {
|
||||
if let vlog_parser::ast::ItemKind::Import(paths) = &item.kind {
|
||||
out.extend(paths.iter().map(|path| path.text()));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn not_in_scope(file: &Path) -> String {
|
||||
format!("{} is not one of the files lucisv was given.", display(file))
|
||||
}
|
||||
|
||||
/// The sentence for a file the engine could read a moment ago and cannot now —
|
||||
/// nothing a user can act on, but never a silent half-answer.
|
||||
fn abandoned(site: &Site<'_>) -> String {
|
||||
format!(
|
||||
"lucisv could not read one of the files inlining `{}` needs, so it made no edits.",
|
||||
site.target
|
||||
)
|
||||
}
|
||||
|
||||
const NOTHING: &str = "there is no module instantiation under the cursor to inline.";
|
||||
@@ -0,0 +1,419 @@
|
||||
//! What lucisv writes where the instantiation was.
|
||||
//!
|
||||
//! One substitution, applied to spans of `S`'s own text: every use of a port
|
||||
//! becomes the name (or the literal) connected to it, and every use of a name
|
||||
//! `S` declares for itself becomes that name, prefixed with the instance's —
|
||||
//! but only when something in `M` already spells it, because an inline that
|
||||
//! renames nothing is the one a reader can check by eye.
|
||||
//!
|
||||
//! The body is copied **verbatim** but for those name spans and the leading
|
||||
//! whitespace of its lines: a comment written in `S` arrives in `M` byte for
|
||||
//! byte, which is both what invariant 3 wants and what lets the verifier
|
||||
//! account for it as a copy rather than as an invention.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind};
|
||||
|
||||
use super::site::{Binding, Site, Value};
|
||||
use super::source::{Param, Source};
|
||||
|
||||
/// The text to write, and what the user is told about it.
|
||||
pub(super) struct Inlined {
|
||||
pub(super) text: String,
|
||||
/// The names of `S` that were prefixed, in declaration order. Empty when
|
||||
/// nothing in `M` collided and the body was copied under its own names.
|
||||
pub(super) prefixed: Vec<String>,
|
||||
/// The `import` statements written into `M` because it lacked them.
|
||||
pub(super) imports: Vec<String>,
|
||||
}
|
||||
|
||||
/// Everything the substitution reads: `S`'s two layers, `M`'s side of the
|
||||
/// instantiation, and the names `M` already holds.
|
||||
pub(super) struct Inputs<'a> {
|
||||
pub(super) text: &'a str,
|
||||
pub(super) semantics: &'a Semantics,
|
||||
pub(super) source: &'a Source,
|
||||
pub(super) site: &'a Site<'a>,
|
||||
/// Every name declared in `M`'s file — the collision test, deliberately a
|
||||
/// superset of the module's own.
|
||||
pub(super) taken: &'a [String],
|
||||
/// The comments the deleted instantiation carried, which are written back
|
||||
/// above the body it becomes.
|
||||
pub(super) carried: &'a [String],
|
||||
/// The package paths `M` already imports.
|
||||
pub(super) held: &'a [String],
|
||||
}
|
||||
|
||||
/// Write the body of `S` as it reads inside `M`, or say why lucisv cannot.
|
||||
pub(super) fn inline(inputs: &Inputs<'_>) -> Result<Inlined, String> {
|
||||
let scope = inputs
|
||||
.semantics
|
||||
.instantiable_scope(&inputs.site.target)
|
||||
.ok_or_else(|| lost(&inputs.site.target))?;
|
||||
let mine: Vec<(SymbolId, &str, SymbolKind)> = inputs
|
||||
.semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, symbol)| symbol.scope == scope)
|
||||
.map(|(id, symbol)| (SymbolId(id as u32), symbol.name.as_str(), symbol.kind))
|
||||
.collect();
|
||||
let internal: Vec<(SymbolId, &str, SymbolKind)> =
|
||||
mine.iter().copied().filter(|(_, _, kind)| *kind != SymbolKind::Port).collect();
|
||||
let prefix = prefix(inputs, &internal)?;
|
||||
|
||||
let mut map: HashMap<SymbolId, String> = HashMap::new();
|
||||
for (id, name, kind) in &mine {
|
||||
let replacement = match kind {
|
||||
SymbolKind::Port => connected(inputs, name)?,
|
||||
_ => format!("{prefix}{name}"),
|
||||
};
|
||||
map.insert(*id, replacement);
|
||||
}
|
||||
let named: Vec<(&str, &String)> =
|
||||
mine.iter().filter_map(|(id, name, _)| Some((*name, map.get(id)?))).collect();
|
||||
let rewrite = Rewrite::read(inputs.semantics, &map, &inputs.source.shorthands, &named);
|
||||
let prefixed = match prefix.is_empty() {
|
||||
true => Vec::new(),
|
||||
false => internal.iter().map(|(_, name, _)| (*name).to_string()).collect(),
|
||||
};
|
||||
let imports: Vec<String> = inputs
|
||||
.source
|
||||
.imports
|
||||
.iter()
|
||||
.filter(|path| !inputs.held.contains(path))
|
||||
.map(|path| format!("import {path};"))
|
||||
.collect();
|
||||
Ok(Inlined { text: text(inputs, &rewrite, &prefix, &imports)?, prefixed, imports })
|
||||
}
|
||||
|
||||
/// The prefix every name `S` declares takes: nothing when `M` spells none of
|
||||
/// them, and `u_s_` when it spells any.
|
||||
fn prefix(
|
||||
inputs: &Inputs<'_>,
|
||||
internal: &[(SymbolId, &str, SymbolKind)],
|
||||
) -> Result<String, String> {
|
||||
let taken = |name: &str| inputs.taken.iter().any(|held| held == name);
|
||||
if !internal.iter().any(|(_, name, _)| taken(name)) {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let prefix = format!("{}_", inputs.site.instance);
|
||||
for (_, name, kind) in internal {
|
||||
if name.starts_with('\\') {
|
||||
return Err(format!(
|
||||
"`{}` also declares `{name}`, and `{name}` is an escaped identifier that lucisv cannot prefix its way out of; no edits were made.",
|
||||
inputs.site.module.name
|
||||
));
|
||||
}
|
||||
if labelled(*kind) {
|
||||
return Err(format!(
|
||||
"`{}` declares `{name}`, whose name `{}` would have to be prefixed to avoid a collision with `{}`'s own — and lucisv does not rewrite the `end … : {name}` label that goes with it; no edits were made.",
|
||||
inputs.site.target,
|
||||
what(*kind),
|
||||
inputs.site.module.name
|
||||
));
|
||||
}
|
||||
let renamed = format!("{prefix}{name}");
|
||||
if taken(&renamed) || internal.iter().any(|(_, other, _)| *other == renamed) {
|
||||
return Err(format!(
|
||||
"`{name}` collides with a name `{}` already holds, and so does `{renamed}`, which is what lucisv would have renamed it to; no edits were made.",
|
||||
inputs.site.module.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(prefix)
|
||||
}
|
||||
|
||||
/// Whether a declaration of this kind can carry an `end … : name` label, which
|
||||
/// lucisv does not rewrite and so will not prefix past.
|
||||
fn labelled(kind: SymbolKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
SymbolKind::Function
|
||||
| SymbolKind::Task
|
||||
| SymbolKind::Block
|
||||
| SymbolKind::Class
|
||||
| SymbolKind::Clocking
|
||||
| SymbolKind::Covergroup
|
||||
| SymbolKind::Property
|
||||
| SymbolKind::Sequence
|
||||
)
|
||||
}
|
||||
|
||||
fn what(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Function => "a function",
|
||||
SymbolKind::Task => "a task",
|
||||
SymbolKind::Block => "a named block",
|
||||
SymbolKind::Class => "a class",
|
||||
SymbolKind::Clocking => "a clocking block",
|
||||
SymbolKind::Covergroup => "a covergroup",
|
||||
SymbolKind::Property => "a property",
|
||||
_ => "a sequence",
|
||||
}
|
||||
}
|
||||
|
||||
/// What one port of `S` is replaced by, or the sentence for a connection
|
||||
/// lucisv will not substitute.
|
||||
fn connected(inputs: &Inputs<'_>, port: &str) -> Result<String, String> {
|
||||
let target = &inputs.site.target;
|
||||
let found: Option<&Binding> = inputs.site.bindings.iter().find(|b| b.port == port);
|
||||
let dir = inputs.source.ports.iter().find(|p| p.name == port).map_or("", |p| p.dir.as_str());
|
||||
let output = dir == "output";
|
||||
match found.map(|b| &b.value) {
|
||||
Some(Value::Name(name)) => Ok(name.clone()),
|
||||
Some(Value::Literal(written)) if !output => Ok(written.clone()),
|
||||
Some(Value::Literal(written)) => Err(format!(
|
||||
"`.{port}({written})` drives `{target}`'s output into a literal, which nothing can be assigned to; connect `.{port}` to a wire first."
|
||||
)),
|
||||
Some(Value::Unconnected) | None => Err(format!(
|
||||
"`.{port}` is left unconnected, and `{target}`'s body uses `{port}` as a name of its own; connect it to a wire first."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name span of `S` that the inline rewrites, and what it writes there.
|
||||
struct Rewrite {
|
||||
/// Sorted by start, non-overlapping.
|
||||
spans: Vec<(TextRange, String)>,
|
||||
}
|
||||
|
||||
impl Rewrite {
|
||||
/// The declarations of the names being prefixed, every reference that
|
||||
/// resolved to one of them or to a port, and every `.name` shorthand that
|
||||
/// has to be spelled out because the name it stands for is changing.
|
||||
fn read(
|
||||
semantics: &Semantics,
|
||||
map: &HashMap<SymbolId, String>,
|
||||
shorthands: &[(String, TextRange)],
|
||||
named: &[(&str, &String)],
|
||||
) -> Rewrite {
|
||||
let mut spans: Vec<(TextRange, String)> = Vec::new();
|
||||
for (id, symbol) in semantics.symbols().iter().enumerate() {
|
||||
let id = SymbolId(id as u32);
|
||||
if symbol.kind == SymbolKind::Port {
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = map.get(&id) {
|
||||
spans.push((symbol.name_span, text.clone()));
|
||||
}
|
||||
}
|
||||
for reference in semantics.references() {
|
||||
let Resolution::Resolved(id) = reference.resolution else { continue };
|
||||
if let Some(text) = map.get(&id) {
|
||||
spans.push((reference.name_span, text.clone()));
|
||||
}
|
||||
}
|
||||
// `.clk_i` becomes `.clk_i(clk)`: the *port*'s name stays exactly what
|
||||
// it was — it belongs to the module being instantiated, not to `S` —
|
||||
// and the signal it binds to is written out beside it. Any rewrite
|
||||
// that landed on the shorthand's own token is dropped first: rewriting
|
||||
// it would connect a different port.
|
||||
for (name, at) in shorthands {
|
||||
let Some((_, replacement)) = named.iter().find(|(held, _)| held == name) else {
|
||||
continue;
|
||||
};
|
||||
if *replacement == name {
|
||||
continue;
|
||||
}
|
||||
spans.retain(|(span, _)| span != at);
|
||||
let spacer = match crate::instantiate::ends_escaped(replacement) {
|
||||
true => " ",
|
||||
false => "",
|
||||
};
|
||||
spans.push((TextRange::empty(at.end), format!("({replacement}{spacer})")));
|
||||
}
|
||||
spans.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
spans.dedup_by_key(|(span, _)| *span);
|
||||
Rewrite { spans }
|
||||
}
|
||||
|
||||
/// `text`'s bytes over `span`, with every rewrite inside it applied.
|
||||
fn apply(&self, text: &str, span: TextRange) -> String {
|
||||
let mut out = String::new();
|
||||
let mut cursor = span.start;
|
||||
for (at, written) in &self.spans {
|
||||
if at.start < cursor || at.end > span.end {
|
||||
continue;
|
||||
}
|
||||
out.push_str(slice(text, TextRange::new(cursor, at.start)));
|
||||
out.push_str(written);
|
||||
cursor = at.end;
|
||||
}
|
||||
out.push_str(slice(text, TextRange::new(cursor, span.end)));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole replacement: the instantiation's own comments, the imports, the
|
||||
/// parameters as `localparam`s, and the body.
|
||||
fn text(
|
||||
inputs: &Inputs<'_>,
|
||||
rewrite: &Rewrite,
|
||||
prefix: &str,
|
||||
imports: &[String],
|
||||
) -> Result<String, String> {
|
||||
let mut lines: Vec<String> = inputs.carried.to_vec();
|
||||
lines.extend(imports.iter().cloned());
|
||||
for param in &inputs.source.params {
|
||||
lines.push(localparam(inputs, rewrite, prefix, param)?);
|
||||
}
|
||||
let indent = &inputs.site.indent;
|
||||
let mut out = lines.join(&format!("\n{indent}"));
|
||||
if inputs.source.body.is_empty() {
|
||||
return Ok(out);
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
out.push_str(indent);
|
||||
}
|
||||
out.push_str(&body(inputs, rewrite));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One parameter of `S` as the `localparam` that stands in its place: the
|
||||
/// override the instantiation wrote, or the default the header did.
|
||||
fn localparam(
|
||||
inputs: &Inputs<'_>,
|
||||
rewrite: &Rewrite,
|
||||
prefix: &str,
|
||||
param: &Param,
|
||||
) -> Result<String, String> {
|
||||
let name = format!("{prefix}{}", param.name);
|
||||
let ty = one_line(inputs, rewrite, param.ty, ¶m.name)?;
|
||||
let written = inputs.site.overrides.iter().find(|(over, _)| *over == param.name);
|
||||
let value = match written {
|
||||
Some(_) if param.local => {
|
||||
return Err(format!(
|
||||
"the instantiation overrides `{}`, which `{}` declares as a `localparam`; nothing was edited.",
|
||||
param.name, inputs.site.target
|
||||
))
|
||||
}
|
||||
Some((_, value)) => value.clone(),
|
||||
None => one_line(inputs, rewrite, param.default, ¶m.name)?,
|
||||
};
|
||||
if value.is_empty() {
|
||||
return Err(format!(
|
||||
"`{}` gives `{}` no default and the instantiation overrides nothing, so lucisv has no value to write for it.",
|
||||
inputs.site.target, param.name
|
||||
));
|
||||
}
|
||||
let ty = match ty.is_empty() {
|
||||
true => String::new(),
|
||||
false => format!("{ty} "),
|
||||
};
|
||||
Ok(format!("localparam {ty}{name} = {value};"))
|
||||
}
|
||||
|
||||
/// One header span — a parameter's type or its default — as a single line,
|
||||
/// with `S`'s own names substituted into it.
|
||||
fn one_line(
|
||||
inputs: &Inputs<'_>,
|
||||
rewrite: &Rewrite,
|
||||
span: TextRange,
|
||||
param: &str,
|
||||
) -> Result<String, String> {
|
||||
if span.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let raw = slice(inputs.text, span);
|
||||
if !plain(raw) {
|
||||
return Err(format!(
|
||||
"`{}` writes a comment inside the declaration of `{param}`, and lucisv would have to copy the comment into `{}` to write the `localparam`; no edits were made.",
|
||||
inputs.site.target, inputs.site.module.name
|
||||
));
|
||||
}
|
||||
let written = rewrite.apply(inputs.text, span);
|
||||
// The spaces *inside* a string literal are the literal's own, so a span
|
||||
// holding one is written as it stands rather than squeezed onto one line.
|
||||
match holds_a_string(&written) {
|
||||
true => Ok(written.trim().to_string()),
|
||||
false => Ok(written.split_whitespace().collect::<Vec<_>>().join(" ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a stretch of text is code and nothing else: no comment, no
|
||||
/// attribute. Both are pieces the verifier accounts for one by one, and
|
||||
/// lucisv writes neither out of a span it only means to read a type from.
|
||||
fn plain(text: &str) -> bool {
|
||||
let Ok(tokens) = tokenize(text) else { return false };
|
||||
tokens.iter().all(|token| {
|
||||
token.leading.is_empty() && token.trailing.is_none() && token.kind != TokenKind::Attribute
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a stretch of text holds a string literal, whose spaces are part of
|
||||
/// what it says.
|
||||
fn holds_a_string(text: &str) -> bool {
|
||||
let Ok(tokens) = tokenize(text) else { return true };
|
||||
tokens.iter().any(|token| token.kind == TokenKind::String)
|
||||
}
|
||||
|
||||
/// `S`'s body, substituted and re-indented to where it lands.
|
||||
fn body(inputs: &Inputs<'_>, rewrite: &Rewrite) -> String {
|
||||
let written = rewrite.apply(inputs.text, inputs.source.body);
|
||||
let from = indent_at(inputs.text, inputs.source.body.start);
|
||||
reindent(&written, &from, &inputs.site.indent, inputs.text, inputs.source.body)
|
||||
}
|
||||
|
||||
/// Move every line of a copied body from one indentation to another, leaving
|
||||
/// the lines that begin *inside* a comment or a string exactly as they are:
|
||||
/// those bytes are the piece's own text, and the verifier counts a comment by
|
||||
/// what it says.
|
||||
fn reindent(text: &str, from: &str, to: &str, source: &str, span: TextRange) -> String {
|
||||
if from == to {
|
||||
return text.to_string();
|
||||
}
|
||||
let inner = interiors(source, span);
|
||||
let mut out = String::new();
|
||||
let mut at = span.start;
|
||||
for (n, line) in text.split_inclusive('\n').enumerate() {
|
||||
let start = at;
|
||||
at += line.len() as u32;
|
||||
let interior = inner.iter().any(|piece| piece.start < start && start < piece.end);
|
||||
match n > 0 && !interior {
|
||||
true => out.push_str(&format!("{to}{}", line.strip_prefix(from).unwrap_or(line))),
|
||||
false => out.push_str(line),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The spans of the multi-line pieces inside `span`: block comments and string
|
||||
/// literals, whose own bytes no re-indentation may touch.
|
||||
fn interiors(text: &str, span: TextRange) -> Vec<TextRange> {
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for token in &tokens {
|
||||
for comment in token.leading.iter().chain(token.trailing.as_ref()) {
|
||||
out.push(comment.span);
|
||||
}
|
||||
if token.kind == TokenKind::String {
|
||||
out.push(token.span);
|
||||
}
|
||||
}
|
||||
out.retain(|piece| piece.start < span.end && span.start < piece.end);
|
||||
out
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
fn slice(text: &str, span: TextRange) -> &str {
|
||||
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
fn lost(name: &str) -> String {
|
||||
format!("lucisv lost track of `{name}`'s own scope, so it made no edits.")
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
//! What the cursor is standing on: the module `M`, the instantiation of `S`
|
||||
//! written directly in its body, and what each of that instantiation's
|
||||
//! connections binds to.
|
||||
//!
|
||||
//! Nothing here reads `S`. This is the half of the refusal list that can be
|
||||
//! answered from `M`'s own text — the shapes of a connection list lucisv will
|
||||
//! not read a substitution out of — so that the cheap gate behind the
|
||||
//! lightbulb and the engine ask exactly the same question.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
Connections, Expr, ExprKind, Instance, Instantiation, Item, ItemKind, ListElem, Module,
|
||||
SourceFile,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// What one connection binds a port to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) enum Value {
|
||||
/// A plain name written in `M`: `.a(sig)`, or the `.a` shorthand.
|
||||
Name(String),
|
||||
/// A literal: `.en(1'b1)`, `.name("x")`.
|
||||
Literal(String),
|
||||
/// `.a()` — written and left open.
|
||||
Unconnected,
|
||||
}
|
||||
|
||||
/// One entry of the connection list, by the port name it names.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct Binding {
|
||||
pub(super) port: String,
|
||||
pub(super) value: Value,
|
||||
}
|
||||
|
||||
/// The instantiation the cursor is on, and everything about it that does not
|
||||
/// need `S`'s declaration.
|
||||
pub(super) struct Site<'t> {
|
||||
/// The module the instantiation is written in.
|
||||
pub(super) module: &'t Module,
|
||||
/// Where that module is written, `module` keyword to `endmodule`.
|
||||
pub(super) module_span: TextRange,
|
||||
/// The instantiated module's name.
|
||||
pub(super) target: String,
|
||||
/// The instance's own name — the `u_s` of `sub u_s (...)`.
|
||||
pub(super) instance: String,
|
||||
/// The bytes the inline deletes: the instantiation item itself.
|
||||
pub(super) span: TextRange,
|
||||
/// The whitespace the instantiation's line begins with.
|
||||
pub(super) indent: String,
|
||||
/// The port connections, in the order the list writes them.
|
||||
pub(super) bindings: Vec<Binding>,
|
||||
/// The parameter overrides, in the order the list writes them.
|
||||
pub(super) overrides: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl<'t> Site<'t> {
|
||||
/// Read the instantiation under `offset`, or say why lucisv will not
|
||||
/// inline it. `None` where there is no instantiation at all — the cheap
|
||||
/// gate's answer for almost every cursor position.
|
||||
pub(super) fn read(
|
||||
tree: &'t SourceFile,
|
||||
text: &str,
|
||||
offset: u32,
|
||||
) -> Option<Result<Site<'t>, String>> {
|
||||
let (module, module_span) = module_at(&tree.items, offset)?;
|
||||
let item = module.items.iter().find(|item| covers(item, offset))?;
|
||||
let ItemKind::Instantiation(inst) = &item.kind else { return None };
|
||||
Some(Site::of(module, module_span, text, item, inst))
|
||||
}
|
||||
|
||||
fn of(
|
||||
module: &'t Module,
|
||||
module_span: TextRange,
|
||||
text: &str,
|
||||
item: &Item,
|
||||
inst: &Instantiation,
|
||||
) -> Result<Site<'t>, String> {
|
||||
if module.kw != "module" && module.kw != "macromodule" {
|
||||
return Err(format!(
|
||||
"the instantiation is written inside a `{}`, and lucisv inlines into a `module`; no edits were made.",
|
||||
module.kw
|
||||
));
|
||||
}
|
||||
let [instance] = inst.instances.as_slice() else {
|
||||
return Err(MANY_INSTANCES.to_string());
|
||||
};
|
||||
if !instance.dims.is_empty() {
|
||||
return Err(format!(
|
||||
"`{}` is an array of instances, which stands for as many copies of `{}` as its range has; lucisv inlines one instance.",
|
||||
instance.name, inst.module
|
||||
));
|
||||
}
|
||||
Ok(Site {
|
||||
module,
|
||||
module_span,
|
||||
target: inst.module.clone(),
|
||||
instance: instance.name.clone(),
|
||||
span: item.span,
|
||||
indent: indent_at(text, item.span.start),
|
||||
bindings: bindings(text, instance)?,
|
||||
overrides: overrides(text, inst)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The `module` whose body holds `offset`.
|
||||
fn module_at(items: &[Item], offset: u32) -> Option<(&Module, TextRange)> {
|
||||
for item in items {
|
||||
let ItemKind::Module(module) = &item.kind else { continue };
|
||||
if item.span.contains(offset) {
|
||||
return Some((module, item.span));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether an item is the one the cursor is on. The end offset counts: a
|
||||
/// cursor sitting just past the `;` is still on the statement it closes.
|
||||
fn covers(item: &Item, offset: u32) -> bool {
|
||||
item.span.contains(offset) || item.span.end == offset
|
||||
}
|
||||
|
||||
/// Every port connection, or the sentence for the shape lucisv will not read.
|
||||
fn bindings(text: &str, instance: &Instance) -> Result<Vec<Binding>, String> {
|
||||
let named = match &instance.conns {
|
||||
Connections::Named(list) => list,
|
||||
Connections::Ordered(list) if list.is_empty() => return Ok(Vec::new()),
|
||||
Connections::Ordered(_) => return Err(POSITIONAL.to_string()),
|
||||
};
|
||||
if !instance.conn_directives.is_empty() {
|
||||
return Err(DIRECTIVES.to_string());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for conn in named.iter().filter_map(ListElem::ok) {
|
||||
if conn.name == "*" {
|
||||
return Err(WILDCARD.to_string());
|
||||
}
|
||||
if conn.name.is_empty() {
|
||||
return Err(POSITIONAL.to_string());
|
||||
}
|
||||
let value = match &conn.expr {
|
||||
// `.clk` is the shorthand for `.clk(clk)`.
|
||||
None => Value::Name(conn.name.clone()),
|
||||
Some(expr) => value_of(text, &conn.name, expr)?,
|
||||
};
|
||||
out.push(Binding { port: conn.name.clone(), value });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every parameter override, as `(name, the text it is given)`.
|
||||
fn overrides(text: &str, inst: &Instantiation) -> Result<Vec<(String, String)>, String> {
|
||||
let Some(params) = &inst.params else { return Ok(Vec::new()) };
|
||||
if !inst.param_directives.is_empty() {
|
||||
return Err(DIRECTIVES.to_string());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for param in params.iter().filter_map(ListElem::ok) {
|
||||
if param.name == "*" || param.name.is_empty() {
|
||||
return Err(POSITIONAL_PARAMS.to_string());
|
||||
}
|
||||
let written = match ¶m.expr {
|
||||
None => param.name.clone(),
|
||||
Some(expr) => slice(text, expr.span).trim().to_string(),
|
||||
};
|
||||
if written.is_empty() {
|
||||
return Err(format!(
|
||||
"`.{}()` overrides `{}` with nothing at all; give it a value first.",
|
||||
param.name, param.name
|
||||
));
|
||||
}
|
||||
out.push((param.name.clone(), written));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What one connection's expression binds to: a plain name, a literal, or a
|
||||
/// refusal naming the expression the user has to give a name of its own.
|
||||
fn value_of(text: &str, port: &str, expr: &Expr) -> Result<Value, String> {
|
||||
let written = slice(text, expr.span).trim().to_string();
|
||||
match &expr.kind {
|
||||
ExprKind::Ident(_) => Ok(Value::Name(written)),
|
||||
ExprKind::Number(_) | ExprKind::Str(_) => Ok(Value::Literal(written)),
|
||||
ExprKind::Empty(_) => Ok(Value::Unconnected),
|
||||
// Everything else — a slice, a concatenation, an arithmetic
|
||||
// expression — is a value the port's name stands for inside the
|
||||
// module, and writing it wherever that name is read would both
|
||||
// duplicate it and change what a left-hand side means.
|
||||
_ => Err(format!(
|
||||
"`.{port}({written})` connects a port to an expression rather than to a name, and lucisv substitutes the connected name wherever the port is used; connect `.{port}({written})` to a named wire first."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
fn slice(text: &str, span: TextRange) -> &str {
|
||||
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
const MANY_INSTANCES: &str =
|
||||
"the instantiation declares more than one instance, and each of them is a copy of the module's body; lucisv inlines one instance at a time.";
|
||||
const POSITIONAL: &str =
|
||||
"the instantiation connects its ports by position, so lucisv cannot tell which port each expression is for; convert to named connections first.";
|
||||
const POSITIONAL_PARAMS: &str =
|
||||
"the instantiation overrides its parameters by position, so lucisv cannot tell which parameter each value is for; convert to named connections first.";
|
||||
const WILDCARD: &str =
|
||||
"the instantiation connects its ports with `.*`, which names no port at all; expand `.*` first (lucisv: expand `.*`).";
|
||||
const DIRECTIVES: &str =
|
||||
"the instantiation's list carries compiler directives, and lucisv does not evaluate one, so it cannot tell which connections are really written.";
|
||||
@@ -0,0 +1,322 @@
|
||||
//! What `S` is made of, and the shapes of `S` lucisv will not copy into
|
||||
//! another module.
|
||||
//!
|
||||
//! An inline copies `S`'s body into `M` and substitutes names into it, so the
|
||||
//! refusals here are all one question asked of different constructs: *would
|
||||
//! this piece still mean the same thing written inside `M`?* A `generate`
|
||||
//! block's names are reachable through the hierarchy, an `initial` block's
|
||||
//! meaning depends on when it runs, a macro's body is text lucisv never read,
|
||||
//! and an `inout` port is a name whose direction the substitution cannot
|
||||
//! honour. Each is a sentence rather than a guess.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
AnsiPort, Connections, Item, ItemKind, ListElem, Module, ParamPort, PortList, SourceFile,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// One port of `S`, in declaration order.
|
||||
pub(super) struct Port {
|
||||
pub(super) name: String,
|
||||
/// `input`, `output`, or empty when the header writes none.
|
||||
pub(super) dir: String,
|
||||
}
|
||||
|
||||
/// One entry of `S`'s parameter port list, in declaration order.
|
||||
pub(super) struct Param {
|
||||
pub(super) name: String,
|
||||
/// Whatever the declaration writes between its keyword and its name
|
||||
/// (`int`, `type`, `logic [3:0]`), inherited from the entry before it when
|
||||
/// this one writes none. A span rather than text: the type may name
|
||||
/// another parameter, and every name inside it is substituted the way the
|
||||
/// body's are.
|
||||
pub(super) ty: TextRange,
|
||||
/// The default value as the header writes it; empty when it writes none.
|
||||
pub(super) default: TextRange,
|
||||
/// True for a header `localparam`, which an instantiation may not
|
||||
/// override.
|
||||
pub(super) local: bool,
|
||||
}
|
||||
|
||||
/// `S`, read.
|
||||
pub(super) struct Source {
|
||||
pub(super) ports: Vec<Port>,
|
||||
pub(super) params: Vec<Param>,
|
||||
/// The bytes the inline copies: `S`'s items and the comments written
|
||||
/// among them. Empty for a module with an empty body.
|
||||
pub(super) body: TextRange,
|
||||
/// The package paths `S`'s header imports (`p::*`, `p::word_t`), one per
|
||||
/// path rather than one per statement — a header may write several paths
|
||||
/// in one `import`, and `M` may already have some of them.
|
||||
pub(super) imports: Vec<String>,
|
||||
/// Every `.name` shorthand `S`'s own body writes in an instantiation of
|
||||
/// its own — `.clk_i` standing for `.clk_i(clk_i)` — as the name and the
|
||||
/// bytes it occupies. The shorthand names a signal *and* a port with one
|
||||
/// token, so an inline that renames the signal has to spell it out; see
|
||||
/// [`shorthands`].
|
||||
pub(super) shorthands: Vec<(String, TextRange)>,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
/// Read `S` out of its own file, or say why lucisv will not inline it.
|
||||
pub(super) fn read(
|
||||
tree: &SourceFile,
|
||||
text: &str,
|
||||
index: &WorkspaceIndex,
|
||||
name: &str,
|
||||
) -> Result<Source, String> {
|
||||
let Some(module) = declaration(tree, name) else {
|
||||
return Err(format!(
|
||||
"the file that declared `{name}` no longer declares it, so lucisv cannot inline it."
|
||||
));
|
||||
};
|
||||
if module.kw != "module" && module.kw != "macromodule" {
|
||||
return Err(format!(
|
||||
"`{name}` is an `{}`, whose signals are its surface rather than a body lucisv can copy; no edits were made.",
|
||||
module.kw
|
||||
));
|
||||
}
|
||||
for item in &module.items {
|
||||
copyable(item, name)?;
|
||||
}
|
||||
Ok(Source {
|
||||
ports: ports(module, index, name)?,
|
||||
params: params(module, text),
|
||||
body: body(module),
|
||||
imports: imports(module),
|
||||
shorthands: shorthands(module, name)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The declaration of `name` in its own file.
|
||||
fn declaration<'t>(tree: &'t SourceFile, name: &str) -> Option<&'t Module> {
|
||||
tree.items.iter().find_map(|item| match &item.kind {
|
||||
ItemKind::Module(module) if module.name == name => Some(module),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The item kinds lucisv will not copy into another module's body.
|
||||
fn copyable(item: &Item, name: &str) -> Result<(), String> {
|
||||
let what = match &item.kind {
|
||||
ItemKind::Initial(_) => "an `initial` block",
|
||||
ItemKind::Final(_) => "a `final` block",
|
||||
ItemKind::MacroItem(_) => {
|
||||
return Err(format!(
|
||||
"`{name}` invokes a macro as one of its items, and lucisv does not expand macros, so it cannot tell what it would be copying."
|
||||
))
|
||||
}
|
||||
ItemKind::Directive(_) => {
|
||||
return Err(format!(
|
||||
"`{name}` writes a compiler directive among its items, and lucisv does not evaluate one, so it cannot tell what its body really is."
|
||||
))
|
||||
}
|
||||
ItemKind::GenerateRegion { .. }
|
||||
| ItemKind::GenIf(_)
|
||||
| ItemKind::GenFor(_)
|
||||
| ItemKind::GenCase(_)
|
||||
| ItemKind::GenBlock(_) => {
|
||||
return Err(format!(
|
||||
"`{name}` uses a `generate` construct, whose block names are reachable through the hierarchy (`u_{name}.gen.x`) and would become names of `M`'s own; lucisv will not inline it."
|
||||
))
|
||||
}
|
||||
ItemKind::Bind(_) => "a `bind` directive",
|
||||
ItemKind::Module(_) | ItemKind::Package { .. } => "a declaration of its own",
|
||||
ItemKind::Error(_) => {
|
||||
return Err(format!("part of `{name}` did not parse, so lucisv will not copy it."))
|
||||
}
|
||||
_ => return Ok(()),
|
||||
};
|
||||
Err(format!(
|
||||
"`{name}` holds {what}, which does not mean the same thing written inside another module; lucisv made no edits."
|
||||
))
|
||||
}
|
||||
|
||||
/// `S`'s ports, in declaration order, or the sentence for a port whose name
|
||||
/// lucisv cannot simply replace with the one connected to it.
|
||||
fn ports(module: &Module, index: &WorkspaceIndex, name: &str) -> Result<Vec<Port>, String> {
|
||||
let declared = match &module.ports {
|
||||
PortList::Ansi(declared) => declared,
|
||||
PortList::NonAnsi(_) => return Err(non_ansi(name)),
|
||||
PortList::Empty | PortList::None => return Ok(Vec::new()),
|
||||
};
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(format!(
|
||||
"`{name}`'s port list carries compiler directives, so which ports it really declares depends on the configuration; lucisv made no edits."
|
||||
));
|
||||
}
|
||||
let mut out: Vec<Port> = Vec::new();
|
||||
let mut dir = String::new();
|
||||
for port in declared.iter().filter_map(ListElem::ok) {
|
||||
if let Some(written) = &port.dir {
|
||||
dir = written.clone();
|
||||
}
|
||||
if port.name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
connectable(port, index, name, &dir)?;
|
||||
out.push(Port { name: port.name.clone(), dir: dir.clone() });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The three port shapes an inline refuses: an `inout`, an unpacked array, and
|
||||
/// an interface.
|
||||
fn connectable(
|
||||
port: &AnsiPort,
|
||||
index: &WorkspaceIndex,
|
||||
name: &str,
|
||||
dir: &str,
|
||||
) -> Result<(), String> {
|
||||
if dir == "inout" {
|
||||
return Err(format!(
|
||||
"`{name}`'s port `{}` is an `inout`, whose two directions lucisv cannot reproduce by substituting a name; no edits were made.",
|
||||
port.name
|
||||
));
|
||||
}
|
||||
if !port.unpacked.is_empty() {
|
||||
return Err(format!(
|
||||
"`{name}`'s port `{}` has an unpacked dimension, and a port array is not one name lucisv can substitute; no edits were made.",
|
||||
port.name
|
||||
));
|
||||
}
|
||||
// An interface port writes no direction and names an interface — or a
|
||||
// modport of one, which is a name with a `.` in it and never a data type.
|
||||
let written = port.ty.name.trim();
|
||||
let head = written.split('.').next().unwrap_or("");
|
||||
let interface = written.contains('.')
|
||||
|| index.units(head).iter().any(|def| def.kind == vlog_semantic::SymbolKind::Interface);
|
||||
match interface && dir.is_empty() {
|
||||
true => Err(format!(
|
||||
"`{name}`'s port `{}` is of interface type `{written}`, whose signals are named through the port rather than substituted for it; lucisv made no edits.",
|
||||
port.name
|
||||
)),
|
||||
false => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `S`'s parameter port list, in declaration order. A continuation entry
|
||||
/// (`#(parameter int A = 1, B = 2)`) inherits the keyword *and* the type of
|
||||
/// the entry before it, which is what the language says and what the
|
||||
/// `localparam` written in its place has to say too.
|
||||
fn params(module: &Module, text: &str) -> Vec<Param> {
|
||||
let Some(declared) = &module.param_ports else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let (mut kw, mut ty) = (String::new(), TextRange::empty(0));
|
||||
for param in declared.iter().filter_map(ListElem::ok) {
|
||||
if let Some(written) = ¶m.kw {
|
||||
kw = written.clone();
|
||||
ty = type_span(text, param);
|
||||
}
|
||||
if param.name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push(Param {
|
||||
name: param.name.clone(),
|
||||
ty,
|
||||
default: param.default.as_ref().map_or_else(|| TextRange::empty(0), |e| e.span),
|
||||
local: kw == "localparam",
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The bytes one parameter writes between its keyword and its name.
|
||||
fn type_span(text: &str, param: &ParamPort) -> TextRange {
|
||||
let head = TextRange::new(param.span.start, param.name_span.start);
|
||||
let written = slice(text, head);
|
||||
let keyword = ["parameter", "localparam"]
|
||||
.iter()
|
||||
.find_map(|kw| written.find(kw).map(|at| at + kw.len()))
|
||||
.unwrap_or(0);
|
||||
TextRange::new(head.start + keyword as u32, head.end)
|
||||
}
|
||||
|
||||
/// The bytes an inline copies: from the first thing written in `S`'s body — an
|
||||
/// item, its leading comment or its attribute — to the last.
|
||||
fn body(module: &Module) -> TextRange {
|
||||
let mut span: Option<TextRange> = None;
|
||||
let mut widen = |extent: TextRange| {
|
||||
span = Some(match span {
|
||||
None => extent,
|
||||
Some(so_far) => {
|
||||
TextRange::new(so_far.start.min(extent.start), so_far.end.max(extent.end))
|
||||
}
|
||||
});
|
||||
};
|
||||
for item in &module.items {
|
||||
widen(extent(item));
|
||||
}
|
||||
for comment in &module.dangling {
|
||||
widen(comment.span);
|
||||
}
|
||||
span.unwrap_or_else(|| TextRange::empty(0))
|
||||
}
|
||||
|
||||
/// The bytes one item owns: itself, its attributes and its own comments.
|
||||
fn extent(item: &Item) -> TextRange {
|
||||
let mut out = item.span;
|
||||
let comments = item
|
||||
.meta
|
||||
.leading
|
||||
.iter()
|
||||
.chain(&item.meta.before_sep)
|
||||
.chain(&item.meta.trailing)
|
||||
.map(|c| c.span)
|
||||
.chain(item.meta.attrs.iter().map(|a| a.span));
|
||||
for span in comments {
|
||||
out = TextRange::new(out.start.min(span.start), out.end.max(span.end));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every `.name` shorthand `S`'s body writes in an instantiation of its own,
|
||||
/// and the refusal for the `.*` that cannot be spelled out one name at a time.
|
||||
///
|
||||
/// This is the one place a name is written **once** and read **twice**:
|
||||
/// `.clk_i` names a port of the module being instantiated and, at the same
|
||||
/// token, the signal connected to it. Substituting a new signal name over it
|
||||
/// would silently reconnect a different port, and leaving it alone would bind
|
||||
/// a name `M` may not even declare — the trial's `counter` inside `cb_filter`
|
||||
/// is that bug caught (work log, 2026-09-06). So the shorthand is *expanded*
|
||||
/// (`.clk_i(clk)`) wherever the signal it names is one the inline renames, and
|
||||
/// a `.*`, which names every signal at once, is refused.
|
||||
fn shorthands(module: &Module, name: &str) -> Result<Vec<(String, TextRange)>, String> {
|
||||
let mut out = Vec::new();
|
||||
for item in &module.items {
|
||||
let ItemKind::Instantiation(inst) = &item.kind else { continue };
|
||||
let params = inst.params.iter().flatten();
|
||||
let conns = inst.instances.iter().flat_map(|instance| match &instance.conns {
|
||||
Connections::Named(list) => list.as_slice(),
|
||||
Connections::Ordered(_) => &[],
|
||||
});
|
||||
for conn in params.chain(conns).filter_map(ListElem::ok) {
|
||||
if conn.name == "*" {
|
||||
return Err(format!(
|
||||
"`{name}`'s body connects `{}`'s ports with `.*`, and inlining renames the signals those ports bind to; expand `.*` in `{name}` first (lucisv: expand `.*`).",
|
||||
inst.module
|
||||
));
|
||||
}
|
||||
if conn.expr.is_none() && !conn.name.is_empty() {
|
||||
out.push((conn.name.clone(), conn.name_span));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The package paths `S`'s header imports, one entry per path.
|
||||
fn imports(module: &Module) -> Vec<String> {
|
||||
module.imports.iter().flat_map(|import| import.paths.iter().map(|path| path.text())).collect()
|
||||
}
|
||||
|
||||
fn slice(text: &str, span: TextRange) -> &str {
|
||||
text.get(span.start as usize..span.end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
fn non_ansi(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` declares its ports in the Verilog-2001 style, with the directions written in its body; convert them to ANSI ports first (lucisv: convert to ANSI ports)."
|
||||
)
|
||||
}
|
||||
@@ -28,12 +28,20 @@
|
||||
//! spans instead of edits — see `docs/features/references-nav/README.md`.
|
||||
|
||||
mod check;
|
||||
mod extract;
|
||||
mod imports;
|
||||
mod inline;
|
||||
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 inline::{inline_module, inline_site, inline_title, InlineSite};
|
||||
pub use references::find_references;
|
||||
|
||||
pub use instantiate::{
|
||||
@@ -76,6 +84,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 {
|
||||
|
||||
@@ -428,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.
|
||||
|
||||
@@ -12,8 +12,8 @@ use std::time::Instant;
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, ListElem, PortList};
|
||||
use vlog_refactor::{
|
||||
add_port, convert_to_ansi, expand_wildcard, 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;
|
||||
|
||||
@@ -653,3 +653,531 @@ fn edited(text: &str, edits: &[vlog_refactor::TextEdit]) -> String {
|
||||
}
|
||||
copy
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// TODO §52 — organize imports
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The census the plan asks for: every scope in the corpus writing two or
|
||||
/// more `import` items, organized in a copy, with the counts reported.
|
||||
///
|
||||
/// Four properties per organized scope, and none of them a percentage. The
|
||||
/// result **parses** (no diagnostic the original did not have). It
|
||||
/// **formats**, and formatting it twice does not move it. Nothing in the file
|
||||
/// stops resolving — the count of references that resolve to *nothing at all*
|
||||
/// may not grow, which is the census-sized shadow of the resolution identity
|
||||
/// `verify_splice` already proved inside the engine. And organizing the result
|
||||
/// again finds nothing to do, which is idempotency.
|
||||
///
|
||||
/// A refusal is not a failure: it is the answer for a scope lucisv cannot
|
||||
/// judge, and the reasons are counted and printed so the ratio is visible.
|
||||
#[test]
|
||||
fn every_scope_with_two_imports_in_the_corpus_organizes_or_refuses() {
|
||||
let Some(files) = corpus() else { return };
|
||||
let sources = read(&files);
|
||||
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
|
||||
let config = vlog_formatter::Config::default();
|
||||
|
||||
let mut scopes = 0usize;
|
||||
let mut organized = 0usize;
|
||||
let mut removed_total = 0usize;
|
||||
let mut sorted_total = 0usize;
|
||||
let mut refusals: Vec<(&'static str, usize)> = Vec::new();
|
||||
let started = Instant::now();
|
||||
for (path, text) in &sources {
|
||||
for offset in import_run_offsets(text) {
|
||||
scopes += 1;
|
||||
match vlog_refactor::organize_counts(&sources, path, offset) {
|
||||
Err(said) => {
|
||||
let reason = refusal_kind(&said);
|
||||
match refusals.iter_mut().find(|(held, _)| *held == reason) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => refusals.push((reason, 1)),
|
||||
}
|
||||
}
|
||||
Ok((edit, removed, sorted)) => {
|
||||
organized += 1;
|
||||
removed_total += removed;
|
||||
sorted_total += sorted;
|
||||
let copy = edited(text, edit.edits_for(path));
|
||||
assert_ne!(
|
||||
©,
|
||||
text,
|
||||
"an organize that changed nothing in {}",
|
||||
path.display()
|
||||
);
|
||||
let before = vlog_parser::parse_source_tolerant(text).1.len();
|
||||
let after = vlog_parser::parse_source_tolerant(©).1.len();
|
||||
assert!(after <= before, "{} stopped parsing", path.display());
|
||||
assert!(
|
||||
unresolved(©) <= unresolved(text),
|
||||
"{} lost a resolution",
|
||||
path.display()
|
||||
);
|
||||
if let Ok(once) = vlog_formatter::format_source(text, &config) {
|
||||
let _ = once;
|
||||
let once =
|
||||
vlog_formatter::format_source(©, &config).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"the formatter refuses the organize of {}: {e}",
|
||||
path.display()
|
||||
)
|
||||
});
|
||||
let twice = vlog_formatter::format_source(&once, &config)
|
||||
.expect("formats a second time");
|
||||
assert_eq!(
|
||||
once,
|
||||
twice,
|
||||
"formatting {}'s organize diverges",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
// Idempotency: the same cursor, over the edited copy.
|
||||
let mut again = sources.clone();
|
||||
if let Some(entry) = again.iter_mut().find(|(p, _)| p == path) {
|
||||
entry.1 = copy.clone();
|
||||
}
|
||||
let repeat = vlog_refactor::organize_imports(&again, path, offset);
|
||||
assert!(repeat.is_err(), "{} organizes twice: {repeat:?}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
refusals.sort_by_key(|(reason, _)| *reason);
|
||||
println!(
|
||||
"corpus organize-imports: {scopes} scopes with 2+ imports, {organized} organized \
|
||||
({removed_total} imports removed, {sorted_total} sorted) in {:.2}s\n refused: {refusals:?}",
|
||||
started.elapsed().as_secs_f64()
|
||||
);
|
||||
assert_eq!(
|
||||
scopes,
|
||||
organized + refusals.iter().map(|(_, n)| n).sum::<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:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// §53.2 inline module
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The tree the inline trial runs over: `corpus/` by default, or whatever
|
||||
/// `LUCISV_INLINE_ROOT` names — a scratch copy of opentitan, for the trial the
|
||||
/// feature README records.
|
||||
fn inline_root() -> Option<Vec<PathBuf>> {
|
||||
let root = match std::env::var("LUCISV_INLINE_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)
|
||||
}
|
||||
|
||||
/// Every instantiation written directly in a module's body, as an offset an
|
||||
/// inline could be asked about.
|
||||
fn instantiations(text: &str) -> Vec<(String, String, 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 };
|
||||
for item in &module.items {
|
||||
if let ItemKind::Instantiation(inst) = &item.kind {
|
||||
out.push((module.name.clone(), inst.module.clone(), item.span.start));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Five real instantiations, inlined in memory: each result parses, formats,
|
||||
/// converges, and leaves the design's census of unbound names where it was.
|
||||
///
|
||||
/// With `LUCISV_INLINE_OUT` set, each case's two files are also written out
|
||||
/// twice — `case_N/before/` and `case_N/after/` — which is what the
|
||||
/// `lucisv check --select unused-signal,undriven-net` half of the trial reads.
|
||||
#[test]
|
||||
fn five_instantiations_of_real_rtl_inline_and_the_result_parses_formats_and_converges() {
|
||||
let Some(files) = inline_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 = census(&sources);
|
||||
let out_dir = std::env::var("LUCISV_INLINE_OUT").ok().map(PathBuf::from);
|
||||
|
||||
let started = Instant::now();
|
||||
let mut done: Vec<String> = Vec::new();
|
||||
let mut refusals = 0usize;
|
||||
'files: for (path, text) in &sources {
|
||||
for (host, target, at) in instantiations(text) {
|
||||
if done.len() == 5 {
|
||||
break 'files;
|
||||
}
|
||||
let edit = match vlog_refactor::inline_module(&sources, path, at) {
|
||||
Ok(edit) => edit,
|
||||
// Printed, not only counted: which instantiations the trial
|
||||
// refuses and why is the other half of a reproducible run.
|
||||
Err(said) => {
|
||||
refusals += 1;
|
||||
println!(" refused `{target}` in `{host}`: {said}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut after: Vec<(PathBuf, String)> = sources.clone();
|
||||
for (file, edits) in &edit.edits {
|
||||
let Some(slot) = after.iter_mut().find(|(held, _)| held == file) else {
|
||||
panic!("the inline edits {} which is not in scope", file.display())
|
||||
};
|
||||
let mut written = slot.1.clone();
|
||||
for one in edits.iter().rev() {
|
||||
written.replace_range(
|
||||
one.range.start as usize..one.range.end as usize,
|
||||
&one.new_text,
|
||||
);
|
||||
}
|
||||
slot.1 = written;
|
||||
}
|
||||
|
||||
let edited = &after.iter().find(|(held, _)| held == path).expect("edited").1;
|
||||
let (_, diagnostics) = vlog_parser::parse_source_tolerant(edited);
|
||||
assert!(
|
||||
diagnostics.is_empty(),
|
||||
"inlining `{target}` into `{host}` leaves {} unparseable: {diagnostics:?}\n{edited}",
|
||||
path.display()
|
||||
);
|
||||
let once = vlog_formatter::format_source(edited, &config)
|
||||
.unwrap_or_else(|e| panic!("the formatter refuses {}: {e}", path.display()));
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
||||
assert_eq!(once, twice, "{} does not converge", path.display());
|
||||
|
||||
// Written before the census is asserted, so a run that fails
|
||||
// leaves the pair on disk to look at.
|
||||
if let Some(dir) = &out_dir {
|
||||
write_case(dir, done.len(), path, &target, &sources, &after);
|
||||
}
|
||||
let now = census(&after);
|
||||
let gained = borne(&before, &now, path);
|
||||
println!(
|
||||
" inlined `{target}` into `{host}` ({}): {} name(s) newly unbound, all of them `{target}`'s own",
|
||||
path.display(),
|
||||
gained.len()
|
||||
);
|
||||
done.push(format!("{target} in {host}"));
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"inline over {} files: {} instantiations inlined, {} refused, in {:.2}s",
|
||||
sources.len(),
|
||||
done.len(),
|
||||
refusals,
|
||||
started.elapsed().as_secs_f64()
|
||||
);
|
||||
assert_eq!(done.len(), 5, "five real instantiations must inline: {done:?}");
|
||||
}
|
||||
|
||||
/// One trial case on disk: the instantiating file and the inlined module's
|
||||
/// own, before the inline and after it, so `lucisv check` can be run over
|
||||
/// each pair.
|
||||
fn write_case(
|
||||
dir: &Path,
|
||||
n: usize,
|
||||
host: &Path,
|
||||
target: &str,
|
||||
before: &[(PathBuf, String)],
|
||||
after: &[(PathBuf, String)],
|
||||
) {
|
||||
let declaring = before
|
||||
.iter()
|
||||
.find(|(path, text)| {
|
||||
path != host && text.contains(&format!("module {target}")) && {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
tree.items
|
||||
.iter()
|
||||
.any(|item| matches!(&item.kind, ItemKind::Module(m) if m.name == target))
|
||||
}
|
||||
})
|
||||
.map(|(path, _)| path.clone());
|
||||
for (label, sources) in [("before", before), ("after", after)] {
|
||||
let out = dir.join(format!("case_{n}")).join(label);
|
||||
if fs::create_dir_all(&out).is_err() {
|
||||
return;
|
||||
}
|
||||
for path in [Some(host.to_path_buf()), declaring.clone()].into_iter().flatten() {
|
||||
let Some((_, text)) = sources.iter().find(|(held, _)| *held == path) else { continue };
|
||||
let Some(name) = path.file_name() else { continue };
|
||||
let _ = fs::write(out.join(name), text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name a design fails to bind, per file, with its duplicates — the
|
||||
/// census an inline is held to.
|
||||
///
|
||||
/// An inline **copies**, so the whole-design count is the wrong number: a name
|
||||
/// `S` already could not resolve is one `M` now cannot resolve either, and the
|
||||
/// total legitimately grows by one per copy. What must hold instead is that
|
||||
/// every name the edited file newly fails to bind is one the *copied* module's
|
||||
/// own file already failed to bind — see [`borne`].
|
||||
fn census(sources: &[(PathBuf, String)]) -> Vec<(PathBuf, Vec<String>)> {
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut out = Vec::new();
|
||||
for (path, 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);
|
||||
let mut names = Vec::new();
|
||||
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(_))) {
|
||||
names.push(reference.name.clone());
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
out.push((path.clone(), names));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The names `edited` newly fails to bind, asserting on the way that no other
|
||||
/// file's census moved at all and that every new name is one some *other*
|
||||
/// file already could not bind — which for an inline is the file `S` was
|
||||
/// copied out of.
|
||||
fn borne(
|
||||
before: &[(PathBuf, Vec<String>)],
|
||||
after: &[(PathBuf, Vec<String>)],
|
||||
edited: &Path,
|
||||
) -> Vec<String> {
|
||||
let mut elsewhere: Vec<String> = Vec::new();
|
||||
let mut gained: Vec<String> = Vec::new();
|
||||
for (path, now) in after {
|
||||
let was = before
|
||||
.iter()
|
||||
.find(|(held, _)| held == path)
|
||||
.map_or_else(Vec::new, |(_, names)| names.clone());
|
||||
if path != edited {
|
||||
assert_eq!(&was, now, "{} was not edited, and its census moved", path.display());
|
||||
elsewhere.extend(now.iter().cloned());
|
||||
continue;
|
||||
}
|
||||
let mut left = was.clone();
|
||||
for name in now {
|
||||
match left.iter().position(|held| held == name) {
|
||||
Some(at) => {
|
||||
left.remove(at);
|
||||
}
|
||||
None => gained.push(name.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in &gained {
|
||||
assert!(
|
||||
elsewhere.contains(name),
|
||||
"`{name}` became unbound in {} and no other file leaves it unbound either",
|
||||
edited.display()
|
||||
);
|
||||
}
|
||||
gained
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
//! Inlining a module: the substitution, the prefixing rule, the refusals and
|
||||
//! the round trip with `extract_module`. See
|
||||
//! `docs/features/extract-inline-module/README.md`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{inline_module, inline_site, inline_title, RefactorEdit, TextEdit};
|
||||
|
||||
const M: &str = "/rtl/top.sv";
|
||||
const S: &str = "/rtl/sub.sv";
|
||||
|
||||
/// A two-port module, and a `top` that instantiates it.
|
||||
const SUB: &str = "\
|
||||
module sub (
|
||||
input logic a,
|
||||
input logic b,
|
||||
output logic q
|
||||
);
|
||||
logic s; // the and
|
||||
assign s = a & b;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const TOP: &str = "\
|
||||
module top (
|
||||
input logic x,
|
||||
input logic y,
|
||||
output logic z
|
||||
);
|
||||
sub u_sub (
|
||||
.a(x),
|
||||
.b(y),
|
||||
.q(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn files(top: &str, sub: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![(PathBuf::from(M), top.to_string()), (PathBuf::from(S), sub.to_string())]
|
||||
}
|
||||
|
||||
/// Inline the instantiation `top` writes, and return the edited `top`.
|
||||
fn inlined(top: &str, sub: &str) -> Result<String, String> {
|
||||
let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let edit = inline_module(&files(top, sub), Path::new(M), at)?;
|
||||
Ok(applied(top, &edit))
|
||||
}
|
||||
|
||||
fn applied(text: &str, edit: &RefactorEdit) -> String {
|
||||
let mut out = text.to_string();
|
||||
for TextEdit { range, new_text } in edit.edits_for(&PathBuf::from(M)).iter().rev() {
|
||||
out.replace_range(range.start as usize..range.end as usize, new_text);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn refusal(top: &str, sub: &str) -> String {
|
||||
inlined(top, sub).expect_err("a refusal")
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the substitution
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_two_port_module_is_inlined_with_its_ports_replaced_by_the_connected_names() {
|
||||
let out = inlined(TOP, SUB).expect("inlines");
|
||||
assert!(out.contains(" logic s; // the and\n"), "{out}");
|
||||
assert!(out.contains("assign s = x & y;"), "{out}");
|
||||
assert!(out.contains("assign z = s;"), "{out}");
|
||||
assert!(!out.contains("sub u_sub"), "the instantiation is gone: {out}");
|
||||
assert_eq!(out.matches("// the and").count(), 1, "the comment travels once: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_edit_touches_only_the_file_the_cursor_is_in() {
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let edit = inline_module(&files(TOP, SUB), Path::new(M), at).expect("inlines");
|
||||
assert_eq!(edit.file_count(), 1, "`sub.sv` is copied out of, never written to");
|
||||
assert_eq!(edit.edit_count(), 1, "one replacement");
|
||||
assert!(edit.created.is_empty());
|
||||
assert!(
|
||||
edit.warnings.iter().any(|w| w.contains("still declared where it was")),
|
||||
"{:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_literal_may_be_connected_to_an_input() {
|
||||
let top = TOP.replace(".b(y)", ".b(1'b1)");
|
||||
let out = inlined(&top, SUB).expect("inlines");
|
||||
assert!(out.contains("assign s = x & 1'b1;"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_implicit_dot_name_connection_is_read_as_the_name_it_stands_for() {
|
||||
let top = "\
|
||||
module top (
|
||||
input logic a,
|
||||
input logic b,
|
||||
output logic q
|
||||
);
|
||||
sub u_sub (.a, .b, .q);
|
||||
endmodule
|
||||
";
|
||||
let out = inlined(top, SUB).expect("inlines");
|
||||
assert!(out.contains("assign s = a & b;"), "{out}");
|
||||
assert!(out.contains("assign q = s;"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_written_inside_the_instantiation_is_written_back_above_the_body() {
|
||||
let top = TOP.replace(".a(x),", ".a(x), // the first");
|
||||
let out = inlined(&top, SUB).expect("inlines");
|
||||
assert_eq!(out.matches("// the first").count(), 1, "{out}");
|
||||
assert!(out.contains("// the first\n"), "{out}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// parameters
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const WIDE: &str = "\
|
||||
module wide #(
|
||||
parameter int W = 4
|
||||
) (
|
||||
input logic [W-1:0] a,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
logic [W-1:0] t;
|
||||
assign t = a;
|
||||
assign q = t;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const USES_WIDE: &str = "\
|
||||
module top (
|
||||
input logic [7:0] x,
|
||||
output logic [7:0] z
|
||||
);
|
||||
wide #(.W(8)) u_wide (
|
||||
.a(x),
|
||||
.q(z)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn wide_files() -> Vec<(PathBuf, String)> {
|
||||
vec![
|
||||
(PathBuf::from(M), USES_WIDE.to_string()),
|
||||
(PathBuf::from("/rtl/wide.sv"), WIDE.to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_becomes_a_localparam_holding_the_override() {
|
||||
let at = USES_WIDE.find("wide #(").expect("the instantiation") as u32 + 1;
|
||||
let edit = inline_module(&wide_files(), Path::new(M), at).expect("inlines");
|
||||
let out = applied(USES_WIDE, &edit);
|
||||
assert!(out.contains("localparam int W = 8;"), "{out}");
|
||||
assert!(out.contains("logic [W-1:0] t;"), "{out}");
|
||||
assert!(!out.contains("u_wide"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_with_no_override_keeps_its_default() {
|
||||
let top = USES_WIDE.replace("wide #(.W(8)) u_wide", "wide u_wide");
|
||||
let files =
|
||||
vec![(PathBuf::from(M), top.clone()), (PathBuf::from("/rtl/wide.sv"), WIDE.to_string())];
|
||||
let at = top.find("wide u_wide").expect("the instantiation") as u32 + 1;
|
||||
let out = applied(&top, &inline_module(&files, Path::new(M), at).expect("inlines"));
|
||||
assert!(out.contains("localparam int W = 4;"), "{out}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// prefixing
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_name_collision_prefixes_every_name_the_module_declares() {
|
||||
// `top` declares an `s` of its own, so `sub`'s `s` becomes `u_sub_s`.
|
||||
let top = TOP.replace(" sub u_sub (", " logic s;\n sub u_sub (");
|
||||
let edit = {
|
||||
let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
inline_module(&files(&top, SUB), Path::new(M), at).expect("inlines")
|
||||
};
|
||||
let out = applied(&top, &edit);
|
||||
assert!(out.contains("logic u_sub_s; // the and"), "{out}");
|
||||
assert!(out.contains("assign u_sub_s = x & y;"), "{out}");
|
||||
assert!(out.contains("assign z = u_sub_s;"), "{out}");
|
||||
assert!(
|
||||
edit.warnings.iter().any(|w| w.contains("`s`") && w.contains("u_sub_")),
|
||||
"the warning says which name collided: {:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_collision_means_no_prefix_and_the_warning_says_so() {
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let edit = inline_module(&files(TOP, SUB), Path::new(M), at).expect("inlines");
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("under its own names")), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// imports
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_import_the_instantiator_lacks_is_copied_in() {
|
||||
let pkg = "package p; typedef logic word_t; endpackage\n";
|
||||
let sub = "\
|
||||
module sub import p::*; (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
word_t s;
|
||||
assign s = a;
|
||||
assign q = s;
|
||||
endmodule
|
||||
";
|
||||
let top = "\
|
||||
module top (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
sub u_sub (.a(x), .q(z));
|
||||
endmodule
|
||||
";
|
||||
let files = vec![
|
||||
(PathBuf::from(M), top.to_string()),
|
||||
(PathBuf::from(S), sub.to_string()),
|
||||
(PathBuf::from("/rtl/p.sv"), pkg.to_string()),
|
||||
];
|
||||
let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let edit = inline_module(&files, Path::new(M), at).expect("inlines");
|
||||
let out = applied(top, &edit);
|
||||
assert!(out.contains("import p::*;"), "{out}");
|
||||
assert!(edit.warnings.iter().any(|w| w.contains("import p::*;")), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_expression_connection_is_refused() {
|
||||
let message = refusal(&TOP.replace(".a(x)", ".a(x & y)"), SUB);
|
||||
assert!(message.contains("connect `.a(x & y)` to a named wire first"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_connection_is_refused() {
|
||||
let top = TOP.replace(".a(x),\n .b(y),\n .q(z)", ".*");
|
||||
let message = refusal(&top, SUB);
|
||||
assert!(message.contains("expand `.*` first"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positional_connections_are_refused() {
|
||||
let top = TOP.replace(".a(x),\n .b(y),\n .q(z)", "x,\n y,\n z");
|
||||
let message = refusal(&top, SUB);
|
||||
assert!(message.contains("convert to named connections first"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unconnected_input_is_refused() {
|
||||
let message = refusal(&TOP.replace(".b(y)", ".b()"), SUB);
|
||||
assert!(message.contains("`.b` is left unconnected"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_connected_to_a_literal_is_refused() {
|
||||
let message = refusal(&TOP.replace(".q(z)", ".q(1'b0)"), SUB);
|
||||
assert!(message.contains("drives `sub`'s output into a literal"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_reference_to_the_instance_is_refused_and_names_the_file() {
|
||||
let top = TOP.replace("endmodule", " assign z = u_sub.s;\nendmodule");
|
||||
let message = refusal(&top, SUB);
|
||||
assert!(message.contains("named as a scope of the design hierarchy in top.sv"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_reference_from_another_file_is_refused_and_names_that_file() {
|
||||
let tb = "module tb;\n top u_top ();\n initial $display(u_top.u_sub.s);\nendmodule\n";
|
||||
let mut files = files(TOP, SUB);
|
||||
files.push((PathBuf::from("/rtl/tb.sv"), tb.to_string()));
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let message = inline_module(&files, Path::new(M), at).expect_err("a refusal");
|
||||
assert!(message.contains("tb.sv"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_naming_the_instance_is_refused() {
|
||||
let top =
|
||||
TOP.replace("endmodule", " bind u_sub sub u_check (.a(x), .b(y), .q(z));\nendmodule");
|
||||
let message = refusal(&top, SUB);
|
||||
assert!(message.contains("named as a scope of the design hierarchy"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_in_the_module_is_refused() {
|
||||
let sub = SUB.replace(
|
||||
" assign q = s;",
|
||||
" generate\n if (1) begin : g\n assign q = s;\n end\n endgenerate",
|
||||
);
|
||||
let message = refusal(TOP, &sub);
|
||||
assert!(message.contains("`generate`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_initial_block_in_the_module_is_refused() {
|
||||
let sub = SUB.replace(" assign q = s;", " assign q = s;\n initial $display(\"hi\");");
|
||||
let message = refusal(TOP, &sub);
|
||||
assert!(message.contains("`initial` block"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_item_in_the_module_is_refused() {
|
||||
let sub = SUB.replace(" assign q = s;", " assign q = s;\n `ASSERT(a, b)");
|
||||
let message = refusal(TOP, &sub);
|
||||
assert!(message.contains("macro"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conditional_directive_in_the_module_is_refused() {
|
||||
let sub = SUB.replace(" assign q = s;", "`ifdef X\n assign q = s;\n`endif");
|
||||
let message = refusal(TOP, &sub);
|
||||
assert!(message.contains("compiler directive"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inout_port_is_refused() {
|
||||
let sub = SUB.replace(" input logic b,", " inout logic b,");
|
||||
let message = refusal(TOP, &sub);
|
||||
assert!(message.contains("is an `inout`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unpacked_array_port_is_refused() {
|
||||
let sub = SUB.replace(" input logic b,", " input logic b [2],");
|
||||
let message = refusal(TOP, &sub);
|
||||
assert!(message.contains("unpacked dimension"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_port_is_refused() {
|
||||
let iface = "interface bus_if;\n logic v;\nendinterface\n";
|
||||
let sub = "\
|
||||
module sub (
|
||||
bus_if m,
|
||||
output logic q
|
||||
);
|
||||
assign q = 1'b0;
|
||||
endmodule
|
||||
";
|
||||
let top = "module top (output logic z);\n sub u_sub (.m(bus), .q(z));\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from(M), top.to_string()),
|
||||
(PathBuf::from(S), sub.to_string()),
|
||||
(PathBuf::from("/rtl/bus_if.sv"), iface.to_string()),
|
||||
];
|
||||
let at = top.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let message = inline_module(&files, Path::new(M), at).expect_err("a refusal");
|
||||
assert!(message.contains("interface type"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_refused() {
|
||||
let mut files = files(TOP, SUB);
|
||||
files.push((PathBuf::from("/rtl/other.sv"), SUB.to_string()));
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let message = inline_module(&files, Path::new(M), at).expect_err("a refusal");
|
||||
assert!(message.contains("more than one indexed file"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_workspace_does_not_declare_is_refused() {
|
||||
let files = vec![(PathBuf::from(M), TOP.to_string())];
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let message = inline_module(&files, Path::new(M), at).expect_err("a refusal");
|
||||
assert!(message.contains("indexes no module named `sub`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_in_the_same_file_is_refused() {
|
||||
let both = format!("{TOP}\n{SUB}");
|
||||
let files = vec![(PathBuf::from(M), both.clone())];
|
||||
let at = both.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let message = inline_module(&files, Path::new(M), at).expect_err("a refusal");
|
||||
assert!(message.contains("same file it is instantiated in"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_differing_timescale_is_refused() {
|
||||
let sub = format!("`timescale 1ps / 1ps\n{SUB}");
|
||||
let top = format!("`timescale 1ns / 1ps\n{TOP}");
|
||||
let message = refusal(&top, &sub);
|
||||
assert!(message.contains("`timescale"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_of_instances_is_refused() {
|
||||
let top = TOP.replace("sub u_sub (", "sub u_sub [1:0] (");
|
||||
let message = refusal(&top, SUB);
|
||||
assert!(message.contains("array of instances"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_name_a_prefix_cannot_resolve_is_refused() {
|
||||
let sub = SUB
|
||||
.replace("logic s; // the and", "logic \\s-1 ; // the and")
|
||||
.replace("assign s = a & b;", "assign \\s-1 = a & b;")
|
||||
.replace("assign q = s;", "assign q = \\s-1 ;");
|
||||
let top = TOP.replace(" sub u_sub (", " logic \\s-1 ;\n sub u_sub (");
|
||||
let message = refusal(&top, &sub);
|
||||
assert!(message.contains("escaped identifier"), "{message}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the cheap gate
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_site_gate_finds_the_instantiation_and_names_what_to_read() {
|
||||
let at = TOP.find("sub u_sub").expect("the instantiation") as u32 + 2;
|
||||
let site = inline_site(TOP, at).expect("a site");
|
||||
assert_eq!(site.module, "sub");
|
||||
assert_eq!(site.instance, "u_sub");
|
||||
assert_eq!(site.units, vec!["sub".to_string(), "top".to_string()]);
|
||||
assert_eq!(inline_title(&site.module), "lucisv: inline `sub` here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_site_gate_is_silent_where_there_is_no_instantiation() {
|
||||
let at = TOP.find("input logic x").expect("a port") as u32;
|
||||
assert_eq!(inline_site(TOP, at), None);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the round trip with §53.1
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn extracting_a_region_and_inlining_it_back_returns_the_original() {
|
||||
let source = "\
|
||||
module m (
|
||||
input logic a,
|
||||
input logic b,
|
||||
output logic q
|
||||
);
|
||||
logic s;
|
||||
assign s = a & b; // the and
|
||||
assign q = s | 1'b0;
|
||||
endmodule
|
||||
";
|
||||
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
|
||||
let start = source.find(" assign s = a & b;").expect("the region") as u32 + 2;
|
||||
let end = source.find("// the and").expect("the comment") as u32 + 10;
|
||||
let extracted = vlog_refactor::extract_module(
|
||||
&files,
|
||||
Path::new("/rtl/m.sv"),
|
||||
start,
|
||||
end,
|
||||
"sum",
|
||||
vlog_refactor::Home::NewFile,
|
||||
)
|
||||
.expect("extracts");
|
||||
let mut after: Vec<(PathBuf, String)> = files.clone();
|
||||
after.push((PathBuf::from("/rtl/sum.sv"), String::new()));
|
||||
for (path, edits) in &extracted.edits {
|
||||
let text = after.iter().find(|(held, _)| held == path).map(|(_, t)| t.clone());
|
||||
let mut text = text.unwrap_or_default();
|
||||
for TextEdit { range, new_text } in edits.iter().rev() {
|
||||
text.replace_range(range.start as usize..range.end as usize, new_text);
|
||||
}
|
||||
match after.iter_mut().find(|(held, _)| held == path) {
|
||||
Some(entry) => entry.1 = text,
|
||||
None => after.push((path.clone(), text)),
|
||||
}
|
||||
}
|
||||
let m = after.iter().find(|(p, _)| p == Path::new("/rtl/m.sv")).expect("m").1.clone();
|
||||
assert!(m.contains("sum u_sum ("), "the extraction really happened: {m}");
|
||||
|
||||
let at = m.find("sum u_sum").expect("the instantiation") as u32 + 2;
|
||||
let back = inline_module(&after, Path::new("/rtl/m.sv"), at).expect("inlines back");
|
||||
let mut round = m.clone();
|
||||
for TextEdit { range, new_text } in back.edits_for(&PathBuf::from("/rtl/m.sv")).iter().rev() {
|
||||
round.replace_range(range.start as usize..range.end as usize, new_text);
|
||||
}
|
||||
let config = vlog_formatter::Config::default();
|
||||
let formatted = |text: &str| vlog_formatter::format_source(text, &config).expect("formats");
|
||||
assert_eq!(
|
||||
formatted(&round),
|
||||
formatted(source),
|
||||
"extract then inline returns the original file modulo layout:\n{round}"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the `.name` shorthand inside `S`'s own body (work log, 2026-09-06)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A module whose body instantiates another with the `.name` shorthand — the
|
||||
/// shape the `common_cells` trial caught: `.q_o` names a port of `inner` *and*
|
||||
/// the signal `q_o` of `S`, with one token.
|
||||
const OUTER: &str = "\
|
||||
module outer (
|
||||
input logic clk_i,
|
||||
input logic d_i,
|
||||
output logic q_o
|
||||
);
|
||||
inner u_inner (
|
||||
.clk_i,
|
||||
.d_i,
|
||||
.q_o
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
const INNER: &str = "\
|
||||
module inner (
|
||||
input logic clk_i,
|
||||
input logic d_i,
|
||||
output logic q_o
|
||||
);
|
||||
assign q_o = d_i;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const USES_OUTER: &str = "\
|
||||
module top (
|
||||
input logic clk_i,
|
||||
input logic data,
|
||||
output logic result
|
||||
);
|
||||
outer u_outer (
|
||||
.clk_i(clk_i),
|
||||
.d_i(data),
|
||||
.q_o(result)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn shorthand_files(outer: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![
|
||||
(PathBuf::from(M), USES_OUTER.to_string()),
|
||||
(PathBuf::from("/rtl/outer.sv"), outer.to_string()),
|
||||
(PathBuf::from("/rtl/inner.sv"), INNER.to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_name_shorthand_in_the_body_is_spelled_out_when_the_name_it_stands_for_changes() {
|
||||
let at = USES_OUTER.find("outer u_outer").expect("the instantiation") as u32 + 2;
|
||||
let out = applied(
|
||||
USES_OUTER,
|
||||
&inline_module(&shorthand_files(OUTER), Path::new(M), at).expect("inlines"),
|
||||
);
|
||||
// The port's own name never moves — it belongs to `inner` — and the signal
|
||||
// it binds to is written out beside it.
|
||||
assert!(out.contains(".d_i(data)"), "{out}");
|
||||
assert!(out.contains(".q_o(result)"), "{out}");
|
||||
// `clk_i` is connected to a `clk_i`, so the shorthand still says what it
|
||||
// said and is left exactly as the author wrote it.
|
||||
assert!(out.contains(".clk_i,"), "{out}");
|
||||
assert!(!out.contains(".data("), "the port name is never rewritten: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_inside_the_inlined_body_is_refused() {
|
||||
let outer = OUTER.replace(".clk_i,\n .d_i,\n .q_o", ".*");
|
||||
let at = USES_OUTER.find("outer u_outer").expect("the instantiation") as u32 + 2;
|
||||
let message = inline_module(&shorthand_files(&outer), Path::new(M), at).expect_err("a refusal");
|
||||
assert!(message.contains("expand `.*` in `outer` first"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_parameter_keeps_the_spaces_inside_its_literal() {
|
||||
let sub = "\
|
||||
module sub #(
|
||||
parameter string NAME = \"a b\"
|
||||
) (
|
||||
input logic a,
|
||||
output logic q
|
||||
);
|
||||
assign q = a;
|
||||
endmodule
|
||||
";
|
||||
let top = "\
|
||||
module top (
|
||||
input logic x,
|
||||
output logic z
|
||||
);
|
||||
sub u_sub (.a(x), .q(z));
|
||||
endmodule
|
||||
";
|
||||
let out = inlined(top, sub).expect("inlines");
|
||||
assert!(out.contains("localparam string NAME = \"a b\";"), "{out}");
|
||||
}
|
||||
@@ -142,6 +142,15 @@ impl<'a> Binder<'a> {
|
||||
self.bind_expr(base, scope);
|
||||
self.bind_expr(arg, scope);
|
||||
}
|
||||
// `a with [i +: n]` — the base and both range operands are
|
||||
// ordinary uses, exactly as a part select's are.
|
||||
ExprKind::StreamWith { base, range } => {
|
||||
self.bind_expr(base, scope);
|
||||
self.bind_expr(&range.msb, scope);
|
||||
if let Some(lsb) = &range.lsb {
|
||||
self.bind_expr(lsb, scope);
|
||||
}
|
||||
}
|
||||
ExprKind::WithConstraint { base, block, .. } => {
|
||||
self.bind_with_constraint(base, block, scope)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,70 @@ use super::decl::param_kind;
|
||||
use super::{Binder, Target};
|
||||
|
||||
impl<'a> Binder<'a> {
|
||||
/// Everything a `randsequence` writes that this crate has an opinion
|
||||
/// about: each production's formals in a scope of its own, and every
|
||||
/// expression and statement written inside its alternatives.
|
||||
fn bind_rand_sequence(&mut self, r: &'a RandSequence, scope: ScopeId) {
|
||||
for p in &r.productions {
|
||||
if let Some(ty) = &p.ret_type {
|
||||
self.bind_data_type(ty, scope);
|
||||
}
|
||||
let inner = self.new_scope(ScopeKind::Function, scope, p.span);
|
||||
self.bind_tf_args(&p.args, inner);
|
||||
for alt in &p.alternatives {
|
||||
for item in &alt.items {
|
||||
self.bind_prod_item(item, inner);
|
||||
}
|
||||
if let Some(w) = &alt.weight {
|
||||
self.bind_expr(&w.expr, inner);
|
||||
if let Some(b) = &w.block {
|
||||
self.bind_stmts(&b.stmts, inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One production item, and the items nested inside it.
|
||||
fn bind_prod_item(&mut self, item: &'a ProdItem, scope: ScopeId) {
|
||||
match item {
|
||||
// The name is a production, which this crate does not declare; the
|
||||
// arguments are ordinary expressions.
|
||||
ProdItem::Ref(r) => {
|
||||
for a in &r.args {
|
||||
self.bind_expr(&a.expr, scope);
|
||||
}
|
||||
}
|
||||
ProdItem::Block(b) => self.bind_stmts(&b.stmts, scope),
|
||||
ProdItem::If { cond, then, els, .. } => {
|
||||
self.bind_expr(cond, scope);
|
||||
self.bind_prod_item(then, scope);
|
||||
if let Some(e) = els {
|
||||
self.bind_prod_item(e, scope);
|
||||
}
|
||||
}
|
||||
ProdItem::Repeat { count, body, .. } => {
|
||||
self.bind_expr(count, scope);
|
||||
self.bind_prod_item(body, scope);
|
||||
}
|
||||
ProdItem::Case { expr, items, .. } => {
|
||||
self.bind_expr(expr, scope);
|
||||
for arm in items {
|
||||
for l in &arm.labels {
|
||||
self.bind_expr(&l.expr, scope);
|
||||
}
|
||||
self.bind_prod_item(&arm.item, scope);
|
||||
}
|
||||
}
|
||||
ProdItem::RandJoin { weight, items, .. } => {
|
||||
self.bind_opt_expr(weight.as_ref(), scope);
|
||||
for i in items {
|
||||
self.bind_prod_item(i, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn bind_stmts(&mut self, stmts: &'a [Stmt], scope: ScopeId) {
|
||||
for s in stmts {
|
||||
self.bind_stmt(s, scope);
|
||||
@@ -133,12 +197,42 @@ impl<'a> Binder<'a> {
|
||||
self.bind_stmt(s, scope);
|
||||
}
|
||||
}
|
||||
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope),
|
||||
StmtKind::ExprStmt(e) => self.bind_expr(e, scope),
|
||||
// `->> @(posedge clk) e;` reads `clk` as ordinarily as `#d e;`
|
||||
// reads `d`, so the trigger's timing control goes through the same
|
||||
// helper every other statement's does.
|
||||
StmtKind::EventTrigger(t) => {
|
||||
if let Some(timing) = &t.timing {
|
||||
self.bind_timing(timing, scope);
|
||||
}
|
||||
self.bind_expr(&t.expr, scope);
|
||||
}
|
||||
StmtKind::VarDecl(d) => self.bind_data_decl(d, scope),
|
||||
// A block-scoped type binds exactly as an item-level one does; the
|
||||
// scope it lands in is the enclosing block's, which is what
|
||||
// IEEE 1800 §6.18 asks for.
|
||||
StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope),
|
||||
// A `randsequence` declares production names in a scope of its
|
||||
// own that nothing outside it can reach (IEEE 1800 §18.17), which
|
||||
// this crate does not model; what it does bind are the ordinary
|
||||
// expressions and statements written inside — the arguments, the
|
||||
// weights, and every code block's statements.
|
||||
StmtKind::RandSequence(r) => self.bind_rand_sequence(r, scope),
|
||||
// A block-scoped `let` binds exactly as an item-level one does: a
|
||||
// compile-time function whose ports are visible only inside its
|
||||
// own body expression.
|
||||
StmtKind::Let(l) => {
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&l.name,
|
||||
SymbolKind::Function,
|
||||
l.name_span,
|
||||
stmt.span,
|
||||
ScopeKind::Function,
|
||||
);
|
||||
self.bind_tf_args(&l.ports, inner);
|
||||
self.bind_expr(&l.value, inner);
|
||||
}
|
||||
StmtKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -878,3 +878,34 @@ endpackage
|
||||
assert_eq!(args, ["named"]);
|
||||
assert!(s.symbols().iter().all(|sym| !sym.name.is_empty()), "no symbol is nameless");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_event_triggers_timing_control_is_bound_like_any_other() {
|
||||
// TODO §54.1's `->>` may carry either half of a timing control, and both
|
||||
// halves read signals: `#d` reads `d`, `@(posedge clk iff en)` reads `clk`
|
||||
// and `en`. The bind arm hand-matched the delay and dropped the event
|
||||
// control, so a rename of `clk` missed this occurrence.
|
||||
let src = "\
|
||||
module m;
|
||||
event e;
|
||||
logic clk, en;
|
||||
int d;
|
||||
initial begin
|
||||
->> @(posedge clk iff en) e;
|
||||
->> #d e;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for (name, occurrence) in [("clk", "clk iff"), ("en", "en)"), ("d", "d e;")] {
|
||||
let r = s
|
||||
.reference_at(nth(src, occurrence, 0))
|
||||
.unwrap_or_else(|| panic!("no reference at the use of {name}"));
|
||||
assert_eq!(r.name, name);
|
||||
assert_eq!(r.resolved(), Some(symbol_id(&s, name)), "{name} resolves to its declaration");
|
||||
}
|
||||
// The triggered event itself is still a use of the `event`.
|
||||
// The first `e;` is the declaration; the second is the first trigger's.
|
||||
let e = s.reference_at(nth(src, "e;", 1)).expect("the triggered event");
|
||||
assert_eq!(e.resolved(), Some(symbol_id(&s, "e")));
|
||||
}
|
||||
+15
-11
@@ -1,6 +1,6 @@
|
||||
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
|
||||
|
||||
**Reading this report today (2026-09-05).** The survey below is a historical
|
||||
**Reading this report today (2026-09-07).** The survey below is a historical
|
||||
v0.21.0 measurement with later amendments, not a fresh list of current failures.
|
||||
Use [repository-analysis.md](repository-analysis.md) and [topo.md](topo.md) for
|
||||
current implementation status. Original probe counts remain historical.
|
||||
@@ -12,12 +12,16 @@ The prior audit's atomic-write, project lint-selection and directory-cycle
|
||||
findings are also fixed. Bare item-level `begin` blocks are recovered for
|
||||
lint/editor consumers; strict formatting still refuses them.
|
||||
|
||||
At committed `9ef1058`, type-name spans replace `vlog_semantic/src/scan.rs`,
|
||||
and package re-exports resolve through shared member edges (facts codec 18).
|
||||
Both are accepted for the next release. The active hierarchical-tail work
|
||||
proposes codec 19; QA is pending, and handshake 23 remains open. DPI-export
|
||||
name binding is a separate remaining gap (handshake 31), and generate-block
|
||||
hierarchy and cross-file macro expansion remain outside these fixes.
|
||||
Current snapshot **`df4e714`**, latest release **v0.49.0**: type-name spans,
|
||||
package re-exports and hierarchical tails shipped in v0.45.0 (facts codec
|
||||
**19**, handshake 23 closed). v0.46–0.49 added five refactorings, the
|
||||
`unused-import` rule (**74 rules** total), and the DUT hierarchy view. The
|
||||
L3 grammar forms, L6 real `randsequence` nodes, L9 ANSI conversion and L10
|
||||
optional UVM indentation are delivered, as annotated below. DPI-export name
|
||||
binding (handshake 31), generate-block hierarchy and cross-file macro expansion
|
||||
remain gaps. Refactor handshakes 32–33 and the newly reproduced UVM-option
|
||||
cache omission (34, fixed in 0.50.0 by TODO §59) are detailed in the current repository analysis. These
|
||||
status updates do not replace the original survey with a new corpus sweep.
|
||||
|
||||
What lucisv 0.21.0 does not yet handle, ranked by severity, from two
|
||||
independent sweeps crossed against each other:
|
||||
@@ -91,14 +95,14 @@ request.
|
||||
|---|---|---|
|
||||
| L1 | `expect (@(posedge clk) prop);` — parsed as a call, not a keyword. | Probe. |
|
||||
| L2 | Tagged unions (`union tagged`, `tagged Valid`, `case … matches`). | Probe. |
|
||||
| L3 | `randsequence` production bodies. | Probe; classes README ("building for a user that does not exist" — corpus 0). |
|
||||
| ~~L3~~ | ~~`randsequence` production bodies.~~ — **closed at 0.49.0 by TODO §54.2**: `randsequence` is a real statement (`ast::randsequence` — productions, weighted alternatives, `rand join`, `repeat`, `if`/`case`, code blocks parsed as statements); the LRM's own examples are `tests/cases/randsequence.cases`. Corpus and opentitan occurrences: 0. | Probe; classes README ("building for a user that does not exist" — corpus 0). |
|
||||
| L4 | `alias` statement. | Probe. |
|
||||
| L5 | `config … endconfig`, `library`. | Probe. |
|
||||
| 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. |
|
||||
| ~~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.~~ — **closed at 0.49.0 by TODO §54.1** (the net-delay clause by §43.2): `->>` with its optional delay or event control, stream `with [range]`, the other `casting_type`s, drive strength on a net declaration, `let` at statement position, `#(min:typ:max)` clocking skews; `tests/cases/coverage_gaps_l6.cases`; the RTL gap fuzzer at 499 gaps, zero failing. | 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. |
|
||||
| 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. |
|
||||
| ~~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).~~ — half **ruled already delivered** (a short, comment-free enum body one-lines since the body became a `Doc::Group`; pinned by `tests/format_options.rs`), half **delivered behind a key** at 0.49.0: `[format] uvm-utils-indent`, default off, 21 corpus files affected when on (TODO §54.3). | Probe observations. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,803 @@
|
||||
# coverage-gaps-l
|
||||
|
||||
## Goal
|
||||
|
||||
Close the three low-priority rows `docs/coverage_gaps.md` still leaves
|
||||
open — **L6** (six small language shapes the grammar never had), **L3**
|
||||
(`randsequence` production bodies) and **L10** (two cosmetics) — as TODO
|
||||
§54 plans them. None of the shapes occurs in the corpus or in opentitan,
|
||||
so the acceptance is hand-written `.cases` tables plus the existing
|
||||
fuzzers, and the byte-identity gates say the round changed nothing for
|
||||
anybody who did not ask for it.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **lucisv is not a legality checker.** Several arms read more than the
|
||||
LRM strictly allows and print back what was written rather than
|
||||
rejecting it: a `->` may carry the delay only `->>` may write; a cast
|
||||
base may be a type with packed dimensions, which §6.24.1's
|
||||
`casting_type` does not name; a drive strength keeps whichever order
|
||||
the source wrote its two keywords in. Every one of them is a shape
|
||||
real tools accept, and reproducing it is the invariant.
|
||||
- **`randsequence` production names are not symbols.** `vlog_semantic`
|
||||
binds the expressions, the formals and the statements written inside a
|
||||
`randsequence`, and declares nothing for the productions themselves:
|
||||
they live in a scope of their own that nothing outside the statement
|
||||
can name (§18.17), and no feature asks for them yet.
|
||||
- **A weight is not a general expression.** §18.17.2's
|
||||
`weight_specification` is a number, a scoped name or a *parenthesized*
|
||||
expression, and the parser reads exactly that (`parse_postfix`). It has
|
||||
to: an unparenthesized `|` separates alternatives, so a weight that
|
||||
swallowed one would eat the rest of the production.
|
||||
- **`:=` is two adjacent tokens.** The lexer has no `:=`; the weight
|
||||
operator is a `:` and an `=` whose spans touch, the same test
|
||||
`dist_weight_op` already makes for a constraint's `dist`.
|
||||
- **The `[format]` keys must never fire on their own.** A key that
|
||||
changes how an already-clean file is laid out defaults to off, and only
|
||||
a checked-in `lucisv.toml` (or a deliberate editor setting) turns it
|
||||
on. The byte-identity gate is what proves it.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser` → everyone.** `StmtKind::EventTrigger` now carries a
|
||||
`Box<EventTrigger>` rather than an `Expr` (arrow text, timing control,
|
||||
two comment slots); `StmtKind` gained `Let(Box<LetDecl>)` and
|
||||
`RandSequence(Box<RandSequence>)`; `ExprKind` gained
|
||||
`StreamWith { base, range }`; `ExprKind::Stream` gained
|
||||
`comments: Box<StreamComments>`; `DataDecl` gained
|
||||
`strength: Option<DriveStrength>`; `DriveStrength` gained
|
||||
`comments: Box<DriveStrengthComments>`; `LetDecl` gained `after_kw`,
|
||||
`eq_comments` and `before_semi`; the clocking grammar's skew became
|
||||
`ClockingSkew` — after the rework below, the LRM's own two alternatives,
|
||||
`Edge { word, after_edge, delay }` and `Delay(ClockingDelay)`, with the
|
||||
new `ClockingDelay` (`Word` / `Paren`) holding the `#` half — with
|
||||
`ClockingDefault` per half, and `ClockingDecl` / `ClockingItem` grew
|
||||
their own comment slots.
|
||||
Every downstream match arm in `vlog_formatter`, `vlog_semantic`,
|
||||
`vlog_linter`, `vlog_refactor` and `vlog_parser/tests/spans.rs` was
|
||||
updated in the same change.
|
||||
- **`vlog_formatter` → `lucisv`, `lucisv_server`.** `Config` gained
|
||||
`uvm_utils_indent: bool`, default `false`. `Config` is no longer
|
||||
exhaustively constructible without it — use `..Config::default()`.
|
||||
- **`lucisv_core` → `lucisv`, `lucisv_server`.** `FileConfig` gained
|
||||
`format_uvm_utils_indent: Option<bool>` and the parser gained the
|
||||
`[format]` table. Unknown keys under it are rejected by name, as
|
||||
everywhere else in this parser.
|
||||
- **`lucisv_server` → the extension.** `ClientSettings` gained
|
||||
`uvm_utils_indent: Option<bool>`, read from
|
||||
`lucisv.format.uvmUtilsIndent`; `editors/vscode/package.json` declares
|
||||
it, default `false`. `lucisv.toml` still outranks it, the ladder
|
||||
`format::settings_for` documents.
|
||||
- **The lexer's keyword table gained `randsequence`**, so
|
||||
`editors/vscode/syntaxes/systemverilog.tmLanguage.json` was regenerated
|
||||
to match (`lucisv_server`'s `the_grammars_keywords_are_exactly_the_lexers`
|
||||
is the gate).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 54.1 the six L6 shapes, each with cases + parity + fuzzers
|
||||
- [x] 54.2 `randsequence` as real nodes
|
||||
- [x] 54.3 the cosmetics behind a config key, corpus impact measured
|
||||
(one key, not two — see the ruling in the work log)
|
||||
- [x] Docs (this README; the strike text below is the lead's to apply)
|
||||
- [x] Gates (guarded)
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-06 — the state this lane was picked up in
|
||||
|
||||
The first dev agent stalled part-way through 54.1. What was in the tree,
|
||||
uncommitted, on `master` at `e1679be`:
|
||||
|
||||
- `->>` complete — lexer operator, `ast::EventTrigger` with `arrow`,
|
||||
`after_arrow`, `timing`, `before_event`, the parser arm, the formatter
|
||||
arm, and every downstream match updated.
|
||||
- Stream `with [range]` half done — `ExprKind::StreamWith`,
|
||||
`ast::StreamRange` and `parse_stream_range` written; **no** formatter
|
||||
arm, **no** semantic/spans arms, and `StreamRange` missing `Clone`, so
|
||||
`cargo check` failed with one error.
|
||||
- Cast bases — `is_cast_base` had gained its `ExprKind::Type(_)` arm.
|
||||
- Nothing at all for drive strength on a net declaration, `let` at
|
||||
statement position, the `#(min:typ:max)` clocking skew, `randsequence`
|
||||
or the cosmetics; no cases file, no fuzzer fixture, no README body.
|
||||
|
||||
The build was fixed first (`#[derive(Debug, Clone)]` on `StreamRange`,
|
||||
then the three missing match arms), and the lane continued from there.
|
||||
|
||||
### 2026-09-06 — 54.1, the six L6 shapes
|
||||
|
||||
1. **`->>`** — as the first agent left it, plus cases. `->` and `->>` are
|
||||
different statements, so the arrow is stored as written and never
|
||||
rewritten. Only `->>` may carry a delay or event control, but the node
|
||||
reads one either way.
|
||||
2. **Stream `with [range]`** — the formatter, binder and span arms it was
|
||||
missing. The gap after the keyword was moved out of the bracket's
|
||||
`before_open` into `WithComments::after_kw`, so all three postfix
|
||||
`with` forms print their head through the one `with_head` function.
|
||||
3. **Cast bases** — `(W+1)'(x)` and `4'(x)` already worked
|
||||
(`ExprKind::Paren` and `ExprKind::Number` were already cast bases);
|
||||
only `logic [3:0]'(x)` was missing, and that is the `ExprKind::Type(_)`
|
||||
arm the first agent added. Recorded as a case so the three stay tested
|
||||
together.
|
||||
4. **Drive strength on a net declaration** — `DataDecl::strength`, read
|
||||
only after a net keyword (the one position §6.6 allows), printed
|
||||
between the net keyword and the delay. `parse_opt_drive_strength`
|
||||
became `pub(super)` and grew five comment slots
|
||||
(`DriveStrengthComments`), which also **fixed a pre-existing hole**:
|
||||
`assign /*c*/ (weak0, pull1) x = y;` and
|
||||
`pullup ( /*c*/ weak1 ) p (x);` were refused by the safety net before
|
||||
this round and format now. `drive_strength` prints its own leading
|
||||
separator, the convention `net_delay` already uses.
|
||||
5. **`let` at statement position** — `StmtKind::Let(Box<LetDecl>)`,
|
||||
dispatched from `parse_keyword_stmt`, printed by the item-level
|
||||
`let_decl`, bound exactly as the item-level one is. `parse_let` reads
|
||||
its own `;`, so `takes_semi()` says the kind takes none. `LetDecl`
|
||||
also gained the comment slots its head never had.
|
||||
6. **`#(min:typ:max)` clocking skew** — `ClockingSkew` became a real
|
||||
enum: `Edge(String)` for `posedge`/`negedge`/`edge`, `Delay` for
|
||||
`#2`/`#1step`, `Paren` for `#( … )`, which goes through
|
||||
`parse_delay_value` and so inherits `MinTypMaxComments`' four slots.
|
||||
The one-token spellings are still text and still printed verbatim.
|
||||
|
||||
**`ast::size_pins` moved once, and the round put it back.** Adding
|
||||
`DataDecl::strength` took `StmtKind` from 392 to 480 bytes, because
|
||||
`DriveStrengthComments` is five vectors. Boxing them
|
||||
(`comments: Box<DriveStrengthComments>`, the treatment
|
||||
`MinTypMaxComments` already gets) brought it back under the pin, which is
|
||||
unchanged at 392/552/96. `EventTrigger`, `LetDecl` and `RandSequence` are
|
||||
boxed in `StmtKind` for the same reason and say so in their doc comments.
|
||||
|
||||
**The gap fuzzer.** Two fixtures were added to `RTL_FIXTURES` — one with
|
||||
all six shapes, one with a clocking block. Nineteen of their eighty gaps
|
||||
failed when they were written, **none of them because of the new
|
||||
shapes**: the `let` head, the two brace pairs of a streaming
|
||||
concatenation and the whole clocking grammar had no comment slots at all,
|
||||
and fail identically on a tree without this round
|
||||
(`let /*C*/ sum = a + b;` as an *item*, `{ /*C*/ <<{a}}`,
|
||||
`clocking /*C*/ cb`, all three reproduced against the tree as found).
|
||||
Every one of them was given an owner rather than being fixture-dodged:
|
||||
`LetDecl::{after_kw, eq_comments, before_semi}`, `StreamComments`
|
||||
(`after_open`, `before_inner`, `before_close`),
|
||||
`ClockingDecl::{after_kw, before_event, before_semi}`, `ClockingDefault`
|
||||
(`before_dir`, `after_dir`), `ClockingItem::before_semi`,
|
||||
`ClockingItemKind::Signals::{after_dir, after_skew}` and the skew's
|
||||
`after_hash`. `EXPECTED_RTL_GAPS` 419 → **499, zero failing**.
|
||||
|
||||
A code block's gap just inside its `{` deliberately has *no* slot: it
|
||||
belongs to the first statement's leading comments, exactly as a
|
||||
`begin`/`end` block's does. Giving it one made the output non-idempotent
|
||||
(the comment printed on its own line, then re-parsed as the statement's
|
||||
leading comment).
|
||||
|
||||
### 2026-09-06 — 54.2, `randsequence`
|
||||
|
||||
Checked first, as the TODO asks: `grep -rn randsequence crates/vlog_parser/src`
|
||||
found **nothing** — it was not an opaque `Verbatim` leaf, it was a parse
|
||||
error (`unsupported statement starting with keyword`), and `randsequence`
|
||||
was not even in the lexer's keyword table.
|
||||
|
||||
Modelled as real nodes in three new files — `ast/randsequence.rs`,
|
||||
`parser/randsequence.rs`, `format/randsequence.rs` — one sub-grammar per
|
||||
file, the way SVA and covergroups already are:
|
||||
|
||||
- `StmtKind::RandSequence(Box<RandSequence>)`; `RandSequence` holds the
|
||||
`( start )` with its three comment slots, the productions and the
|
||||
dangling comments before `endsequence`.
|
||||
- `Production { meta, ret_type, name, name_span, has_parens, args,
|
||||
before_colon, alternatives, before_semi, span }`. The return type is
|
||||
told from the name by lookahead: a type keyword, `void`, or two
|
||||
identifiers in a row.
|
||||
- `Alternative { before_bar, after_bar, items, before_weight, weight }`,
|
||||
with `Weight { after_op, expr, block }` for `:= n { … }`.
|
||||
- `ProdItem` = `Ref(ProdRef)` | `Block(CodeBlock)` | `If` | `Repeat` |
|
||||
`Case` | `RandJoin`, each with the slots its own keywords open. The
|
||||
`rs_case` arm reuses the `case` statement's `case_labels` printer,
|
||||
including the `default` whose `:` the LRM makes optional.
|
||||
- `CodeBlock` is `{ statements }` parsed by the ordinary statement
|
||||
grammar, so `break`, `return` and declarations inside one are the
|
||||
statements they already were.
|
||||
|
||||
**Layout.** One production per line inside the `randsequence` /
|
||||
`endsequence` pair. One alternative rides on the head's `:` line — the
|
||||
common shape, and a code block in it cuddles onto the `:` the way a
|
||||
`begin` cuddles onto an `if`. Several alternatives are one group: flat
|
||||
while they fit, otherwise one per line with each `|` starting its own,
|
||||
indented under the head. The `.cases` table pins both.
|
||||
|
||||
`randsequence` had to go into the lexer's keyword table, which made
|
||||
`editors/vscode/syntaxes/systemverilog.tmLanguage.json` drift; the
|
||||
alternation was regenerated in the same change (there is a test for it).
|
||||
|
||||
### 2026-09-06 — 54.3, the cosmetics — one key shipped, one gap already closed
|
||||
|
||||
**`enum-one-line`: no key shipped. The behaviour is already the
|
||||
default.** The TODO's own text hedges ("today it always breaks? Confirm
|
||||
with a case"), and the confirmation says it does not. Measured over every
|
||||
shape the gap names — a `typedef enum` with and without a base type, an
|
||||
anonymous enum in a variable declaration, each written broken across
|
||||
lines — the formatter already prints `typedef enum {A, B, C} e_t;` on one
|
||||
line, because the enum body is a `Doc::Group` like every other list; and
|
||||
a body with a comment in it still breaks, which is the condition the gap
|
||||
asks for. Corpus impact of the key as specified: **0 files**, because it
|
||||
would switch nothing. Shipping a config key that never changes a byte is
|
||||
the abstraction CLAUDE.md's "Simplicity first" says to stop building, so
|
||||
it was not shipped. `tests/format_options.rs` pins both directions of
|
||||
the existing behaviour instead, so nothing takes it away. **The lead's
|
||||
call at review** if a key is wanted anyway.
|
||||
|
||||
**`uvm-utils-indent`: shipped, default off.** A real gap — the
|
||||
`` `uvm_field_* `` macros between `` `uvm_object_utils_begin `` and
|
||||
`` `uvm_object_utils_end `` are plain macro items with no block, so they
|
||||
print in the `_begin`'s own column. The key is a targeted rule in
|
||||
`item_seq`: exactly those four macro names (`uvm_object_utils_begin`,
|
||||
`uvm_component_utils_begin` and their `_end`s) open and close one indent
|
||||
level over the run between them. An unbalanced `_begin` still prints
|
||||
everything it opened, one level in — lucisv reproduces the file it was
|
||||
given. It reaches the formatter three ways, in the ladder
|
||||
`format::settings_for` documents: `[format] uvm-utils-indent` in
|
||||
`lucisv.toml` (highest), `lucisv.format.uvmUtilsIndent` in the editor,
|
||||
and off otherwise. There is deliberately **no CLI flag**: a key that
|
||||
changes how clean files look is the project's decision, not a run's.
|
||||
|
||||
**Corpus impact, key ON** (scratch copy of the 860-file corpus with a
|
||||
`lucisv.toml` in every directory — the discovery walk stops at each
|
||||
vendored `.git`, so one at the root is not enough):
|
||||
|
||||
| | files |
|
||||
|---|---|
|
||||
| corpus files formatted | 854 (+6 that error, the known six) |
|
||||
| files whose output changes with the key on | **21** |
|
||||
| of those, not idempotent | 0 |
|
||||
| of those, comment lines lost | 0 |
|
||||
|
||||
The 21: `opentitan/hw/ip/uart/dv/env/uart_env_cfg.sv`;
|
||||
`ibex/dv/uvm/icache/dv/env/ibex_icache_env_cfg.sv`;
|
||||
`ibex/dv/uvm/icache/dv/ibex_icache_core_agent/{ibex_icache_core_req_item,
|
||||
ibex_icache_core_rsp_item, ibex_icache_core_bus_item}.sv`;
|
||||
`ibex/dv/uvm/icache/dv/ibex_icache_mem_agent/{ibex_icache_mem_req_item,
|
||||
ibex_icache_mem_resp_item, ibex_icache_mem_bus_item,
|
||||
ibex_icache_mem_model}.sv`;
|
||||
`ibex/dv/uvm/core_ibex/env/core_ibex_env_cfg.sv`;
|
||||
`ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/{ibex_mem_intf_response_agent_cfg,
|
||||
ibex_mem_intf_seq_item}.sv`;
|
||||
`ibex/dv/uvm/core_ibex/common/ibex_cosim_agent/{ibex_rvfi_seq_item,
|
||||
ibex_ifetch_seq_item, ibex_ifetch_pmp_seq_item, ibex_cosim_cfg}.sv`;
|
||||
`ibex/dv/uvm/core_ibex/common/irq_agent/irq_seq_item.sv`;
|
||||
`ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_agent_cfg.sv`;
|
||||
`ibex/vendor/google_riscv-dv/src/{riscv_pmp_cfg, riscv_instr_gen_config,
|
||||
riscv_vector_cfg}.sv`. Twenty-six corpus files write the macros; the
|
||||
other five have nothing between `_begin` and `_end` to indent.
|
||||
|
||||
With the key **off** — the shipped default — the corpus is byte-identical
|
||||
to 0.48.1 over all 860 files.
|
||||
|
||||
### The greps §54 asks for, per shape
|
||||
|
||||
Run 2026-09-06 over the 860-file corpus and over opentitan's
|
||||
`hw/` (2 553 SystemVerilog files):
|
||||
|
||||
| shape | corpus | opentitan |
|
||||
|---|---|---|
|
||||
| `->>` | 0 | 0 (one hit, in a Python script) |
|
||||
| `with [` (stream range) | 0 | 0 (23 hits, all Markdown prose) |
|
||||
| `(strength0, strength1)` on a net declaration | 0 | 0 |
|
||||
| `let` at statement position | 0 | 0 |
|
||||
| `#(min:typ:max)` clocking skew | 0 | 0 |
|
||||
| `randsequence` | 0 | 0 |
|
||||
|
||||
The two byte-identity gates are the second, stronger statement of the
|
||||
same thing: nothing in either tree formats differently because of this
|
||||
round.
|
||||
|
||||
### Attack tests (CLAUDE.md invariant 4)
|
||||
|
||||
`verify.rs` was **not touched** and no normalization was widened, so no
|
||||
new forgiveness needs defending. The pairs were written anyway, in
|
||||
`tests/verification.rs`, one per plausible way a new printer could have
|
||||
lost or rewritten something: `->` ⇄ `->>`, a dropped `->>` timing
|
||||
control, a stream range narrowed to an index or its `+:` swapped for
|
||||
`-:`, a dropped or reordered drive strength, `#(1:2:3)` rewritten as
|
||||
`#1`, a dropped `randsequence` production, a reordered alternative, a
|
||||
`|` turned into juxtaposition, a dropped `:=` weight, and a `let` losing
|
||||
its ports. All ten are refused. The eleventh asserts the other
|
||||
direction for `uvm-utils-indent`: moving leading whitespace is not a
|
||||
divergence, and dropping one of the macros it indents is.
|
||||
|
||||
### Files touched outside the expected set
|
||||
|
||||
- `crates/vlog_parser/src/token.rs` — `randsequence` added to the
|
||||
keyword table (54.2 needs it).
|
||||
- `editors/vscode/syntaxes/systemverilog.tmLanguage.json` — regenerated
|
||||
for that keyword; a workspace test fails otherwise.
|
||||
- `editors/vscode/package.json` — the `lucisv.format.uvmUtilsIndent`
|
||||
setting declaration.
|
||||
- `crates/vlog_parser/src/ast/expr.rs`, `parser/primary.rs`,
|
||||
`format/expr.rs` — `StreamComments`, a gap-fuzzer finding, not a shape
|
||||
§54 names.
|
||||
- `crates/vlog_parser/src/ast/decl.rs`, `parser/tf.rs`,
|
||||
`format/routine.rs` — `LetDecl`'s comment slots, likewise.
|
||||
- `crates/vlog_formatter/src/format/instance.rs`, `format/item.rs`,
|
||||
`format/decl.rs` — `DriveStrengthComments` reaches the two constructs
|
||||
that already wrote a strength, so those printers moved from `String` to
|
||||
`Doc`.
|
||||
|
||||
### 2026-09-07 — Rework, the four QA findings
|
||||
|
||||
**HIGH 1 — `edge_identifier [delay_control]`.** `ClockingSkew` was three
|
||||
mutually exclusive variants, so `input negedge #(1:2:3) c;` was a parse
|
||||
error. It is now the LRM's own two alternatives — `Edge { word,
|
||||
after_edge, delay: Option<ClockingDelay> }` and `Delay(ClockingDelay)` —
|
||||
with the `#` half factored into `ClockingDelay` (`Word` for `#2`/`#1step`,
|
||||
`Paren` for `#( … )`) so the one node serves both alternatives and an
|
||||
edge-inside-an-edge is not representable. `parse_clocking_skew` reads the
|
||||
edge, then `gap_before("#")` — the gap is the skew's own slot only when a
|
||||
`#` really follows, so `input edge /*c*/ sig;` still gives that comment to
|
||||
`after_skew`, the slot that already owned it. The formatter prints the
|
||||
edge, the separator (space or that slot's comments) and the delay, all as
|
||||
written; nothing is re-laid-out or reordered.
|
||||
|
||||
- Cases: two entries in `tests/cases/coverage_gaps_l6.cases` — every form
|
||||
the finding names (`default input negedge #(1:2:3) output posedge #5;`,
|
||||
`input negedge #(1:2:3) sig;`, `output posedge #5 other;`, `input
|
||||
posedge #1step a, b;`, `input edge c;`) and one for the comment slots
|
||||
either side of the `#`.
|
||||
- Parser: `a_clocking_skew_reads_a_delay_behind_its_edge` and
|
||||
`an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode`
|
||||
(strict/tolerant parity — the tolerant parse of the same source returns
|
||||
**zero** diagnostics and the same tree).
|
||||
- Fuzzer: the RTL clocking fixture gained `output negedge #5 o;`.
|
||||
`EXPECTED_RTL_GAPS` 499 → **505**, zero failing — the six new gaps all
|
||||
have owners, the one between the edge and its `#` being
|
||||
`Edge::after_edge`.
|
||||
- Attack pairs: `a_clocking_skew_rewritten_into_a_bare_delay_is_rejected`
|
||||
gained both halves of the new shape — `negedge #5` printed as `negedge`
|
||||
and as `#5` are each refused. `verify.rs` is still untouched.
|
||||
|
||||
**HIGH 2 — `->> @(posedge clk) e;` bound nothing.** `bind/stmt.rs`'s
|
||||
`EventTrigger` arm hand-matched `TimingControl::Delay`; it now calls the
|
||||
shared `bind_timing`, which is what every other statement's timing control
|
||||
goes through, so an event control's signals (and an `iff` guard) are
|
||||
ordinary references again. Test:
|
||||
`an_event_triggers_timing_control_is_bound_like_any_other` in
|
||||
`vlog_semantic/tests/semantics.rs` — `clk`, `en` and the delay's `d` each
|
||||
resolve to their declaration, and the triggered event still does.
|
||||
**Census re-derived** (`cargo test -p vlog_semantic --test corpus --
|
||||
--nocapture`): 860 files / 27 486 symbols / 103 875 references / 1 197
|
||||
unresolved / 0 unplaced — **no delta**, as expected: the corpus writes
|
||||
`->>` nowhere, so the only references this can add are in files that do
|
||||
not exist yet.
|
||||
|
||||
**MEDIUM — the `[format]` table had no unit tests.** Three added, written
|
||||
the way the `[lint]` table's are: `the_format_table_carries_uvm_utils_indent`
|
||||
(true, false, absent → `None` which is what makes the default off, the
|
||||
table mixed with top-level and `[lint]` keys),
|
||||
`the_format_table_rejects_what_it_does_not_support` (unknown key named
|
||||
under `[format]`, `"yes"` and `1` refused as non-booleans, no value,
|
||||
duplicate key, the key written above any table, `[format.x]` refused as an
|
||||
unknown table) and `a_bad_format_key_names_the_file_and_line` (through
|
||||
`Discovery`, so the message is `<path>:4: unknown key …`). The overlay
|
||||
ladder is pinned where it is composed: `a_format_key_climbs_the_ladder_from_off`
|
||||
in `lucisv_server/src/format.rs` — off by default, the editor setting when
|
||||
only it speaks, `lucisv.toml` winning over the editor in **both**
|
||||
directions, and a `lucisv.toml` that names other keys staying silent about
|
||||
this one.
|
||||
|
||||
**LOW — nested `` `uvm_object_utils_begin ``.** `item_seq`'s single
|
||||
`Option<Vec<Doc>>` became a stack, so a `_begin` inside an open run opens a
|
||||
level of its own and each `_end` closes the `_begin` it matches; an `_end`
|
||||
with nothing open closes nothing and moves no indentation, and an unmatched
|
||||
`_begin` still prints everything it opened (unchanged, and still tested).
|
||||
Two tests in `tests/format_options.rs`:
|
||||
`a_nested_begin_opens_a_level_of_its_own_and_its_end_closes_that_one`
|
||||
(one nested pair, idempotent) and
|
||||
`an_end_with_no_begin_open_changes_no_indentation` (a lone `_end`, and one
|
||||
after a closed pair).
|
||||
|
||||
**Gates** (guarded, 2026-09-07). `cargo fmt` clean; `cargo clippy
|
||||
--all-targets` clean, no warnings; `cargo test --workspace` **4 163
|
||||
passed, 0 failed** (4 154 before the rework, +9: two parser, one
|
||||
semantic, two formatter-option, three `lucisv_core` config and one
|
||||
`lucisv_server` ladder test — the two `.cases` entries ride inside the one
|
||||
`case_tables` test); `tools/corpus_check.sh` **814/820** formattable, the
|
||||
same six parse errors, **0** verification errors, **0** crashes.
|
||||
|
||||
Byte identity, all 860 corpus files, `format --stdout` current tree vs
|
||||
`~/.cache/lucisv-baselines/lucisv-0.48.1`: **0 differing** — the shipped
|
||||
default still changes nothing for anybody who did not ask for it. With
|
||||
`uvm-utils-indent` **on**: **exactly the 21 files listed above**, the same
|
||||
set, each idempotent and with the same comment-line count. The key was
|
||||
delivered through `--stdin-filename` pointing at a scratch directory
|
||||
holding the `lucisv.toml` (a `.git` beside it stops the walk), so the
|
||||
comparison needed no copy of the corpus and never wrote to it.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-07 — QA pass, TODO §54 (L3/L6/L10)
|
||||
|
||||
**What was run.** `cargo build --release -p lucisv` (binary reflects the
|
||||
uncommitted tree). Guarded: `cargo test --workspace` — **4 154 passed, 0
|
||||
failed** (matches the work log's count exactly); `cargo clippy
|
||||
--all-targets` — clean, no warnings; `tools/corpus_check.sh` — **814/820**
|
||||
formattable, the same six parse errors named in the work log, 0
|
||||
verification errors, 0 crashes. `node --test editors/vscode/*_test.js` — 5
|
||||
suites, all green, including `hierarchySections_test.js` (unrelated §56
|
||||
work sharing the tree) and the grammar keyword-parity test
|
||||
(`the_grammars_keywords_are_exactly_the_lexers`, part of the workspace
|
||||
run) — confirms the regenerated `systemverilog.tmLanguage.json` matches
|
||||
the lexer's keyword table, `randsequence` included.
|
||||
|
||||
**Byte identity.** Built a parallel (`xargs -P 8`) `format --stdout`
|
||||
diff of all 860 corpus files, current tree vs
|
||||
`~/.cache/lucisv-baselines/lucisv-0.48.1`: **0 differing.** Opentitan
|
||||
`hw/` (3 947 `.sv`/`.v`/`.svh`/`.vh` files, a superset of the "2 553"
|
||||
`.sv`-only figure quoted elsewhere): `format --check` outcome (exit code)
|
||||
identical between 0.48.1 and current for every file, **0 differing**;
|
||||
`git -C opentitan status --porcelain` afterward showed only the three
|
||||
pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
|
||||
— opentitan untouched otherwise.
|
||||
|
||||
**`uvm-utils-indent` ON**, scratch copy of the corpus with a `lucisv.toml`
|
||||
at the root and inside each vendored `.git` directory (`opentitan`,
|
||||
`ibex`, `common_cells`, `picorv32` — the discovery-stop trap the work log
|
||||
warns about): the parallel diff found **exactly the 21 files the README
|
||||
lists**, byte for byte the same set, no others. All 21 reformatted a
|
||||
second time produced identical output (idempotent) and kept the same
|
||||
comment-line count. `corpus_check.sh` over the same scratch copy: 814/820
|
||||
formattable, 0 verification errors, 0 crashes — the key does not change
|
||||
which files parse.
|
||||
|
||||
**Shape matrix, by hand** (`target/release/lucisv format --stdout`,
|
||||
idempotency and comment-slot checks on each): `->`/`->>` distinct and
|
||||
both forms (bare, `#5`, `@(posedge clk)`, inside `fork`) — correct, and
|
||||
`->` never rewritten. Stream `with [range]`, `[i+:4]`, `[i-:4]`, nested
|
||||
streams — correct and idempotent. Casts `(W+1)'(x)`, `4'(x)`,
|
||||
`logic [3:0]'(x)`, `signed'(x)`, `pkg::t'(x)`, `int'(x)` — all format
|
||||
unchanged. Drive strength on `wire`/`tri`/`wand`, every strength pair,
|
||||
`(supply0, supply1) [7:0] v`, comments in all five slots (including the
|
||||
pre-existing `assign`/`pullup` hole the work log says this round fixed —
|
||||
confirmed, both now format with their comments kept), strength+delay in
|
||||
the LRM's only legal order (strength then delay) — correct; the reverse
|
||||
order (`wire #5 (strong0, weak1) w`) is correctly refused with a parse
|
||||
error rather than silently reordered or misparsed. `let` at statement
|
||||
position, with and without ports, inside a function, comments in every
|
||||
slot — correct. `randsequence`: re-typed three LRM-style examples
|
||||
(a plain grammar, one with `:=` weights of a number/parenthesized
|
||||
expr/scoped name, `rand join (0.5)`, `repeat`, `if`/`else`, `case` with
|
||||
`default`, `break`/`return`/`for` inside a code block, a production with
|
||||
return type and args, a reference to an undefined production — parses,
|
||||
does not crash the binder), nested `randsequence`, comments in every slot
|
||||
named in the AST doc comments (`after_kw`, `after_open`, `before_close`,
|
||||
`before_colon`, `after_bar`, `before_bar`, `before_weight`, `after_op`,
|
||||
dangling) — all preserved, output idempotent.
|
||||
`grep -rn randsequence` over the corpus and over opentitan's `hw/`: **0
|
||||
hits in both**, not even as a plain identifier — the keyword-addition risk
|
||||
is confirmed negligible, matching the work log's claim.
|
||||
Strict/tolerant parity: wrote a temporary test
|
||||
(`crates/vlog_parser/tests/qa_l6_parity_scratch.rs`, removed after) that
|
||||
parses every L6 shape and the `randsequence` example through both `parse`
|
||||
and `parse_tolerant` and asserts identical trees and zero recovered
|
||||
diagnostics — held for all of them. Attack pairs
|
||||
(`crates/vlog_formatter/tests/verification.rs`): all eleven ran as part
|
||||
of the workspace suite and pass (arrow rewrite both directions, dropped
|
||||
`->>` timing, stream range narrowed and `+:`/`-:` swapped, dropped and
|
||||
reordered drive strength, `#(1:2:3)` rewritten as `#1`, dropped
|
||||
production, reordered alternative, `|` to juxtaposition, dropped weight,
|
||||
`let` losing its ports, uvm-utils-indent whitespace-vs-macro-drop) —
|
||||
`verify.rs` itself is untouched, confirmed by `git diff`.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- **HIGH — `ClockingSkew` has no arm for `edge_identifier` followed by a
|
||||
`delay_control`.** IEEE 1800-2017 §14.3: `clocking_skew ::=
|
||||
edge_identifier [ delay_control ] | delay_control`. The shipped grammar
|
||||
(`crates/vlog_parser/src/parser/module.rs:350` `parse_clocking_skew`,
|
||||
mirrored in `crates/vlog_formatter/src/format/module.rs`'s
|
||||
`ClockingSkew` match) treats `Edge`, `Delay` and `Paren` as mutually
|
||||
exclusive: `parse_clocking_skew` returns as soon as it reads
|
||||
`posedge`/`negedge`/`edge`, so a trailing delay is never looked for.
|
||||
Reproduction: `input negedge #5 c;`, `input posedge #(1:2:3) c;`,
|
||||
`output negedge #(1:2:3) c;` (the exact shape named in TODO §54.1's own
|
||||
plan text) and the `default` form
|
||||
(`default input posedge #(1:2:3) output #(2:3:4);`) all fail with
|
||||
`expected identifier (found "#")` / `expected ';' (found "#")`. Confirmed
|
||||
this is new-in-scope, not a pre-existing hole widened: 0.48.1 also
|
||||
rejects it, but 0.48.1 had **no** `#(1:2:3)` skew at all
|
||||
(`expected a clocking skew delay (found "(")`), so "edge plus a
|
||||
parenthesized min:typ:max" was never reachable before this round added
|
||||
`Paren`; the round added two of the three LRM alternatives for a skew
|
||||
that follows an edge and missed the third. Not a corruption (the file is
|
||||
refused, not misprinted), but it is a real hole in a shape the
|
||||
TODO and this round's own Handshakes section call complete. Needs a
|
||||
`ClockingSkew::Edge` variant (or a new `EdgeThenDelay` arm) that
|
||||
optionally reads a trailing `delay_control`, on both the parser and the
|
||||
formatter side, plus a `.cases`/fixture entry.
|
||||
- **HIGH — `->> @(posedge clk) e;`'s event control is never bound.**
|
||||
`crates/vlog_semantic/src/bind/stmt.rs`'s `StmtKind::EventTrigger(t)` arm
|
||||
hand-matches only `TimingControl::Delay` to bind its expression:
|
||||
```
|
||||
StmtKind::EventTrigger(t) => {
|
||||
if let Some(TimingControl::Delay { expr, .. }) = &t.timing {
|
||||
self.bind_expr(expr, scope);
|
||||
}
|
||||
self.bind_expr(&t.expr, scope);
|
||||
}
|
||||
```
|
||||
but the same file already has a shared `bind_timing` helper (used by
|
||||
`wait`, `always @(...)` and others) that handles both
|
||||
`TimingControl::Delay` *and* `TimingControl::Event(SensList)` via
|
||||
`bind_sens_list`. The `EventTrigger` arm does not call it, so
|
||||
`TimingControl::Event` — `->> @(posedge clk) e;`, the exact shape TODO
|
||||
§54.1 and this round's own fixtures use — silently binds nothing for
|
||||
`clk` (or an `iff` guard). Verified with a temporary test
|
||||
(`crates/vlog_semantic/tests/qa_event_trigger_scratch.rs`, removed
|
||||
after): `s.reference_at(offset of "clk")` returns `None` — no reference
|
||||
recorded at all, not merely unresolved. Effect: go-to-definition,
|
||||
find-references and rename on a signal named only inside an event
|
||||
trigger's event control silently do nothing (a rename would miss this
|
||||
occurrence, leaving a stale name behind — a real correctness bug for
|
||||
the refactor tooling, even though it does not touch `vlog_formatter`'s
|
||||
own invariants). Fix is mechanical: replace the hand-match with
|
||||
`if let Some(timing) = &t.timing { self.bind_timing(timing, scope); }`.
|
||||
- **MEDIUM — no unit-test coverage for the `[format]` table in
|
||||
`lucisv_core::config`.** The `[lint]` table has thorough tests in
|
||||
`crates/lucisv_core/src/config.rs` (`the_lint_table_carries_select_and_ignore`,
|
||||
`the_lint_table_rejects_what_it_does_not_support`, duplicate-key and
|
||||
bad-header cases). No equivalent exists for `[format]`/`uvm-utils-indent`
|
||||
— `parse_format_entry` and `parse_bool` have no direct test in this
|
||||
crate. End-to-end behavior is correct (verified by hand: `[format]
|
||||
uvm-utils-indent = "yes"` gives
|
||||
`` `uvm-utils-indent` expects `true` or `false`, found `"yes"` `` and
|
||||
exit code 2; unknown `[format]` keys are named; duplicate keys are
|
||||
rejected — all exercised only through the CLI, not as a `lucisv_core`
|
||||
regression test). Per CLAUDE.md ("new behavior needs tests in the same
|
||||
change"), this is a gap the dev should close; not fixed here because
|
||||
QA's scope for this lane is verification, not edits to files outside
|
||||
the QA log.
|
||||
- **LOW — nested `` `uvm_object_utils_begin `` does not nest.** Given two
|
||||
begins before their ends (`_begin(c) … _begin(d) … _end … _end`), the
|
||||
indent opens once and **closes on the first `_end`**, not a matched
|
||||
pair: everything after the first `_end` (including the second `_begin`
|
||||
and its own field) prints back at the outer level rather than nesting
|
||||
or erroring. Idempotent, no comments or macros lost — just a shape the
|
||||
rule does not track a stack for. Real UVM code never nests these macros
|
||||
(they themselves expand to `begin`/`end`), so impact is negligible, and
|
||||
the QA brief flagged this exact case as open ("error? or double
|
||||
indent — pin"). Recording the actual, observed behavior since the
|
||||
feature README does not say which was chosen; the lead's call whether
|
||||
it is worth a stack-based fix or a comment pinning it as intentional.
|
||||
- Everything else in the plan (six L6 shapes, `randsequence` as real
|
||||
nodes, the one shipped `[format]` key, the docs list, the gates) checks
|
||||
out exactly as the work log describes. `EXPECTED_RTL_GAPS` at 499 with
|
||||
the full workspace run green covers the gap-fuzzer request; a temporary
|
||||
fixture with comments in every clocking/`let` slot was not added
|
||||
separately since the two RTL fixtures already added by this round cover
|
||||
every slot named in the work log and the run above is green.
|
||||
|
||||
**Verdict: REWORK.** Two HIGH findings are concrete, reproducible, in
|
||||
the files this round touches, and sit squarely inside the shapes TODO
|
||||
§54.1 names as done (the clocking skew grammar; the `->>` event-control
|
||||
binding). Neither corrupts formatter output or breaks an invariant in
|
||||
`verify.rs` — CLAUDE.md invariants 1-4 hold — but "the six L6 shapes,
|
||||
each with cases + parity + fuzzers" and "every downstream match arm...
|
||||
updated" (Handshakes) are not yet true for these two cases. Suggested
|
||||
fix scope for the next dev pass: extend `ClockingSkew` (parser +
|
||||
formatter + a `.cases` entry) for `edge_identifier [delay_control]`, and
|
||||
point `EventTrigger`'s bind arm at the existing `bind_timing` helper. The
|
||||
MEDIUM and LOW findings are not blockers but should be picked up in the
|
||||
same pass since the files are already open.
|
||||
|
||||
### 2026-09-07 — Re-check of the rework
|
||||
|
||||
Re-read the prior QA entry above and the dev's "Rework, the four QA
|
||||
findings" work-log entry, then re-diffed the seven files the rework
|
||||
touched (`ast/module.rs`, `parser/module.rs`, `format/module.rs`,
|
||||
`format/item.rs`, `bind/stmt.rs`, `lucisv_core/src/config.rs`,
|
||||
`lucisv_server/src/format.rs`) against clean `master` — all four fixes
|
||||
are exactly where the work log says.
|
||||
|
||||
**HIGH 1 re-attacked (`ClockingSkew::Edge`'s trailing delay).** Built
|
||||
`target/release/lucisv` from the tree and ran every shape by hand with
|
||||
`format --stdout`: `default input negedge #(1:2:3) output posedge #5;`,
|
||||
the per-signal forms (`input negedge #(1:2:3) a;`, `input posedge
|
||||
#1step a;`, `input edge b;`, `input #2 c;` delay-only unchanged, `output
|
||||
posedge d;` edge-only unchanged), a comment on both sides of the `#`
|
||||
(`input negedge /*A*/ #/*B*/(1:2:3) a;`) and after the edge with no `#`
|
||||
following (`input edge /*C*/ a;` — confirmed the comment lands in
|
||||
`after_skew`, not lost), comments inside the min:typ:max parens
|
||||
(`negedge #(1 /*D*/:2 /*E*/:3)`). All eight round-trip and are
|
||||
idempotent (checked by reformatting the output). `posedge negedge a;`
|
||||
(illegal double edge) and `default input;` (illegal — the `default`
|
||||
form's `clocking_skew` is not optional, unlike the per-signal item's) are
|
||||
both correctly refused with a parse error, not silently accepted.
|
||||
`inout posedge sig;` is accepted and printed back verbatim — traced this
|
||||
to pre-existing behavior on `master` (`git show HEAD:.../module.rs`
|
||||
already lets any of `input`/`output`/`inout` read an optional skew with
|
||||
no direction-specific gate); the rework did not touch that gate, so it is
|
||||
not a rework regression and is left as a pre-existing "not a legality
|
||||
checker" shape per the feature's own Assumptions — noted, not filed.
|
||||
Ran the two new parser tests directly:
|
||||
`cargo test -p vlog_parser --lib a_clocking_skew_reads_a_delay_behind_its_edge`
|
||||
and `--lib an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode` —
|
||||
both `ok`, the tolerant one asserting zero recovered diagnostics as
|
||||
claimed. Attack pairs re-run
|
||||
(`cargo test -p vlog_formatter --test verification
|
||||
a_clocking_skew_rewritten_into_a_bare_delay_is_rejected`) — `ok`, both
|
||||
new pairs (`negedge #5` → `negedge`, `negedge #5` → `#5`) rejected.
|
||||
`verify.rs` confirmed untouched (`git diff --stat` empty for it).
|
||||
|
||||
**HIGH 2 re-attacked (`->>`'s event control binding nothing).** Ran
|
||||
`->> @(posedge clk iff en) e;` and `->> #d e;` as two separate statements
|
||||
(the LRM's `delay_or_event_control` is one alternative, not both at once
|
||||
— a source combining them, as one out of the four literal test shapes in
|
||||
the task brief would, is correctly refused with a parse error, confirming
|
||||
`->>`'s grammar has not been loosened to accept both halves at once) —
|
||||
both format unchanged and idempotent. Ran
|
||||
`cargo test -p vlog_semantic --test semantics
|
||||
an_event_triggers_timing_control_is_bound_like_any_other` — `ok`,
|
||||
confirming `clk`, `en` and `d` each resolve and the triggered `e`
|
||||
resolves too. Re-derived the census
|
||||
(`cargo test -p vlog_semantic --test corpus -- --nocapture`): **860
|
||||
files / 27 486 symbols / 103 875 references / 1 197 unresolved / 0
|
||||
unplaced** — matches the work log's claim exactly, no delta.
|
||||
|
||||
**MEDIUM re-attacked (`[format]` table unit tests).** Ran the three new
|
||||
`lucisv_core` tests directly — `the_format_table_carries_uvm_utils_indent`,
|
||||
`the_format_table_rejects_what_it_does_not_support`,
|
||||
`a_bad_format_key_names_the_file_and_line` — all `ok`. Added two
|
||||
temporary scratch tests (removed after) to probe the edges the brief
|
||||
asked about: a `[format]` header written **twice** is not refused as a
|
||||
duplicate *table* — it just re-enters the same table (no state tracks
|
||||
"seen this header before"; only individual keys are duplicate-checked via
|
||||
`Option::is_some()`), and setting the same key again under the re-entered
|
||||
header **is** caught as `duplicate key`. This matches `[lint]`'s own
|
||||
behavior exactly (same lack of a table-repeat check), so it is consistent
|
||||
existing design, not a rework gap. `uvm-utils-indent = true` written
|
||||
under `[lint]` is correctly refused as `` unknown key `uvm-utils-indent`
|
||||
under `[lint]` (known keys: select, ignore, waivers) `` — the two tables
|
||||
are genuinely separate. Read `a_format_key_climbs_the_ladder_from_off` in
|
||||
`lucisv_server/src/format.rs` in full: it pins all four rungs (nobody
|
||||
speaks → off; editor only → editor wins; `lucisv.toml` over the editor in
|
||||
both directions; a `lucisv.toml` naming other keys stays silent about
|
||||
this one) — matches the Handshakes section's description of the ladder.
|
||||
|
||||
**LOW re-attacked (nested `` `uvm_object_utils_begin ``).** Ran the two
|
||||
new `format_options.rs` tests — `ok` on both. Added a temporary scratch
|
||||
test (removed after) with **three** nesting levels
|
||||
(`uvm_object_utils_begin(c)` → `uvm_component_utils_begin(d)` →
|
||||
`uvm_object_utils_begin(e)`) and an unrelated macro (`` `uvm_info ``, not
|
||||
one of the four tracked names) interleaved at every level: it never
|
||||
pushes or pops the stack, each `_end` closes exactly the `_begin` it
|
||||
matches (printing at that `_begin`'s own column, not the run's), and the
|
||||
whole thing is idempotent with the key off leaving the source untouched.
|
||||
Hand-traced the stack logic in `item_seq` first to predict the expected
|
||||
output, then let the test's own first run tell me the actual result to
|
||||
cross-check the trace — they agreed, confirming the stack behaves as a
|
||||
real matched-pair nest, not the single-level, first-`_end`-closes-all
|
||||
behavior the original finding described.
|
||||
|
||||
**Gates (guarded, 2026-09-07).**
|
||||
`cargo build --release -p lucisv` — clean, used for every hand-attack
|
||||
above. `cargo clippy --all-targets` — clean, no warnings.
|
||||
`tools/guard.sh -- cargo test --workspace` (full, uncapped output,
|
||||
not `| tail`) — **4 166 passed, 0 failed**; the three extra were my own
|
||||
temporary scratch tests (two in `lucisv_core`, one in
|
||||
`vlog_formatter/tests/format_options.rs`), all removed afterward —
|
||||
4 166 − 3 = **4 163, exactly the dev's count**.
|
||||
`tools/guard.sh -- tools/corpus_check.sh` — **814/820** formattable, the
|
||||
same six parse errors, 0 verification errors, 0 crashes.
|
||||
`cargo test -p vlog_formatter --test verification
|
||||
a_comment_in_every_rtl_gap_still_formats` — `ok`; `EXPECTED_RTL_GAPS` is
|
||||
505 in the source and the test passes at that count with 0 failing.
|
||||
|
||||
**Byte identity.** All 860 corpus files, `format --stdout`, current tree
|
||||
vs current tree with no config (both built from this uncommitted tree,
|
||||
run in parallel with `xargs -P 8`): **0 differing** — the shipped default
|
||||
(key off) still changes nothing. Key **on**: built a scratch copy of the
|
||||
corpus (`cp -R`, not touching the real `corpus/` directory) with a
|
||||
`[format]\nuvm-utils-indent = true` `lucisv.toml` at the root and inside
|
||||
each vendored `.git` directory (`opentitan`, `ibex`, `common_cells`,
|
||||
`picorv32` — the discovery-stop trap the work log warns about), then
|
||||
diffed `format --stdout` of every corpus file against its scratch-copy
|
||||
counterpart: **exactly 21 files differ**, byte-for-byte the same 21 paths
|
||||
the README lists (verified by sorting and comparing the list, not just
|
||||
the count). All 21 reformatted a second time from their own output
|
||||
(written under the scratch tree so discovery still finds the config) are
|
||||
byte-identical to the first pass — idempotent — and each keeps the same
|
||||
`//`/`/*` occurrence count before and after. (First pass at this check
|
||||
wrote the second-pass input to `/tmp`, outside the scratch tree the
|
||||
config lives in, which silently fell back to the key-off default and
|
||||
made all 21 look non-idempotent — a test-harness mistake on my part, not
|
||||
a formatter bug; corrected by keeping the round-trip inside the scratch
|
||||
tree and it cleared immediately.)
|
||||
|
||||
**New findings.** None. Every finding from the 2026-09-07 QA pass above
|
||||
was fixed exactly as described, each fix is covered by a passing test I
|
||||
ran directly (not just trusted from the log), and the gate numbers match
|
||||
what the work log claims to the exact digit everywhere they were
|
||||
checkable (census, `EXPECTED_RTL_GAPS`, workspace test count net of my
|
||||
own scratch tests, corpus 814/820, the 21-file set). The one thing worth
|
||||
recording for the lead, not as a defect: `inout <skew> sig;` inside a
|
||||
clocking block is accepted and printed back rather than refused, but this
|
||||
predates the entire §54 lane (confirmed against `git show HEAD`) and is
|
||||
consistent with the feature's own "not a legality checker" Assumption —
|
||||
out of scope for this rework, not filed as a finding.
|
||||
|
||||
Temporary test files/functions used for this re-check
|
||||
(`qa_scratch_duplicate_format_table_header`,
|
||||
`qa_scratch_format_key_under_lint_table_is_unknown` in
|
||||
`crates/lucisv_core/src/config.rs`;
|
||||
`qa_scratch_three_levels_nested_with_an_unrelated_macro_interleaved` in
|
||||
`crates/vlog_formatter/tests/format_options.rs`) were all removed before
|
||||
finishing; `git status`/`git diff` confirm neither file carries them
|
||||
anymore.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 — lead.** Accepted after one rework; ships in 0.49.0 with
|
||||
§53.2 and closes the coverage tables. The first dev stalled under machine
|
||||
load and the second finished from the tree, the recipe that worked for
|
||||
§49. The right calls were made where the plan was wrong: a short
|
||||
comment-free enum body already one-lines, so no key was built and the
|
||||
behaviour is pinned; `randsequence` was a parse error rather than an
|
||||
opaque leaf, so it became real nodes with the LRM's own examples as the
|
||||
cases; the slot work beyond the letter (`let`, stream concatenations,
|
||||
the clocking grammar, drive strengths — one of which fixed a pre-existing
|
||||
refusal) is what the gap fuzzer's zero-failure bar demands, and it stands
|
||||
at 505 gaps. QA's HIGHs were exactly the two shapes the plan text named
|
||||
and the dev had not reached (`edge #delay` skews; `->>`'s event control
|
||||
unbound), fixed with the LRM's own two-alternative shape for a clocking
|
||||
skew and the shared `bind_timing`; the config table now has the tests the
|
||||
`[lint]` table always had, and the utils-macro indent tracks nesting.
|
||||
`uvm-utils-indent` stays default off: 21 corpus files change with it on,
|
||||
which is the project's choice, not the formatter's. Byte-identity with
|
||||
the key off is 0 of 860 differing, and the opentitan sweep is identical.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
**`docs/coverage_gaps.md`.** Strike three rows:
|
||||
|
||||
- **L3** — `~~| L3 | randsequence production bodies. | … |~~` — **closed
|
||||
at 0.49.0 by TODO §54.2**: `randsequence` is a real statement with a
|
||||
production list (`ast::randsequence`), weighted alternatives, `rand
|
||||
join`, `repeat`, `if`/`else` and `case` production items and code
|
||||
blocks parsed as statements; the LRM's own examples are
|
||||
`tests/cases/randsequence.cases`. Corpus and opentitan occurrences: 0,
|
||||
so nothing moved.
|
||||
- **L6** — all seven clauses of the row are now delivered (the net-delay
|
||||
clause was already struck by §43.2): `->>` with its optional delay or
|
||||
event control, stream `with [range]`, the LRM's other `casting_type`s,
|
||||
drive strength on a net declaration, `let` at statement position and
|
||||
the `#(min:typ:max)` clocking skew — **closed at 0.49.0 by TODO
|
||||
§54.1**, with `tests/cases/coverage_gaps_l6.cases` and the RTL gap
|
||||
fuzzer at 499 gaps, zero failing.
|
||||
- **L10** — half **ruled already delivered** (a short, comment-free enum
|
||||
body has been one-lined since the body became a `Doc::Group`; measured
|
||||
2026-09-06, pinned by `tests/format_options.rs`), half **delivered
|
||||
behind a key**: `` `uvm_field_* `` indentation is `[format]
|
||||
uvm-utils-indent`, default off, 21 corpus files affected when on.
|
||||
|
||||
**`README.md`** — the config table gains one row:
|
||||
|
||||
| key | value | default | meaning |
|
||||
|---|---|---|---|
|
||||
| `[format] uvm-utils-indent` | `true` / `false` | `false` | Indent the `` `uvm_field_* `` macros between `` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level. |
|
||||
|
||||
**`docs/site/`** — the same row on the configuration page, and on the
|
||||
editors page the new VS Code setting:
|
||||
|
||||
| setting | default | meaning |
|
||||
|---|---|---|
|
||||
| `lucisv.format.uvmUtilsIndent` | `false` | The editor's spelling of `[format] uvm-utils-indent`; a checked-in `lucisv.toml` outranks it. |
|
||||
|
||||
**`docs/site/src/content/docs/guides/syntax.md`** — the sentence
|
||||
"`randsequence` and a small set of rare expression/port forms remain
|
||||
outside the formatter grammar" must drop `randsequence`; it is inside the
|
||||
grammar as of 0.49.0.
|
||||
|
||||
**`docs/topo.md`** — a row for this lane: `coverage-gaps-l` touches
|
||||
`vlog_parser` (ast + parser + token table), `vlog_formatter`,
|
||||
`vlog_semantic` (bind), `vlog_linter`, `vlog_refactor`, `lucisv_core`
|
||||
(config), `lucisv_server` (settings, format) and `editors/vscode`.
|
||||
@@ -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.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -23,12 +23,17 @@ what they would have been anyway (modulo one extra summary segment).
|
||||
assumption parallel-files already relies on. If that ever stops being
|
||||
true (a formatter that reads the file's *name*, or another file), this
|
||||
cache silently goes wrong and the assumption must be revisited here.
|
||||
- **`line-length` and `indent` are the whole config surface.** They are
|
||||
the only two things `lucisv_core::config::FileConfig` can put into
|
||||
`vlog_formatter::Config`. The key stores the *resolved values*, not the
|
||||
config file's path or mtime — so moving a `lucisv.toml` around, or
|
||||
switching from a file to an equivalent `--line-length` flag, correctly
|
||||
does **not** invalidate anything, while a real value change does.
|
||||
- **The key covers every `FileConfig` field that reaches the formatter.**
|
||||
Today that is `line-length`, `indent` and `[format] uvm-utils-indent` —
|
||||
everything `lucisv_core::config::FileConfig` can put into
|
||||
`vlog_formatter::Config` (see `lucisv/src/args.rs::config_with`). Any
|
||||
future setting that changes formatted output must join `Entry` and the
|
||||
store line in the same change; a setting left out is a stale clean
|
||||
verdict, which is exactly the bug TODO §59 fixed. The key stores the
|
||||
*resolved values*, not the config file's path or mtime — so moving a
|
||||
`lucisv.toml` around, or switching from a file to an equivalent
|
||||
`--line-length` flag, correctly does **not** invalidate anything, while
|
||||
a real value change does.
|
||||
`exclude` is not part of the key: it changes *which* files are visited,
|
||||
never how one is formatted.
|
||||
- **The version string is the workspace version** (`env!("CARGO_PKG_VERSION")`
|
||||
@@ -56,8 +61,8 @@ what they would have been anyway (modulo one extra summary segment).
|
||||
|
||||
### The key
|
||||
|
||||
Per file: **(content hash, line-length, indent, lucisv version)**, keyed on
|
||||
the file path.
|
||||
Per file: **(content hash, line-length, indent, uvm-utils-indent, lucisv
|
||||
version)**, keyed on the file path.
|
||||
|
||||
- **Content hash: hand-rolled FNV-1a, 64-bit**, over the file's bytes
|
||||
(`cache::content_hash`). Two reasons it is not
|
||||
@@ -111,7 +116,7 @@ the hash of **the bytes that were written** goes in.
|
||||
|
||||
| Situation | Cache read | Cache write | Reported as |
|
||||
|---|---|---|---|
|
||||
| Hit (hash + line-length + indent + version all match) | skip all work | entry kept | `left unchanged`, plus `N files from cache` |
|
||||
| Hit (hash + line-length + indent + uvm-utils-indent + version all match) | skip all work | entry kept | `left unchanged`, plus `N files from cache` |
|
||||
| Miss, file is already formatted | — | record `hash(src)` | `left unchanged` |
|
||||
| Miss, file rewritten in place (write succeeded) | — | record `hash(output)` | `reformatted` |
|
||||
| Miss, `--check`/`--diff` says it would reformat | — | **nothing** | `would be reformatted`, exit 1 |
|
||||
@@ -140,7 +145,7 @@ One text file, `<cache-dir>/cache`, one line per path, tab-separated,
|
||||
hand-rolled in the style of the corpus TSV:
|
||||
|
||||
```
|
||||
<content-hash, 16 hex digits>\t<line-length>\t<indent>\t<version>\t<path>
|
||||
<content-hash, 16 hex digits>\t<line-length>\t<indent>\t<uvm-utils-indent, `true`/`false`>\t<version>\t<path>
|
||||
```
|
||||
|
||||
The path is last because it is the only field that can contain
|
||||
@@ -153,7 +158,7 @@ third-party dependency between them (`rayon`, in `lucisv`). `serde` exists
|
||||
in the workspace only because `lucisv_server` needs it for LSP wire
|
||||
messages — `lucisv`/`lucisv_core` do not depend on it, and taking it here
|
||||
would put a proc-macro build step into the CLI's dependency graph to
|
||||
encode five fields. Five fields on a line need no schema; CLAUDE.md's
|
||||
encode six fields. Six fields on a line need no schema; CLAUDE.md's
|
||||
"standard library first" says so.
|
||||
|
||||
Loading, corruption and staleness:
|
||||
@@ -168,6 +173,15 @@ Loading, corruption and staleness:
|
||||
silently (that is not corruption, just another lucisv's entry). It is not
|
||||
carried forward on write, so alternating between two lucisv versions
|
||||
rebuilds the cache each time.
|
||||
- **A well-formed line in an older field layout is dropped the same way.**
|
||||
A five-field line is the shape lucisv wrote before `uvm-utils-indent`
|
||||
joined the key: it says nothing about the option, so it is skipped
|
||||
individually rather than trusted or treated as corruption. (The version
|
||||
field alone already makes a 0.49.0 store miss at 0.50.0; the tolerance
|
||||
is what keeps the codec self-describing when the two ever come apart —
|
||||
a hand-written store, a downgrade.) A five-field line that is *not*
|
||||
well formed in that older shape is corruption like any other, and
|
||||
discards the file.
|
||||
- **Writing is atomic**: the new text goes to `<cache-dir>/cache.<pid>.tmp`
|
||||
and is `rename`d over `cache`. A reader therefore sees the old file or
|
||||
the new one, never a half-written one.
|
||||
@@ -256,12 +270,19 @@ the only writer of an entry is the code path that just observed
|
||||
- **Consumes `docs/features/config-discovery/README.md`'s promise** that
|
||||
the cache key "must include the resolved per-file settings … not just
|
||||
file content + lucisv version". Done, with the *values*
|
||||
(`Config::max_width`, `Config::indent_width`) rather than the config
|
||||
file's identity, so two trees governed by different `lucisv.toml` files
|
||||
that happen to say the same thing share entries correctly.
|
||||
- **Consumes `vlog_formatter::Config`** read-only, for its two fields.
|
||||
Nothing in `vlog_parser` / `vlog_formatter` / `vlog_linter` was
|
||||
touched.
|
||||
(`Config::max_width`, `Config::indent_width`,
|
||||
`Config::uvm_utils_indent`) rather than the config file's identity, so
|
||||
two trees governed by different `lucisv.toml` files that happen to say
|
||||
the same thing share entries correctly.
|
||||
- **Consumes `vlog_formatter::Config`** read-only, for every field
|
||||
`args.rs::config_with` can set from a `lucisv.toml`. **The contract this
|
||||
crate owes back (TODO §59, 2026-09-07):** a new formatter setting that
|
||||
changes output is a change to `cache::Entry`, to
|
||||
`lucisv/src/main.rs::entry_for` and to the store line, in the same
|
||||
commit — otherwise a warm cache serves the old setting's verdict.
|
||||
`Config::uvm_utils_indent` was added in 0.49.0 without that and is the
|
||||
reason this line exists. Nothing in `vlog_parser` / `vlog_formatter` /
|
||||
`vlog_linter` was touched.
|
||||
- **Where the module lives: `lucisv_core::cache`,** next to `config` and
|
||||
`walk`. `lucisv_core` is by its own doc comment "the parts of lucisv that
|
||||
decide *which* files are processed and *with what settings*", and "this
|
||||
@@ -269,8 +290,9 @@ the only writer of an entry is the code path that just observed
|
||||
It also keeps the door open for `lucisv_server`: a language server that
|
||||
wanted to avoid re-formatting an unedited buffer on save would want the
|
||||
same predicate, and would otherwise have to duplicate the file format.
|
||||
Nothing in the module is CLI-specific — it takes paths, `u64`s and two
|
||||
`usize`s and has no opinion about arguments or reporting.
|
||||
Nothing in the module is CLI-specific — it takes paths and the bare
|
||||
scalars of the key (a `u64`, two `usize`s and a `bool`) and has no
|
||||
opinion about arguments or reporting.
|
||||
- **Promises to whoever changes the formatter's output** (alignment
|
||||
inference, `--lines`, any style change): **bump the workspace version**,
|
||||
or every user with a warm cache keeps their old formatting on files
|
||||
@@ -289,7 +311,10 @@ the only writer of an entry is the code path that just observed
|
||||
(`load` / `disabled` / `is_clean` / `record` / `store`).
|
||||
- [x] Hand-rolled tab-separated store, sorted by path, atomic
|
||||
temp+rename write, self-ignoring `.gitignore` in the cache dir.
|
||||
- [x] Corrupt / unreadable / wrong-version entries ignored, never fatal.
|
||||
- [x] Corrupt / unreadable / wrong-version entries ignored, never fatal;
|
||||
so is a line in the pre-`uvm-utils-indent` five-field shape.
|
||||
- [x] `[format] uvm-utils-indent` in `Entry`, in `entry_for` and as the
|
||||
store's fourth field (TODO §59).
|
||||
- [x] `--no-cache` and `--cache-dir <PATH>` in `args.rs` and `--help`,
|
||||
accepted (and inert) for `lucisv check`.
|
||||
- [x] Lookup at the top of `process_file`; entries collected through the
|
||||
@@ -303,7 +328,8 @@ the only writer of an entry is the code path that just observed
|
||||
content change invalidates, indent change invalidates, wrong
|
||||
version ignored, `--no-cache`, corrupt file tolerated, `--check`
|
||||
exit codes, `--threads` determinism with a warm cache, default
|
||||
cache dir is cwd-relative and self-ignoring).
|
||||
cache dir is cwd-relative and self-ignoring, `uvm-utils-indent`
|
||||
invalidates in both directions, an older store is rebuilt).
|
||||
- [x] Root `.gitignore` entry, `README.md` Cache section, `TODO.md` §3
|
||||
box.
|
||||
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test`.
|
||||
@@ -438,6 +464,75 @@ their work lands.
|
||||
- No `Cargo.toml` / `Cargo.lock` change: no new dependency, and
|
||||
`lucisv_core` still has an empty `[dependencies]`.
|
||||
|
||||
### 2026-09-07 — dev agent (TODO §59: `uvm-utils-indent` joins the key)
|
||||
|
||||
The owner's audit (topo §2.9 row 34, and the "Confirmed cache omission"
|
||||
paragraph of `docs/repository-analysis.md`) found the key stale against
|
||||
0.49.0's `[format] uvm-utils-indent`. `args.rs::config_with` sets
|
||||
`Config::uvm_utils_indent`, the formatter indents `` `uvm_field_* ``
|
||||
under it, but `Entry` and `entry_for` still named only content,
|
||||
line-length and indent — so a clean `--check` cached with the option off
|
||||
kept exiting 0 after the option was turned on, while `--no-cache
|
||||
--check` exited 1. Reproduced first, on the fixture from the audit.
|
||||
|
||||
**The fix, four lines of real change.** `Entry` gains
|
||||
`uvm_utils_indent: bool` (equality is derived, so the key follows for
|
||||
free); `lucisv/src/main.rs::entry_for` fills it from the same `Config`
|
||||
the formatter is handed; `render` writes it as the store's fourth field,
|
||||
`true`/`false`, after `indent` and before the version.
|
||||
|
||||
**Why `true`/`false` and not `0`/`1`.** The parser's style is one
|
||||
`.parse()` per field; `bool: FromStr` accepts exactly `true`/`false`, so
|
||||
the round trip is `{}` out and `.parse().ok()?` back, with no mapping
|
||||
either way and no new failure mode. A numeric encoding would have needed
|
||||
a hand-written `"0" => false` match for no gain.
|
||||
|
||||
**The five-field tolerance.** `parse` now matches on the field slice:
|
||||
six fields is the current shape; five fields *that are well formed in
|
||||
the old shape* (hex content, numeric line-length and indent, non-empty
|
||||
path) is a store written before the option joined the key, and is
|
||||
dropped individually exactly like another version's entry; anything else
|
||||
still discards the whole file, because partial trust in a file caught
|
||||
lying is still not worth the branch. The precision matters — a blanket
|
||||
"wrong field count → skip the line" would have quietly forgiven
|
||||
`not-hex\t100\t2\t0.2.0\t/a.sv`, which the corruption tests require to be
|
||||
fatal. The version field alone already makes a 0.49.0 store miss at
|
||||
0.50.0, so this tolerance buys nothing today; it is there so the codec
|
||||
stays self-describing when the two come apart (a hand-written store, a
|
||||
downgrade).
|
||||
|
||||
**Tests.** `cache.rs`:
|
||||
`uvm_utils_indent_alone_is_a_different_entry` (equality differs on the
|
||||
option alone; the line round-trips carrying it),
|
||||
`a_line_without_the_option_is_dropped_but_not_fatal` (an old-shape line
|
||||
next to a current one: the old one is not trusted, the current one
|
||||
survives, and the old one is not carried forward), plus the option's
|
||||
column added to `entries_round_trip_through_the_file`,
|
||||
`the_file_is_sorted_and_carries_the_version`,
|
||||
`another_versions_entry_is_dropped_but_not_fatal` and two new
|
||||
six-field corruption cases (a non-boolean option, an empty path).
|
||||
`crates/lucisv/tests/cli.rs`:
|
||||
`changing_uvm_utils_indent_invalidates_the_entry` — the audit's own
|
||||
probe through the real binary, in both directions (clean under `false`,
|
||||
cached, flip to `true` → exit 1; format under `true`, cached, flip back
|
||||
to `false` → exit 1) — and
|
||||
`a_store_written_before_the_option_joined_the_key_is_rebuilt`. The CLI
|
||||
regression was checked against the bug: with `entry_for` pinned to
|
||||
`false` it fails with "1 file from cache" at exit 0, which is exactly
|
||||
the audit's step 2.
|
||||
|
||||
**Note for the lead.** `README.md`'s key sentence (line ~89, which still
|
||||
lists four fields) and its `--no-cache` workaround paragraph (lines
|
||||
~99-103, "In v0.49.0, the new `uvm-utils-indent` option is missing from
|
||||
this key") are now stale, as is `docs/topo.md` row 34, and
|
||||
`docs/repository-analysis.md`'s "Confirmed cache omission" paragraph
|
||||
describes a fixed bug. Per the brief this lane did not touch those three
|
||||
files; they are the lead's to strike at merge.
|
||||
|
||||
**Gates:** `cargo fmt` clean, `cargo clippy --all-targets` silent,
|
||||
`cargo test -p lucisv_core` / `-p lucisv` / `--workspace` green, all
|
||||
through `tools/guard.sh -m 8 -t 1800`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
@@ -595,8 +690,219 @@ apply, but the same spirit (attack the exact class of thing that could
|
||||
silently corrupt trust) was applied here to the cache's own trust
|
||||
boundary instead.
|
||||
|
||||
### 2026-09-07 — QA agent (TODO §59: `uvm-utils-indent` joins the key)
|
||||
|
||||
Read CLAUDE.md, TODO §59, this README's amended Handshakes and the
|
||||
2026-09-07 dev entry above, then `git diff` for `cache.rs`, `main.rs`,
|
||||
`cli.rs`. The workspace built clean on trunk this time (no concurrent
|
||||
lane mid-landing), so all gates ran directly, no scratchpad rsync
|
||||
needed.
|
||||
|
||||
**Gates.**
|
||||
- `cargo fmt -- --check`: clean.
|
||||
- `tools/guard.sh -m 8 -t 1800 -- cargo clippy --all-targets`: silent.
|
||||
Re-ran scoped with `-p lucisv_core -p lucisv --all-targets --
|
||||
-D warnings` after a touch to force recompilation (not just a cached
|
||||
"Finished"): still silent.
|
||||
- `tools/guard.sh -m 8 -t 1800 -- cargo test -p lucisv_core -p lucisv`:
|
||||
**36** (`lucisv` unit) + **107** (`cli.rs`) + **102** (`lucisv_core`
|
||||
unit) = 245, all green. (The dev's log counts pre-date this run; §59
|
||||
added 2 `cache.rs` unit tests, 2 `cli.rs` tests, and touched shared
|
||||
corruption-vector tests in place, so the totals climbed from the
|
||||
2026-08-19 136 baseline.) Confirmed
|
||||
`a_store_written_before_the_option_joined_the_key_is_rebuilt` and
|
||||
`changing_uvm_utils_indent_invalidates_the_entry` both present and
|
||||
passing.
|
||||
- `cargo build --release -p lucisv`: clean, used for every probe below
|
||||
as `target/release/lucisv`.
|
||||
|
||||
**Step 2 — the audit's probe, by hand, `--cache-dir` in a scratch dir**
|
||||
(fixture: the UVM class from the brief, `[format]
|
||||
uvm-utils-indent = false` first).
|
||||
|
||||
- Fixed binary: format under `false` → `--check` exits 0, `1 file from
|
||||
cache`. Flip to `true` → `--check` exits **1**, `would reformat:
|
||||
c.sv`. Correct.
|
||||
- 0.49.0 baseline (`~/.cache/lucisv-baselines/lucisv-0.49.0`): same
|
||||
sequence — format under `false`, cache hit, flip to `true` →
|
||||
`--check` exits **0**, `1 file from cache` (the bug, reproduced
|
||||
exactly), while `--check --no-cache` on the same binary correctly
|
||||
says `would reformat` / exit 1 — confirming the option really does
|
||||
change output and only the cache is stale.
|
||||
- Other direction on the fixed binary: format under `true` (file is
|
||||
reformatted, output differs from the `false` rendering — confirmed
|
||||
`assert_ne!`-style by hand), cache hit under `true`, flip to `false`
|
||||
→ exits **1**. Correct.
|
||||
|
||||
**Step 3 — attacking the key.**
|
||||
|
||||
- (a) Entry recorded under `true`, then run under `false` with the
|
||||
same content: `--check` reports `would reformat`, no `from cache` —
|
||||
miss, as required.
|
||||
- (b) Option set via a `lucisv.toml` in a **parent** directory (file
|
||||
under `sub/`, config in the parent, config discovery finds it):
|
||||
formatted clean under `false`, cache hit; flipped the *parent*
|
||||
config to `true` → `--check` exits 1, `would reformat`. The key
|
||||
follows the resolved value regardless of which directory in the
|
||||
chain set it, as the Assumptions section claims.
|
||||
- (c) A store written by the real 0.49.0 binary (five fields) read by
|
||||
the fixed binary: not an error, `1 file left unchanged` **without**
|
||||
"from cache" (the old-shape line is dropped individually, not
|
||||
trusted), and the store is six fields after this run. The next
|
||||
`--check` is then `1 file from cache` in the new shape. Matches the
|
||||
five-field-tolerance branch exactly.
|
||||
- (d) A store written by the fixed binary (six fields) read by the
|
||||
real 0.49.0 binary: read `crates/lucisv_core/src/cache.rs` at
|
||||
`v0.49.0` (`git show v0.49.0:...`) — its parser is
|
||||
`line.splitn(5, '\t')`. Against a six-field line this splits on only
|
||||
the first 4 tabs, so 0.49.0's "version" slot actually receives the
|
||||
*uvm* field's text (`"false"`/`"true"`) and its "path" slot receives
|
||||
everything after that, `"<real-version>\t<real-path>"` (with the
|
||||
join tab folded in raw). Since that captured "version" text is never
|
||||
equal to 0.49.0's own `VERSION` constant, the `if version == VERSION`
|
||||
check fails and the line is silently **not inserted** — the same
|
||||
code path 0.49.0 already uses for "another version's entry," not an
|
||||
error return. No `path.is_empty()` trip either (path is nonempty).
|
||||
Verified empirically: 0.49.0 read the six-field store, did not
|
||||
crash, reported plain `1 file left unchanged` (no "from cache" — a
|
||||
real re-verify, not a false hit, and correct anyway since the file
|
||||
is genuinely clean), and rewrote the store back to its own five-field
|
||||
shape on exit. No false hit, no crash, confirmed both by code
|
||||
reading and by running it.
|
||||
- (e) Six-field line with `uvm` = `"1"`: `bool::from_str` only accepts
|
||||
the literal strings `true`/`false`, so `.parse().ok()?` fails and
|
||||
`parse()` returns `None` → whole store discarded. Verified: seeded a
|
||||
store with one genuine clean entry plus this line, `--check` on the
|
||||
genuine file no longer says "from cache" (it re-verified). The
|
||||
`"yes"` case is already the unit test
|
||||
`a_corrupt_file_is_ignored_wholesale`'s `"...\tyes\t0.2.0\t/a.sv\n"`
|
||||
vector — read it, it exercises the same `.parse().ok()?` branch as
|
||||
`"1"` does (both are non-`true`/`false` strings; no reason for one to
|
||||
behave differently from the other, and this run confirms `"1"`
|
||||
directly since the brief calls it out by name). Five-field line with
|
||||
non-hex content (`"nothex\t100\t2\t0.49.0\tc.sv"`): `prefix()`'s
|
||||
`u64::from_str_radix(content, 16)` fails first, `?` short-circuits
|
||||
before the shape is even fully validated → `None` → discarded.
|
||||
Verified by hand: seeded that single bad line, `--check` did not
|
||||
trust it (no "from cache"), file re-verified clean on its own
|
||||
merits.
|
||||
- (f) Two files, one old-shape (five-field, `a.sv`) and one new-shape
|
||||
(six-field, `b.sv`) line in the same store: `--check a.sv b.sv`
|
||||
reports `2 files left unchanged, 1 file from cache` — exactly one
|
||||
hit (`b.sv`), `a.sv` silently rebuilt, neither line poisoned the
|
||||
other. Matches `a_line_without_the_option_is_dropped_but_not_fatal`.
|
||||
|
||||
Also checked, prompted by the TODO item's own wording ("a store line
|
||||
with four fields"): a genuine four-field line (`hash\t100\t2\t0.49.0`,
|
||||
no `uvm`/no path) matches neither the six- nor the five-field pattern
|
||||
in `parse`'s `match`, falls to `_ => return None`, and **discards the
|
||||
whole store** — including a separately-present, otherwise-good
|
||||
six-field entry for another file. Verified: seeded a good entry for
|
||||
`realfile.sv` plus a bogus four-field line, and the previously-good
|
||||
entry was no longer served ("from cache" absent) on the next
|
||||
`--check`. This is the fourth malformed-line shape (three, five,
|
||||
seven+ fields all land here too, by the same `_` arm) and behaves like
|
||||
every other corruption case — correct, and consistent with "guilty
|
||||
until proven innocent" for a change that *could* have silently
|
||||
widened forgiveness but provably didn't.
|
||||
|
||||
**Step 4 — path shapes that could confound the parser.** Read `parse`
|
||||
and `splitn(6, '\t')`. The path field is always the **last** slot
|
||||
(index 5) of an at-most-6-way split, so no matter what the path
|
||||
contains, it receives everything left after the fifth tab is
|
||||
consumed — it cannot be mistaken for field 4 (`uvm`) and cannot cause
|
||||
a `true`/`false` field to be mis-identified as a path or vice versa:
|
||||
- **Path literally `"true"`**: line
|
||||
`42b10c60d1dbc11a\t100\t2\tfalse\t0.49.0\ttrue` parses to
|
||||
`uvm_utils_indent = false`, `path = "true"` — positionally
|
||||
unambiguous. Verified with a real file named `true` in a scratch
|
||||
dir: formats, caches, hits on the next `--check`.
|
||||
- **Path containing an embedded tab**: `key()` (used both to look up
|
||||
and to record) rejects any path containing `\t` or `\n` outright, so
|
||||
**lucisv itself can never write such a line** — this class is only
|
||||
reachable via a hand-forged/corrupted store. Reasoned from
|
||||
`splitn(6, '\t')`: a forged line
|
||||
`deadbeefdeadbeef\t100\t2\ttrue\t0.49.0\ta\tb.sv` (6 tabs, one more
|
||||
than the 5 the split consumes) parses with `path = "a\tb.sv"` intact
|
||||
— the sixth-and-final split field folds the extra tab in, so it
|
||||
round-trips as one field rather than desyncing the columns. Since
|
||||
`key()` can never *produce* a tab-containing lookup key for a real
|
||||
file, this forged entry can never be hit by any real run; verified
|
||||
by seeding exactly this line plus a real file, confirming no crash
|
||||
and no false hit, and that the forged line (path does not exist on
|
||||
disk) is silently pruned by `render()`'s existence check on the next
|
||||
write.
|
||||
|
||||
**Step 5 — README cross-check.** Handshakes' "Consumes
|
||||
`vlog_formatter::Config`" paragraph states the obligation on the next
|
||||
formatter setting explicitly, naming `Entry`, `entry_for` and "the
|
||||
store line" together, in the same commit — matches CLAUDE.md's rule 4
|
||||
posture (widen the safety-adjacent surface only with the accompanying
|
||||
proof). The Storage section's line grammar
|
||||
(`<hash>\t<line-length>\t<indent>\t<uvm-utils-indent>\t<version>\t<path>`)
|
||||
matches `render()`'s `writeln!` argument order exactly
|
||||
(content, line_length, indent, uvm_utils_indent, VERSION, path).
|
||||
|
||||
**Step 6 — size.** `cache.rs`: 191 lines before `mod tests` (118
|
||||
non-blank/non-comment) — nowhere near the 300–600 target.
|
||||
`lucisv/src/main.rs`: 568 lines before `mod tests` — the `entry_for`
|
||||
change added 4 lines and did not push it toward a threshold. No file
|
||||
touched by this diff is newly over any CLAUDE.md size line.
|
||||
|
||||
**One non-blocking observation for the lead.** Step 3(c)/(d) used
|
||||
today's actual pairing — the release-tagged `lucisv-0.49.0` baseline
|
||||
against this uncommitted fix's local build, which *also* self-reports
|
||||
`CARGO_PKG_VERSION = "0.49.0"` because the workspace version has not
|
||||
been bumped for this change. That means in exactly the scenario just
|
||||
tested, the **shape-based** (five- vs six-field) tolerance is what
|
||||
kept the cross-binary read safe — the *version* field could not have,
|
||||
since both binaries carry the identical string. This slightly
|
||||
sharpens (not contradicts, once you know which pairing was meant) the
|
||||
dev's work-log claim that the five-field tolerance "buys nothing
|
||||
today" — that claim is true only *after* whatever release actually
|
||||
ships this fix bumps `Cargo.toml`'s version per the existing
|
||||
release-commit pattern (`git log` shows each `Release X.Y.Z` commit
|
||||
does this), which is a lead/release-time step, not something this
|
||||
diff needed to do itself. Recorded so the version bump isn't skipped
|
||||
at merge — no code change needed here, the fallback already covers
|
||||
the pre-bump window correctly, as demonstrated above.
|
||||
|
||||
**Verdict: PASS.** No corruption, no crash, no false hit, no
|
||||
mis-parse in any attacked case; both directions of the audit's own
|
||||
probe reproduce the bug on 0.49.0 and are fixed on the new binary;
|
||||
the five-field tolerance is precise (old-shape-well-formed lines drop
|
||||
individually, anything else on five fields is fatal like any other
|
||||
malformed line, confirmed with `"nothex"` content); a four-field line
|
||||
(the TODO item's own wording) discards the whole store as corruption,
|
||||
confirmed by direct repro; no file crossed a CLAUDE.md size threshold.
|
||||
Ticking the §59 QA line in `TODO.md`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 (lead, §59).** Accepted. Read the diff (`Entry`, the store
|
||||
line, `parse`'s two arms, `entry_for`, the six cache tests, the two CLI
|
||||
regressions) and both logs.
|
||||
|
||||
- The key now covers every `FileConfig` field that reaches the formatter,
|
||||
and the Handshakes say so as an obligation on whoever adds the next one.
|
||||
That is the actual fix; the codec change is its consequence.
|
||||
- The five-field arm is deliberately *conditional* (well-formed old shape
|
||||
only), so the existing "one malformed line discards the store" posture
|
||||
is unchanged — the corruption tests still bite on a non-hex content,
|
||||
a `yes` option, an empty path. Right call; a blanket field-count skip
|
||||
would have been a forgiveness with no attack test behind it.
|
||||
- QA's cross-version check is the one that matters: a 0.49.0 store is
|
||||
dropped individually and rebuilt; a 0.50.0 store read by 0.49.0 lands
|
||||
the option text in 0.49.0's version slot and is skipped as another
|
||||
version's entry. Neither direction can produce a false hit.
|
||||
- QA's note on the version bump is taken: the release chain bumps
|
||||
`CARGO_PKG_VERSION` to 0.50.0 before the tag, so the version field
|
||||
invalidates a 0.49.0 store on its own and the shape arm is belt and
|
||||
braces.
|
||||
- Docs applied at merge: README.md's key sentence and the workaround
|
||||
paragraph replaced by a one-line history note; topo row 34 struck;
|
||||
repository-analysis and coverage_gaps annotated as fixed.
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed. Warm runs are
|
||||
2-4× faster in parallel and up to 7.7× single-threaded, bought without
|
||||
touching a single correctness property.**
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,355 @@
|
||||
# performance-take4
|
||||
|
||||
TODO §58 — the fourth opentitan performance round. **0.49.0 against 0.43.0**,
|
||||
with take 3's 0.43.0 column carried beside every row so each one is a
|
||||
before/after, and 0.39.0 kept for the CLI sweeps. Output:
|
||||
`docs/performance_take4.md`, a `docs/perf/README.md` entry, and — the round's
|
||||
one durable artefact — a **committed** harness in `tools/perf/`.
|
||||
|
||||
## Goal
|
||||
|
||||
Measure what 0.44–0.49 did to the server and the CLI on a 3 976-file corpus,
|
||||
with the same table shapes take 3 used, so a reader can put the two documents
|
||||
side by side and read a row across four releases. Read-only: a regression is
|
||||
filed with a reproduction, never fixed here. And leave behind the client the
|
||||
last three rounds each lost — take 2's scripts were gone when take 3 ran, and
|
||||
take 3's were gone when this one started, so take 3's numbers had to be
|
||||
re-derived from take 2's *prose*. `tools/perf/` ends that.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The tree at `4c2dae3` is 0.49.0.** Verified: `target/release/lucisv
|
||||
--version` prints `0.49.0`, and the server binary's mtime (01:13) is later
|
||||
than the last change under `crates/` (01:12:49), so no rebuild was needed
|
||||
before timing.
|
||||
- **The two servers differ only in their code.** Both were driven by the same
|
||||
Python client, in the same session, on the same corpus commit, within one
|
||||
hour of each other. That is what makes tonight's 0.43.0 column — not take
|
||||
3's — the honest baseline: the harness and the machine are held fixed.
|
||||
- **The machine is a desktop, and it was busier than take 3's.** Load average
|
||||
3.7–7.1 throughout, with WindowServer at 45–51% and loginwindow at 24–29%.
|
||||
Take 3 measured at load 2–4. Sub-millisecond rows therefore sit on a fatter
|
||||
floor than take 3's; §9 says so and §8.9 dismisses the lot. Every
|
||||
conclusion below is drawn from a 0.49.0-vs-0.43.0 pair taken on this
|
||||
machine, in this state.
|
||||
- **`--select error,warning,style` is not "all rules"** — three rule classes
|
||||
by name, which is what §58 asked for.
|
||||
- **"Cold cache" is lucisv's store, not the OS page cache.** opentitan has now
|
||||
been walked by four measurement rounds.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `lucisv-server`'s wire protocol: `initialize` with
|
||||
`initializationOptions.storagePath` (index-persistence),
|
||||
`workspace/configuration` for the `lucisv` section (index-scope's
|
||||
`index.scope` / `index.scopeDepth`), `--verbose`'s
|
||||
`timing: <method> answered in <n> ms` over `window/logMessage`
|
||||
(verbose-timing), and `lucisv/moduleHierarchy` with `params: {}`
|
||||
(dut-hierarchy). None of these is changed by this round.
|
||||
- **Consumes** the CLI's `format --cache-dir <path> --check`,
|
||||
`format --no-cache --check` and `check [--select …]`. Note the argument
|
||||
order: `--cache-dir` is a *subcommand* option, so it follows `format`.
|
||||
- **Promises** `tools/perf/` to take 5: `lspclient.py` and `bench.py` keep
|
||||
their phase names and their `results.jsonl` row shape
|
||||
(`phase`/`label`/`row`/`ms`/`n`/`note`), so a later round can diff a row
|
||||
against this one by name. A phase that changes what it measures gets a new
|
||||
name rather than a new meaning.
|
||||
- **Requests nothing** of another module. Two observations that a future lane
|
||||
may want are filed as findings in `docs/performance_take4.md` §8, not as
|
||||
handshake requests, because this lane fixes nothing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] harness in `tools/perf/` with its README; runs from a clean checkout
|
||||
- [x] server table re-measured, 0.49.0 vs 0.43.0 vs take 3 — take 4 §2
|
||||
- [x] new rows: didOpen release numbers, the five refactoring offer sites,
|
||||
tail rename and instance-head completion, moduleHierarchy, index size
|
||||
and RSS
|
||||
- [x] CLI sweeps, three binaries, RSS included; outcome diff since 0.43.0
|
||||
- [x] `docs/performance_take4.md` + perf README entry
|
||||
- [x] opentitan status unchanged after every phase; no guard kill
|
||||
- [x] QA (TODO §58's last line) — PASS, see QA log
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-07 (dev).**
|
||||
|
||||
- Read CLAUDE.md, TODO §58, `docs/performance_take3.md` in full, and the perf
|
||||
README's 2026-09-05 entry. Recorded provenance for all five binaries
|
||||
(§1). Confirmed the tree's server binary is current; **no rebuild ran**.
|
||||
- Built the 0.43.0 server from the `v0.43.0` tag in a scratch `git worktree`
|
||||
under the scratchpad (57.75 s, under the guard). The main tree was never
|
||||
checked out, reset or stashed. The worktree was removed after the last
|
||||
measurement.
|
||||
- Wrote `tools/perf/` — `lspclient.py`, `sites.py`, `bench.py`, `sweep.sh`,
|
||||
`sweeptable.py`, `outcomes.sh`, `README.md`. Standard library only.
|
||||
Deviations from take 3's client, all deliberate: sites are resolved from
|
||||
the file *text* at run time rather than hard-coded; the scan barrier is
|
||||
1.5 s of silence rather than the `$/progress` `end` (the end report is
|
||||
followed by more chatter); and there is a `probe` phase, which is how the
|
||||
new offer sites below were found rather than guessed.
|
||||
- **Found the new offer sites empirically.** Swept every instantiation-shaped
|
||||
and `import` line in a set of RTL files with `codeAction` and kept the
|
||||
positions that actually offer. That turned up
|
||||
`sha3_fpv.sv 54:4` (expand `.*`), `aes_sbox_canright_masked.sv 42:2`
|
||||
(organize imports), `aes_wrap.sv 66:2` (inline `tlul_cmd_intg_gen`) and
|
||||
confirmed take 3's `aes_wrap.sv 78:2` (connect 2 missing ports). **There is
|
||||
no `convert to ANSI` site**: a scan of all 1 311 module headers in
|
||||
opentitan's `hw/` found zero non-ANSI ones, so that row measures an ANSI
|
||||
header instead and the corpus fact is reported in §6b.
|
||||
- **Found the §49 tail site empirically too.** The first two candidates did
|
||||
not resolve — `pwrmgr.sv`'s `u_fsm.state_q` sits inside a `` ` ``-macro
|
||||
assertion argument, and `pinmux.sv`'s `u_reg.intg_err` did not resolve
|
||||
either — so the round uses `entropy_src_core.sv`'s
|
||||
`u_entropy_src_main_sm.state_q`, which does. The two that do not are
|
||||
recorded in §8.
|
||||
- Ran the untimed per-file outcome sweeps for all three CLI binaries, then
|
||||
the timed CLI sweeps, then the LSP phases for 0.49.0 and for 0.43.0.
|
||||
`git -C opentitan status --porcelain` was checked after every phase and
|
||||
reported the same three pre-existing modified files every time. **No guard
|
||||
kill occurred**; the largest resident set anything reached was 588 MB
|
||||
(`lucisv-server` after a warm workspace scan), 7% of the 8 GB limit.
|
||||
- Three phases (`widen`, `blockers`, `rss`) were first written with one try
|
||||
per cell; that violated §58's three-tries rule, so they were rewritten to
|
||||
loop and **re-run on both binaries**, and the single-try rows were deleted
|
||||
from `results.jsonl` before the re-run. Nothing else in the file was
|
||||
edited after it was written.
|
||||
- **Split the harness after the measurements and re-verified it.** `bench.py`
|
||||
reached 537 production lines, over §58's ~500; the phases for what 0.44–0.49
|
||||
added moved to `phases_new.py` and the shared registry/config/session code
|
||||
to `harness.py` (330 / 152 / 76 production lines). **Every one of the 20
|
||||
phases was then re-run through the split files**, and ten rows were checked
|
||||
against the document within its stated tolerances — `didOpen
|
||||
pinmux_reg_top.sv` (doc 112.1 / 127.9–130.7 → 125.6 / 113.1–129.7 ms), the
|
||||
tail rename (793.2 / 750.7–751.9 → 785.0 / 746.3–753.9), the 128-fan-out
|
||||
eager `codeAction` (511.8 / 467.1–473.6 → 506.8 / 474.2), `moduleHierarchy`
|
||||
(76.2 / 41.1–53.8 → 68.7 / 41.1–53.1), the port-action resolve
|
||||
(163.9 / 158.2–159.5 → 163.1 / 157.3–160.4), the warm workspace scan
|
||||
(1 266 → 1 248), cold RSS (542 736 → 541 152 KB), `rename` on `aes`
|
||||
(165.1 / 133.5–139.4 → 164.5 / 137.2), `didOpen spi_device.sv`
|
||||
(15.5 / 13.8–15.1 → 13.7 / 15.3–15.0) and `tailcompletion`
|
||||
(1.11 / 0.45–0.53 → 0.96 / 0.47). All inside tolerance; the verification run
|
||||
is `scratchpad/verify.jsonl`, labelled `verify-0.49.0`.
|
||||
- Wrote `docs/performance_take4.md` (§0–§10), the perf README entry, and
|
||||
ticked §58's dev lines in `TODO.md`.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-07 (QA).**
|
||||
|
||||
Read CLAUDE.md, TODO §58, this README, `docs/performance_take4.md` in full
|
||||
(961 lines), `tools/perf/README.md`, the harness source, and the dev's raw
|
||||
logs at `~/.cache/lucisv-perf/take4/{results.jsonl,verify.jsonl}` and the
|
||||
scratchpad (`logs/`, `outcomes/`, `sweep/`, `census.py` +
|
||||
`logs/census-0.49.0.txt`).
|
||||
|
||||
**Setup.** `python3 -m py_compile tools/perf/*.py` — clean. Built the
|
||||
0.43.0 server from a fresh clone (not a worktree, per the hard rules):
|
||||
`git clone -q --no-checkout … && git checkout -q v0.43.0`, then
|
||||
`tools/guard.sh -m 8 -t 1800 -- cargo build --release -p lucisv_server`
|
||||
(58.10 s, no kill). Binary sha256 `7f0f27d6…`, matches §1's row exactly.
|
||||
Verified `target/release/lucisv --version` → `0.49.0` and
|
||||
`lucisv-server` sha256 `c6e40ecd…`, matching §1. All three CLI baseline
|
||||
shas/sizes (`0c943c4c…`/3236768 B for 0.49.0, `89379a12…`/2828576 B for
|
||||
0.43.0) matched by direct `shasum`/`ls`.
|
||||
|
||||
**1. Harness.** Compiles clean. Ran every phase listed below through
|
||||
`tools/perf/bench.py` exactly as `tools/perf/README.md` documents — no
|
||||
undocumented step was needed. One thing the README doesn't spell out:
|
||||
`bench.py`'s `--tries N` is the *repeat* count, and the printed/recorded
|
||||
list is `[first, repeat×N]` (so `--tries 4` prints 5 numbers) — obvious
|
||||
once seen, but worth a line in the README for take 5.
|
||||
|
||||
**2. Rows re-run, both binaries, committed harness** (`--tries 3` or `4`
|
||||
matching the phase; my raw rows are in
|
||||
`scratchpad/qa/results/results.jsonl`, labels `0.49.0-qa`/`0.43.0-qa`):
|
||||
|
||||
| Row | Doc (first / repeats) | **QA re-run 0.49.0** | **QA re-run 0.43.0** | Verdict |
|
||||
|---|---|---|---|---|
|
||||
| Workspace scan, cold | 2712/2691–2712 (49) · 2645/2640–2656 (43) | **2712.4/2690.9–2711.9** | **2637.0/2620.9–2632.3** | in band |
|
||||
| Workspace scan, warm | 1266.1/1239.8–1285.6 (49) · 1173.4/1167.1–1173.6 (43) | **1252.1/1244.7–1271.5** | **1183.6/1168.7–1185.3** | in band |
|
||||
| `didOpen pinmux_reg_top.sv`→request | 112.1/127.9–130.7 (49) · 1605/1604–1611 (43) | **127.5/103.4–126.5** (mean 119.1, doc mean 123.6, −3.6%) | **1621.1/1518.6–1565.7** (mean 1568.4, doc mean 1607.4, −2.4%) | in band (§9's ±10%/±5%) |
|
||||
| `codeAction prim_flop_2sync (128)`, lazy | 15.0/8.1–10.5 | **17.5/7.2–11.0** | **13.3/9.8–11.5** | in band |
|
||||
| `codeAction prim_flop_2sync (128)`, eager | 511.8/467.1–473.6 | **511.8/468.8–473.1** (traced exactly to the dev's own row, see §4 below) — QA re-run: **497.2/468.4–479.1** | **271.0/237.0–241.2** | in band |
|
||||
| `codeAction` comment line, lazy (§8.2) | 4.70/3.18–3.84 (49) · 2.17/1.12–1.32 (43) | **2.81/2.24–2.38** (run1), **7.43/4.11–5.46** (run2) | **1.81/1.15–1.61** | see finding B below |
|
||||
| `rename` on `aes` | 165.1/133.5–139.4 (49) · 159.8/133.2–136.2 (43) | **165.0/133.5–139.4** | **158.5/130.7–135.5** | in band |
|
||||
| `completion` at 0 chars | 7.2/4.2–5.3 (49) · 7.8/4.2–5.4 (43) | **7.1/3.9–5.1** | **9.0/4.4–5.0** | in band |
|
||||
| tail `rename` (§49, new row) | 793.2/750.7–751.9 (49) · 88.0/65.8–66.7 (43) | **777.8/747.9–751.2**, tail edited | **87.4/65.6–66.4**, tail NOT edited | in band, correctness match |
|
||||
| `moduleHierarchy` (new row) | 76.2/41.1–53.8 (49) · 70.3/41.0–48.8 (43) | **71.9/40.8–53.9**, 2 600 051 B, 1546/1529/schema 2 | **70.3/40.8–44.3** (a subset of retries) | in band, payload byte-identical |
|
||||
|
||||
10 rows re-run (task asked for 8), both binaries, all inside §9's stated
|
||||
tolerance bands except the comment-line row, which is finding B.
|
||||
|
||||
**3. CLI outcome diff, independently re-derived**, two trees (`hw/ip`,
|
||||
`hw/top_earlgrey/ip`), plus `hw/top_darjeeling/ip` to nail down the
|
||||
17/2/1 split:
|
||||
|
||||
- `format --check --no-cache`: `diff` against 0.43.0/0.49.0 is **empty**
|
||||
on both `hw/ip` (1777 lines each) and `hw/top_earlgrey/ip` (47 lines
|
||||
each) — byte-identical formatter verdicts, confirmed.
|
||||
- `check` (default rules): `diff` empty on both trees (446/15 lines) —
|
||||
byte-identical, confirmed.
|
||||
- `check --select error,warning,style`: `hw/ip` 7734→7751 (**+17**),
|
||||
`hw/top_earlgrey/ip` 551→553 (**+2**), `hw/top_darjeeling/ip`
|
||||
382→383 (**+1**) — **17+2+1 = 20**, every added line is a
|
||||
`[unused-import]` style finding, nothing else changed anywhere. Doc's
|
||||
claim confirmed exactly.
|
||||
- Re-timed `format --check` warm and `check` default on `hw/ip`, three
|
||||
tries, three binaries, `/usr/bin/time -l`: format warm 0.55–0.67 s
|
||||
across all three binaries (doc: 0.58–0.63); `check` default
|
||||
0.35–0.41 s (doc: 0.34–0.41); `check --select` 0.46–0.60 s, confirming
|
||||
the 1.27×-ish slope (mine: 0.47 mean 0.43 → 0.59 mean 0.49, 1.26×;
|
||||
doc 1.27×). All in band.
|
||||
|
||||
**4. §8.2 mechanism, read not fixed.** `crates/vlog_refactor/src/inline/mod.rs:73`
|
||||
(`inline_site`) and `crates/vlog_refactor/src/extract/mod.rs:82`
|
||||
(`extract_site`) both call `parse_source_tolerant(text)` — a full tolerant
|
||||
parse of the whole buffer — on every invocation, and refuse (`None`) if
|
||||
that parse produced any diagnostic. Both are called from the server's
|
||||
`code_actions` gating on *every* `textDocument/codeAction`:
|
||||
`crates/lucisv_server/src/inline_module.rs:50` and
|
||||
`crates/lucisv_server/src/extract.rs:76`/`:113`. The doc's claim — the
|
||||
gates parse the cursor's buffer on every request, unconditionally, offer
|
||||
or not — is accurate and the two file:line citations for `inline_site`
|
||||
check out exactly; the doc names `extract_site` in prose but doesn't cite
|
||||
its own definition/call site (`extract/mod.rs:82`, `extract.rs:76`) — a
|
||||
cosmetic citation gap, not a wrong claim, since I verified `extract_site`
|
||||
does the identical thing.
|
||||
|
||||
**5. Attack — internal consistency and corpus facts.**
|
||||
|
||||
- **Census (§6b, 2 440 positions, extract 89%/inline 11%).** The dev's
|
||||
`scratchpad/census.py` + `logs/census-0.49.0.txt` gives files 205,
|
||||
positions 2440, extract 2171, inline 263, organize 12, connect 1 —
|
||||
matches the document exactly. I re-ran an independent subset (aes/rtl
|
||||
only, 40 files, edited `dirs=` in a copy of the script) and got 914
|
||||
positions, extract 870 (95.2%), inline 129 (14.1%), organize 12,
|
||||
connect 1 — the organize/connect *sites* are byte-identical to the
|
||||
full run's list (all 12 organize sites and the 1 connect site live in
|
||||
`aes/rtl`), and the extract/inline proportions are in the same range;
|
||||
the difference from 89%/11% is explained by `prim/rtl`'s different mix
|
||||
of item shapes, not an inconsistency.
|
||||
- **"Zero non-ANSI headers of 1 311" (§6b).** No script or log for this
|
||||
claim exists anywhere in `tools/perf/` or the scratchpad — filed as
|
||||
finding A. I wrote an independent census (line-anchored `module NAME`
|
||||
regex, comments stripped, port-list scanned for `input`/`output`/
|
||||
`inout`/`ref`) over all 3 932 `.sv`/`.v` files under `opentitan/hw`:
|
||||
1310 module headers (doc: 1311, a 1-header methodology difference),
|
||||
2 apparent "non-ANSI" hits that turned out to be false positives on
|
||||
inspection (`hw/vendor/lowrisc_ibex/.../tb.sv` and
|
||||
`hw/vendor/pulp_riscv_dbg/tb/tb_top.sv` — both `module NAME #(params) ;`
|
||||
with **no port list at all**, not a non-ANSI port list). Net: **zero
|
||||
genuine non-ANSI headers**, confirming the doc's claim in substance
|
||||
even though it isn't traceable to a committed artifact.
|
||||
- **File-count sanity**: `find hw/ -name '*.sv' -o -name '*.v' | wc -l`
|
||||
→ 3932, matches §6b's "3 932 `.sv`/`.v` files" exactly.
|
||||
|
||||
**6. Traceability sample (task asked for 25; I checked ~30).** Every one
|
||||
of the following was found verbatim in `results.jsonl`, a `sweep/*.txt`
|
||||
log, `logs/sweeptable.txt`, an `outcomes/*.txt` file, or
|
||||
`logs/census-0.49.0.txt`: the §0 `prim_flop_2sync (128) eager` wire/verbose
|
||||
pair, the §1 sha256/size sextet, the §2 workspace-scan cold/warm rows, the
|
||||
`didOpen pinmux_reg_top.sv` row, the tail-rename row, `codeAction
|
||||
prim_flop_2sync (128) eager` and `prim_alert_sender (67) eager`, `didOpen
|
||||
aes_core.sv`, the `expand .*` offer+resolve pair, `rename aes`, the
|
||||
`spi_device.sv` widen cell, `moduleHierarchy` (both binaries, payload
|
||||
2 600 051 B, 1546/1529/schema 2), the cold/warm RSS triples and index
|
||||
sizes (45404/39940 KB) for both binaries, every `hw/ip` row in
|
||||
`sweeptable.txt` (format cold/warm, check default/select, RSS), every
|
||||
outcome-count line (`found 445/446/7751/7734/7735 violations`, `1772/1773
|
||||
files would be reformatted`), and the load-average extremes (7.10, 3.68)
|
||||
in `logs/outcomes-load-before.txt`/`logs/lsp-0.49.0-machine.txt`. **Not
|
||||
traceable**: the §6b "1 311 module headers / zero non-ANSI" pair (finding
|
||||
A above) — no script, log, or note anywhere records how it was computed.
|
||||
|
||||
**7. opentitan and tree status.** `git -C opentitan status --porcelain`
|
||||
checked after every phase of my own re-runs (scan, didopen, codeaction ×2,
|
||||
rename, completion, hierarchy, tailrename, both outcome sweeps, both
|
||||
timed sweeps, the census re-run) — every single time, exactly the three
|
||||
pre-existing files: `hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`.
|
||||
Never written to otherwise. Main tree `git status --short` shows only the
|
||||
dev's untracked/modified files (`TODO.md`, `docs/perf/README.md`,
|
||||
`docs/features/performance-take4/`, `docs/performance_take4.md`,
|
||||
`tools/perf/`) plus this QA-log edit. **No guard kill** in any of my
|
||||
~20 guarded invocations (server sessions, the one `cargo build`, CLI
|
||||
sweeps); largest RSS I observed was the 0.49.0 server's 588 608 KB after
|
||||
a warm scan, same as the doc reports.
|
||||
|
||||
### Findings
|
||||
|
||||
**A (low, traceability).** `docs/performance_take4.md:428-430`'s "zero
|
||||
non-ANSI headers" / "1 311 module headers" claim has no backing script or
|
||||
log anywhere in `tools/perf/` or the scratchpad, unlike every other census
|
||||
in this round. This breaks `tools/perf/README.md:103-104`'s own rule
|
||||
("Nothing in the document may quote a number that is not in this file or
|
||||
in a sweep.sh / outcomes.sh log"). Independently reproduced as
|
||||
substantively correct (§5 above: 1310 headers, 0 genuine non-ANSI after
|
||||
excluding two no-port-list false positives) — not a correctness defect,
|
||||
but the number should not have shipped without a saved script, and a
|
||||
future round should add one before quoting a from-scratch corpus census.
|
||||
|
||||
**B (informational, not blocking).** The comment-line lazy `codeAction`
|
||||
row — §8.2's central piece of evidence for the "2.9×" gate-cost claim —
|
||||
is noisier than its own 1–20 ms/±20% tolerance band. Two independent QA
|
||||
reruns of the `codeaction` phase on the *same* 0.49.0 binary, minutes
|
||||
apart, gave means of 2.42 ms and 5.25 ms for this row (doc: 3.91 ms
|
||||
mean), a 2.2× swing between two back-to-back runs of the identical
|
||||
binary and harness — each individual run falls outside ±20% of the
|
||||
document's number, in opposite directions. The qualitative finding holds
|
||||
(0.49.0 consistently slower than 0.43.0 at this cursor: my 0.43.0 mean
|
||||
was 1.43 ms both times) and the *average* of my two 0.49.0 reruns
|
||||
(≈2.68×) lands close to the doc's claimed 2.9×, but a single three/four-try
|
||||
reading — which is what the document and the harness's default both
|
||||
take — is not reliable at this row's magnitude on this machine. Not a
|
||||
finding against the document's conclusion, but future rounds should take
|
||||
more tries (8–10) for any sub-5 ms row used as load-bearing evidence for a
|
||||
specific multiplier.
|
||||
|
||||
### Verdict: **PASS**
|
||||
|
||||
Both findings are minor and non-blocking: finding A is a traceability gap
|
||||
with a substance-confirmed number, finding B is a reproducibility caveat
|
||||
that strengthens rather than undermines the document's own qualitative
|
||||
claim. Every row I re-ran landed inside §9's tolerance or is explained by
|
||||
machine noise the document already documents; the CLI outcome diff
|
||||
("byte-identical formatter verdicts", "20 new unused-import findings,
|
||||
17/2/1 split") reproduced exactly on three independent trees; the §8.2
|
||||
mechanism claim checks out against the source; opentitan was never
|
||||
written to; the main tree carries only the dev's files; no guard kill
|
||||
occurred anywhere in this QA pass.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 (lead).** Accepted. Read the document end to end, the §2 table
|
||||
against take 3's, the perf README entry, the harness README and the QA log.
|
||||
|
||||
- The round answers the question it was asked: 0.49.0 against 0.43.0 with
|
||||
the same client in the same hour, so the columns are comparable in a way
|
||||
take 3's could not be. The one-line reading (four things moved) is
|
||||
supported by the table, and §8.9's dismissal of the sub-millisecond rows
|
||||
is the right call on a desktop-loaded machine.
|
||||
- §8.2 verified in the source by me and by QA: `inline_site` and
|
||||
`extract_site` each re-parse the whole buffer on every `codeAction`
|
||||
(`crates/vlog_refactor/src/inline/mod.rs:74`, `extract/mod.rs:83`),
|
||||
called from `inline_module.rs:51` and `extract.rs:76`, while the server
|
||||
already holds the document's tree. The fix is the shape §37.1 used and is
|
||||
filed for the owner's ruling in TODO's loop-3 list, not done here (this
|
||||
lane fixes nothing, by design).
|
||||
- §8.3 (the tail rename at 751 ms) is filed correctly as a cost of a
|
||||
correct answer; `completion` on the same surface being free points at
|
||||
rename's reference walk, which is where a future lane should look first.
|
||||
- The harness is the durable result: nine files, standard library only,
|
||||
phases named so take 5 can diff rows by name. The 500-line split was the
|
||||
right response to §58's size rule.
|
||||
- QA finding A (the header census untraceable) fixed by a traceability
|
||||
note in §6b naming the method and QA's independent count; finding B (the
|
||||
comment-line row noisier than its band) is already stated in the
|
||||
document's tolerance text and the multiplier holds across both QA
|
||||
reruns, so no change.
|
||||
- Deviations accepted: the busier machine (stated as the largest caveat,
|
||||
mitigated structurally), the six-file harness, the ANSI row measuring an
|
||||
ANSI header because the corpus has no other kind.
|
||||
|
||||
Docs applied at merge: perf README entry (the dev's), TODO §58 ticked, the
|
||||
§8.2 gate and §8.3 walk added to the loop-3 open items.
|
||||
@@ -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
|
||||
|
||||
|
||||
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user