Compare commits

...
31 Commits
Author SHA1 Message Date
lucio bc59336d91 Release 0.51.0 — performance take 5
ci / checks (push) Successful in 1m2s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m27s
2026-09-08 04:37:51 -05:00
lucio b2a5f0a171 Perf take 5 closed (§60.5): perf README entry with the accepted numbers, the plan's and the tracker's status lines
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 32s
2026-09-08 04:36:11 -05:00
lucio 32204eba71 Perf take 5 P4b (§60.4): the startup staged behind the configuration answer (one scan at the answered scope, 2 s bound), the store not rewritten when unchanged and opened at the first step that needs it, the corpus read a file at a time in its own step, open buffers' folders at the head of the work list and a held opening request answered once that head is published; warm start 1.33 → ~1.05 s, warm idle RSS −15 to −20 %, store byte-identical across sessions, first useful answer correct in every session; state.rs split into state/ (pure move) 2026-09-08 04:36:11 -05:00
lucio 243472901d topo: perf5-p4 edges applied (table_sizes, the parsed timing lines, the trace plumbing) and the perf5 module ownership entries
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 34s
2026-09-08 00:07:17 -05:00
lucio 4621214a51 Perf take 5 P4a (§60.4): startup and memory instrumented on the --verbose channel (scan_trace, cache counters, table sizes; scanprofile/scanserve phases) — a session runs an empty scan before configuration that still opens and rewrites the 45 MB store (184 ms of a 1.33 s warm start), warm has no dominant stage and 27 % is store I/O, cold is 59 % parse; P4b ruled
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 35s
2026-09-08 00:05:43 -05:00
lucio 8e65da1ba8 Perf take 5 P3 (§60.3): one parse for the CLI package census — package_exports_in reads the census's own parse, an AST gate spares the nine files in ten that declare no package, the one-file index is built from the parse; the unused-import increment on hw/ip 142 → 5 ms, peak RSS −8.6 %, every output byte-identical
ci / checks (push) Successful in 1m12s
ci / corpus (push) Successful in 36s
2026-09-07 22:48:04 -05:00
lucio 5c9fdb2c62 Perf take 5 P2d (§60.2): handshake 33 closed by an opt-in word-census rung (module_select::hierarchical_users — stronger than the transitive walk, which cannot reach a bind from a file that instantiates nothing); the P2d census proves the 133 indirect files are container files a tail folds through, so no narrowing ships; the rename warnings stage lexes and indexes each file once (list-identical over 13 renames); tail rename 780 → 388 ms, 2.01×
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 34s
2026-09-07 21:53:19 -05:00
lucio e51a2c7f21 Perf take 5 P2a–c (§60.2): rename reuses its analysis, verification untouched — a --verbose stage trace (the tail rename was 238 files, 717 parses, two thirds repeated), one parse+analysis per file inside the scope (FileFacts::analyzed, Scope::build_keeping), the after-index absorbed from the edited files' records with every verifier check unchanged and re-attacked; tail rename 780 → 420 ms, aes rename −25%, resolves −20%, parses K+E
ci / checks (push) Successful in 1m10s
ci / corpus (push) Successful in 45s
2026-09-07 19:37:57 -05:00
lucio dafa4f0500 Perf take 5 P1c (§60.1): offer predicates instead of throwaway edits — port_offers/organize_offer answer the lightbulb from the plan-time checks with the same titles and counts, the click still recomputes and verifies; aes_reg_top offer 21.8 → 5.5 ms, aes 7.8 → 1.7, organize-imports 15.4 → 4.9; the organize-imports offer contract documented as optimistic like every other lazy offer (lead ruling on QA's finding)
ci / checks (push) Successful in 1m6s
ci / corpus (push) Successful in 41s
2026-09-07 17:35:24 -05:00
lucio 6c1f863417 Perf take 5 P1 (§60.1): code-action discovery stops repeating work — lint/config/fence gated by the requested kinds (only: [] answers at once), the fence answer asked only when a fix exists and memoized per Document, the four offer selectors read the document's own parse (additive _in APIs, text forms as wrappers), a per-thread parse counter proves a repeated offer parses nothing; pinmux no-offer comment 310 → 24 ms, queued definition likewise
ci / checks (push) Successful in 1m24s
ci / corpus (push) Successful in 36s
2026-09-07 16:05:26 -05:00
lucio 501b36d8b8 Perf take 5 P0 (§60.0): the harness tells the truth — schema 2 (units, status, result counts, client shape, fingerprints), command-bearing offers measured by a real execute phase with applyEdit capture, offerkinds/offerqueue phases, cold sweep tries actually cold; reference re-taken on the unchanged 0.50.0 binary
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 34s
2026-09-07 14:35:12 -05:00
lucio 9c75b7a4e5 TODO §60: performance take 5 sequenced into lanes P0–P4 with gates
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 37s
2026-09-07 13:44:00 -05:00
lucio be084f07b5 docs: performance take 5 — the owner's analysis, implementation plan, tracker and baseline evidence at 0.50.0 (bbdbfe9) 2026-09-07 13:44:00 -05:00
lucio bbdbfe9045 TODO: loop-2 coda — §58 and §59 shipped as 0.50.0
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 33s
2026-09-07 04:33:39 -05:00
lucio 3bd55acb98 Release 0.50.0 — the format cache key, performance take 4
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m26s
2026-09-07 04:32:49 -05:00
lucio c37b13de31 Format cache: uvm-utils-indent joins the key (§59, topo 34) — Entry carries the option, the store line has it as a fourth field, a 0.49.0 store is rebuilt not trusted; CLI regression both toggle directions
ci / checks (push) Successful in 1m15s
ci / corpus (push) Successful in 34s
2026-09-07 04:31:26 -05:00
lucio d8d1791c1c tools/perf: drop the committed __pycache__, ignore it
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 34s
2026-09-07 04:01:41 -05:00
lucio d10e57aa6e Perf take 4 (§58): 0.49.0 vs 0.43.0 on opentitan — §46's didOpen fix 14× in the release build, the eager codeAction path 2×, the tail rename at 11×, the index +14%; harness committed in tools/perf/; findings filed for loop 3
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 33s
2026-09-07 04:01:29 -05:00
lucio 414d501847 §57 closed: 0.49.0 verified (8 assets, vsix contents checked), memory rewritten; §58 perf take 4 and §59 cache-key fix filed
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 33s
2026-09-07 02:43:13 -05:00
lucio 4123905aa1 docs: repository analysis, topo and site refreshed at 0.49.0 by the owner's audit; handshake 34 filed (format cache omits uvm-utils-indent) 2026-09-07 02:43:13 -05:00
lucioandClaude Fable 5.1 df4e71411f TODO: §8 backlog closed, §55 deferred to loop 3, §57 items ticked; 0.49.0 ruled the closing release
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:16:25 -05:00
lucioandClaude Fable 5.1 6759f0eea1 Loop 2 closed: TODO order section closed with the release map and the open items for loop 3; CLAUDE.md re-measured at 0.49.0; §57 tree and docs items ticked
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:15:28 -05:00
lucioandClaude Fable 5.1 4c2dae323e Release 0.49.0 — inline module, the last coverage gaps
ci / checks (push) Successful in 1m6s
ci / corpus (push) Successful in 35s
release / build-and-publish (push) Successful in 6m20s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:13:53 -05:00
lucioandClaude Fable 5.1 a69a1cb528 Coverage gaps L3, L6, L10: six language shapes, randsequence as real nodes, an opt-in uvm_field_* indent
TODO §54 (docs/features/coverage-gaps-l); closes docs/coverage_gaps.md
L3, L6 and L10. The first dev stalled under machine load; a second
finished from the tree.

54.1 `->>` with optional delay or event control (`StmtKind::EventTrigger`),
stream `with [range]` (`ExprKind::StreamWith`), the LRM's other
`casting_type`s, drive strength on a net declaration (`DataDecl::strength`,
whose comment slots also fix a pre-existing refusal on an `assign` with
a comment before its strength), `let` at statement position
(`StmtKind::Let`), and `#(min:typ:max)` clocking skews — `ClockingSkew`
as the LRM's two alternatives, `edge [delay]` | `delay` (review rework of
QA's HIGH). Comment slots added to `let`, stream concatenations and the
clocking grammar; the RTL gap fuzzer at 505 gaps, zero failing.
54.2 `randsequence` (it was a parse error; the keyword is new):
`RandSequence` → `Production` → `Alternative` → `ProdItem` (ref, block,
if, repeat, case, rand join), code blocks by the statement grammar; one
production per line, alternatives aligned; the LRM's examples as cases.
54.3 `[format] uvm-utils-indent` / `lucisv.format.uvmUtilsIndent`, default
off, tracking nested `_begin`/`_end` pairs; 21 corpus files change with
it on, all idempotent. A short comment-free enum body already one-lines,
so no key was built — the behaviour is pinned. `[format]` table tests
added (review rework). `->>`'s event control is bound through the shared
`bind_timing` (review rework of QA's second HIGH).

0 of 820 corpus files differ from 0.48.x with the key off; the opentitan
sweep is identical; no corpus or opentitan file writes any of the new
shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:12:49 -05:00
lucioandClaude Fable 5.1 e1679bebc5 Inline module: a module's body copied into its instantiator with ports and parameters substituted, and a verifier that knows a copy
ci / checks (push) Successful in 1m29s
ci / corpus (push) Successful in 37s
TODO §53.2 (docs/features/extract-inline-module), the fifth §8
refactoring; extract → inline round-trips byte-equal after formatting.

`vlog_refactor::inline_module` (inline/{mod,site,source,render}.rs):
every symbol bound in `S`'s module scope is classified once — a port
becomes the name or literal connected to it, anything else `S` declares
at module scope is prefixed `u_S_` only when `M`'s file already spells
one of them; parameters become `localparam`s with the override or
default; the body is copied verbatim except name spans, with `.name`
shorthand connections expanded when their signal is renamed. Refusals:
`.*`, positional lists, expression connections, an unconnected port, an
output into a literal, any hierarchical reference to `u_S` in the handed
files, `S` unknown/twice/in `M`'s own file, interface/`inout`/unpacked/
non-ANSI ports, `initial`/`final`, macros, directives, any `generate`, a
differing `timescale`, collisions prefixing cannot resolve. Server:
`refactor.inline` lazy action, `lucisv.inlineModule`.

Verifier: `Moving` gains `Origin::{Moved, Copied}` — a copied region's
pieces join the transit under rule 0, "a copied file appears in no
edit"; eight attack pairs through the production entry; QA's neutering
map shows every rule load-bearing. QA's MEDIUMs filed: topo §2.9-32
(same blind spot) and §2.9-33 (`module_sources` lacks a transitive-
instantiators rung).

Trials: corpus 5 inlined / 9 refused, opentitan 5 / 56, the lint census
0 → 0 on every pair. 0 of 854 corpus files differ from 0.48.x.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 21:04:05 -05:00
lucioandClaude Fable 5.1 94b0711efb Release 0.48.2 — the 0.48.0 packages rebuilt from the commit that has the hierarchy view
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 6m51s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:14:15 -05:00
lucioandClaude Fable 5.1 449b874798 DUT-centred hierarchy view: star a module as DUT, its children and its parents in their own sections, everything else re-rooted
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 6m20s
TODO §56 (docs/features/dut-hierarchy), the owner's request of 2026-09-06.

Client-only, over the flat `lucisv/moduleHierarchy` snapshot the server
already sends. `hierarchySections.js`: per starred DUT, in starred
order, the DUT's forward subtree (the DUT at the top) and an upward tree
from the DUT through every module that instantiates it (labelled `via
<instance>`, cycles cut with one `recursive` row), then one section for
every module in no DUT's subtree or ancestor closure, re-rooted where
its only parents are DUT ancestors (the review ruling — a monitor beside
the DUT under the same bench stays on screen); a module both below one
DUT and above another appears in both DUT sections; a starred name the
index lacks keeps its sections with a "not in the index" row. Star and
unstar from the webview row menu (the pane is a WebviewView, so the
menu is the renderer's, driven by a `menuTable()` per render), the
`lucisv.hierarchy.{starDut,unstarDut,clearDuts}` commands and title
actions, persistence in `workspaceState` in starred order, and the
`lucisv.hierarchy.duts` setting whose entries show locked. With nothing
starred the pane is byte-identical to before (pinned).

opentitan `hw/ip` (847 modules): `aes` → 3 sections with `tb` in its
parents and 5 modules under `aes_tb` re-rooted into others; `aes` +
`hmac` → 5 sections; every module reachable in both configurations; QA's
200-trial fuzz found no overlap and no gap. `extract_test.js` added to
`.vscodeignore`.

(Committed after the 0.48.0 version commit: the release chain broke at a
test-output grep and cut the tag one commit early; the tag is moved here.)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:04:05 -05:00
lucioandClaude Fable 5.1 4d342367b9 Release 0.48.0 — a DUT-centred hierarchy view
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 37s
release / build-and-publish (push) Successful in 6m54s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:03:33 -05:00
lucioandClaude Fable 5.1 a5ca0c9b10 Release 0.47.0 — organize imports, extract module
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m9s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 23:04:14 -05:00
lucioandClaude Fable 5.1 acf20f7e62 Extract module: dataflow-inferred ports, a new file where the client can create one, and a verifier ledger that follows the move
TODO §53.1 (docs/features/extract-inline-module), the fourth §8
refactoring; §53.2 inline module is unstarted and runs as its own lane.

`vlog_refactor::extract` (region, flow, boundary, render): a selection
of whole module items becomes a new module — a name declared outside
and read inside is an `input`, written inside an `output` (assign and
procedural LHS, for init/step, ++/--, force/release/deassign, `-> ev`,
an initialiser, an output/inout connection through the index), written
on both sides refused; parameters passed through `#(.P(P))`, used
imports copied, the port's type taken from the declaration's own text;
the selection replaced by an instantiation rendered from the new
module's text. Forty-three refusal sentences. `RefactorEdit::created`;
the server emits `CreateFile` document changes when the client reads
both halves of the capability, else writes the module below its source;
`refactor.extract` action carrying `lucisv.extractModule [uri, range,
name]`, and a name prompt in the VS Code extension through the language
client's middleware.

The verifier's never-dropped ledger follows the move (review rework of
QA's two HIGHs): `verify_move(moving: &[(file, region)])` — a piece
deleted inside the moved region must land exactly once in the file the
move names, a deletion outside the region stays an ordinary deletion,
four equations, twelve attack pairs through the production entry;
`check.rs` split (pure move) into `check/{mod,ledger}.rs`. `interface`
and `program` bodies are refused (one AST node, gated on `kw`). QA's
re-attack: PASS; its MEDIUM (a same-file relocation as two edits) is
filed as topo §2.9-32.

Trials: corpus 5 extracted / 6 refused, opentitan `hw/ip/{aes,uart,
spi_host,hmac}` 5 / 5, the unresolved-name census held for every
accepted extraction. 0 of 820 corpus files differ from 0.46.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 23:04:14 -05:00
lucioandClaude Fable 5.1 e6eaf53c35 Organize imports: unused imports removed, duplicates merged, the run sorted; the unused-import rule; source.organizeImports
ci / checks (push) Successful in 1m2s
ci / corpus (push) Successful in 47s
TODO §52 (docs/features/organize-imports), the third §8 refactoring.

The judgement lives in `vlog_semantic::imports` (one implementation for
the refactoring and the rule): an import is used when a reference in its
scope, or one nested in it, resolves to a member of the package through
it — `resolve::lexical`'s walk stopped at the scope, every import whose
path admits the name and whose package exports it (binder tables
same-file, `members_of_chain` with re-exports otherwise) marked used, a
deliberate superset; a qualified `p::y` and an import's own package name
never count; an `export p::x` / `export p::*` / `export *::*` in the
scope marks the import it re-exports through as used (IEEE 1800 §26.6 —
the review rework of QA's HIGH, pinned four ways). Refuse to judge: an
unknown or twice-declared package, a macro call or conditional directive
anywhere in the scope, a class with an out-of-file base, a parse
diagnostic, two imports on one line. `vlog_refactor::organize_imports`
deletes the unused lines, merges exact duplicates, sorts the run at the
scope's top (package, item, `*` first), keeps every comment; the
verifier's resolution check refuses a removal a reference needs (attack
pair). `unused-import` (Style, off; safe fix) through
`MentionOracle::package_exports`, silent without a project. Server:
`lucisv: organize imports (removes N, sorts M)` under
`source.organizeImports`, `lucisv.organizeImports`.

Corpus: 40 scopes with ≥ 2 imports, 1 organized, 32 refused for macros;
the rule finds 2, both substantiated. opentitan: 33 of 33 UVM env
packages refused (`` `include "uvm_macros.svh" ``). 0 of 860 corpus
files differ from 0.46.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 20:00:31 -05:00
236 changed files with 43816 additions and 2431 deletions

No files matched your search

+1
View File
@@ -7,3 +7,4 @@
.DS_Store
/.zcode
/.claude
__pycache__/
+180
View File
@@ -4,6 +4,186 @@ 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.51.0 — 2026-09-08
### Performance take 5 — the implementation round
The owner's take-5 plan (`docs/performance_take5.md`) implemented end to
end, each stage measured against the 0.50.0 reference on opentitan
(`docs/perf/README.md`, 2026-09-08). Behaviour is unchanged everywhere the
suites and the byte-identity gates can see; what changed is how much work
the same answers cost.
- **Code actions stop repeating work.** A code-action request runs the
lint pass and reads the project configuration only when the client asks
for quick fixes or fix-all (`only: []` answers at once); the formatter's
fence answer is computed only when a finding carries a fix and once per
document revision; the four refactoring selectors read the document's
own parse instead of re-parsing the buffer; the ports and
organize-imports lightbulbs are answered from the plan-time checks with
the same titles and counts, the click still recomputing and verifying.
On opentitan's 42 192-line generated file a no-offer cursor move fell
from 310 ms to 24 ms, and the navigation queued behind it with it; an
offering cursor from 22 ms to 5.5 ms.
- **Rename reuses its analysis; the verifier is untouched.** A rename
parses and analyses each selected file once and builds its after-index
from the edited files' fresh records; every check the verifier makes is
the same code, re-attacked. The hierarchical-tail rename fell from 780
to 388 ms (2.01×), an ordinary rename 141 → 92 ms, the extract command
246 → 149 ms. A `--verbose` session now logs a per-stage rename trace.
Topology handshake 33 is closed: inline-module's hierarchical-use
refusal now sees every file whose tokens write the dissolved instance's
name, including a `bind` in a file that instantiates nothing in the
chain.
- **The CLI's package census parses once.** With `unused-import` on,
`check --select error,warning,style` no longer builds a one-file index
for every file: the census reads package exports off its one parse and
skips the nine files in ten that declare no package. The rule's cost on
`hw/ip` fell from 142 ms to 5 ms; every output is byte-identical.
- **Startup.** The server asks for the client's settings before its first
scan (2 s bound for a client that never answers) and runs one scan at
the answered scope — the empty default-scope scan is gone; the index
store is not rewritten when nothing changed and is opened at the first
step that needs it; the corpus is read a file at a time in its own step
rather than all up front; the open buffers' folders are indexed first
and the first navigation after opening a file is answered once that
folder is published — correct in every session, at ~250–275 ms, where
it used to be 84–208 ms or over a second depending on a race. Warm
start 1.33 → ~1.05 s, warm idle RSS −15 to −20 %, the store
byte-identical across sessions. `--verbose` logs a per-stage scan trace.
- **The harness** (`tools/perf/`) records units, status, result counts and
edit fingerprints on every row, measures the extract/inline commands for
real, and is what every number above was taken with.
## 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
+7
View File
@@ -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
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.46.0"
version = "0.51.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.46.0"
version = "0.51.0"
[[package]]
name = "lucisv_server"
version = "0.46.0"
version = "0.51.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.46.0"
version = "0.51.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.46.0"
version = "0.51.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -265,11 +265,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.46.0"
version = "0.51.0"
[[package]]
name = "vlog_refactor"
version = "0.46.0"
version = "0.51.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -278,7 +278,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.46.0"
version = "0.51.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.46.0"
version = "0.51.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+45 -10
View File
@@ -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
+1031 -12
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -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
}
+91 -26
View File
@@ -71,6 +71,49 @@ 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>>>,
}
/// What one file contributes to a [`Census`]: its words, the units it
/// declares, and the packages it exports from.
type PerFile = (
Vec<String>,
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
Vec<(String, Option<Vec<String>>)>,
);
/// One file's three contributions, off **one** parse.
///
/// The word census wants the tokens, the interface table wants the tree and
/// the package table wants both — so a run that asks for either table lexes
/// and parses the file exactly once and all three read that. A run that asks
/// for neither never parses at all: `harvest_text` lexes and stops, which is
/// what the word census alone needs.
///
/// A file that cannot be read contributes nothing, and so does one that does
/// not lex (`harvest_text` and a `ParsedSource` with no tokens agree on that).
/// The file's own check is what reports the error.
fn harvest_one(job: &Job, interfaces: bool, packages: bool) -> PerFile {
let Ok(src) = std::fs::read_to_string(&job.path) else {
return (Vec::new(), Vec::new(), Vec::new());
};
if !interfaces && !packages {
return (words::harvest_text(&src), Vec::new(), Vec::new());
}
let parsed = ParsedSource::parse(&src);
let declared = match interfaces {
true => vlog_linter::module_interfaces(parsed.file()),
false => Vec::new(),
};
let exports = match packages {
true => vlog_linter::package_exports_in(&job.path, parsed.file(), parsed.tokens(), &src),
false => Vec::new(),
};
(words::harvest(parsed.tokens()), declared, exports)
}
impl Census {
@@ -81,34 +124,29 @@ impl Census {
/// file's own check reports the error.
///
/// `interfaces` says whether the run also needs each unit's ports and
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
/// 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>)>);
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());
};
if !interfaces {
return (words::harvest_text(&src), Vec::new());
}
// 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()))
})
.collect();
/// parameters (`unknown-port`, `unknown-parameter`), and `packages`
/// whether it needs each package's exported names (`unused-import`).
/// Either costs a **parse** of every file on top of the lex the word
/// census already pays for, so each 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, packages: bool) -> Census {
let per_file: Vec<PerFile> =
jobs.par_iter().map(|job| harvest_one(job, interfaces, packages)).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 +160,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 +172,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 +205,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 +237,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 +335,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() {
+6 -1
View File
@@ -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
+197 -5
View File
@@ -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));
@@ -2231,3 +2294,132 @@ fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
}
// ----------------------------------------------------------------------
// The package half of the census and `unused-import` (perf5-p3, 2026-09-07)
// ----------------------------------------------------------------------
/// A package with two exported names, and the two importers the rule has to
/// tell apart.
const PKG: &str = "package p_pkg;\n localparam int A = 1;\n localparam int B = 2;\nendpackage\n";
const USES_PKG: &str = "module uses_pkg;\n import p_pkg::*;\n localparam int C = A;\nendmodule\n";
const IGNORES_PKG: &str =
"module ignores_pkg;\n import p_pkg::*;\n localparam int C = 1;\nendmodule\n";
/// The style selection the rule lives in — `unused-import` is `Severity::Style`
/// and so is off in a default `check`.
const ALL_STYLE: [&str; 2] = ["--select", "error,warning,style"];
/// The headline: over a project, an import nothing in its file uses is
/// reported, and one the file does use is not — and it is the *package
/// census* that makes the difference, because the rule can only judge an
/// import whose package the run can answer for.
#[test]
fn an_unused_package_import_is_reported_over_a_project() {
let dir = TempDir::new("pkg-census");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write("ignores_pkg.sv", IGNORES_PKG);
let out = run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]);
let text = stdout(&out);
assert!(text.contains("unused-import"), "{text}");
assert!(text.contains("ignores_pkg.sv"), "{text}");
assert!(
!text.lines().any(|line| line.contains("uses_pkg.sv") && line.contains("unused-import")),
"the file that reads `A` keeps its import: {text}"
);
assert_eq!(code(&out), 1);
}
/// `unused-import` is a style rule, so a default `check` neither reports it
/// nor is changed by the presence of a package in the run.
#[test]
fn a_default_check_says_nothing_about_imports() {
let dir = TempDir::new("pkg-default");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write("ignores_pkg.sv", IGNORES_PKG);
let out = run(&["check", &dir.root()]);
assert!(!stdout(&out).contains("unused-import"), "{}", stdout(&out));
}
/// A package the run does not contain is a package the run cannot answer
/// for, and the rule is silent about every import of it. This is the
/// conservative direction the whole feature is built around: an accusation
/// needs a known export list.
#[test]
fn an_import_of_a_package_outside_the_run_is_not_reported() {
let dir = TempDir::new("pkg-unknown");
dir.write("p_pkg.sv", PKG);
dir.write("uses_pkg.sv", USES_PKG);
dir.write(
"stranger.sv",
"module stranger;\n import elsewhere_pkg::*;\n localparam int C = 1;\nendmodule\n",
);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("elsewhere_pkg"), "an unknown package is unknowable: {text}");
}
/// A package that re-exports from another one answers `None`: only a whole
/// project index settles what a re-export chain lets through, and the CLI's
/// one-file census will not guess. Every import of it goes quiet.
#[test]
fn an_import_of_a_re_exporting_package_is_not_reported() {
let dir = TempDir::new("pkg-reexport");
dir.write("p_pkg.sv", PKG);
dir.write(
"r_pkg.sv",
"package r_pkg;\n import p_pkg::*;\n export p_pkg::*;\n localparam int D = 1;\n\
endpackage\n",
);
dir.write(
"ignores_r.sv",
"module ignores_r;\n import r_pkg::*;\n localparam int C = 1;\nendmodule\n",
);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("r_pkg"), "a re-export chain is unknowable: {text}");
}
/// Two files declaring one package name is a name the run cannot answer for,
/// whatever the two say — `Census::of`'s merge turns the second contribution
/// into `None`, and the rule goes quiet about it.
#[test]
fn an_import_of_a_package_two_files_declare_is_not_reported() {
let dir = TempDir::new("pkg-duplicate");
dir.write("p_pkg.sv", PKG);
dir.write("p_pkg_copy.sv", "package p_pkg;\n localparam int Z = 9;\nendpackage\n");
dir.write("ignores_pkg.sv", IGNORES_PKG);
let text = stdout(&run(&["check", &dir.root(), ALL_STYLE[0], ALL_STYLE[1]]));
assert!(!text.contains("unused-import"), "a duplicate package is unknowable: {text}");
}
/// The gate is a claim about *cost*, not about answers, so the answers get
/// their own end-to-end pin: a run whose only package file is surrounded by
/// files holding the word `package` in strings and comments reports exactly
/// what a run without those files reports.
#[test]
fn text_that_merely_says_package_changes_no_finding() {
let bare = TempDir::new("pkg-bare");
bare.write("p_pkg.sv", PKG);
bare.write("ignores_pkg.sv", IGNORES_PKG);
let plain = stdout(&run(&["check", &bare.root(), ALL_STYLE[0], ALL_STYLE[1]]));
let noisy = TempDir::new("pkg-noisy");
noisy.write("p_pkg.sv", PKG);
noisy.write("ignores_pkg.sv", IGNORES_PKG);
noisy.write(
"talker.sv",
"// package q_pkg; endpackage\n\
module talker;\n initial $display(\"package q_pkg; endpackage\");\nendmodule\n",
);
let with_noise = stdout(&run(&["check", &noisy.root(), ALL_STYLE[0], ALL_STYLE[1]]));
for finding in plain.lines().filter(|line| line.contains("unused-import")) {
let tail = finding.rsplit('/').next().unwrap_or(finding);
assert!(with_noise.contains(tail), "{tail} lost: {with_noise}");
}
assert_eq!(
plain.matches("unused-import").count(),
with_noise.matches("unused-import").count(),
"{plain}\n---\n{with_noise}"
);
}
+94 -19
View File
@@ -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,
+103 -1
View File
@@ -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]
+43 -6
View File
@@ -108,23 +108,49 @@ impl Candidates {
/// here, exactly as every file used to be. The two produce the same words
/// because they are the same function over the same tokens
/// ([`words_of_tokens`]).
///
/// Test-only since 2026-09-08: a scan holds every file's words and no
/// file's text, so it calls [`Candidates::from_words`]. This is that call
/// with the lex in front of it, which is what a test building tables from
/// a fixture's text wants and what makes the two one function.
#[cfg(test)]
pub fn build(
index: &WorkspaceIndex,
sources: &[(PathBuf, String)],
mut known: HashMap<PathBuf, Vec<String>>,
) -> Candidates {
let words = sources
.iter()
.map(|(path, text)| {
let words = known.remove(path).unwrap_or_else(|| words_in(text));
(path.clone(), words)
})
.collect();
Candidates::from_words(index, words)
}
/// [`Candidates::build`] for a caller that already holds **every** file's
/// words — the form a scan uses.
///
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
/// and drops it again, so there is no text left to lex when the tables are
/// built at the end. There never was any lexing to do: since `FACTS_FORMAT`
/// 13 a file's identifier census is one of its facts, so a scan already has
/// the words of every file it stepped, cached or parsed, and `build`'s
/// `known` covered the whole list. This is that call without the text it
/// no longer reads (`docs/features/perf5-p4/README.md` §P4b3).
///
/// Order-independent: the word counts are a sum and `words` is sorted at
/// the end, so a map is as good as a list here.
pub fn from_words(index: &WorkspaceIndex, words: HashMap<PathBuf, Vec<String>>) -> Candidates {
let mut out = Candidates::default();
out.take_index_tables(index);
for (path, text) in sources {
let words = match known.remove(path) {
Some(words) => words,
None => words_in(text),
};
for (path, words) in words {
for word in &words {
*out.word_files.entry(word.clone()).or_default() += 1;
}
if !words.is_empty() {
out.per_file.insert(path.clone(), words);
out.per_file.insert(path, words);
}
}
out.words = out.word_files.keys().cloned().collect();
@@ -293,6 +319,17 @@ impl Candidates {
self.remask_words();
}
/// How many entries each completion table holds, and what the word table
/// weighs — the startup memory question, asked of the one table that
/// grows with the corpus rather than with its declarations.
///
/// A walk, so it is asked once at the end of a traced scan and never on a
/// request path (`docs/features/perf5-p4/README.md`).
pub fn sizes(&self) -> (usize, usize, usize, usize) {
let word_bytes: usize = self.words.iter().map(String::len).sum();
(self.units.len(), self.macros.len(), self.words.len(), word_bytes)
}
/// Index names starting with `prefix`, case-insensitively.
pub fn units(&self, prefix: &str) -> &[Candidate] {
matching(&self.units, prefix, |c| &c.name)
+12
View File
@@ -133,6 +133,18 @@ fn title(violation: &Violation) -> String {
format!("lucisv: {what} [{}]", violation.rule)
}
/// Whether a client asking for `only` wants anything [`code_actions`] can
/// offer — a quick fix or the fix-all action.
///
/// The two kinds this module answers for are the only two the **lint pass**
/// answers for, so this is the question the dispatcher asks before reading the
/// buffer's configuration and running the rules. A client asking for
/// `refactor.*` or `source.organizeImports` alone gets neither, and now pays
/// for neither (take 5 §P1a).
pub fn wants_fixes(only: Option<&[CodeActionKind]>) -> bool {
wanted(only, &CodeActionKind::QUICKFIX) || wanted(only, &CodeActionKind::new(FIX_ALL))
}
/// Whether a client asking for `only` wants this kind. A filter is a prefix of
/// the kinds it selects (`source` selects `source.fixAll.lucisv`), and no filter
/// at all selects everything.
+384
View File
@@ -0,0 +1,384 @@
//! 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::{Document, 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.
/// Whether `[start, end)` is a selection lucisv could extract, asked of the
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
///
/// A buffer on the large-file fast path keeps the text form, whose parse is of
/// the real bytes rather than of the empty analysis that path installs — see
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
fn site_at(doc: &Document, start: u32, end: u32) -> Option<vlog_refactor::ExtractSite> {
match doc.large {
true => vlog_refactor::extract_site(&doc.text, start, end),
false => vlog_refactor::extract_site_in(&doc.tree, &doc.diagnostics, &doc.text, start, end),
}
}
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) = site_at(doc, 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) = site_at(doc, 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));
}
}
+33
View File
@@ -0,0 +1,33 @@
//! The fenced regions of an open buffer, asked once per document revision.
//!
//! `vlog_formatter::fence::protected_regions` takes **text** and parses it
//! itself, on purpose: one fence answer for every front end, and none of them
//! able to feed it a stale tree. That contract
//! (`docs/features/shared-fence-filter/README.md`) is not amended here, and
//! `fence.rs` is not touched — the call is still
//! `protected_regions(&doc.text)`, byte for byte the same question.
//!
//! What this module adds is that the answer is computed **once** for a given
//! buffer instead of once per `textDocument/codeAction`. That is safe for one
//! structural reason: a `Document` is built whole by
//! `Workspace::set_document` and thrown away by it, so the text a `Document`
//! holds cannot change without a new `Document` — and `answer_request`
//! flushes every pending change before a handler runs. There is no revision
//! number to compare because there is no way to be looking at the wrong one.
//!
//! A 42 192-line generated buffer is where this is worth having: the fence
//! parse alone measured ~59 ms of that file's code-action cost (take 5 §P1,
//! `docs/features/perf5-p1/README.md`).
use vlog_formatter::fence::{self, Region};
use crate::state::Document;
/// The regions of `doc` no tool may edit automatically.
///
/// Computed on first use and kept for the life of this `Document`. The
/// caller borrows the answer rather than a copy of it, so asking twice costs
/// a pointer.
pub fn of(doc: &Document) -> &[Region] {
doc.fences.get_or_init(|| fence::protected_regions(&doc.text))
}
+41
View File
@@ -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:
+426
View File
@@ -0,0 +1,426 @@
//! 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::{Document, 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(doc) = ws.document(uri) else { return Vec::new() };
let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() };
let Ok((removed, sorted)) = counts_at(doc, &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 two counts the offered title promises, asked of the buffer's own parse,
/// analysis and token stream, and **without** verifying the splice.
///
/// `organize_counts` computes the whole edit and runs `check::verify_splice`,
/// which rebuilds the index over every in-scope file and re-analyzes them —
/// about two thirds of the offer's cost for an answer the offer discards (take
/// 5 §P1c, `docs/features/perf5-p1/README.md`). [`resolve`] and [`execute`]
/// still compute and verify the real edit when the user picks the action.
///
/// A buffer on the large-file fast path keeps the text form, exactly as
/// [`packages_at`] does.
fn counts_at(
doc: &Document,
files: &[(PathBuf, String)],
path: &Path,
offset: u32,
) -> Result<(usize, usize), String> {
match doc.large {
true => vlog_refactor::organize_offer(files, path, offset),
false => vlog_refactor::organize_offer_in(
files,
path,
&doc.tree,
&doc.diagnostics,
&doc.semantics,
&doc.tokens,
offset,
),
}
}
/// 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.
/// Every package the scope at `offset` imports, asked of the buffer's own
/// parse and its own diagnostics rather than of its text (take 5 §P1b). A
/// buffer on the large-file fast path keeps the text form, whose parse is of
/// the real bytes — see `ports::modules_at` for the whole reason.
fn packages_at(doc: &Document, offset: u32) -> Vec<String> {
match doc.large {
true => vlog_refactor::imported_packages(&doc.text, offset),
false => {
vlog_refactor::imported_packages_in(&doc.tree, &doc.diagnostics, &doc.text, offset)
}
}
}
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 = packages_at(doc, 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();
}
}
+54 -10
View File
@@ -116,14 +116,39 @@ pub struct IncludeGraph {
impl IncludeGraph {
/// Scan every in-scope file for its `` `include``s and resolve them.
///
/// Test-only since 2026-09-08: the scan that used to hold every file's
/// text no longer does, and calls [`IncludeGraph::from_includes`] with the
/// lines it read at each file's own step. This is that call with the scan
/// in front of it — which is what makes it the right thing for a test to
/// build a graph from a fixture with, and the two provably one function.
#[cfg(test)]
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
let scanned: Vec<(PathBuf, Vec<Include>)> =
sources.iter().map(|(path, text)| (path.clone(), scan(text))).collect();
let borrowed: Vec<(&Path, &[Include])> =
scanned.iter().map(|(path, found)| (path.as_path(), found.as_slice())).collect();
IncludeGraph::from_includes(&borrowed, incdirs)
}
/// [`IncludeGraph::build`] for a caller that has already read each file's
/// `` `include`` lines off its text — the form a scan uses.
///
/// Since 2026-09-08 a scan reads a file's text at the step that indexes it
/// and drops it again, so the text is not there to be scanned when the
/// graph is built at the end; [`scan`] runs once per file, at that step,
/// and the lines it found are what arrives here
/// (`docs/features/perf5-p4/README.md` §P4b3). The two entries are the
/// same function over the same lines — `build` is this one with the scan
/// in front of it — so a graph built either way is the same graph.
pub fn from_includes(sources: &[(&Path, &[Include])], incdirs: Vec<PathBuf>) -> IncludeGraph {
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
// Learned before the edges: `resolve` consults both tables, and an edge
// resolved against a half-filled one would be keyed inconsistently.
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.to_path_buf()).collect();
graph.relearn(&paths);
for (path, text) in sources {
graph.rescan_edges(path, text);
for (path, found) in sources {
graph.rescan_found(path, found);
}
graph.respell();
graph
@@ -151,9 +176,11 @@ impl IncludeGraph {
self.respell();
}
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
/// the scope resolves to right now — the form a scan publishing what it
/// has indexed so far uses.
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
/// lines have already been read, with the `+incdir+`s the scope resolves
/// to right now — the form a scan publishing what it has indexed so far
/// uses. The lines come from the step that indexed each file, for the
/// reason [`IncludeGraph::from_includes`] gives.
///
/// `known` is the scan's whole work list rather than the files it has
/// reached, so the known-file and folded-spelling tables are complete from
@@ -162,11 +189,16 @@ impl IncludeGraph {
/// `relearn` for the batch, for the same reason
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
/// its index tables once.
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
pub fn absorb_includes(
&mut self,
incdirs: &[PathBuf],
known: &[PathBuf],
batch: &[(&Path, &[Include])],
) {
self.incdirs = incdirs.to_vec();
self.relearn(known);
for (path, text) in batch {
self.rescan_edges(path, text);
for (path, found) in batch {
self.rescan_found(path, found);
}
self.respell();
}
@@ -183,8 +215,14 @@ impl IncludeGraph {
/// each one lands. A file that includes nothing holds no entry at all,
/// which is what keeps `raw` a set of edges rather than a set of files.
fn rescan_edges(&mut self, path: &Path, text: &str) {
self.rescan_found(path, &scan(text));
}
/// [`IncludeGraph::rescan_edges`] with the file's `` `include`` lines
/// already in hand: where the disk says each one lands, held.
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
let targets: Vec<PathBuf> =
scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect();
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
match targets.is_empty() {
true => self.raw.remove(path),
false => self.raw.insert(path.to_path_buf(), targets),
@@ -230,6 +268,12 @@ impl IncludeGraph {
}
}
/// How many resolved edges the graph holds and how many files it knows —
/// the two numbers that say what a rebuilt graph weighs.
pub fn sizes(&self) -> (usize, usize) {
(self.edges.values().map(Vec::len).sum(), self.known.len())
}
/// The `+incdir+` directories an include is looked for in, in filelist
/// order — the search rungs past the including file's own directory.
pub fn incdirs(&self) -> &[PathBuf] {
+431 -10
View File
@@ -24,14 +24,17 @@
//! `docs/features/index-persistence/README.md` and is the same one
//! `lucisv_core::cache` accepts.
use std::cell::Cell;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Instant;
use lucisv_core::cache::content_hash;
use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT};
use crate::scan_trace::CacheWork;
use crate::settings::ClientSettings;
/// The store inside the cache directory.
@@ -51,6 +54,45 @@ const VERSION: &str = env!("CARGO_PKG_VERSION");
/// The subdirectory of the OS cache directory this server's stores live in.
const OS_DIR: [&str; 2] = ["lucisv", "index"];
/// What one load of the store found — the numbers that decide whether the file
/// on disk is *already* the file a compaction would write.
///
/// [`IndexCache::render`] writes this build's header and then one line per
/// path in path order, so a store this build compacted and nothing has
/// appended to since comes back with every line kept, no line dropped, no path
/// named twice and the paths ascending. Anything else — another version's
/// header, a torn line, a record the checksum rejects, two lines for one path,
/// a session's appends still unvacuumed — means the file and the render differ,
/// and compaction is what makes them the same.
#[derive(Clone, Copy, Default)]
struct Load {
/// Whether the first line was this build's own header.
header: bool,
/// Record lines the store held below the header.
read: usize,
/// Of those, the ones that became an entry of their own.
kept: usize,
/// Lines that were not a record this build can use.
dropped: usize,
/// Lines naming a path an earlier line had already named.
duplicates: usize,
/// Whether the paths arrived strictly ascending, the order `render` writes
/// them in.
ordered: bool,
}
impl Load {
/// Whether these lines are exactly the lines [`IndexCache::render`] would
/// write from the entries they produced.
fn canonical(&self) -> bool {
self.header
&& self.ordered
&& self.dropped == 0
&& self.duplicates == 0
&& self.kept == self.read
}
}
/// What one entry asserts: a file with exactly this content contributed
/// exactly these facts.
struct Entry {
@@ -75,6 +117,18 @@ pub struct IndexCache {
/// False for a missing store — which the first write claims — and for one
/// from another version, which the first write replaces wholesale.
header_ok: bool,
/// What [`IndexCache::open`] read out of the store, which is what
/// [`IndexCache::already_compact`] asks whether a rewrite would reproduce.
load: Load,
/// What this cache's own work has cost since it was opened, for the
/// startup breakdown (`docs/features/perf5-p4/README.md`).
///
/// A `Cell` because [`IndexCache::facts_for`] is a `&self` read and the
/// hash/decode split is exactly the number §P4a needed. Counted whether
/// anything is going to read it or not: four clock reads per file are
/// noise beside the decode they bracket, and a flag threaded down here to
/// save them would cost more code than time.
work: Cell<CacheWork>,
}
impl IndexCache {
@@ -96,24 +150,62 @@ impl IndexCache {
/// whose tail was cut inside a multi-byte character costs the record that
/// was torn and no other. Reading the whole buffer as text would have
/// rejected all of it for one bad byte at the end.
///
/// The load is *counted* as well as performed — lines read, kept, dropped
/// and duplicated, and whether the paths arrived in order — because those
/// five numbers are what say whether the file already is what
/// [`IndexCache::compact`] would write over it.
pub fn open(dir: Option<PathBuf>) -> IndexCache {
let Some(dir) = dir else { return IndexCache::disabled() };
let bytes = std::fs::read(dir.join(FILE)).unwrap_or_default();
let mut lines = store_lines(&bytes).into_iter();
let header_ok = lines.next() == Some(header().as_bytes());
let mut entries = HashMap::new();
let mut load = Load { header: header_ok, ordered: true, ..Load::default() };
if header_ok {
let mut previous: Option<PathBuf> = None;
for line in lines {
let Ok(line) = std::str::from_utf8(line) else { continue };
if let Some((path, entry)) = parse_entry(line) {
// A later record for a path wins: the log is appended to
// as a rescan goes, so the last one written is the one
// that describes the file as the server last saw it.
entries.insert(path, entry);
load.read += 1;
let Ok(line) = std::str::from_utf8(line) else {
load.dropped += 1;
continue;
};
let Some((path, entry)) = parse_entry(line) else {
load.dropped += 1;
continue;
};
if let Some(previous) = &previous {
load.ordered &= *previous < path;
}
previous = Some(path.clone());
// A later record for a path wins: the log is appended to
// as a rescan goes, so the last one written is the one
// that describes the file as the server last saw it.
match entries.insert(path, entry) {
Some(_) => load.duplicates += 1,
None => load.kept += 1,
}
}
}
IndexCache { dir: Some(dir), entries, log: None, header_ok }
let work = Cell::new(CacheWork { opens: 1, ..CacheWork::default() });
IndexCache { dir: Some(dir), entries, log: None, header_ok, load, work }
}
/// What this cache has spent and moved since it was opened.
pub fn work(&self) -> CacheWork {
self.work.get()
}
/// How many records this cache is holding.
pub fn entry_count(&self) -> usize {
self.entries.len()
}
/// The encoded bytes those records weigh — the retention §P4's memory
/// hypothesis is about, since every one of them sits beside a decoded
/// copy in the workspace index.
pub fn encoded_bytes(&self) -> usize {
self.entries.values().map(|entry| entry.facts.len()).sum()
}
/// Where this cache writes. Test-only: production opens a cache from a
@@ -133,11 +225,28 @@ impl IndexCache {
/// they were written with, which [`IndexCache::open`] drops before it ever
/// gets here.
pub fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
let entry = self.entries.get(path)?;
if entry.content != content_hash(text.as_bytes()) {
let looking = Instant::now();
let found =
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()));
let mut work = self.work.get();
work.lookup_ns += elapsed_ns(looking);
let Some(entry) = found else {
work.misses += 1;
self.work.set(work);
return None;
};
let decoding = Instant::now();
let facts = FileFacts::decode(&entry.facts);
work.decode_ns += elapsed_ns(decoding);
work.decoded_bytes += entry.facts.len();
// A record that no longer decodes costs a parse, so it is a miss —
// the counters say what the scan actually did, not what it looked up.
match facts.is_some() {
true => work.hits += 1,
false => work.misses += 1,
}
FileFacts::decode(&entry.facts)
self.work.set(work);
facts
}
/// Record what parsing `text` found, and write it through immediately.
@@ -149,13 +258,36 @@ impl IndexCache {
/// the checksum of the facts it was written with) for the same reasons it
/// rejects any other malformed record. That is the whole crash-safety
/// argument, and it is why records are one line each.
///
/// **A record the store already holds is not written again.** An open
/// buffer is indexed from its own analysis on every scan and its record is
/// written through with it, so a warm session appends a line for every
/// open buffer that is byte-identical to the line already in the store —
/// a duplicate the next load collapses, at the price of making the store
/// non-canonical and so owing [`IndexCache::compact`] a full rewrite. The
/// test is the exact one: same path, same content hash, same encoded
/// facts. Anything that differs by a byte is a new record and is appended
/// as it always was.
pub fn record(&mut self, facts: &FileFacts, text: &str) {
if self.dir.is_none() {
return;
}
let encoding = Instant::now();
let Some(encoded) = facts.encode() else { return };
let content = content_hash(text.as_bytes());
let mut work = self.work.get();
work.encode_ns += elapsed_ns(encoding);
if self.holds(facts.path(), content, &encoded) {
work.repeats += 1;
self.work.set(work);
return;
}
let writing = Instant::now();
self.append(&line(content, &encoded));
work.write_ns += elapsed_ns(writing);
work.records += 1;
work.written_bytes += encoded.len();
self.work.set(work);
self.entries.insert(facts.path().to_path_buf(), Entry { content, facts: encoded });
}
@@ -171,7 +303,76 @@ impl IndexCache {
/// Atomic and silent: written to a temporary file and renamed, and a
/// failure anywhere leaves the previous store standing. A cache that could
/// fail a rescan would be worse than no cache.
///
/// **Skipped when the rewrite would reproduce the file byte for byte**
/// ([`IndexCache::already_compact`]). A warm session whose every file hit
/// the store appends nothing, so the store it loaded is the store it would
/// write, and rewriting 44 MiB to produce the same 44 MiB was 182 ms of a
/// 1.33 s start (`docs/features/perf5-p4/README.md`, §P4b (a)).
pub fn compact(&mut self) {
let before = self.store_bytes();
let compacting = Instant::now();
let rewriting = !self.already_compact();
if rewriting {
self.compact_now();
}
let mut work = self.work.get();
work.compact_ns += elapsed_ns(compacting);
work.compactions += usize::from(rewriting);
work.store_before = before;
work.store_after = self.store_bytes();
self.work.set(work);
}
/// Whether the store on disk is already exactly what [`IndexCache::render`]
/// would write over it.
///
/// Four things have to hold, and any one of them failing compacts as
/// before:
///
/// * the store was **loaded canonical** — this build's header, every line
/// a record this build can read, no path named twice, the paths
/// ascending ([`Load::canonical`]);
/// * **nothing has been appended since**, so no line is out of order and
/// no path has a second one;
/// * **no entry's file is gone**, because `render` drops those;
/// * there is a directory to write in at all.
///
/// **Crash safety is untouched.** A session that appended nothing left the
/// store exactly as it found it, so what is on disk is already the
/// compacted file and there is no half-written state a rewrite would
/// resolve; skipping it only means the append log — which has no appends —
/// stays as it is. The existence sweep is the one part that costs
/// anything, one `stat` per entry, against the whole-store render and
/// write it stands in for.
fn already_compact(&self) -> bool {
self.dir.is_some()
&& self.load.canonical()
&& self.work.get().records == 0
&& self.entries.keys().all(|path| path.exists())
}
/// Whether the store already holds exactly this record — the same path,
/// the same content hash and the same encoded facts, byte for byte.
///
/// Only exactly that counts. A record whose facts differ by a byte under
/// the same hash is still written, because the line on disk and the facts
/// in hand would then disagree and the store must say what this session
/// last saw.
fn holds(&self, path: &Path, content: u64, encoded: &str) -> bool {
self.entries
.get(path)
.is_some_and(|entry| entry.content == content && entry.facts == encoded)
}
/// The store file's size on disk, or 0 when there is no store.
fn store_bytes(&self) -> u64 {
let Some(dir) = self.dir.as_ref() else { return 0 };
std::fs::metadata(dir.join(FILE)).map(|meta| meta.len()).unwrap_or_default()
}
/// [`IndexCache::compact`] without the accounting around it.
fn compact_now(&mut self) {
let Some(dir) = self.dir.clone() else { return };
// The append handle must go before the rename, or a later append would
// write into the file the rename replaced.
@@ -342,6 +543,11 @@ fn line(content: u64, facts: &str) -> String {
/// `None` for anything that is not a whole record whose facts still match
/// their checksum, which includes the torn last line of a store whose writer
/// was killed.
/// Nanoseconds since `from`, saturated into the counters' `u64`.
fn elapsed_ns(from: Instant) -> u64 {
from.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
}
fn parse_entry(line: &str) -> Option<(PathBuf, Entry)> {
let (hash, rest) = line.split_once('\t')?;
// Exactly as wide as `line` writes it: a hash that reads as a number but
@@ -720,6 +926,221 @@ mod tests {
}
}
/// A store two files were recorded into and then compacted — this build's
/// header and one line per path in path order, which is what every
/// session after a whole rescan finds on disk.
fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) {
let one = dir.file("a.sv", M);
let two = dir.file("b.sv", M);
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.record(&facts(&one, M), M);
cache.record(&facts(&two, M), M);
cache.compact();
assert_eq!(cache.work().compactions, 1, "premise: the store was written");
(one, two)
}
/// The store's bytes and its modification time — "not rewritten" as
/// something a test can see rather than infer.
fn store_stamp(dir: &TempDir) -> (Vec<u8>, std::time::SystemTime) {
let path = dir.path.join(FILE);
let bytes = std::fs::read(&path).expect("read store");
let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime");
(bytes, stamp)
}
/// Rewrite the store's record lines, keeping this build's header.
fn rewrite_records(dir: &TempDir, records: &[String]) {
let mut text = header();
for record in records {
text.push('\n');
text.push_str(record);
}
text.push('\n');
std::fs::write(dir.path.join(FILE), text).expect("write store");
}
/// The store's record lines, header excluded.
fn records_of(dir: &TempDir) -> Vec<String> {
dir.store_text().lines().skip(1).map(str::to_string).collect()
}
#[test]
fn a_canonical_store_nothing_appended_to_is_not_rewritten() {
// §P4b (a): a warm session hits the store for every file, appends
// nothing, and would rewrite 44 MiB to produce the same 44 MiB —
// 182 ms of a 1.33 s start. What is on disk is already what `render`
// writes, so the rewrite is skipped and the file is not touched at
// all: not its bytes, not even its modification time.
let dir = TempDir::new("alreadycompact");
let (one, _) = compacted_store(&dir);
let before = store_stamp(&dir);
let mut warm = IndexCache::open(Some(dir.path.clone()));
assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads");
warm.compact();
assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical");
assert_eq!(store_stamp(&dir), before, "so the store was not touched");
// And what is on disk is still a store: the next session reads it.
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
}
#[test]
fn a_record_the_store_already_holds_is_not_appended_again() {
// An open buffer is indexed from its own analysis on *every* scan and
// its record is written through with it, so a warm session would
// append a byte-identical duplicate for each open buffer — which
// costs the store its canonical shape and so owes the next scan a
// whole 44 MiB rewrite. The same record is a no-op; a changed one is
// not (`docs/features/perf5-p4/README.md`, §P4b (a)).
let dir = TempDir::new("repeatrecord");
let (one, _) = compacted_store(&dir);
let before = store_stamp(&dir);
let mut warm = IndexCache::open(Some(dir.path.clone()));
warm.record(&facts(&one, M), M);
assert_eq!(warm.work().records, 0, "nothing was appended");
assert_eq!(warm.work().repeats, 1, "and the store was already holding it");
assert_eq!(store_stamp(&dir), before, "so the store on disk did not move");
warm.compact();
assert_eq!(warm.work().compactions, 0, "which leaves it canonical");
assert_eq!(store_stamp(&dir), before);
// One byte of difference and the record is written exactly as before.
let edited = "module m;\n sub u ();\n wire w;\nendmodule\n";
warm.record(&facts(&one, edited), edited);
assert_eq!(warm.work().records, 1, "different bytes are a new record");
assert_eq!(warm.work().repeats, 1);
warm.compact();
assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again");
assert_eq!(
IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited),
Some(facts(&one, edited)),
"the newer record is what the next session reads"
);
}
#[test]
fn a_store_with_two_lines_for_one_path_is_compacted() {
// The growth bound the skip must not cost: a session that saved a
// file appended a second line for its path, and only a rewrite folds
// the two back into one.
let dir = TempDir::new("dupline");
let (one, _) = compacted_store(&dir);
let mut records = records_of(&dir);
let repeat = records[0].clone();
records.push(repeat);
rewrite_records(&dir, &records);
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.compact();
assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical");
assert_eq!(records_of(&dir).len(), 2, "one line per path again");
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
}
#[test]
fn a_store_with_a_line_this_build_cannot_read_is_compacted() {
// A record dropped at load — a torn append, bit rot, a checksum that
// no longer matches — means the file on disk holds a line `render`
// would not write, so the store is not canonical and the rewrite is
// what removes it.
let dir = TempDir::new("droppedline");
let (one, _) = compacted_store(&dir);
let mut records = records_of(&dir);
records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0));
rewrite_records(&dir, &records);
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.compact();
assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical");
assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone");
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
}
#[test]
fn a_store_whose_records_are_out_of_path_order_is_compacted() {
// `render` writes paths sorted, so a store that arrives unsorted was
// not written by a compaction of this shape and rewriting it is not a
// no-op — even though every line in it is a good record.
let dir = TempDir::new("unsorted");
let (one, _) = compacted_store(&dir);
let mut records = records_of(&dir);
records.reverse();
rewrite_records(&dir, &records);
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.compact();
assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical");
let sorted: Vec<String> = records_of(&dir);
assert_eq!(sorted.len(), 2);
assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}");
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
}
#[test]
fn a_session_that_recorded_one_file_compacts() {
// The moment an append happens the store on disk is no longer the
// store `render` would write — the appended line is out of order at
// best and a second line for its path at worst — so the rewrite is
// owed exactly as it always was.
let dir = TempDir::new("appended");
let (one, _) = compacted_store(&dir);
let third = dir.file("c.sv", M);
let mut cache = IndexCache::open(Some(dir.path.clone()));
assert!(cache.facts_for(&one, M).is_some(), "the other two still hit");
cache.record(&facts(&third, M), M);
cache.compact();
assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite");
assert_eq!(records_of(&dir).len(), 3);
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some());
}
#[test]
fn a_store_holding_a_file_that_is_gone_is_compacted() {
// `render` drops an entry whose file no longer exists, so a store
// holding one is not what a rewrite would produce — and the rewrite
// is what prunes it, exactly as before.
let dir = TempDir::new("goneentry");
let (one, two) = compacted_store(&dir);
std::fs::remove_file(&two).expect("remove");
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.compact();
assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned");
assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone");
assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some());
}
#[test]
fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() {
// The header is the one line the skip may never leave standing: its
// records were dropped at load, so a session that keeps it leaves a
// store nobody can read on disk for ever.
let dir = TempDir::new("foreignheader");
let file = dir.file("m.sv", M);
let encoded = facts(&file, M).encode().expect("encodes");
let foreign = format!(
"lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n",
line(content_hash(M.as_bytes()), &encoded)
);
std::fs::write(dir.path.join(FILE), foreign).expect("write");
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.compact();
assert_eq!(cache.work().compactions, 1, "another version's header is not canonical");
let text = dir.store_text();
assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}");
}
#[test]
fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() {
// The line is well-formed as far as the store is concerned — hash,
+270
View File
@@ -0,0 +1,270 @@
//! 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::module_select::Reach;
use crate::state::{Document, 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.
/// Whether the cursor is on an instantiation lucisv could inline, asked of the
/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b).
///
/// A buffer on the large-file fast path keeps the text form, whose parse is of
/// the real bytes rather than of the empty analysis that path installs — see
/// `ports::modules_at` and `docs/features/perf5-p1/README.md`.
fn site_at(doc: &Document, offset: u32) -> Option<vlog_refactor::InlineSite> {
match doc.large {
true => vlog_refactor::inline_site(&doc.text, offset),
false => vlog_refactor::inline_site_in(&doc.tree, &doc.diagnostics, &doc.text, offset),
}
}
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) = site_at(doc, 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) = site_at(doc, 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 — **plus the fifth rung**: every file whose tokens
// write the instance's own name down. A file naming
// `u_wrapper.u_top.u_sub.s` reaches this instance through modules it does
// not itself instantiate, and the first four rungs have nothing that asks
// for it (topology handshake 33). The rung is the exact census
// `no_hierarchy` can refuse from, so this set answers that refusal the way
// the whole workspace would.
let scopes = [site.instance.clone()];
let files = ws.module_sources_reaching(&path, &site.units, Reach { scopes: &scopes });
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));
}
}
+48 -9
View File
@@ -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
@@ -433,13 +445,23 @@ pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation
// line a checked-in waiver file had waived.
let ctx = run.context(doc).with_tab_width(tab_width);
let found = lint_with(&ctx, &run.rules, &run.external).0;
// One tolerant parse per code-action request: `protected_regions` takes
// text and parses internally, on purpose — one fence answer for every
// front end, none of which can feed it a stale tree (see
// `docs/features/shared-fence-filter/README.md`). The per-keystroke
// diagnostics path pays nothing, because it never reads a fix.
let regions = fence::protected_regions(&doc.text);
found.into_iter().filter(|violation| !fix_touches_fence(violation, &regions)).collect()
// The fence answer is a whole second tolerant parse of the buffer:
// `protected_regions` takes text and parses internally, on purpose — one
// fence answer for every front end, none of which can feed it a stale tree
// (see `docs/features/shared-fence-filter/README.md`). It protects
// *fixes*, so a pass whose findings carry no fix has nothing to protect
// and nothing to ask: the filter below would be the identity. Skipping it
// there is take 5 §P1a. The per-keystroke diagnostics path pays nothing
// either, because it never reads a fix.
if !found.iter().any(|violation| violation.fix.is_some()) {
return found;
}
// Asked once per document revision rather than once per request: the text
// a `Document` holds cannot change without a new `Document` (§P1b,
// `crate::fences`). The question itself is unchanged — still
// `protected_regions` over this buffer's text.
let regions = crate::fences::of(doc);
found.into_iter().filter(|violation| !fix_touches_fence(violation, regions)).collect()
}
/// True when a violation carries a fix any edit of which lands in a fenced
@@ -516,6 +538,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");
+94 -7
View File
@@ -13,21 +13,26 @@ mod convert;
mod design_hierarchy;
mod diagnostics;
mod expand;
mod extract;
mod fences;
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;
mod linked;
mod lint;
mod locate;
mod module_select;
mod nav;
mod on_type;
mod pairs;
@@ -35,6 +40,9 @@ mod pairs;
mod perf;
mod ports;
mod rename;
mod rename_trace;
mod scan_order;
mod scan_trace;
mod selection;
mod server;
mod settings;
@@ -59,11 +67,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 +136,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
token_server_cancel: token_server_cancel_support(&params),
hierarchy_view,
code_action_resolve: code_action_resolve_support(&params),
create_files: create_files_support(&params),
};
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
@@ -260,6 +270,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 +410,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 +539,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 +1221,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::{
+146
View File
@@ -0,0 +1,146 @@
//! Which files can name a scope *inside* the module a refactoring rewrites.
//!
//! [`Workspace::module_sources`](crate::state::Workspace::module_sources)'s
//! four rungs answer "who declares, instantiates or refers to these **names**".
//! That is enough for the port refactorings and for extract, whose refusals
//! are about the names themselves. It is not enough for inline-module, whose
//! `no_hierarchy` refusal is about a *path through the design hierarchy*:
//! `tb.sv` writing `u_wrapper.u_top.u_sub.s` names the instance `u_sub` that
//! inlining dissolves, and `tb.sv` instantiates `wrapper` — not `top`, not
//! `sub`. No rung asks for it, `no_hierarchy` only sees what it is handed, and
//! the inline was **silently accepted**, dissolving a scope a testbench walks
//! through. §53.2's QA reproduced exactly that; it is topology handshake 33.
//!
//! **The rung is the instance's own word census.** `no_hierarchy` refuses when
//! some handed file's token stream holds an `Ident` spelling the instance with
//! a `.` (or a `bind`) beside it. [`WorkspaceIndex::files_mentioning`] is the
//! census of every file whose token stream writes a word down at all — read
//! off `FileFacts::words`, which `vlog_semantic::words::harvest` fills from
//! every `Ident` token *and* from the raw text of macro invocations,
//! directives and attributes. So a file that could raise that refusal is
//! always in this answer, and [`hierarchical_users`] hands inline exactly the
//! files that could change its mind.
//!
//! That is a stronger claim than the transitive-instantiator walk the topology
//! row asks for, and it is why this module does not do that walk. Climbing the
//! instantiation edges upward from the host module finds the wrapper levels,
//! but it misses `bind tb.u_wrapper.u_top.u_sub …` written in an SVA file that
//! instantiates nothing in the chain, and `$root`-anchored and macro-built
//! paths with it — all shapes `no_hierarchy` refuses over and all shapes the
//! word census holds. It also selects files that instantiate up the chain and
//! never spell the instance, which no refusal can turn on. The census is both
//! the tighter and the more complete answer. Written out in the feature
//! README's handshake note, with the failing `bind` fixture that settled it.
//!
//! The rung can only **add** files, so an edit stays the edit it was and a
//! refusal it makes possible is one the whole-workspace engine also makes.
//! Nothing here reads a file or parses anything: it is a walk over the records
//! the index already holds, binary-searching each file's sorted word list.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use vlog_semantic::WorkspaceIndex;
/// The extra reach one refactoring asks for.
///
/// A caller that needs none passes [`Reach::none`] — which is what
/// `module_sources` itself does, so the port and extract paths are unchanged
/// by this module in answer and in cost.
#[derive(Debug, Clone, Copy, Default)]
pub struct Reach<'a> {
/// The scope names whose *inside* the refactoring dissolves: for
/// inline-module, the instance it removes. Every file whose tokens write
/// one of these words is wanted, because every file that could refuse
/// over a hierarchical path through it does.
pub scopes: &'a [String],
}
impl Reach<'_> {
/// No extra reach — the four rungs alone.
pub fn none() -> Reach<'static> {
Reach { scopes: &[] }
}
}
/// Every file whose token stream writes one of `reach`'s scope names.
///
/// The caller unions this into the set its own rungs filled, so a path this
/// rung is the first to ask for is still just a path.
pub fn hierarchical_users(index: &WorkspaceIndex, reach: Reach<'_>) -> BTreeSet<PathBuf> {
let mut out = BTreeSet::new();
for scope in reach.scopes {
out.extend(
index
.files_mentioning(scope)
.filter_map(|file| index.path(file))
.map(Path::to_path_buf),
);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// `tb` → `wrapper` → `top` → `sub`, the shape §53.2's QA reported: `tb`
/// names `u_sub` through two levels it does not itself instantiate, and
/// `sva.sv` names it through a `bind` while instantiating nothing at all.
fn ladder() -> WorkspaceIndex {
WorkspaceIndex::build(vec![
(PathBuf::from("/w/sub.sv"), "module sub; logic s; endmodule\n"),
(PathBuf::from("/w/top.sv"), "module top; sub u_sub (); endmodule\n"),
(PathBuf::from("/w/wrapper.sv"), "module wrapper; top u_top (); endmodule\n"),
(
PathBuf::from("/w/tb.sv"),
"module tb; wrapper u_wrapper (); assign x = u_wrapper.u_top.u_sub.s; endmodule\n",
),
(
PathBuf::from("/w/sva.sv"),
"module chk (input logic a); endmodule\nbind tb.u_wrapper.u_top.u_sub chk u_chk (.a(1'b0));\n",
),
(PathBuf::from("/w/stranger.sv"), "module stranger; logic q; endmodule\n"),
])
}
fn names(paths: &BTreeSet<PathBuf>) -> Vec<String> {
paths
.iter()
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.collect()
}
#[test]
fn every_file_that_writes_the_instance_down_is_wanted() {
let index = ladder();
let scopes = ["u_sub".to_string()];
let found = hierarchical_users(&index, Reach { scopes: &scopes });
assert_eq!(
names(&found),
vec!["sva.sv".to_string(), "tb.sv".to_string(), "top.sv".to_string()],
"the declaring file, the bench two levels up, and the bind that instantiates nothing"
);
}
#[test]
fn a_file_that_never_writes_it_is_not() {
let index = ladder();
let scopes = ["u_sub".to_string()];
assert!(!names(&hierarchical_users(&index, Reach { scopes: &scopes }))
.contains(&"stranger.sv".to_string()));
}
#[test]
fn a_name_nothing_writes_wants_nothing() {
let index = ladder();
let scopes = ["u_no_such_instance".to_string()];
assert!(hierarchical_users(&index, Reach { scopes: &scopes }).is_empty());
}
#[test]
fn no_reach_asked_for_is_no_work_done() {
let index = ladder();
assert!(hierarchical_users(&index, Reach::none()).is_empty());
}
}
+14 -7
View File
@@ -401,7 +401,7 @@ fn what_a_scan_does_before_its_first_file() {
});
workspace.adopt_roots(vec![dir.clone()]);
let started = Instant::now();
let mut scan = workspace.begin_scan(&mut |_| {});
let mut scan = workspace.begin_scan(&mut |_| {}, false);
let head = started.elapsed();
let started = Instant::now();
workspace.scan_step(&mut scan, &mut |_| {});
@@ -556,7 +556,7 @@ fn what_a_jump_into_a_new_folder_costs_before_and_after() {
let added: Vec<PathBuf> =
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
let started = Instant::now();
let mut scan = incremental.begin_widen(&added, &mut |_| {});
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
while incremental.scan_step(&mut scan, &mut |_| {}) {}
black_box(incremental.finish_scan(scan));
let widen = started.elapsed();
@@ -646,7 +646,7 @@ fn what_a_widen_that_subsumes_the_old_scope_costs() {
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
let mut read = 0usize;
let started = Instant::now();
let mut scan = incremental.begin_widen(&added, &mut |_| {});
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
while incremental.scan_step(&mut scan, &mut |_| read += 1) {}
// Split out because it is where the 2026-08-29 round's fix landed: folding
// a widen's words into the completion table used to move the table's tail
@@ -1120,9 +1120,15 @@ fn a_rename_before_and_after() {
let _ = black_box(vlog_refactor::rename(&sources, &path, black_box(offset), "renamed"));
});
let rename_after = mean(20, || {
let _ = black_box(crate::rename::rename(&ws, &uri, black_box(offset), "renamed"));
let _ = black_box(crate::rename::rename_traced(
&ws,
&uri,
black_box(offset),
"renamed",
&mut None,
));
});
let fan_out = ws.rename_sources(&path, "sub", Some("renamed")).len();
let fan_out = ws.rename_sources_traced(&path, "sub", Some("renamed")).0.len();
// Building the file set at all, and the one rung of it that is a linear
// walk over every file's records rather than a keyed lookup
// (`WorkspaceIndex::files_spelling`, the new name's dangling-use rung —
@@ -1130,7 +1136,7 @@ fn a_rename_before_and_after() {
// it is the only part of the set builder whose cost grows with the
// workspace rather than with the symbol.
let file_set = mean(2_000, || {
black_box(ws.rename_sources(black_box(&path), "sub", Some("renamed")));
black_box(ws.rename_sources_traced(black_box(&path), "sub", Some("renamed")));
});
let spelling_rung = mean(2_000, || {
black_box(ws.index().files_spelling(black_box("renamed")).count());
@@ -1138,7 +1144,8 @@ fn a_rename_before_and_after() {
// A measurement of an answer that was not given is worthless.
assert!(crate::rename::prepare(&ws, &uri, offset).is_ok());
let (edit, _) = crate::rename::rename(&ws, &uri, offset, "renamed").expect("renames");
let (edit, _) =
crate::rename::rename_traced(&ws, &uri, offset, "renamed", &mut None).expect("renames");
assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops");
eprintln!(
+59 -6
View File
@@ -36,7 +36,7 @@ use vlog_parser::LineIndex;
use vlog_refactor::{ModuleRef, RefactorEdit};
use crate::convert::Positions;
use crate::state::Workspace;
use crate::state::{Document, Workspace};
use crate::uri::{path_to_uri, uri_to_path};
/// The kind every port refactoring is filed under, so a client can ask for
@@ -73,6 +73,24 @@ pub fn commands() -> Vec<String> {
/// ([`Workspace::module_sources`]), which is ~1.4 ms per instantiating file:
/// fine once, when the user has clicked, and not fine on every cursor move,
/// which is why [`offers`] exists.
/// Every module name a port refactoring at `offset` could act on, asked of
/// the buffer's **own parse** rather than of its text.
///
/// `doc.tree` is the tolerant parse of `doc.text`, which is exactly what the
/// text form would build (`docs/features/one-parse/README.md`), so the answer
/// is the same and the parse is not paid for twice (take 5 §P1b).
///
/// A buffer on the large-file fast path is the exception, and deliberately so:
/// its `tree` is the analysis of the *empty* file, while the text form parses
/// the real bytes and may offer. That is today's behaviour and this reuse does
/// not change it — see `docs/features/perf5-p1/README.md`.
fn modules_at(doc: &Document, offset: u32) -> Vec<String> {
match doc.large {
true => vlog_refactor::port_action_modules(&doc.text, offset),
false => vlog_refactor::port_action_modules_in(&doc.tree, offset),
}
}
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
let Some(path) = doc.path.clone() else { return Vec::new() };
@@ -82,7 +100,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
// find something, it says which module, so the files handed to the engine
// are that module's own fan-out rather than every file in scope
// (`Workspace::module_sources`).
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
let modules = modules_at(doc, offset);
if modules.is_empty() {
return Vec::new();
}
@@ -146,7 +164,7 @@ pub fn offers(
) -> Vec<CodeActionOrCommand> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
let Some(path) = doc.path.clone() else { return Vec::new() };
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
let modules = modules_at(doc, offset);
// A name the workspace declares twice is a refusal the engine makes over
// the fan-out, where it can see both declarations. The offer cannot, so it
// asks the index the same question rather than offering an action that
@@ -155,10 +173,10 @@ pub fn offers(
return Vec::new();
}
let sources = offer_sources(ws, &path, &doc.text, &modules);
vlog_refactor::port_actions(&sources, &path, offset)
offered(doc, &sources, &path, offset)
.into_iter()
.map(|action| {
let title = counted(ws, action.title, &modules);
.map(|offer| {
let title = counted(ws, offer.title, &modules);
let data =
serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() })
.ok();
@@ -172,6 +190,40 @@ pub fn offers(
.collect()
}
/// Which refactorings the cursor would be offered, and what each title says —
/// asked of the buffer's **own** parse and analysis rather than recomputed.
///
/// `vlog_refactor::port_offers_in` runs each of the four planners' plan-time
/// half over `doc`'s existing tree, diagnostics and semantics plus, at most,
/// one parse of the instantiated module's declaring file. It builds no index
/// and verifies nothing, which is the whole of take 5 §P1c: the offer used to
/// compute four verified plans over one or two files and throw all four edits
/// away (`docs/features/perf5-p1/README.md`). [`resolve`] still recomputes and
/// verifies the real refactoring over the module's whole fan-out when the user
/// clicks.
///
/// A buffer on the large-file fast path keeps the text form, whose parse is of
/// the real bytes — [`modules_at`] draws the same line, and for the same
/// reason.
fn offered(
doc: &Document,
sources: &[(PathBuf, String)],
path: &Path,
offset: u32,
) -> Vec<vlog_refactor::PortOffer> {
match doc.large {
true => vlog_refactor::port_offers(sources, path, offset),
false => vlog_refactor::port_offers_in(
sources,
path,
&doc.tree,
&doc.diagnostics,
&doc.semantics,
offset,
),
}
}
/// The files an [`offers`] call reads: the buffer the request names, and the
/// declaration of every module an instantiation under the cursor names.
///
@@ -349,6 +401,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()))
}
+37 -10
View File
@@ -20,6 +20,7 @@ use vlog_parser::LineIndex;
use crate::convert::Positions;
use crate::locate::display_name;
use crate::rename_trace::SelectionTrace;
use crate::state::Workspace;
use crate::uri::path_to_uri;
@@ -48,11 +49,19 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameRe
/// The whole rename as a `WorkspaceEdit`, plus whatever the engine wants the
/// user told. An `Err` is the engine's own sentence, returned verbatim.
pub fn rename(
/// `trace` is filled whenever the request got as far as asking the engine,
/// refusals included, because a rename that refuses after 800 ms is exactly
/// the kind this exists to explain (take 5 §P2a). Its two halves are the
/// server's ([`SelectionTrace`]: which rung wanted which file) and the
/// engine's ([`vlog_refactor::RenameTrace`]: where the time and the parses
/// went); it reaches a user only through `--verbose`'s `timing:` channel, and
/// a caller that wants none passes `&mut None`.
pub fn rename_traced(
ws: &Workspace,
uri: &Uri,
offset: u32,
new_name: &str,
trace: &mut Option<String>,
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
@@ -62,11 +71,18 @@ pub fn rename(
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
// the engine will say so, and saying it is cheap either way.
let old_name = vlog_refactor::rename_name_at(&doc.semantics, offset);
let sources = match &old_name {
Some(name) => ws.rename_sources(&path, name, Some(new_name)),
None => ws.sources(),
let (sources, selection) = match &old_name {
Some(name) => ws.rename_sources_traced(&path, name, Some(new_name)),
None => {
let all = ws.sources();
let selection = SelectionTrace::whole_scope(all.len(), 0.0);
(all, selection)
}
};
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
let mut engine = vlog_refactor::RenameTrace::default();
let outcome = vlog_refactor::rename_traced(&sources, &path, offset, new_name, &mut engine);
*trace = Some(format!("{} {}", selection.line(), engine.line()));
let refactoring = outcome?;
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
for (path, edits) in &refactoring.edits {
@@ -116,7 +132,7 @@ pub fn rename(
/// about the one shape it cannot see.
///
/// Subtracting the handed set leaves out every open buffer too, because
/// [`Workspace::rename_sources`] puts every open buffer in it.
/// [`Workspace::rename_sources_traced`] puts every open buffer in it.
fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String)]) -> Vec<String> {
let index = ws.index();
index
@@ -141,6 +157,17 @@ mod tests {
use std::path::{Path, PathBuf};
use std::str::FromStr;
/// [`rename_traced`] with the trace thrown away — what a test that is not
/// about the trace asks.
fn rename(
ws: &Workspace,
uri: &Uri,
offset: u32,
new_name: &str,
) -> Result<(WorkspaceEdit, Vec<String>), String> {
rename_traced(ws, uri, offset, new_name, &mut None)
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
@@ -281,7 +308,7 @@ mod tests {
fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec<PathBuf> {
let doc = ws.document_for_path(path).expect("the request's file is open");
match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
None => ws.sources(),
}
.into_iter()
@@ -301,7 +328,7 @@ mod tests {
let everything = ws.sources();
let doc = ws.document_for_path(path).expect("the request's file is open");
let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
None => everything.clone(),
};
for (path, text) in &subset {
@@ -955,7 +982,7 @@ mod tests {
// The premise: `far.svh` is in no rung of the fan-out, so the engine
// never sees it. Asked of the same function `rename` asks.
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
assert!(
!handed.iter().any(|(path, _)| path.ends_with("far.svh")),
"premise: the engine is not handed far.svh — {handed:?}"
@@ -989,7 +1016,7 @@ mod tests {
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
let (ws, uri) = macro_workspace(&tree, &far);
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
assert!(
handed.iter().any(|(path, _)| path.ends_with("far.svh")),
"premise: instantiating `sub` puts far.svh in the source set"
+302
View File
@@ -0,0 +1,302 @@
//! Which rung of the rename fan-out put each file in the engine's input.
//!
//! Take 5 §P2a (`docs/features/perf5-p2/README.md`). `Workspace::rename_sources_traced`
//! climbs six rungs and has one escape hatch, and the tracker's own note says
//! it plainly: *two output files is not an input count*. A rename of `state_q`
//! may hand the engine hundreds of files and nobody could say which rung asked
//! for them. This module is the answer — a set of paths that also remembers
//! **why** each one was added.
//!
//! [`Wanted`] is a `BTreeMap<PathBuf, Rung>` with a current [`Rung`]: the
//! selector sets the rung it is on and inserts exactly as it did before, so
//! the selection logic is not changed by being watched. The first rung to ask
//! for a path is the one recorded, which is what makes the counts add up to
//! the selected set rather than over-counting a file three rungs want.
//!
//! Take 5 §P2d added the second question on top of the first: of the files a
//! rung asked for, how many **write neither name down** and are therefore in
//! the request only to shape how the others resolve ([`indirect_census`]).
//! That census is what says which rung a narrower selector would have to
//! argue about, and the argument it needs.
//!
//! Nothing here decides anything. A [`SelectionTrace`] is written, logged once
//! behind `--verbose`, and dropped.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use vlog_semantic::WorkspaceIndex;
/// Why one file is in a rename's input.
///
/// One variant per rung of [`crate::state::Workspace::rename_sources_traced`]'s
/// ladder, in the order the ladder climbs them.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Rung {
/// The file the request was made in.
#[default]
Request,
/// A file declaring one of the two names — its own file, from
/// `workspace_symbols` or `hierarchical_declarations`.
Declaration,
/// A file the index recorded a use of such a declaration in.
Reference,
/// A file instantiating the name, or one of its containers.
Instantiation,
/// A file whose `` `define`` table names it or spells it in a macro body.
MacroText,
/// A file spelling the **new** name in a use this workspace had to look
/// outside that file to answer.
Speller,
/// An open buffer, added whatever else it is.
OpenBuffer,
}
impl Rung {
/// The name this rung is counted under in the `timing:` line.
fn label(self) -> &'static str {
match self {
Rung::Request => "request",
Rung::Declaration => "declaration",
Rung::Reference => "reference",
Rung::Instantiation => "instantiation",
Rung::MacroText => "macro",
Rung::Speller => "speller",
Rung::OpenBuffer => "open",
}
}
/// Every rung, in ladder order — so a trace line always has the same
/// fields whether or not a rung contributed.
const ALL: [Rung; 7] = [
Rung::Request,
Rung::Declaration,
Rung::Reference,
Rung::Instantiation,
Rung::MacroText,
Rung::Speller,
Rung::OpenBuffer,
];
}
/// How many files each rung was the first to ask for, and whether the
/// ambiguity escape hatch fired.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SelectionTrace {
counts: Vec<(Rung, usize)>,
/// The index could not bound the fan-out, so every in-scope file went.
pub fallback: bool,
/// How many files went in the end.
pub selected: usize,
/// Milliseconds the selection itself took, reading and all.
pub ms: f64,
/// Per rung, how many of its files write **neither** name down —
/// [`indirect_census`]. Empty on the fallback path, which climbs no rung.
pub indirect: Vec<(Rung, usize)>,
}
impl SelectionTrace {
/// The trace of a selection that gave up and handed over the whole scope
/// — the ambiguity escape hatch, and a cursor with no name to fan out
/// from. No rung ran, so none is counted.
pub fn whole_scope(selected: usize, ms: f64) -> SelectionTrace {
SelectionTrace { counts: Vec::new(), fallback: true, selected, ms, indirect: Vec::new() }
}
/// One file added by `rung`, if no earlier rung had it.
fn add(&mut self, rung: Rung) {
match self.counts.iter_mut().find(|(held, _)| *held == rung) {
Some((_, count)) => *count += 1,
None => self.counts.push((rung, 1)),
}
}
/// How many files this rung was the first to ask for.
pub fn count(&self, rung: Rung) -> usize {
self.counts.iter().find(|(held, _)| *held == rung).map_or(0, |(_, count)| *count)
}
/// The trace as one `timing:`-style fragment.
pub fn line(&self) -> String {
let rungs: Vec<String> = Rung::ALL
.iter()
.map(|rung| format!("{}={}", rung.label(), self.count(*rung)))
.collect();
format!(
"select={:.1}ms selected={} fallback={} rungs{{{}}} {}",
self.ms,
self.selected,
self.fallback,
rungs.join(" "),
census_line(&self.indirect)
)
}
}
/// The path set a fan-out fills, plus the rung it is currently climbing.
///
/// `paths` is exactly the `BTreeSet<PathBuf>` the selector built before; the
/// only difference is that an insertion also tells the trace which rung made
/// it. A path already held is not re-attributed, so the counts partition the
/// selected set.
#[derive(Debug, Default)]
pub struct Wanted {
paths: BTreeMap<PathBuf, Rung>,
trace: SelectionTrace,
rung: Rung,
}
impl Wanted {
/// An empty set, on the rung a request's own file is added by.
pub fn new() -> Wanted {
Wanted::default()
}
/// Climb to `rung`: every insertion until the next call is attributed to
/// it.
pub fn on(&mut self, rung: Rung) {
self.rung = rung;
}
/// Add one path, attributed to the current rung if it is new.
///
/// `entry(…).or_insert(…)`, not `insert(…)`: the map keeps the **first**
/// rung to ask for a path, which is what makes the counts partition the
/// selected set. A plain `insert` would overwrite with the last.
pub fn insert(&mut self, path: PathBuf) {
let rung = self.rung;
let before = self.paths.len();
self.paths.entry(path).or_insert(rung);
if self.paths.len() != before {
self.trace.add(rung);
}
}
/// [`Wanted::insert`] over an iterator — the shape the selector's
/// `wanted.extend(...)` calls had.
pub fn extend(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
for path in paths {
self.insert(path);
}
}
/// The paths, in path order and each with the rung that asked for it, and
/// the trace of how they got there.
pub fn finish(self) -> (BTreeMap<PathBuf, Rung>, SelectionTrace) {
let Wanted { paths, mut trace, .. } = self;
trace.selected = paths.len();
(paths, trace)
}
}
/// How many files each rung asked for that **write neither name down**.
///
/// The census §P2d turns on. Every direct input of the four verifier checks is
/// a file that spells one of the two names: an occurrence is a use of the old
/// name, `check::watched_files` watches exactly the files whose text holds
/// either as a whole word, `Scope::warnings` speaks only about the two names,
/// and an edited file is a subset of the watched ones. A selected file that
/// writes neither is therefore in the request for one reason only — **it
/// shapes how the others resolve**, by declaring a unit some path hops
/// through or a base class a member lookup climbs to.
///
/// So this is not "files that could be dropped". It is the exact set whose
/// contribution is *indirect*, which is the set a narrower selector has to
/// argue about one shape at a time. Counting it by rung says which rung the
/// argument would have to be made for.
///
/// The word census is `FileFacts::words`, so this reads no file and parses
/// nothing. It is asked of the **selected** files only — one `facts_for` and
/// two binary searches each — rather than through
/// [`WorkspaceIndex::files_mentioning`], which would walk every record in the
/// workspace to answer about a couple of hundred of them. On the tail rename
/// that is the difference between ~1.7 ms and ~0.05 ms, and a diagnostic that
/// costs a measurable slice of the request it is measuring is a bad
/// instrument.
///
/// A path the index has no record for — an open buffer the scan has not
/// reached — counts as spelling the name: the census may not claim a file is
/// idle when it does not know.
pub fn indirect_census(
index: &WorkspaceIndex,
paths: &BTreeMap<PathBuf, Rung>,
names: [&str; 2],
) -> Vec<(Rung, usize)> {
let idle = |path: &Path| match index.facts_for(path) {
Some(facts) => !names
.iter()
.any(|name| facts.words().binary_search_by(|w| w.as_str().cmp(name)).is_ok()),
None => false,
};
Rung::ALL
.iter()
.map(|rung| {
let count = paths.iter().filter(|(path, held)| *held == rung && idle(path)).count();
(*rung, count)
})
.collect()
}
/// [`indirect_census`] as one `timing:`-style fragment — every rung named,
/// whether or not it contributed, so the line's shape never moves.
pub fn census_line(census: &[(Rung, usize)]) -> String {
let fields: Vec<String> = Rung::ALL
.iter()
.map(|rung| {
let count = census.iter().find(|(held, _)| held == rung).map_or(0, |(_, n)| *n);
format!("{}={}", rung.label(), count)
})
.collect();
format!("indirect{{{}}}", fields.join(" "))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_rung_to_ask_for_a_path_is_the_one_counted() {
let mut wanted = Wanted::new();
wanted.insert(PathBuf::from("/rtl/a.sv"));
wanted.on(Rung::Reference);
wanted.insert(PathBuf::from("/rtl/a.sv"));
wanted.insert(PathBuf::from("/rtl/b.sv"));
let (paths, trace) = wanted.finish();
assert_eq!(paths.len(), 2);
assert_eq!(trace.count(Rung::Request), 1);
assert_eq!(trace.count(Rung::Reference), 1);
assert_eq!(trace.selected, 2);
// And the map agrees with the counts: a re-insertion does not
// re-attribute, which is what makes the census partition the set.
assert_eq!(paths[&PathBuf::from("/rtl/a.sv")], Rung::Request);
assert_eq!(paths[&PathBuf::from("/rtl/b.sv")], Rung::Reference);
}
#[test]
fn the_census_counts_only_the_files_that_write_neither_name() {
let index = WorkspaceIndex::build(vec![
(PathBuf::from("/w/decl.sv"), "module decl; logic state_q; endmodule\n"),
(PathBuf::from("/w/user.sv"), "module user; decl u_d (); endmodule\n"),
(PathBuf::from("/w/reads.sv"), "module reads; assign x = u_d.state_q; endmodule\n"),
]);
let mut paths = BTreeMap::new();
paths.insert(PathBuf::from("/w/decl.sv"), Rung::Declaration);
paths.insert(PathBuf::from("/w/reads.sv"), Rung::Reference);
paths.insert(PathBuf::from("/w/user.sv"), Rung::Instantiation);
let census = indirect_census(&index, &paths, ["state_q", "state_q_x"]);
let count = |rung: Rung| census.iter().find(|(r, _)| *r == rung).map_or(0, |(_, n)| *n);
assert_eq!(count(Rung::Declaration), 0, "it declares the name");
assert_eq!(count(Rung::Reference), 0, "it spells the name");
assert_eq!(count(Rung::Instantiation), 1, "it only instantiates the container");
assert!(census_line(&census).contains("instantiation=1"), "{}", census_line(&census));
}
#[test]
fn every_rung_appears_in_the_line_even_at_zero() {
let trace = SelectionTrace::default();
let line = trace.line();
for rung in Rung::ALL {
assert!(line.contains(&format!("{}=0", rung.label())), "{line} lacks {rung:?}");
}
}
}
+193
View File
@@ -0,0 +1,193 @@
//! What order a scan walks its work list in, and how much of that order a
//! request answered mid-scan is owed.
//!
//! A scan indexes every in-scope file, and [`vlog_semantic::IndexBuilder`]
//! sorts its records by path inside `finish`, so **no insertion order can
//! reach the finished index**. What the order decides is what the *prefix* of
//! a scan holds — which file the progress bar names first, and what a request
//! answered between two files can see (`docs/features/scan-interleave`).
//!
//! Three groups, in this order:
//!
//! 1. the **open buffers' own files** — the ones the user is looking at;
//! 2. every other file under those buffers' **raised scope directories** —
//! the neighbourhood `docs/features/index-scope/README.md`'s folder rung
//! would have indexed for them;
//! 3. everything else, in path order.
//!
//! Group 1 was the whole of `Workspace::open_first` until 2026-09-08, and on
//! its own it made the first useful answer of a workspace-scoped session
//! *empty*: a definition sent with the opening `didOpen` was answered off a
//! prefix holding that one buffer and the alphabet after it, and the module it
//! named lives in the folder next door. Group 2 is that folder
//! (`docs/features/perf5-p4/README.md` §P4b3).
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vlog_semantic::index_order;
/// A scan's work list, ordered, with the length of its head segment.
pub struct WorkList {
/// Every file the scan will index, in the order it will index them.
pub files: Vec<PathBuf>,
/// How many files at the front of `files` are the user's own
/// neighbourhood — groups 1 and 2 above.
///
/// **0 means there is no neighbourhood worth waiting for**: no buffer is
/// open, none of them has a folder in scope, or the folders cover so much
/// of the work list that "the user's own folder" and "the workspace" are
/// the same wait. See [`work_list`].
pub head: usize,
}
/// The user's own file.
const OWN: u8 = 0;
/// A file under one of the folders the user's own files raise to.
const FOLDER: u8 = 1;
/// Everything else.
const TAIL: u8 = 2;
/// Order `files` open-buffers-first, then their folders, then the rest.
///
/// `open` is every open buffer's own path and `folders` the directories those
/// buffers raise to (`Workspace::raised`). Both may be empty, and an empty
/// `folders` is the ordering this function had before 2026-09-08.
///
/// The head is reported raw; [`worth_waiting`] is what bounds it, because the
/// bound is against the **whole** scan and this function may be ordering only
/// what is left of one.
pub fn work_list(files: Vec<PathBuf>, open: &[PathBuf], folders: &[PathBuf]) -> WorkList {
// Asked of `vlog_semantic` rather than re-derived here, so the count a
// scan reports is the count the index will hold: sorted by path, one entry
// per path.
let ordered = index_order(files.into_iter().map(|path| (path, ())));
let own: HashSet<&Path> = open.iter().map(PathBuf::as_path).collect();
let mut ranked: Vec<(u8, PathBuf)> =
ordered.into_iter().map(|(path, ())| (rank(&path, &own, folders), path)).collect();
// Stable, so each group keeps the path order `index_order` sorted it into.
ranked.sort_by_key(|(rank, _)| *rank);
let head = ranked.iter().take_while(|(rank, _)| *rank < TAIL).count();
WorkList { files: ranked.into_iter().map(|(_, path)| path).collect(), head }
}
/// `pending` — the files a held request would wait for — or **0** when that is
/// too many to wait for in a scan of `total` files.
///
/// A request held for the startup scan waits for the whole neighbourhood
/// before it is answered ([`WorkList::head`]), which is a good trade only
/// while the neighbourhood is a small part of the scan: a buffer opened from a
/// workspace *root* raises to that root, and waiting for "its folder" would be
/// waiting for the entire scan and answering nothing at all until it ended. So
/// a neighbourhood that is not a minority of the workspace is no
/// neighbourhood — the ordering still applies, and the drain falls back to the
/// first interleave point exactly as it did before.
///
/// **`pending` is what is left to wait for, not where the segment ends.** A
/// `didOpen` can arrive at any point of a scan, and re-ordering puts its
/// folder next: 124 files is 124 files of waiting whether the scan has done
/// none of the workspace or nine tenths of it.
pub fn worth_waiting(pending: usize, total: usize) -> usize {
match pending * 2 > total {
true => 0,
false => pending,
}
}
/// Which of the three groups `path` belongs to.
fn rank(path: &Path, own: &HashSet<&Path>, folders: &[PathBuf]) -> u8 {
if own.contains(path) {
return OWN;
}
match folders.iter().any(|folder| path.starts_with(folder)) {
true => FOLDER,
false => TAIL,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn paths(names: &[&str]) -> Vec<PathBuf> {
names.iter().map(PathBuf::from).collect()
}
fn names(list: &WorkList) -> Vec<String> {
list.files.iter().map(|p| p.display().to_string()).collect()
}
#[test]
fn with_nothing_open_the_list_is_path_order_and_there_is_no_head() {
let list = work_list(paths(&["/w/z.sv", "/w/a.sv", "/w/m.sv"]), &[], &[]);
assert_eq!(names(&list), ["/w/a.sv", "/w/m.sv", "/w/z.sv"]);
assert_eq!(list.head, 0, "nothing is waited for when nothing is open");
}
#[test]
fn the_open_buffer_leads_then_its_folder_then_the_rest() {
let list = work_list(
paths(&[
"/w/other/far.sv",
"/w/ip/aes/rtl/aes.sv",
"/w/ip/aes/dv/tb.sv",
"/w/other/near.sv",
]),
&paths(&["/w/ip/aes/dv/tb.sv"]),
&paths(&["/w/ip/aes"]),
);
assert_eq!(
names(&list),
["/w/ip/aes/dv/tb.sv", "/w/ip/aes/rtl/aes.sv", "/w/other/far.sv", "/w/other/near.sv"],
"the buffer, then its folder, then the rest in path order"
);
assert_eq!(list.head, 2, "the buffer and its folder are what a held request waits for");
}
#[test]
fn a_folder_that_is_most_of_the_workspace_is_not_a_head_to_wait_for() {
// A buffer opened from the workspace root raises to the root, so
// "its folder" is the whole scan. The order is unchanged; the drain
// falls back to the first interleave point.
let files = paths(&["/w/a.sv", "/w/b.sv", "/w/c.sv"]);
let list = work_list(files, &paths(&["/w/a.sv"]), &paths(&["/w"]));
assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv", "/w/c.sv"]);
assert_eq!(list.head, 3, "the ranking itself says the whole list is the folder");
assert_eq!(worth_waiting(list.head, 3), 0, "and that is no head at all");
}
#[test]
fn exactly_half_is_still_a_head_and_one_more_is_not() {
assert_eq!(worth_waiting(2, 4), 2, "two of four is a minority");
assert_eq!(worth_waiting(3, 4), 0, "three of four is not");
assert_eq!(worth_waiting(0, 4), 0, "and nothing is nothing");
}
#[test]
fn the_bound_is_against_the_whole_scan_and_not_against_what_is_left() {
// The `didOpen` that names a folder can arrive at any point of a scan.
// Measured against the tail alone, a 124-file folder would stop being
// worth waiting for once 3 700 of a 3 976-file workspace were done —
// which is exactly when it costs least.
assert_eq!(worth_waiting(124, 3_976), 124, "124 files of 3 976, at any point of it");
}
#[test]
fn a_path_handed_over_twice_is_one_file() {
let list = work_list(paths(&["/w/a.sv", "/w/a.sv", "/w/b.sv"]), &[], &[]);
assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv"]);
}
#[test]
fn an_open_buffer_outside_the_scope_still_lends_its_folder() {
// The buffer's own file is not in the work list — it is over the size
// cap, say — but the folder it raised is still the neighbourhood.
let list = work_list(
paths(&["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]),
&paths(&["/w/ip/aes/dv/huge.sv"]),
&paths(&["/w/ip/aes"]),
);
assert_eq!(names(&list), ["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]);
assert_eq!(list.head, 1);
}
}
+543
View File
@@ -0,0 +1,543 @@
//! What one workspace scan spent its time on, and what the tables it left
//! behind weigh — the startup breakdown take 5 §P4a exists to measure.
//!
//! A [`ScanTrace`] rides on the [`crate::state::Scan`] it describes. It is a
//! bag of sums and counters and nothing else: no per-file allocation, no
//! per-file string, no `Vec` that grows with the work list, so a traced scan
//! costs a handful of clock reads per file and two `format!`s at the end. It
//! is off unless `--verbose` asked for it ([`ScanTrace::new`]), and off means
//! [`ScanTrace::now`] hands back `None` and every `add` below is a branch.
//!
//! The three lines it renders go out on the `timing:` channel
//! (`docs/features/verbose-timing/README.md`) when the scan ends. They are
//! `key=value` after a human prefix because both readers matter: a person
//! grepping an output channel, and `tools/perf/phases_p4.py`, which turns
//! them into schema-2 rows.
use std::cell::Cell;
use std::time::Instant;
use vlog_semantic::WorkspaceIndex;
thread_local! {
static READS: Cell<u64> = const { Cell::new(0) };
}
/// How many source files this thread has read off disk for a scan.
///
/// A work counter, not a timer, and modelled on `vlog_parser::stats::parses`
/// for the same reason: the claim a scan makes since 2026-09-08 is that it
/// reads each file's bytes **exactly once** — the content hash, the parse and
/// the `` `include`` scan all come out of that one read — and the honest way
/// to prove that is to count the reads. A stopwatch would be a flake; a count
/// is not.
///
/// Per thread, because `cargo test` runs tests in parallel and a process-wide
/// counter would be adding up every other test's scans. Monotone and never
/// reset, so a caller measures a delta.
///
/// Only a test asks — this is a bin crate, so nothing outside it can — while
/// [`count_read`] is **unconditional**: one non-atomic add per file is noise
/// beside the read it counts, and gating the increment as well would mean the
/// path under test and the shipped path were not the same code.
#[cfg(test)]
pub fn source_reads() -> u64 {
READS.with(Cell::get)
}
/// Count one file read off disk — see [`source_reads`].
pub fn count_read() {
READS.with(|reads| reads.set(reads.get() + 1));
}
use crate::candidates::Candidates;
use crate::includes::IncludeGraph;
use crate::index_cache::IndexCache;
/// What the persistent store's own work cost, counted inside
/// [`crate::index_cache::IndexCache`] because that is where it happens.
///
/// Always counted, trace or no trace: the four clock reads a file costs here
/// are noise beside the read and the decode they bracket, and a flag threaded
/// through the cache to save them would be more code than it saves time.
#[derive(Clone, Copy, Default)]
pub struct CacheWork {
/// Hashing the text and finding the entry — what every lookup pays,
/// whether it hits or misses.
pub lookup_ns: u64,
/// Decoding the record of a lookup that hit.
pub decode_ns: u64,
/// Encoding a record on the way out.
pub encode_ns: u64,
/// Appending an encoded record to the log.
pub write_ns: u64,
/// Rewriting the whole store at the end of a whole scan.
pub compact_ns: u64,
/// Lookups that found a record for exactly these bytes.
pub hits: usize,
/// Lookups that did not, and so cost a parse.
pub misses: usize,
/// Records written through.
pub records: usize,
/// Write-throughs the store already held, byte for byte, and so did not
/// append again — one per open buffer on a warm scan (§P4b (a)).
pub repeats: usize,
/// Encoded bytes handed to `FileFacts::decode`.
pub decoded_bytes: usize,
/// Encoded bytes appended to the log.
pub written_bytes: usize,
/// Times the store was read off disk. One per whole rescan that reached a
/// file — a scan whose work list is empty opens nothing (§P4b (b1)).
pub opens: usize,
/// Times the store was actually rewritten. Zero when the rewrite would
/// have reproduced the file byte for byte (§P4b (a)).
pub compactions: usize,
/// The store file's size before and after a compaction, in bytes.
pub store_before: u64,
pub store_after: u64,
}
impl CacheWork {
/// This session's counters minus the ones a scan started with, so a scan
/// reports its own work rather than the process's.
pub fn since(self, before: CacheWork) -> CacheWork {
CacheWork {
lookup_ns: self.lookup_ns.saturating_sub(before.lookup_ns),
decode_ns: self.decode_ns.saturating_sub(before.decode_ns),
encode_ns: self.encode_ns.saturating_sub(before.encode_ns),
write_ns: self.write_ns.saturating_sub(before.write_ns),
compact_ns: self.compact_ns.saturating_sub(before.compact_ns),
hits: self.hits.saturating_sub(before.hits),
misses: self.misses.saturating_sub(before.misses),
records: self.records.saturating_sub(before.records),
repeats: self.repeats.saturating_sub(before.repeats),
decoded_bytes: self.decoded_bytes.saturating_sub(before.decoded_bytes),
written_bytes: self.written_bytes.saturating_sub(before.written_bytes),
opens: self.opens.saturating_sub(before.opens),
compactions: self.compactions.saturating_sub(before.compactions),
store_before: self.store_before,
store_after: self.store_after,
}
}
}
/// How big the tables a finished scan leaves behind are — the memory half of
/// §P4a, in counts and bytes rather than in a resident-set reading.
#[derive(Clone, Copy, Default)]
pub struct TableSizes {
pub index_files: usize,
pub unit_names: usize,
pub unit_defs: usize,
pub members: usize,
pub hier_members: usize,
pub reference_keys: usize,
pub reference_sites: usize,
pub defines: usize,
pub instantiations: usize,
pub fact_words: usize,
pub fact_word_bytes: usize,
pub candidate_units: usize,
pub candidate_macros: usize,
pub candidate_words: usize,
pub candidate_word_bytes: usize,
pub include_edges: usize,
pub include_known: usize,
}
/// One scan's stage times, counts and end-state sizes.
///
/// Every `*_ms` is a sum over however many times that stage ran: `parse_ms`
/// is every parse of the scan added up, `absorb_ms` is the one final absorb,
/// `publish_absorb_ms` is the mid-scan ones.
#[derive(Default)]
pub struct ScanTrace {
on: bool,
/// When the scan began — the first thing [`crate::state::Workspace::begin_scan`] does.
started: Option<Instant>,
/// How long the server had been alive when this scan began.
pub since_start_ms: f64,
/// Whether this scan rebuilds the whole index or folds a widen in.
pub kind: &'static str,
/// Which scan of the session this is, counting from 1.
pub number: u32,
// -- discovery ------------------------------------------------------
/// Resolving the scope, walking it, asking the size cap about each file
/// and taking every open buffer's text. **Not** reading the files: since
/// 2026-09-08 that happens at the step that indexes each one, and is
/// `read_ms` below (`docs/features/perf5-p4/README.md` §P4b3).
pub discovery_ms: f64,
/// Sorting into index order and putting the user's own neighbourhood at
/// the front ([`crate::scan_order`]).
pub order_ms: f64,
/// Reading the persistent store off disk.
pub cache_open_ms: f64,
/// Reading one file's text off disk, at the step that indexes it, summed
/// over the scan. An open buffer's text is not read and not timed here:
/// the scan took it when the work list was.
pub read_ms: f64,
/// Files the scan will read, known when the work list is taken — and the
/// bytes it has read so far, which only equals the whole list once the
/// scan has finished.
pub read: usize,
pub read_bytes: usize,
/// The bytes the scan **holds** for its whole life: the open buffers'
/// texts, taken with the work list because their facts were. Every other
/// file's text lives from its own step to the end of it, which is what
/// `work_kib` on the memory line reports.
pub work_bytes: usize,
/// Files the size cap kept out.
pub skipped: usize,
/// Entries the store held when it was opened, and their encoded bytes.
pub cache_entries: usize,
pub cache_bytes: usize,
// -- per file -------------------------------------------------------
/// Parsing a file the store could not answer for, and its bytes.
pub parse_ms: f64,
pub parse_bytes: usize,
/// Files indexed from an open buffer's own finished analysis. Untimed:
/// there is nothing to time — the facts are already in hand, and what
/// that file then costs is the record the store writes through, which is
/// counted with every other record below.
pub buffers: usize,
/// The store's own work over this scan.
pub cache: CacheWork,
// -- mid-scan publishes ---------------------------------------------
pub publishes: usize,
pub published: usize,
pub publish_absorb_ms: f64,
pub publish_candidates_ms: f64,
pub publish_includes_ms: f64,
pub publish_overlay_ms: f64,
/// When the first publish landed, measured from the start of the scan —
/// the earliest moment a request answered mid-scan can see any of it.
pub first_publish_ms: f64,
// -- the end --------------------------------------------------------
/// Working out which files left the scope.
pub gone_ms: f64,
pub absorb_ms: f64,
pub candidates_ms: f64,
pub includes_ms: f64,
/// Re-resolving every open buffer against the finished index.
pub overlay_ms: f64,
pub overlays: usize,
/// The whole scan, `begin_scan` to the end of `finish_scan`.
pub total_ms: f64,
pub sizes: TableSizes,
}
impl ScanTrace {
/// A trace that records, or one that does nothing at all.
pub fn new(on: bool) -> ScanTrace {
ScanTrace { on, started: on.then(Instant::now), ..ScanTrace::default() }
}
/// A trace for a scan that is starting, numbered so a session's lines can
/// be told apart — or an inert one when nobody asked for a trace.
///
/// `scans` is the session's own count of scans so far and is advanced
/// here, so a line's number is the number of the scan that prints it.
/// `since_start_ms` is left for the server to stamp: how long the process
/// had been alive is the server's own knowledge, not the workspace's.
pub fn opened(scans: &mut u32, on: bool, kind: &'static str) -> ScanTrace {
*scans = scans.saturating_add(1);
ScanTrace { kind, number: *scans, ..ScanTrace::new(on) }
}
/// Whether anything below will be recorded.
pub fn on(&self) -> bool {
self.on
}
/// The work list's size, the bytes the scan will hold for as long as it
/// runs, and the store counters this scan is measured from.
///
/// `held` is what the scan is carrying — the open buffers' texts — and not
/// the work list's own bytes, which are read a file at a time and let go
/// again ([`ScanTrace::saw_read`]).
///
/// `cache` is the baseline [`ScanTrace::landed`] subtracts: a widen
/// inherits the store the previous scan opened, so the counters on it are
/// the session's and not this scan's. A whole scan that opens one of its
/// own resets the baseline when it does.
pub fn measure_work(&mut self, files: usize, held: usize, skipped: usize, cache: CacheWork) {
if !self.on {
return;
}
self.read = files;
self.work_bytes = held;
self.skipped = skipped;
self.cache = cache;
}
/// One file's text, read at the step that indexes it.
pub fn saw_read(&mut self, bytes: usize, from: Option<Instant>) {
if !self.on {
return;
}
ScanTrace::add(&mut self.read_ms, from);
self.read_bytes += bytes;
}
/// Close this trace: the tables the finished scan left behind, measured.
///
/// Every size below is a walk, so all of them are behind [`ScanTrace::on`]
/// and none of them happens in a session that did not ask for a trace.
pub fn landed(
&mut self,
overlays: usize,
cache: &IndexCache,
index: &WorkspaceIndex,
candidates: &Candidates,
includes: &IncludeGraph,
) {
if !self.on {
return;
}
// Read first, before a single size below is walked: describing a scan
// is not part of the scan, and charging the walks to `total_ms` would
// make the trace inflate the very number it exists to explain.
self.total_ms = self.elapsed_ms();
self.overlays = overlays;
self.cache = cache.work().since(self.cache);
// At the *end*, so the store's retention is what the finished scan
// leaves resident rather than what it started from — the two differ
// by every record a cold scan wrote.
self.cache_entries = cache.entry_count();
self.cache_bytes = cache.encoded_bytes();
let tables = index.table_sizes();
let counts = index.counts();
let (units, macros, words, word_bytes) = candidates.sizes();
let (include_edges, include_known) = includes.sizes();
self.sizes = TableSizes {
index_files: counts.files,
unit_names: tables.unit_names,
unit_defs: tables.unit_defs,
members: tables.members,
hier_members: tables.hier_members,
reference_keys: tables.reference_keys,
reference_sites: tables.reference_sites,
defines: counts.defines,
instantiations: counts.instantiations,
fact_words: tables.words,
fact_word_bytes: tables.word_bytes,
candidate_units: units,
candidate_macros: macros,
candidate_words: words,
candidate_word_bytes: word_bytes,
include_edges,
include_known,
};
}
/// The clock a stage is timed from — `None`, and so free, when off.
pub fn now(&self) -> Option<Instant> {
self.on.then(Instant::now)
}
/// Add the time since `from` to `slot`. Nothing at all when off, because
/// `now` handed out no clock to be since.
pub fn add(slot: &mut f64, from: Option<Instant>) {
if let Some(from) = from {
*slot += millis(from);
}
}
/// How long this scan has been running, or 0 when it is not being traced.
pub fn elapsed_ms(&self) -> f64 {
self.started.map(millis).unwrap_or_default()
}
/// Stamp the first publish, if this is the first one.
pub fn saw_publish(&mut self, files: usize) {
self.publishes += 1;
self.published += files;
if self.publishes == 1 {
self.first_publish_ms = self.elapsed_ms();
}
}
/// The stage line: every `*_ms` this scan collected, in the order the
/// scan spends them.
pub fn stage_line(&self) -> String {
let c = &self.cache;
format!(
"scan {} stages ({}, {} files): discovery={:.2} order={:.2} cache_open={:.2} \
read={:.2} lookup={:.2} decode={:.2} parse={:.2} encode={:.2} store_write={:.2} \
publish_absorb={:.2} publish_candidates={:.2} publish_includes={:.2} \
publish_overlay={:.2} gone={:.2} absorb={:.2} compact={:.2} candidates={:.2} \
includes={:.2} overlay={:.2} total={:.2} since_start={:.2} ms",
self.number,
self.kind,
self.read,
self.discovery_ms,
self.order_ms,
self.cache_open_ms,
self.read_ms,
nanos(c.lookup_ns),
nanos(c.decode_ns),
self.parse_ms,
nanos(c.encode_ns),
nanos(c.write_ns),
self.publish_absorb_ms,
self.publish_candidates_ms,
self.publish_includes_ms,
self.publish_overlay_ms,
self.gone_ms,
self.absorb_ms,
nanos(c.compact_ns),
self.candidates_ms,
self.includes_ms,
self.overlay_ms,
self.total_ms,
self.since_start_ms,
)
}
/// The count line: how much work of each kind there was to spend that
/// time on.
pub fn count_line(&self) -> String {
let c = &self.cache;
format!(
"scan {} counts ({}): read={} read_kib={} skipped={} hits={} misses={} buffers={} \
records={} repeats={} decoded_kib={} written_kib={} opens={} compactions={} \
publishes={} published={} first_publish={:.2} overlays={}",
self.number,
self.kind,
self.read,
kib(self.read_bytes),
self.skipped,
c.hits,
c.misses,
self.buffers,
c.records,
c.repeats,
kib(c.decoded_bytes),
kib(c.written_bytes),
c.opens,
c.compactions,
self.publishes,
self.published,
self.first_publish_ms,
self.overlays,
)
}
/// The memory line: what the scan left resident, table by table.
pub fn memory_line(&self) -> String {
let s = &self.sizes;
format!(
"scan {} memory ({}): store_before_kib={} store_after_kib={} cache_entries={} \
cache_encoded_kib={} index_files={} unit_names={} unit_defs={} members={} \
hier_members={} reference_keys={} reference_sites={} defines={} instantiations={} \
fact_words={} fact_word_kib={} candidate_units={} candidate_macros={} \
candidate_words={} candidate_word_kib={} include_edges={} include_known={} \
work_kib={}",
self.number,
self.kind,
kib(self.cache.store_before as usize),
kib(self.cache.store_after as usize),
self.cache_entries,
kib(self.cache_bytes),
s.index_files,
s.unit_names,
s.unit_defs,
s.members,
s.hier_members,
s.reference_keys,
s.reference_sites,
s.defines,
s.instantiations,
s.fact_words,
kib(s.fact_word_bytes),
s.candidate_units,
s.candidate_macros,
s.candidate_words,
kib(s.candidate_word_bytes),
s.include_edges,
s.include_known,
kib(self.work_bytes),
)
}
}
/// Milliseconds since `from`.
fn millis(from: Instant) -> f64 {
from.elapsed().as_secs_f64() * 1_000.0
}
/// Nanoseconds as milliseconds, the unit every line is written in.
fn nanos(ns: u64) -> f64 {
ns as f64 / 1_000_000.0
}
/// Bytes as whole KiB, rounded down — the unit every size field carries.
fn kib(bytes: usize) -> usize {
bytes / 1024
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_trace_that_is_off_hands_out_no_clock_and_stays_zero() {
let trace = ScanTrace::new(false);
assert!(!trace.on());
assert!(trace.now().is_none());
assert_eq!(trace.elapsed_ms(), 0.0);
let mut slot = 0.0;
ScanTrace::add(&mut slot, trace.now());
assert_eq!(slot, 0.0, "an off trace cannot accumulate");
}
#[test]
fn a_trace_that_is_on_accumulates_into_the_slot_it_is_given() {
let trace = ScanTrace::new(true);
let started = trace.now();
assert!(started.is_some());
let mut slot = 0.0;
ScanTrace::add(&mut slot, started);
ScanTrace::add(&mut slot, started);
assert!(slot >= 0.0, "two adds are two summands, never a replacement");
}
#[test]
fn the_first_publish_is_the_one_that_is_stamped() {
let mut trace = ScanTrace::new(true);
trace.saw_publish(10);
let first = trace.first_publish_ms;
trace.saw_publish(5);
assert_eq!(trace.publishes, 2);
assert_eq!(trace.published, 15);
assert_eq!(trace.first_publish_ms, first, "a later publish never moves the stamp");
}
#[test]
fn cache_work_reports_a_scans_own_share_and_never_goes_negative() {
let before = CacheWork { hits: 10, lookup_ns: 500, ..CacheWork::default() };
let after = CacheWork { hits: 25, lookup_ns: 900, ..CacheWork::default() };
let mine = after.since(before);
assert_eq!(mine.hits, 15);
assert_eq!(mine.lookup_ns, 400);
// A counter that somehow went backwards saturates rather than wrapping
// into a nonsense number the tracker would then quote.
assert_eq!(before.since(after).hits, 0);
}
#[test]
fn every_line_names_its_scan_and_is_one_line() {
let mut trace = ScanTrace::new(true);
trace.kind = "whole";
trace.number = 2;
trace.read = 124;
for line in [trace.stage_line(), trace.count_line(), trace.memory_line()] {
assert!(line.starts_with("scan 2 "), "{line}");
assert!(!line.contains('\n'), "a timing line is one line: {line}");
assert!(line.contains("(whole, 124 files)") || line.contains("(whole)"), "{line}");
}
}
}
+14 -6
View File
@@ -61,7 +61,7 @@ impl Server {
}],
};
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
self.pending.insert(id, Pending::Configuration);
self.pending.insert(id, Pending::Configuration(std::time::Instant::now()));
}
/// Ask the client to watch the source files and the filelist for us,
@@ -174,7 +174,7 @@ impl Server {
pub(super) fn response(&mut self, response: Response) {
match self.pending.remove(&response.id) {
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
Some(Pending::Configuration) => self.configured(response),
Some(Pending::Configuration(asked)) => self.configured(asked, response),
None => {}
}
}
@@ -211,7 +211,8 @@ impl Server {
/// string) means the same thing: the client has no settings for us, which
/// is the defaults. Nothing here is worth a popup — the user did not ask
/// for this request and cannot act on its failure.
fn configured(&mut self, response: Response) {
fn configured(&mut self, asked: std::time::Instant, response: Response) {
self.timed(self.timer().map(|_| asked), |took| format!("configuration answered in {took}"));
let answered = response.response_result.unwrap_or(Value::Null);
let section = answered.get(0).cloned().unwrap_or(Value::Null);
self.apply_settings(settings::from_section(&section));
@@ -271,6 +272,12 @@ impl Server {
self.verbose.then(std::time::Instant::now)
}
/// How long this server has been alive, in milliseconds — the clock every
/// startup number is read against.
pub(super) fn since_start(&self) -> f64 {
self.born.elapsed().as_secs_f64() * 1_000.0
}
/// One timing line for work that was being timed — and nothing at all,
/// closure included, for work that was not.
pub(super) fn timed(
@@ -297,7 +304,7 @@ impl Server {
}
/// One line for a request the order contract makes wait, naming which of
/// [`Server::must_wait`]'s three clauses held it.
/// [`Server::must_wait`]'s four clauses held it.
///
/// The question this answers is the one a slow-looking editor raises:
/// "was that request slow, or was it never started?". Silent for anything
@@ -308,11 +315,12 @@ impl Server {
}
let Message::Request(request) = message else { return };
self.timing(format!(
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
"{} HELD behind a rescan (answering={}, wanted={}, already held={}, staging={})",
request.method,
self.answering_a_rescan,
self.rescan_wanted,
self.held.len()
self.held.len(),
self.staging
));
}
}
+110 -24
View File
@@ -26,17 +26,17 @@ use lsp_types::request::{
};
use lsp_types::{
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
CodeAction, CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams,
DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams,
DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams,
FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams,
RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams,
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
SemanticTokensResult, SignatureHelpParams, TextDocumentPositionParams,
TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, Uri,
WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, WorkspaceSymbolParams,
WorkspaceSymbolResponse,
CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams, CodeLensParams,
CompletionParams, DocumentDiagnosticParams, DocumentDiagnosticReportResult,
DocumentHighlightParams, DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse,
ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse,
HoverParams, InlayHintParams, InlineCompletionParams, LinkedEditingRangeParams, Position,
ReferenceParams, RenameFilesParams, RenameParams, SelectionRangeParams, SemanticTokens,
SemanticTokensDeltaParams, SemanticTokensParams, SemanticTokensRangeParams,
SemanticTokensRangeResult, SemanticTokensResult, SignatureHelpParams,
TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams,
TypeHierarchySupertypesParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
@@ -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 {
@@ -246,14 +246,35 @@ impl Server {
let uri = p.text_document.uri;
let only = p.context.only;
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
// A code-action request carries no `tabSize`, so the width a
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
// or from the built-in default.
let tab_width =
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
let run = lint::LintRun::for_document(&self.workspace, doc);
let mut actions =
code_action::code_actions(&run, &uri, doc, p.range, only.as_deref(), tab_width);
// A filter naming no kind at all selects nothing: every
// `wanted` below is false, so the answer is empty however much
// work is done to reach it. Answering here is what keeps a
// client that asks for nothing from paying for config
// discovery, a lint pass and four selectors (take 5 §P1a).
if only.as_deref().is_some_and(<[CodeActionKind]>::is_empty) {
return to_value(Vec::<CodeActionOrCommand>::new());
}
let mut actions: Vec<CodeActionOrCommand> = Vec::new();
// Quick fixes and `source.fixAll.lucisv` are the only two
// families the lint pass answers for, so a request for neither
// — an organize-on-save, a refactor-only menu — does not read
// the project's configuration and does not lint.
if code_action::wants_fixes(only.as_deref()) {
// A code-action request carries no `tabSize`, so the width a
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
// or from the built-in default.
let tab_width =
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
let run = lint::LintRun::for_document(&self.workspace, doc);
actions.extend(code_action::code_actions(
&run,
&uri,
doc,
p.range,
only.as_deref(),
tab_width,
));
}
// The port refactorings answer for the cursor, not for a range:
// the request's start is where the user is.
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
@@ -268,13 +289,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)),
}
@@ -316,7 +368,16 @@ impl Server {
let Some(offset) = self.offset(&uri, position) else {
return Ok(Value::Null);
};
match rename::rename(&self.workspace, &uri, offset, &new_name) {
// One `timing: rename trace …` line behind `--verbose`, and
// nothing at all otherwise: where a rename's selection, its
// stages and its whole-file parses went (take 5 §P2a).
let mut trace = None;
let outcome =
rename::rename_traced(&self.workspace, &uri, offset, &new_name, &mut trace);
if let (true, Some(line)) = (self.verbose, trace) {
self.timing(format!("rename trace {line}"));
}
match outcome {
Ok((edit, warnings)) => {
self.report_scope(warnings);
to_value(edit)
@@ -343,6 +404,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);
+98 -14
View File
@@ -28,8 +28,10 @@ impl Server {
/// or a file the client renamed or deleted.
pub(super) fn reindex(&mut self) {
// A rescan asked for by a message this scan answered is *this* scan's
// successor, not a scan inside it. See `scan_until_settled`.
if self.scanning {
// successor, not a scan inside it — and one asked for before the
// startup scan has begun is that scan itself. See
// `scan_until_settled` and [`Server::scan_owed`].
if self.scan_owed() {
self.rescan_wanted = true;
return;
}
@@ -84,8 +86,9 @@ impl Server {
// bytes a moment later. One more scan when this one ends is the whole
// answer, and it is the same flag every other mid-scan trigger sets.
// `true` because the caller's fallback — a whole rebuild, right now —
// is exactly what must not happen.
if self.scanning {
// is exactly what must not happen. Same for the startup's
// configuration wait, whose scan reads this file from disk anyway.
if self.scan_owed() {
self.rescan_wanted = true;
return true;
}
@@ -122,11 +125,17 @@ impl Server {
/// sets, and it is what keeps the coalescing rule one rule
/// (`docs/features/scan-interleave/README.md`).
pub(super) fn reindex_widened(&mut self, added: Vec<std::path::PathBuf>) {
if self.scanning {
// Before the startup scan has begun there is nothing to widen *into*:
// that scan resolves the scope afresh, the buffer this `didOpen` just
// installed is already in it, and `open_first` puts the buffer at the
// head of its work list. So the widen is folded into the one scan
// rather than run as a second one (`server/startup.rs`).
if self.scan_owed() {
self.rescan_wanted = true;
return;
}
let started = self.timer();
let since_start = self.since_start();
if started.is_some() {
// The folders by name: which folder a jump widened into is the one
// thing the file log below it does not say in one line.
@@ -138,9 +147,10 @@ impl Server {
paths.join(", ")
));
}
let verbose = started.is_some();
let bar = self.begin_indexing();
let mut scan =
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
self.watching(bar.as_ref(), |ws, watch| ws.begin_widen(&added, watch, verbose));
let total = scan.total();
// No drain between the files: a widen is a rescan a message asked for,
// and `must_wait` would hold every request queued behind it anyway. It
@@ -163,6 +173,7 @@ impl Server {
plural(total)
)
});
self.say_scan_trace(since_start);
self.refresh_code_lenses();
self.hierarchy_index_changed();
self.generation += 1;
@@ -208,6 +219,8 @@ impl Server {
};
self.answering_a_rescan = false;
self.scanning = false;
// A neighbourhood can only be owed by a scan, and there is none now.
self.head_owed = false;
warnings
}
@@ -224,8 +237,10 @@ impl Server {
// scope and walking it is part of what a scan costs, and a number that
// left it out would be the wrong answer to "why was that slow?".
let started = self.timer();
let since_start = self.since_start();
let verbose = started.is_some();
let bar = self.begin_indexing();
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_scan(watch, verbose));
let interleave = scan.total() > INTERLEAVE_ABOVE;
let total = scan.total();
if started.is_some() {
@@ -252,9 +267,27 @@ impl Server {
plural(total)
)
});
self.say_scan_trace(since_start);
warnings
}
/// The three `timing: scan …` lines the startup breakdown is read from —
/// stages, counts and the sizes the scan left resident.
///
/// Silent without `--verbose`, because a scan that was not traced left a
/// trace of zeroes and three lines of them would be a lie
/// (`docs/features/perf5-p4/README.md` holds the field list).
fn say_scan_trace(&mut self, since_start: f64) {
let mut trace = self.workspace.take_scan_trace();
if !trace.on() {
return;
}
trace.since_start_ms = since_start;
self.timing(trace.stage_line());
self.timing(trace.count_line());
self.timing(trace.memory_line());
}
/// Do one piece of a scan with the progress bar and the per-file log
/// watching it.
///
@@ -291,25 +324,76 @@ impl Server {
/// to and no reason to go on scanning, so it stops the scan the same way a
/// `shutdown` does.
fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool {
let mut batch = Vec::new();
// Nothing may be answered off a prefix that does not yet hold the
// folder the user is working in: a definition into the file next door
// would be `[]` (`docs/features/perf5-p4/README.md` §P4b3).
self.head_owed = !scan.neighbourhood_indexed();
let mut batch = self.waiting_for_this_scan();
while let Ok(message) = self.queue.try_recv() {
batch.push(message);
}
if batch.is_empty() {
return false;
}
let opened = opened_in(&batch);
// A `didOpen` in this burst names a folder the work list has not been
// ordered around yet, so the requests behind it in the burst are owed
// that ordering before they are answered — which is exactly what the
// widen this `didOpen` used to trigger made them wait for. The flag is
// set *before* the batch is applied, so `must_wait` holds them; it is
// recomputed below once the new head segment is known.
let opened = !opened_in(&batch).is_empty();
self.head_owed |= opened;
self.workspace.publish_scan(scan);
self.stopped = !matches!(self.process_batch(batch), Ok(false));
// The file the user has just opened is the one they are looking at, so
// it is indexed next rather than when the alphabet reaches it — the
// open-first rule, for a file opened after the work list was taken.
for path in opened {
scan.index_next(&path);
// The files the user has just opened, and the folders around them, are
// what they are looking at, so they are indexed next rather than when
// the alphabet reaches them — the open-first rule, for buffers opened
// after the work list was taken.
if opened {
self.workspace.open_next(scan);
self.head_owed = !scan.neighbourhood_indexed();
}
self.stopped
}
/// What the startup's configuration wait set aside, when this scan is the
/// one those messages were waiting for.
///
/// **Not an exemption from the order contract — the other side of it.** A
/// request that arrives before the startup scan has begun is held for the
/// same reason one arriving *during* it is answered: there is no index at
/// all to answer it from, and the scan it is waiting for is the server's
/// own startup, with nothing queued ahead of it and — being the session's
/// first — an empty `gone` set. So the startup scan answers it exactly as
/// it answers a message that turns up while it runs, off the same
/// published prefix.
///
/// A scan a **message** asked for takes nothing: its held messages are
/// queued behind the message that asked for it, and answering them off a
/// half-updated index is precisely the trade
/// `docs/features/scan-interleave/README.md`'s decision 2 refuses. Same
/// for a scan with a further rescan already wanted — the requests behind
/// that ask are owed its effect.
///
/// **And not at the very first file.** A prefix holding the user's own
/// buffer and nothing else answers a definition in the file next door with
/// `[]` — coherent, and useless, which is what §P4b2 measured
/// (`docs/features/perf5-p4/README.md`). So the startup scan takes what it
/// was handed once it has stepped the user's whole neighbourhood
/// ([`Server::head_owed`], from [`Scan::neighbourhood_indexed`]); the
/// `publish_scan` in [`Server::answer_what_is_waiting`] is what then makes
/// that neighbourhood answerable, in the same call. A scan with no
/// neighbourhood — nothing open, or a folder covering the workspace — says
/// so with `head` 0 and drains at the first file exactly as before.
/// Requests arriving *after* that are answered at every interleave point,
/// as they always were.
fn waiting_for_this_scan(&mut self) -> Vec<lsp_server::Message> {
if self.answering_a_rescan || self.rescan_wanted || self.head_owed {
return Vec::new();
}
std::mem::take(&mut self.held)
}
/// Publish a new completed hierarchy revision after any index mutation.
pub(super) fn hierarchy_index_changed(&mut self) {
self.hierarchy_revision = self.hierarchy_revision.saturating_add(1);
+66 -137
View File
@@ -44,10 +44,9 @@ use lsp_server::{Connection, Message, RequestId};
use lsp_types::notification::{Cancel, Notification as _};
use lsp_types::{SemanticToken, Uri};
use crate::settings::ClientSettings;
use crate::state::Workspace;
use batch::{burst, cancelled_in, cancelled_response, forward};
use batch::{burst, cancelled_in, cancelled_response};
mod batch;
mod client;
@@ -59,6 +58,7 @@ mod large_file;
mod notification;
mod progress;
mod semantic_tokens;
mod startup;
#[cfg(test)]
mod tests;
@@ -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.
@@ -185,6 +192,24 @@ pub struct Server {
/// another one, and this is what turns that into the flag below rather
/// than a scan inside a scan.
scanning: bool,
/// Whether the startup scan is still *owed* — the window between the
/// `workspace/configuration` request that opens a session and the answer
/// that decides the scope its one scan runs at
/// (`server/startup.rs`). Nothing has been indexed yet, so a rescan
/// trigger in this window is folded into the scan that is about to run
/// rather than run as a scan of its own, and every request waits for it —
/// there is nothing to answer one from. Never true again after
/// construction.
staging: bool,
/// Whether the scan now running still owes the user's own neighbourhood —
/// their open buffers and the folders those raise to, which
/// [`crate::scan_order`] puts at the head of its work list. Until it has
/// been indexed there is nothing worth answering a request off: the prefix
/// holds the alphabet rather than what the user is looking at, and §P4b2
/// measured what that answers, which is `[]`
/// (`docs/features/perf5-p4/README.md`). False whenever no scan is
/// running, and false during a scan with no neighbourhood to wait for.
head_owed: bool,
/// A rescan asked for while a scan was running. Coalesced: any number of
/// requests is one more scan when this one ends, whatever asked for them.
rescan_wanted: bool,
@@ -207,6 +232,11 @@ pub struct Server {
/// costs is the branch that reads this field — see
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
verbose: bool,
/// When this server was built — the moment after `initialize`/`initialized`
/// that `main` hands control over. Every startup number is measured from
/// here, so a scan's line can say how much of the wait came before it
/// (`docs/features/perf5-p4/README.md`).
born: std::time::Instant,
}
/// How long a burst of `didChange` notifications may sit unanalyzed once the
@@ -245,8 +275,9 @@ enum Pending {
/// A `workspace/applyEdit`, remembering the command that asked for it so
/// a refusal can be named to the user.
ApplyEdit(String),
/// A `workspace/configuration` asking for the `lucisv` section.
Configuration,
/// A `workspace/configuration` asking for the `lucisv` section, and when
/// it was asked — the config round trip is part of what a startup costs.
Configuration(std::time::Instant),
}
/// One semantic-token answer, kept so the next delta request can be answered
@@ -257,136 +288,6 @@ struct TokenAnswer {
}
impl Server {
/// The server, with its first index built.
///
/// The startup scan runs at the **default** settings — including the
/// folder scope — because neither settings door can deliver anything
/// before `initialized`; a client whose `lucisv.index.scope` differs pays
/// one extra rescan when its settings land, exactly as `lucisv.exclude`
/// has always cost one.
pub fn new(
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
storage: Option<std::path::PathBuf>,
verbose: bool,
) -> Server {
Server::started(
connection,
roots,
abilities,
ClientSettings::default(),
storage,
verbose,
Vec::new(),
)
}
/// [`Server::new`] with a client's settings already in hand — the seam the
/// tests start a session from. Only a test has any settings this early:
/// one whose subject is not the scope says so here rather than driving a
/// `didChangeConfiguration` and then reasoning about the extra rescan it
/// buys.
///
/// `queued` is what the client had already sent when the server was built
/// — the opening burst, put straight onto the queue the startup scan
/// drains. Empty for [`Server::new`]; a test fills it because racing the
/// forwarder thread for it would make the test a coin toss rather than a
/// check.
fn started(
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
client: ClientSettings,
storage: Option<std::path::PathBuf>,
verbose: bool,
queued: Vec<Message>,
) -> Server {
// Started before the first scan, not in `run`: the scan below answers
// whatever the client has already sent, and it can only do that off a
// queue that is already being filled.
let (forwarded, queue) = forward(&connection);
for message in queued {
let _ = forwarded.send(message);
}
let mut server = Server {
connection,
workspace: Workspace::default(),
config_warnings: HashSet::new(),
lint_config_problems: std::cell::RefCell::default(),
said_lint_names: Vec::new(),
abilities,
watchers: None,
registrations: 0,
request_ids: 0,
pending: HashMap::new(),
generation: 0,
hierarchy_revision: 0,
tokens: HashMap::new(),
token_results: 0,
indexings: 0,
dirty: Vec::new(),
queue,
scanning: false,
rescan_wanted: false,
answering_a_rescan: false,
stopped: false,
held: Vec::new(),
verbose,
};
// Nothing has been built yet, so there is no rebuild to owe: the
// `true` this returns for a non-default `client` is the rebuild that
// is about to happen anyway.
let _ = server.workspace.set_client_settings(client);
// Before the first build, because it is one rung of the ladder that
// decides where that build reads its cache from
// (`docs/features/index-persistence/README.md`).
server.workspace.set_storage_path(storage);
// The earliest legal moment for anything server-initiated: `main`
// builds this only after `initialize_finish`, which returns once the
// client's `initialized` notification has arrived — and consumes it,
// so the loop below never sees one to hang these off instead. The
// first index build is the slowest one of the session, so it gets the
// same bar every later rescan gets.
//
// And it answers messages while it runs, which is what stops the first
// request of a session waiting out the whole scan
// (`docs/features/scan-interleave/README.md`). Everything below it is
// therefore reached with the client's opening burst already handled —
// and skipped altogether if that burst shut the server down.
server.workspace.adopt_roots(roots);
let warnings = server.scan_until_settled(false);
if server.stopped {
return server;
}
server.hierarchy_index_changed();
// A buffer can now be *opened* during the startup scan, and what was
// published for it then was computed against a half-built index. This
// is the same debt a rescan pays at the end of `reindex`, owed here
// for the first time because before this round no buffer could exist
// at this point. Nothing at all is sent when nothing is open, which is
// every session whose client did not get a `didOpen` in edgeways.
if !server.workspace.open_uris().is_empty() {
server.refresh_code_lenses();
server.generation += 1;
for uri in server.workspace.open_uris() {
server.publish(&uri);
}
}
server.report_scope(warnings);
server.register_watchers();
// The pull half of the settings model. Asked here because this is the
// same moment the watchers are registered — the earliest legal one —
// and answered later, in the loop: the settings therefore arrive
// *after* the first index build, exactly as a pushed
// `didChangeConfiguration` always has (it cannot arrive before
// `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist`
// costs one extra rescan when it lands; nothing is stale in between,
// it is simply the default scope until the client answers.
server.request_configuration();
server
}
/// Receive until the client shuts us down or the channel closes.
///
/// One blocking receive, then everything already queued behind it, then
@@ -521,7 +422,7 @@ impl Server {
/// setting or an added workspace folder before a go-to-definition. Those
/// four ask for a rescan, and "applied" for them means the rescan has
/// **run**: one message at a time, the server would have finished it
/// before ever taking the request. Three clauses, one rule:
/// before ever taking the request. Four clauses, one rule:
///
/// * `answering_a_rescan` — this scan is one a message asked for, so
/// every request that arrives while it runs arrived *after* that
@@ -529,7 +430,19 @@ impl Server {
/// * `rescan_wanted` — a message in this very burst has just asked for
/// one, and the requests behind it in the burst are owed the same;
/// * `held` — a request is already waiting, and answering a newer one
/// ahead of it would reorder them just as badly.
/// ahead of it would reorder them just as badly;
/// * `staging` — the startup scan has not begun, because the settings
/// that decide its scope are still in flight. There is no index at all
/// to answer from, so a request waits for that scan — and is answered
/// *inside* it, mid-way, exactly as one arriving while it runs is
/// ([`Server::waiting_for_this_scan`]);
/// * `head_owed` — the scan running has not yet reached the end of the
/// user's own folder. There *is* an index, but the part of it a request
/// is asking about is the part not built yet, and answering off the
/// alphabet's prefix returns `[]` rather than an answer. A request
/// behind a `didOpen` is owed that `didOpen`'s effect on the scan
/// order, which is the same rule the other four state
/// ([`Server::head_owed`]).
///
/// What is left answered mid-scan is exactly what is queued behind
/// *nothing*: the opening burst of a session, whose scan is the server's
@@ -537,7 +450,23 @@ impl Server {
/// the round is about, and it is the one a user feels
/// (`docs/features/scan-interleave/README.md`).
fn must_wait(&self) -> bool {
self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty()
self.answering_a_rescan
|| self.rescan_wanted
|| !self.held.is_empty()
|| self.staging
|| self.head_owed
}
/// Whether a scan is running or already owed — the two states in which a
/// rescan trigger records that one more scan is wanted instead of running
/// one itself.
///
/// The second is the startup's configuration wait (`server/startup.rs`):
/// the scan it is waiting for has not begun, and when it does it will
/// resolve the scope afresh and read every file in it, so anything asked
/// for now is satisfied by it.
fn scan_owed(&self) -> bool {
self.scanning || self.staging
}
/// Whether the installed index covers the whole scope with no indexing
+310
View File
@@ -0,0 +1,310 @@
//! What a session does before its message loop: ask the client for its
//! settings, wait a bounded moment for the answer, and run **one** startup
//! scan at the scope that answer decided.
//!
//! Before 2026-09-08 the order was the other way round — scan at the
//! defaults, then ask — and a client whose `lucisv.index.scope` differs from
//! the default folder scope (which is every VS Code session that sets one)
//! paid a whole second scan when the answer landed. With no buffer open the
//! first of those scans indexes **zero files**, so what it bought was the
//! round-trip wait and nothing else; §P4b then made it cost 0.15 ms instead
//! of 181 ms, which turned the head start it had accidentally been giving the
//! opening `didOpen` into a genuine race and made the first useful answer of
//! a warm session bimodal. Staging removes the scan rather than the race:
//! there is one scan, it runs at the settings the client actually wants, and
//! the opening burst is answered *inside* it exactly as
//! `docs/features/scan-interleave/README.md` has always answered the startup
//! scan's own arrivals.
//!
//! The bound below is what a client that advertised
//! `workspace/configuration` and then never answers costs: after it, the scan
//! runs at the defaults exactly as it used to, and an answer that turns up
//! afterwards is an ordinary settings change with an ordinary rescan behind
//! it. See `docs/features/perf5-p4/README.md` §P4b2 and
//! `docs/features/folders-and-config/README.md`.
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
use lsp_server::{Connection, Message};
use super::batch::{burst, forward};
use super::{ClientAbilities, Pending, Server};
use crate::settings::ClientSettings;
use crate::state::Workspace;
/// How long a startup waits for the client's `workspace/configuration`
/// answer before scanning at the defaults.
///
/// **Not a budget — a bound on a client that never answers.** The round trip
/// itself is single-digit milliseconds: §P4a measured the whole of it,
/// including the empty scan that used to run in front of it, at 27–85 ms, and
/// with that scan gone what is left is the client's own reply. Two seconds is
/// therefore two orders of magnitude of slack for a slow client, and still
/// short enough that a client which advertised the capability and then says
/// nothing does not leave a workspace unindexed.
pub(super) const CONFIGURATION_WAIT: Duration = Duration::from_secs(2);
/// Everything a session starts with that is not the connection or the roots.
///
/// One struct rather than six more parameters: `started` is the seam every
/// test starts a session from, and the two fields only a test ever sets
/// ([`Startup::queued`] and [`Startup::wait`]) would otherwise be positional
/// arguments nobody can read at the call site.
pub(super) struct Startup {
/// What the client said it can do, read once at `initialize`.
pub(super) abilities: ClientAbilities,
/// Settings already in hand. Only a test has any this early: one whose
/// subject is not the scope says so here rather than driving a
/// `didChangeConfiguration` and then reasoning about the extra rescan it
/// buys.
pub(super) client: ClientSettings,
/// `initializationOptions.storagePath` — where the persistent index cache
/// goes.
pub(super) storage: Option<std::path::PathBuf>,
/// `--verbose`: whether every operation says how long it took.
pub(super) verbose: bool,
/// What the client had already sent when the server was built — the
/// opening burst, put straight onto the queue the wait and the startup
/// scan drain. Empty for [`Server::new`]; a test fills it because racing
/// the forwarder thread for it would make the test a coin toss rather
/// than a check.
pub(super) queued: Vec<Message>,
/// How long to wait for the settings answer before scanning at the
/// defaults. [`CONFIGURATION_WAIT`] in a real session; a test says what
/// it means to test, and `Duration::ZERO` is the client that never
/// answers.
pub(super) wait: Duration,
}
impl Server {
/// The server, with its first index built.
///
/// The startup scan runs at the settings the client answered a
/// `workspace/configuration` with — asked first thing and waited for, up
/// to [`CONFIGURATION_WAIT`]. A client that cannot be asked, or that does
/// not answer inside the bound, gets the scan at the **defaults**
/// (including the folder scope) exactly as every client did before
/// 2026-09-08, and pays one extra rescan if its settings land later.
pub fn new(
connection: Connection,
roots: Vec<std::path::PathBuf>,
abilities: ClientAbilities,
storage: Option<std::path::PathBuf>,
verbose: bool,
) -> Server {
let startup = Startup {
abilities,
client: ClientSettings::default(),
storage,
verbose,
queued: Vec::new(),
wait: CONFIGURATION_WAIT,
};
Server::started(connection, roots, startup)
}
/// A server that owns nothing yet: no index, no settings, no roots — only
/// its connection, what the client can do, and the queue its messages are
/// already arriving on.
///
/// The forwarder starts here rather than in `run` because both the
/// settings wait and the startup scan answer whatever the client has
/// already sent, and they can only do that off a queue that is already
/// being filled. `queued` is what a test says the client had sent by then.
fn empty(
connection: Connection,
abilities: ClientAbilities,
verbose: bool,
queued: Vec<Message>,
) -> Server {
let (forwarded, queue) = forward(&connection);
for message in queued {
let _ = forwarded.send(message);
}
Server {
connection,
workspace: Workspace::default(),
config_warnings: HashSet::new(),
lint_config_problems: std::cell::RefCell::default(),
said_lint_names: Vec::new(),
abilities,
watchers: None,
registrations: 0,
request_ids: 0,
pending: HashMap::new(),
generation: 0,
hierarchy_revision: 0,
tokens: HashMap::new(),
token_results: 0,
indexings: 0,
dirty: Vec::new(),
queue,
scanning: false,
head_owed: false,
staging: false,
rescan_wanted: false,
answering_a_rescan: false,
stopped: false,
held: Vec::new(),
verbose,
born: Instant::now(),
}
}
/// [`Server::new`] with everything spelled out — the seam the tests start
/// a session from.
pub(super) fn started(
connection: Connection,
roots: Vec<std::path::PathBuf>,
startup: Startup,
) -> Server {
let Startup { abilities, client, storage, verbose, queued, wait } = startup;
let mut server = Server::empty(connection, abilities, verbose, queued);
// Nothing has been built yet, so there is no rebuild to owe: the
// `true` this returns for a non-default `client` is the rebuild that
// is about to happen anyway.
let _ = server.workspace.set_client_settings(client);
// Before the first build, because it is one rung of the ladder that
// decides where that build reads its cache from
// (`docs/features/index-persistence/README.md`).
server.workspace.set_storage_path(storage);
server.workspace.adopt_roots(roots);
// The earliest legal moment for anything server-initiated: `main`
// builds this only after `initialize_finish`, which returns once the
// client's `initialized` notification has arrived — and consumes it,
// so the loop below never sees one to hang these off instead.
server.stage_for_configuration(wait);
if server.stopped {
return server;
}
// The first index build is the slowest one of the session, so it gets
// the same bar every later rescan gets. And it answers messages while
// it runs — the ones the wait above set aside included — which is what
// stops the first request of a session waiting out the whole scan
// (`docs/features/scan-interleave/README.md`). Everything below it is
// therefore reached with the client's opening burst already handled —
// and skipped altogether if that burst shut the server down.
let warnings = server.scan_until_settled(false);
if server.stopped {
return server;
}
server.hierarchy_index_changed();
// A buffer can be *opened* before or during the startup scan, and what
// was published for it then was computed against a half-built index.
// This is the same debt a rescan pays at the end of `reindex`, owed
// here for the first time because before scan-interleave no buffer
// could exist at this point. Nothing at all is sent when nothing is
// open, which is every session whose client did not get a `didOpen`
// in edgeways.
if !server.workspace.open_uris().is_empty() {
server.refresh_code_lenses();
server.generation += 1;
for uri in server.workspace.open_uris() {
server.publish(&uri);
}
}
server.report_scope(warnings);
server.register_watchers();
server
}
/// Ask the client for its settings and hold everything until they arrive,
/// so the one startup scan runs at the scope the client actually wants.
///
/// Silent for a client that never advertised `workspace/configuration`:
/// that one is only ever *pushed* settings, so there is nothing to wait
/// for and the scan runs at the defaults immediately, byte for byte as it
/// always has.
///
/// [`Server::staging`] is what makes the window safe. While it is set,
/// every rescan trigger a message pulls — a `didOpen` that widened the
/// scope, a pushed setting, a save — records that one more scan is wanted
/// instead of running one, and [`Server::must_wait`] holds every request.
/// Clearing `rescan_wanted` afterwards is not dropping those asks: the
/// scan about to run is the session's **first**, it resolves the scope
/// afresh and reads every file in it from disk, and it runs at the
/// settings that have just landed — so it is what every one of them was
/// asking for.
fn stage_for_configuration(&mut self, wait: Duration) {
if !self.abilities.configuration {
return;
}
self.staging = true;
self.request_configuration();
self.await_configuration(wait);
self.staging = false;
self.rescan_wanted = false;
}
/// Read the client's messages until it answers the settings pull, the
/// bound runs out, or it goes away.
///
/// **The bound is observed on the receive itself.** `recv_timeout` with
/// whatever is left of it blocks in the transport, wakes on the next
/// message, and returns `Timeout` at the deadline — so there is no poll,
/// no busy-wait and no clock the loop has to be woken to read. A client
/// that answers late is not stranded: its answer arrives in `run` as an
/// ordinary `Message::Response`, goes through the same `configured` →
/// `apply_settings` it always did, and costs the one rescan a settings
/// change has always cost — under the order contract, held requests and
/// all.
fn await_configuration(&mut self, wait: Duration) {
if wait.is_zero() {
return;
}
let asked = Instant::now();
while self.pending.values().any(|p| matches!(p, Pending::Configuration(_))) {
let Some(left) = wait.checked_sub(asked.elapsed()) else { return };
let Ok(message) = self.queue.recv_timeout(left) else { return };
let batch = burst(&self.queue, message);
// A `shutdown` in the burst has already been through
// `handle_shutdown` by the time this returns `Ok(true)`;
// `started` then returns without scanning at all.
self.stopped = !matches!(self.process_batch(batch), Ok(false));
if self.stopped {
return;
}
self.take_the_answer_out_of_held();
}
}
/// Apply a settings answer that a held request took down with it.
///
/// **Measured, not theorised** (2026-09-08): without this, one warm
/// session in three waited the whole two-second bound and then rescanned,
/// because `process_batch` moves *everything behind* a request that must
/// wait into `held` — the rule that keeps a burst's arrival order intact
/// across the wait — and the client's answer to the pull can be in that
/// burst behind the editor's opening `textDocument/definition`. Left
/// there, the loop above sees the pull still outstanding and blocks until
/// the bound, which is the opposite of what staging is for.
///
/// Reordering it is sound because that rule is about the **client's**
/// message stream. The answer to a request the *server* sent is not part
/// of it: the client replies to a pull from wherever it handles
/// server-initiated requests, and no ordering promise ties that reply to a
/// request the editor happened to send at the same moment. Only a
/// `Pending::Configuration` answer is taken — everything else in `held`,
/// requests included, keeps its place and its order.
fn take_the_answer_out_of_held(&mut self) {
let waiting = std::mem::take(&mut self.held);
let mut answers = Vec::new();
for message in waiting {
match message {
Message::Response(response)
if matches!(
self.pending.get(&response.id),
Some(Pending::Configuration(_))
) =>
{
answers.push(response);
}
kept => self.held.push(kept),
}
}
for answer in answers {
self.response(answer);
}
}
}
@@ -0,0 +1,545 @@
//! What a `textDocument/codeAction` request does, and — just as much — what
//! it no longer does.
//!
//! Take 5 §P1 (`docs/features/perf5-p1/README.md`) removed work from this
//! path: an empty `context.only` answers before the configuration is read, the
//! lint pass runs only when a fix family is asked for, the fence answer is
//! computed only when a fix exists and only once per document revision, and
//! the four refactoring selectors read the buffer's own parse instead of
//! parsing its text again. Every one of those is asserted here **by counting
//! parses**, not by timing them: `vlog_parser::stats::parses()` is a
//! thread-local count and a request is answered on this thread.
use super::*;
/// A module with a tab in it — one `no-tabs` finding, carrying a Safe fix —
/// an instantiation of `sub`, so the port and inline families have something
/// to look at, and a comment line where nothing at all is offered.
///
/// Line 1 is the tab, line 2 the instantiation, line 3 the comment.
const FIXABLE: &str = "module m;\n\twire a;\n sub u_sub (.a(a));\n // nothing here\nendmodule\n";
/// The declaration `FIXABLE` instantiates.
const SUB: &str = "module sub (\n input logic a,\n input logic b\n);\nendmodule\n";
/// A finding with **no** fix: `module-filename` does not offer to rename a
/// file. So a lint pass over this buffer produces a violation, and nothing
/// that a fence could protect.
const UNFIXABLE: &str = "module other;\nendmodule\n";
/// A zero-width range at a position — the shape an editor sends on a cursor
/// move.
fn cursor(uri: &Uri, line: u32, character: u32) -> Value {
serde_json::json!({
"textDocument": { "uri": uri },
"range": {
"start": { "line": line, "character": character },
"end": { "line": line, "character": character },
},
"context": { "diagnostics": [] },
})
}
/// `cursor`, with a `context.only` filter.
fn filtered(uri: &Uri, line: u32, character: u32, only: &[&str]) -> Value {
let mut params = cursor(uri, line, character);
params["context"]["only"] = serde_json::json!(only);
params
}
/// The whole-file parses one request performed.
fn parses_during(session: &mut Session, params: Value) -> (u64, Value) {
let before = vlog_parser::stats::parses();
let result = session.result(CodeActionRequest::METHOD, params);
(vlog_parser::stats::parses() - before, result)
}
/// The titles an answer carries, in the order it carries them.
fn titles(result: &Value) -> Vec<String> {
result
.as_array()
.expect("an action list")
.iter()
.map(|action| action["title"].as_str().unwrap_or_default().to_string())
.collect()
}
/// The kinds an answer carries, in order.
fn kinds(result: &Value) -> Vec<String> {
result
.as_array()
.expect("an action list")
.iter()
.map(|action| action["kind"].as_str().unwrap_or_default().to_string())
.collect()
}
/// A session over a tree holding `m.sv` and `sub.sv`, with `m.sv` open.
fn opened(tree: &Tree, text: &str) -> (Session, Uri) {
tree.write("sub.sv", SUB);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), text);
session.drain();
(session, uri)
}
/// [`opened`] against a client that can `codeAction/resolve` — the shape that
/// is *offered* actions without their edits, which is the path §P1c changed.
fn opened_lazily(tree: &Tree, text: &str) -> (Session, Uri) {
tree.write("sub.sv", SUB);
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("m.sv"), text);
session.drain();
(session, uri)
}
// ------------------------------------------------------------------
// §P1a — the work a filtered request no longer does
// ------------------------------------------------------------------
#[test]
fn an_empty_only_filter_answers_empty_and_does_no_work_at_all() {
let tree = Tree::new("caempty");
let (mut session, uri) = opened(&tree, FIXABLE);
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &[]));
assert_eq!(result, serde_json::json!([]), "no kind is selected, so no action is");
assert_eq!(
parses, 0,
"an empty filter reads no configuration, lints nothing and parses nothing"
);
}
#[test]
fn a_refactor_only_request_never_runs_the_lint_pass() {
let tree = Tree::new("carefactor");
let (mut session, uri) = opened(&tree, FIXABLE);
// The buffer has a fixable finding, so a lint pass here would ask for the
// fence regions — a whole-file parse of its own. One parse means exactly
// one selector ran and the lint pass did not.
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["refactor.extract"]));
assert_eq!(parses, 0, "the selector reads the buffer's own parse (§P1b): {result:#?}");
assert!(
!titles(&result).iter().any(|title| title.contains("no-tabs")),
"and no quick fix is offered: {result:#?}"
);
}
#[test]
fn a_quickfix_only_request_never_runs_the_selectors() {
let tree = Tree::new("caquickfix");
let (mut session, uri) = opened(&tree, FIXABLE);
let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["quickfix"]));
assert_eq!(parses, 1, "the fence parse alone — no selector ran: {result:#?}");
assert_eq!(
titles(&result),
vec!["lucisv: use spaces, not tabs [no-tabs]".to_string()],
"{result:#?}"
);
}
#[test]
fn a_pass_whose_findings_carry_no_fix_never_asks_about_fences() {
let tree = Tree::new("canofix");
let (mut session, uri) = opened(&tree, UNFIXABLE);
let (parses, result) = parses_during(&mut session, filtered(&uri, 0, 0, &["quickfix"]));
assert_eq!(result, serde_json::json!([]), "the finding has no fix to offer");
assert_eq!(parses, 0, "and nothing to protect, so no fence parse");
}
#[test]
fn the_kind_filter_is_a_prefix_and_still_selects_the_whole_family() {
let tree = Tree::new("caprefix");
let (mut session, uri) = opened(&tree, FIXABLE);
// `source` selects `source.fixAll.lucisv`, which is a fix family: the
// lint pass must run for it.
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["source"]));
assert_eq!(kinds(&result), vec!["source.fixAll.lucisv".to_string()], "{result:#?}");
// `refactor` selects every refactoring family and no fix family.
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"]));
assert!(
kinds(&result).iter().all(|kind| kind.starts_with("refactor")),
"no fix family under a refactor filter: {result:#?}"
);
}
#[test]
fn an_unfiltered_request_keeps_the_order_quick_fixes_fix_all_then_refactorings() {
let tree = Tree::new("caorder");
let (mut session, uri) = opened(&tree, FIXABLE);
// The cursor is on the tabbed line, so the quick fix is offered, and the
// buffer's one instantiation puts a refactoring family behind it.
let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 1, 1));
let kinds = kinds(&result);
assert_eq!(kinds.first().map(String::as_str), Some("quickfix"), "{result:#?}");
assert_eq!(kinds.get(1).map(String::as_str), Some("source.fixAll.lucisv"), "{result:#?}");
// Everything after the two fix families is a refactoring, and there is at
// least one — an answer of two actions would prove nothing about order.
assert!(kinds.len() > 2, "a refactoring is offered here too: {result:#?}");
assert!(
kinds[2..].iter().all(|kind| kind.starts_with("refactor")),
"the refactoring families come last: {kinds:#?}"
);
}
#[test]
fn a_fix_spanning_the_cursor_is_still_offered() {
let tree = Tree::new("caspan");
// A trailing-whitespace finding whose span starts before the cursor and
// ends after it: the cursor is *inside* the fix, not at its start.
let (mut session, uri) = opened(&tree, "module m;\n wire a; \nendmodule\n");
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 10, &["quickfix"]));
assert!(
titles(&result).iter().any(|title| title.contains("no-trailing-whitespace")),
"{result:#?}"
);
}
#[test]
fn a_cursor_with_no_selection_is_still_offered_the_extraction() {
let tree = Tree::new("cacursor");
let (mut session, uri) = opened(&tree, FIXABLE);
// A zero-width range on a whole item: extraction takes the item the
// cursor is in, so an empty selection must not disable it.
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"]));
assert!(
kinds(&result).iter().any(|kind| kind == "refactor.extract"),
"an empty range still extracts: {result:#?}"
);
}
// ------------------------------------------------------------------
// §P1b — the work a repeated request no longer does
// ------------------------------------------------------------------
#[test]
fn a_repeated_offer_where_nothing_is_offered_parses_nothing_at_all() {
let tree = Tree::new("carepeat");
let (mut session, uri) = opened(&tree, FIXABLE);
// The comment line: every family is asked, and every family answers
// nothing, so the four gates are the whole of the work. This is the
// pinmux-comment cursor of take 5's headline row, in miniature.
let (first, expected) = parses_during(&mut session, cursor(&uri, 3, 2));
assert!(first <= 1, "the first request pays for the fence answer at most: {first}");
// Every request after it, on the same revision, parses nothing: the four
// selectors read `doc.tree` and the fence answer is the one already made.
for round in 0..3 {
let (parses, again) = parses_during(&mut session, cursor(&uri, 3, 2));
assert_eq!(parses, 0, "round {round} re-parsed the buffer");
assert_eq!(again, expected, "round {round} answered differently");
}
}
#[test]
fn the_gate_only_families_parse_nothing_even_where_they_do_offer() {
let tree = Tree::new("carepeatgate");
let (mut session, uri) = opened(&tree, FIXABLE);
// Extraction and inlining are answered by their gate alone — the offer
// carries a command, not an edit, so no engine runs. On the
// instantiation both of them offer, and neither parses.
let only = &["refactor.extract", "refactor.inline"];
let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only));
assert_eq!(kinds(&first).len(), 2, "both families offer here: {first:#?}");
for round in 0..3 {
let (parses, again) = parses_during(&mut session, filtered(&uri, 2, 2, only));
assert_eq!(parses, 0, "round {round}");
assert_eq!(again, first, "round {round}");
}
}
#[test]
fn the_port_offer_reads_the_declaring_file_once_and_nothing_else() {
let tree = Tree::new("carepeatports");
let (mut session, uri) = opened_lazily(&tree, FIXABLE);
// §P1b gave the port family its *gate* for free, but a gate that said yes
// still handed the engine one or two files and paid for four verified
// plans whose edits were thrown away — 21.15 ms of a 21.83 ms request on
// opentitan. §P1c replaced that with a predicate that reads the buffer's
// own parse and, at most, one parse of the instantiated module's
// declaring file. This assertion is what would notice a second one
// reappearing.
let only = &["refactor.rewrite.lucisv.ports"];
let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only));
assert!(!kinds(&first).is_empty(), "the port family offers here: {first:#?}");
for round in 0..3 {
let (parses, again) = parses_during(&mut session, filtered(&uri, 2, 2, only));
assert_eq!(parses, 1, "round {round}: `sub.sv`'s parse, and no other (§P1c)");
assert_eq!(again, first, "round {round}: and the same menu every time");
}
// The buffer's *own* parse is not among them: the gate was answered from
// `doc.tree`, and so is everything the predicate asks of the buffer.
let (gate_only, _) = parses_during(&mut session, filtered(&uri, 3, 2, only));
assert_eq!(gate_only, 0, "at a cursor the gate refuses, nothing is parsed");
}
#[test]
fn the_organize_imports_offer_never_parses_the_buffer_it_is_offered_on() {
let tree = Tree::new("caimports");
tree.write("a_pkg.sv", "package a_pkg;\n localparam int A = 1;\nendpackage\n");
tree.write("b_pkg.sv", "package b_pkg;\n localparam int B = 2;\nendpackage\n");
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
let uri = session.open(
&tree.path.join("user.sv"),
"module user;\n import b_pkg::*;\n import a_pkg::*;\n logic q;\n assign q = A;\nendmodule\n",
);
session.drain();
let only = &["source.organizeImports"];
let (_, first) = parses_during(&mut session, filtered(&uri, 1, 2, only));
assert_eq!(
titles(&first),
vec!["lucisv: organize imports (removes 1, sorts 1)".to_string()],
"the unused import goes and the used one is written back: {first:#?}"
);
// The buffer's own parse, analysis and token stream are the `Document`'s,
// and no splice is verified for a menu (§P1c). What is left is one
// `Scope::build` — the index that decides which import supplies a used
// name — over the buffer and the two packages it imports: **3** parses,
// where verifying the splice used to build a second index over the same
// three and re-analyze them. The buffer's own share of that index is the
// residue §P1c names and does not remove.
for round in 0..3 {
let (parses, again) = parses_during(&mut session, filtered(&uri, 1, 2, only));
assert_eq!(parses, 3, "round {round}: one index over the buffer and its two packages");
assert_eq!(again, first, "round {round}");
}
}
#[test]
fn an_offer_the_fan_out_refuses_says_so_on_resolve_rather_than_crashing() {
let tree = Tree::new("caresolvegone");
tree.write("sub.sv", SUB);
// `sub`'s one instantiation connects by position, which makes the removal
// refuse whole — but it lives in a file the *offer* never reads, since an
// offer reads the buffer and the module's declaration and nothing else
// (`docs/features/lazy-code-action/README.md`). So the lightbulb appears
// and the click declines: the contract §P1c inherited and did not widen.
tree.write(
"other.sv",
"module other;\n logic x;\n logic y;\n sub u_pos (x, y);\nendmodule\n",
);
let abilities = ClientAbilities { code_action_resolve: true, ..Default::default() };
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
let uri = session.open(&tree.path.join("sub.sv"), SUB);
session.drain();
let only = &["refactor.rewrite.lucisv.ports"];
let offered = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 14, only));
let titles = titles(&offered);
assert_eq!(
titles,
vec!["lucisv: remove port `b` (updates 1 instantiation)".to_string()],
"the offer is made, counted from the index: {offered:#?}"
);
let action = offered.as_array().and_then(|list| list.first()).expect("the offer").clone();
assert!(action.get("edit").is_none(), "a lazy offer carries no edit: {action:#?}");
let refused = session.request(CodeActionResolveRequest::METHOD, action);
let error = refused.response_result.expect_err("the fan-out refuses this removal");
assert_eq!(error.message, "lucisv: the action is no longer available.");
}
#[test]
fn an_empty_filter_parses_nothing_however_often_it_is_asked() {
let tree = Tree::new("carepeatempty");
let (mut session, uri) = opened(&tree, FIXABLE);
for round in 0..4 {
let (parses, result) = parses_during(&mut session, filtered(&uri, 2, 2, &[]));
assert_eq!(parses, 0, "round {round}");
assert_eq!(result, serde_json::json!([]), "round {round}");
}
}
#[test]
fn the_first_offer_after_a_change_parses_the_buffer_once_and_no_more() {
let tree = Tree::new("cachange");
let (mut session, uri) = opened(&tree, FIXABLE);
let _ = parses_during(&mut session, cursor(&uri, 3, 2));
// A `didChange` is flushed by the request behind it, so the parse
// `Document::new` makes is counted inside this request — one parse, plus
// the fence answer, and nothing from the four selectors.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": format!("{FIXABLE}// changed\n") }],
}),
);
let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2));
assert!(parses <= 2, "the document's own parse, plus at most the fence answer: {parses}");
// And the request after that one is free again.
let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2));
assert_eq!(parses, 0, "the new revision is reused like any other");
}
#[test]
fn a_fence_typed_into_the_buffer_is_seen_by_the_next_request() {
let tree = Tree::new("cafence");
// A tab on line 1: a `no-tabs` finding with a Safe fix, offered as a
// quick fix.
let (mut session, uri) = opened(&tree, "module m;\n\twire a;\nendmodule\n");
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
assert_eq!(titles(&result).len(), 1, "the fix is offered: {result:#?}");
// Now fence that line. The memo is held on the `Document`, and a change
// builds a new one — so the answer must be the new text's, not the old
// text's.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{
"text": "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\nendmodule\n",
}],
}),
);
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 1, &["quickfix"]));
assert!(result.as_array().expect("a list").is_empty(), "fenced: {result:#?}");
// And back again: removing the fence restores the fix, which a memo that
// outlived its revision could not do.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 3 },
"contentChanges": [{ "text": "module m;\n\twire a;\nendmodule\n" }],
}),
);
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
assert_eq!(titles(&result).len(), 1, "unfenced again: {result:#?}");
}
#[test]
fn an_external_waiver_still_keeps_its_fix_out_of_the_offer() {
let tree = Tree::new("cawaiver");
tree.write("waivers.txt", "no-tabs\n");
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\twire a;\nendmodule\n");
session.drain();
// Without the waiver configured the fix is there.
let before = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
assert_eq!(titles(&before).len(), 1, "{before:#?}");
// A `lucisv.toml` written between requests changes the pass, and the
// configuration is read per request — nothing about it is memoized.
tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n");
let after = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"]));
assert!(after.as_array().expect("a list").is_empty(), "the new config is read: {after:#?}");
}
#[test]
fn an_untitled_buffer_is_offered_the_fix_families_and_no_refactoring() {
let tree = Tree::new("cauntitled");
tree.write("sub.sv", SUB);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
session.notify(
DidOpenTextDocument::METHOD,
serde_json::json!({
"textDocument": {
"uri": uri, "languageId": "systemverilog", "version": 1, "text": FIXABLE,
}
}),
);
session.drain();
let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
assert!(
!kinds(&result).iter().any(|kind| kind == "refactor.extract"),
"an untitled buffer has no directory to extract into: {result:#?}"
);
}
#[test]
fn a_buffer_with_crlf_endings_and_an_astral_character_offers_the_same_actions() {
let tree = Tree::new("cacrlf");
let lf = "// \u{1F600}\nmodule m;\n sub u_sub (.a(1));\nendmodule\n";
let (mut session, uri) = opened(&tree, lf);
// Line 2, character 2 is inside the instantiation in both encodings; the
// comment above it puts a non-BMP character in front of every offset, so
// the UTF-16 conversion is doing real work.
let plain = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": lf.replace('\n', "\r\n") }],
}),
);
let windows = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
assert_eq!(titles(&plain), titles(&windows), "{plain:#?}\n{windows:#?}");
assert_eq!(kinds(&plain), kinds(&windows));
}
#[test]
fn a_buffer_that_does_not_parse_offers_what_it_always_offered() {
let tree = Tree::new("cabroken");
let (mut session, uri) =
opened(&tree, "module m;\n sub u_sub (.a(1));\n logic ;;; w\nendmodule\n");
let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 6, &["refactor"]));
// The three gates that refuse over parse diagnostics still refuse; the
// port family, which never had that check, still answers.
assert!(
!kinds(&result).iter().any(|kind| kind == "refactor.extract" || kind == "refactor.inline"),
"a broken parse offers no extraction and no inline: {result:#?}"
);
}
#[test]
fn an_index_refresh_does_not_change_what_the_cursor_offers() {
let tree = Tree::new("careindex");
let (mut session, uri) = opened(&tree, FIXABLE);
let before = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
// A saved file elsewhere rebuilds the index; the buffer is untouched, so
// its own parse — and its fence answer — stay exactly as they were.
tree.write("other.sv", "module other_one;\nendmodule\n");
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
session.drain();
let after = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2));
assert_eq!(titles(&before), titles(&after), "{before:#?}\n{after:#?}");
}
#[test]
fn a_large_buffer_still_answers_its_command_from_its_text() {
// The large-file fast path installs the analysis of the *empty* file, so
// a `doc.tree` reader would find nothing in a large buffer. The four
// selectors therefore keep their text form there — which is exactly what
// they did before §P1b, and this pins it.
//
// `textDocument/codeAction` cannot show it: the fast path answers that
// method with an empty list before the dispatch is entered
// (`server/large_file.rs`). `workspace/executeCommand` is not gated, and
// is where a large buffer really does reach a selector.
let tree = Tree::new("calarge");
tree.write("sub.sv", SUB);
let mut body = String::from("module big;\n logic a;\n sub u_sub (.a(a), .b(a));\n");
for i in 0..20 {
body.push_str(&format!(" logic pad{i};\n"));
}
body.push_str("endmodule\n");
assert!(body.len() > 100, "the premise: over the test threshold");
let settings = crate::settings::ClientSettings {
large_file_threshold: 100,
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
let mut session =
Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings);
let path = tree.path.join("big.sv");
std::fs::write(&path, &body).expect("write");
let uri = session.open(&path, &body);
session.drain();
let response = session.request(
ExecuteCommand::METHOD,
serde_json::json!({
"command": crate::inline_module::INLINE_MODULE,
"arguments": [uri, { "line": 2, "character": 2 }],
}),
);
let refusal = match response.response_result {
Ok(_) => None,
Err(error) => Some(error.message),
};
assert_ne!(
refusal.as_deref(),
Some("there is no module instantiation at this position to inline."),
"a large buffer's selector reads its text, so the instantiation is found"
);
}
@@ -0,0 +1,344 @@
//! Topology handshake 33: the file that reaches an instance through modules
//! it does not itself instantiate.
//!
//! `tb.sv` writes `u_wrapper.u_top.u_sub.s`. It instantiates `wrapper`;
//! `wrapper` instantiates `top`; `top` is where `sub u_sub (…)` is written and
//! where the inline happens. None of `module_sources`' four rungs asks for
//! `tb.sv` — it declares neither `sub` nor `top`, refers to neither, and
//! instantiates neither — so `inline/mod.rs::no_hierarchy` never saw the path
//! and the inline was **silently accepted**, dissolving a scope a testbench
//! walks through. §53.2's QA reproduced exactly this.
//!
//! `module_select`'s fifth rung is the fix and this file is its pin: the
//! ladder, the deeper ladder, the shapes the rung must **not** walk, and the
//! callers whose answers must not move.
use super::*;
use crate::module_select::Reach;
use crate::state::Workspace;
const SUB: &str = "\
module sub (
input logic a,
output logic q
);
logic s;
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
";
const WRAPPER: &str = "\
module wrapper (
input logic x,
output logic z
);
top u_top (
.x(x),
.z(z)
);
endmodule
";
/// The instantiation of `sub` in `top.sv`: line 4, on the module name.
fn inline_cursor() -> Value {
serde_json::json!({ "line": 4, "character": 2 })
}
/// A tree holding the three-level ladder, with `tb.sv` written by the caller
/// so each test can say what the bench does.
fn ladder(name: &str) -> Tree {
let tree = Tree::new(name);
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
tree.write("wrapper.sv", WRAPPER);
tree
}
/// A wide session with `top.sv` open, ready to be asked to inline.
fn opened(tree: &Tree) -> (Session, Uri) {
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("top.sv"), TOP);
session.drain();
(session, uri)
}
/// Run `lucisv.inlineModule` at the `sub` instantiation; `Err` is the
/// engine's own sentence.
fn inline(session: &mut Session, uri: &Uri) -> Result<Value, String> {
let response = session.request(
ExecuteCommand::METHOD,
serde_json::json!({
"command": crate::inline_module::INLINE_MODULE,
"arguments": [uri, inline_cursor()],
}),
);
response.response_result.map_err(|error| error.message)
}
#[test]
fn a_bench_two_levels_above_the_instance_refuses_the_inline() {
let tree = ladder("h33ladder");
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
);
let (mut session, uri) = opened(&tree);
let refusal = inline(&mut session, &uri).expect_err("the bench names the instance");
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
assert!(refusal.contains("tb.sv"), "{refusal}");
}
#[test]
fn a_bench_three_levels_above_the_instance_refuses_the_inline() {
let tree = ladder("h33deep");
tree.write(
"outer.sv",
"module outer (\n input logic x,\n output logic z\n);\n\
\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
);
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n outer u_outer (.x(x), .z(z));\n\
\n initial $display(\"%b\", u_outer.u_wrapper.u_top.u_sub.s);\nendmodule\n",
);
let (mut session, uri) = opened(&tree);
let refusal = inline(&mut session, &uri).expect_err("three levels up is still the same scope");
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
assert!(refusal.contains("tb.sv"), "{refusal}");
}
#[test]
fn the_level_the_four_rungs_already_saw_still_refuses() {
// `wrapper.sv` instantiates `top` directly, so it was always in the set.
// The fifth rung must not change what the fourth already answered.
let tree = ladder("h33direct");
tree.write(
"wrapper.sv",
"module wrapper (\n input logic x,\n output logic z\n);\n\
\n top u_top (.x(x), .z(z));\n logic peek;\n assign peek = u_top.u_sub.s;\nendmodule\n",
);
let (mut session, uri) = opened(&tree);
let refusal = inline(&mut session, &uri).expect_err("the direct parent names the instance");
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
assert!(refusal.contains("wrapper.sv"), "{refusal}");
}
#[test]
fn a_ladder_nobody_reaches_into_still_inlines() {
// The rung selects more files; selecting them must not invent a refusal.
let tree = ladder("h33clean");
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
);
let (mut session, uri) = opened(&tree);
let edit = inline(&mut session, &uri).expect("nothing names the instance");
assert!(edit.is_object() || edit.is_null(), "{edit:#?}");
}
#[test]
fn a_generated_scope_two_levels_above_is_refused_and_stays_refused() {
let tree = ladder("h33generate");
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
\n initial $display(\"%b\", u_wrapper.gen[0].u_top.u_sub.s);\nendmodule\n",
);
let (mut session, uri) = opened(&tree);
let refusal = inline(&mut session, &uri).expect_err("a generated path walks the same scope");
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
}
#[test]
fn a_bind_two_levels_above_the_instance_refuses_the_inline() {
let tree = ladder("h33bind");
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
);
tree.write(
"sva.sv",
"module checker_m (input logic a);\nendmodule\n\
\nbind tb.u_wrapper.u_top.u_sub checker_m u_chk (.a(1'b0));\n",
);
let (mut session, uri) = opened(&tree);
let refusal = inline(&mut session, &uri).expect_err("a bind names the instance as a scope");
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
assert!(refusal.contains("sva.sv"), "{refusal}");
}
#[test]
fn an_unsaved_bench_that_adds_the_path_refuses_the_inline() {
// The bench on disk names nothing; the buffer does. Open buffers are a
// rung of their own, and this pins that the fifth rung did not displace
// it.
let tree = ladder("h33unsaved");
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
);
let (mut session, uri) = opened(&tree);
session.open(
&tree.path.join("tb.sv"),
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
);
session.drain();
let refusal = inline(&mut session, &uri).expect_err("the unsaved text names the instance");
assert!(refusal.contains("`u_sub` is named as a scope of the design hierarchy"), "{refusal}");
}
#[test]
fn a_second_declaration_of_the_inlined_module_still_refuses_for_being_ambiguous() {
let tree = ladder("h33duplicate");
tree.write("sub_again.sv", SUB);
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\nendmodule\n",
);
let (mut session, uri) = opened(&tree);
let refusal = inline(&mut session, &uri).expect_err("two `sub`s is ambiguous");
assert!(refusal.contains("sub"), "{refusal}");
assert!(
!refusal.contains("named as a scope of the design hierarchy"),
"the ambiguity refusal, not the hierarchy one: {refusal}"
);
}
#[test]
fn a_macro_hiding_the_path_selects_the_file_and_still_does_not_refuse() {
// Today's behaviour, pinned rather than asserted to be right. The fifth
// rung *does* hand `tb.sv` over — `words::harvest` splits raw text, so
// `u_sub` written inside a `` `define`` body is in the file's census. But
// `no_hierarchy` tokenizes, and a directive line is one opaque token, so
// there is no `Ident` spelling `u_sub` for it to find. The selection is
// not the limit here; the lexical refusal is. The whole-workspace engine
// answers exactly the same way, which is the parity that matters.
let tree = ladder("h33macro");
tree.write(
"tb.sv",
"`define PEEK u_wrapper.u_top.u_sub.s\n\
module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
\n initial $display(\"%b\", `PEEK);\nendmodule\n",
);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let scopes = ["u_sub".to_string()];
let selected = crate::module_select::hierarchical_users(ws.index(), Reach { scopes: &scopes });
assert!(selected.contains(&tree.path.join("tb.sv")), "the census sees raw text: {selected:?}");
let (mut session, uri) = opened(&tree);
inline(&mut session, &uri).expect("a macro-hidden path is not a token `no_hierarchy` can see");
}
#[test]
fn the_rung_is_the_instances_word_census_and_nothing_wider() {
// A package, an interface and a class are not scopes an inline dissolves,
// and the rung is keyed by the instance's spelling alone — so a caller
// that names one of them by mistake selects only the files that really
// do write that word.
let tree = Tree::new("h33units");
tree.write("p.sv", "package p;\n localparam K = 1;\nendpackage\n");
tree.write("user.sv", "module user;\n import p::*;\n logic a;\nendmodule\n");
tree.write("stranger.sv", "module stranger;\n logic b;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let scopes = ["p".to_string()];
let found = crate::module_select::hierarchical_users(ws.index(), Reach { scopes: &scopes });
assert_eq!(
found,
[tree.path.join("p.sv"), tree.path.join("user.sv")].into_iter().collect(),
"{found:?}"
);
}
#[test]
fn the_selected_set_answers_the_inline_exactly_as_the_whole_workspace_does() {
// The claim the fifth rung is worth having: `no_hierarchy` refuses from a
// token census, and the rung *is* that census, so the narrowed set and
// `sources()` cannot disagree. Six shapes, each run through the engine
// twice — the one the four rungs missed, the one they saw, the bind, the
// generated path, the macro-hidden path, and the clean ladder.
let benches = [
("h33p1", " initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\n", ""),
("h33p2", "", ""),
("h33p3", "", "module chk (input logic a);\nendmodule\nbind tb.u_wrapper.u_top.u_sub chk u_chk (.a(1'b0));\n"),
("h33p4", " initial $display(\"%b\", u_wrapper.gen[0].u_top.u_sub.s);\n", ""),
("h33p5", " initial $display(\"%b\", `PEEK);\n", ""),
("h33p6", " initial $display(\"%b\", u_wrapper.u_top.z);\n", ""),
];
for (name, extra, sva) in benches {
let tree = ladder(name);
tree.write(
"tb.sv",
&format!(
"`define PEEK u_wrapper.u_top.u_sub.s\n\
module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n{extra}endmodule\n"
),
);
if !sva.is_empty() {
tree.write("sva.sv", sva);
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join("top.sv");
let offset = TOP.find("sub u_sub").expect("the instantiation") as u32;
let units = ["sub".to_string(), "top".to_string()];
let scopes = ["u_sub".to_string()];
let narrowed = ws.module_sources_reaching(&path, &units, Reach { scopes: &scopes });
let whole = ws.sources();
assert_eq!(
vlog_refactor::inline_module(&narrowed, &path, offset).map(|edit| edit.edits),
vlog_refactor::inline_module(&whole, &path, offset).map(|edit| edit.edits),
"{name}: the narrowed set and the whole workspace disagree"
);
}
}
#[test]
fn the_four_rung_selector_answers_exactly_what_it_did_before() {
// Every other caller of `module_sources` — the port actions, extract —
// asks with no reach, and the fifth rung must therefore be invisible to
// them. Asserted as an equality against the rungs' own answer rather
// than as a count, so a file appearing is a failure whatever its name.
let tree = ladder("h33unchanged");
tree.write(
"tb.sv",
"module tb;\n logic x, z;\n wrapper u_wrapper (.x(x), .z(z));\n\
\n initial $display(\"%b\", u_wrapper.u_top.u_sub.s);\nendmodule\n",
);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let units = ["sub".to_string(), "top".to_string()];
let path = tree.path.join("top.sv");
let four: Vec<PathBuf> =
ws.module_sources(&path, &units).into_iter().map(|(path, _)| path).collect();
assert_eq!(
four,
vec![tree.path.join("sub.sv"), tree.path.join("top.sv"), tree.path.join("wrapper.sv")],
"the four rungs, unchanged — and `tb.sv` is exactly what they miss"
);
let scopes = ["u_sub".to_string()];
let five: Vec<PathBuf> = ws
.module_sources_reaching(&path, &units, Reach { scopes: &scopes })
.into_iter()
.map(|(path, _)| path)
.collect();
assert!(five.contains(&tree.path.join("tb.sv")), "{five:?}");
for path in &four {
assert!(five.contains(path), "the fifth rung only ever adds: {path:?} went missing");
}
}
+95 -14
View File
@@ -10,6 +10,7 @@
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use lsp_server::{Notification, Request, Response};
use lsp_types::notification::{
@@ -19,16 +20,16 @@ use lsp_types::notification::{
PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest,
Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
GotoTypeDefinition, HoverRequest, InlayHintRequest, InlineCompletionRequest,
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
RegisterCapability, Rename, Request as _, SelectionRangeRequest,
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, UnregisterCapability,
WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration,
WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest,
CodeLensRefresh, CodeLensRequest, Completion, DocumentDiagnosticRequest,
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, HoverRequest,
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare,
UnregisterCapability, WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate,
WorkspaceConfiguration, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
DidChangeWatchedFilesParams, FileChangeType, FileEvent, LogMessageParams, MessageType,
@@ -39,22 +40,28 @@ use serde_json::Value;
use super::batch::{is_shutdown, widen_of, Widen};
use super::progress::{reports, MAX_REPORTS};
use super::startup::{Startup, CONFIGURATION_WAIT};
use super::*;
use crate::settings::ClientSettings;
use crate::uri::path_to_uri;
use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
mod apply_edit;
mod cancel;
mod code_action;
mod file_ops;
mod folders;
mod formatting;
mod hierarchy_reach;
mod index;
mod large_file;
mod progress;
mod pull_diagnostics;
mod requests;
mod scan;
mod scan_trace;
mod settings;
mod startup;
mod sync;
mod tokens;
mod watchers;
@@ -85,7 +92,11 @@ impl Tree {
}
fn write(&self, rel: &str, text: &str) {
std::fs::write(self.path.join(rel), text).expect("write");
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("parent");
}
std::fs::write(&path, text).expect("write");
}
}
@@ -157,8 +168,21 @@ impl Session {
// this module counts the messages a session produces, and the
// timing lines are tested where they are observable as protocol
// traffic — `tests/e2e.rs`, against the real binary and its flag.
let server =
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
//
// `wait: ZERO` is the client that never answers the settings pull:
// the request goes out and the startup scan runs at what this
// harness already put in `settings`, which is what every session in
// this module was before the startup was staged. The staging itself
// is tested in `startup.rs`, where the answer is queued.
let startup = Startup {
abilities,
client: settings,
storage,
verbose: false,
queued: Vec::new(),
wait: Duration::ZERO,
};
let server = Server::started(server_end, roots, startup);
Session { server, client }
}
@@ -185,7 +209,64 @@ impl Session {
for message in on_the_wire {
client.sender.send(message).expect("the client's wire traffic");
}
let server = Server::started(server_end, roots, abilities, settings, None, false, queued);
let startup = Startup {
abilities,
client: settings,
storage: None,
verbose: false,
queued,
wait: Duration::ZERO,
};
let server = Server::started(server_end, roots, startup);
Session { server, client }
}
/// A session whose startup is **staged**: the settings pull goes out
/// first and the startup scan waits `wait` for the answer
/// (`server/startup.rs`). `queued` is what the client had already sent
/// when the server was built — the answer among it, for a client that
/// answers.
///
/// The settings start at the defaults, which is the whole point: what a
/// staged session indexes is what the *answer* said, not what a test put
/// in ahead of it.
fn staged(
roots: Vec<PathBuf>,
abilities: ClientAbilities,
verbose: bool,
wait: Duration,
queued: Vec<Message>,
) -> Session {
let (server_end, client) = Connection::memory();
let startup = Startup {
abilities,
client: ClientSettings::default(),
storage: None,
verbose,
queued,
wait,
};
Session { server: Server::started(server_end, roots, startup), client }
}
/// [`Session::wide`] against a client that spawned the server with
/// `--verbose` — the only sessions that are ever told what a scan spent
/// its time on (`docs/features/perf5-p4/README.md`).
fn verbose_wide(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
let (server_end, client) = Connection::memory();
let startup = Startup {
abilities: ClientAbilities::default(),
client: wide,
storage,
verbose: true,
queued: Vec::new(),
wait: Duration::ZERO,
};
let server = Server::started(server_end, roots, startup);
Session { server, client }
}
@@ -17,7 +17,7 @@ fn workspace_of(tag: &str, files: usize) -> Tree {
}
/// A `workspace/symbol` request over the wire, by id.
fn symbol_request(id: i32, query: &str) -> Message {
pub(super) fn symbol_request(id: i32, query: &str) -> Message {
Message::Request(Request::new(
RequestId::from(id),
WorkspaceSymbolRequest::METHOD.to_string(),
@@ -28,7 +28,7 @@ fn symbol_request(id: i32, query: &str) -> Message {
/// Where the indexing bar's `end` sits among everything the server said,
/// and where the response to `id` sits. `None` for either if it never
/// came.
fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
pub(super) fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
let ended = messages.iter().position(|message| {
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
&& n.params["value"]["kind"] == "end")
@@ -0,0 +1,288 @@
//! What a scan says it spent its time on (`docs/features/perf5-p4/README.md`).
//!
//! Three claims, one test each: the lines exist only under `--verbose`, the
//! counts on them are the work the scan actually did, and the stages add up
//! to the scan they describe.
use super::*;
/// A tree of `files` one-package files.
pub(super) fn trace_tree(tag: &str, files: usize) -> Tree {
let tree = Tree::new(tag);
for n in 0..files {
tree.package(&format!("t{n:03}.sv"), &format!("t{n:03}"));
}
tree
}
/// Every `timing: scan …` line the server has said since the last drain.
pub(super) fn scan_lines(session: &Session) -> Vec<String> {
session
.logged()
.into_iter()
.filter(|(typ, text)| *typ == MessageType::LOG && is_trace_line(text))
.map(|(_, text)| text)
.collect()
}
/// Whether a log line is one of a scan's three trace lines — `timing: scan
/// <number> …` — rather than the `scan started`/`scan finished` pair the
/// verbose-timing feature already had.
pub(super) fn is_trace_line(text: &str) -> bool {
let Some(rest) = text.strip_prefix("timing: scan ") else { return false };
rest.split_whitespace().next().is_some_and(|word| word.parse::<u32>().is_ok())
}
/// The one line of `lines` whose prefix says it is that kind.
pub(super) fn line_of(lines: &[String], kind: &str) -> String {
lines
.iter()
.find(|line| line.contains(&format!(" {kind} (")))
.unwrap_or_else(|| panic!("no {kind} line among {lines:#?}"))
.clone()
}
/// The value of `key=` on a `key=value` line, as text.
pub(super) fn field<'a>(line: &'a str, key: &str) -> &'a str {
let at = line.find(&format!("{key}=")).unwrap_or_else(|| panic!("no {key} on {line}"));
let rest = &line[at + key.len() + 1..];
rest.split_whitespace().next().unwrap_or("")
}
/// The value of `key=` as a number.
fn number(line: &str, key: &str) -> f64 {
let text = field(line, key);
text.parse().unwrap_or_else(|_| panic!("{key}={text} is not a number on {line}"))
}
#[test]
fn without_the_flag_a_scan_says_nothing_about_its_stages() {
// The shipped state. `Session::wide` is every other test in this module,
// and none of them may start seeing three extra log lines per scan.
let tree = trace_tree("tracequiet", 12);
let session = Session::wide(vec![tree.path.clone()], false);
assert!(scan_lines(&session).is_empty(), "verbose is off: {:#?}", session.logged());
}
#[test]
fn the_flag_makes_a_scan_say_what_it_spent_and_what_it_left() {
let tree = trace_tree("traceverbose", 12);
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let lines = scan_lines(&session);
// Three lines, and they name the same scan.
let stages = line_of(&lines, "stages");
let counts = line_of(&lines, "counts");
let memory = line_of(&lines, "memory");
for line in [&stages, &counts, &memory] {
assert!(line.starts_with("timing: scan 1 "), "{line}");
assert!(line.contains("whole"), "the startup scan is a whole scan: {line}");
}
// The counts are this fixture's, exactly: twelve files walked and read,
// none skipped, none open, and no store to hit.
assert_eq!(field(&counts, "read"), "12");
assert_eq!(field(&counts, "skipped"), "0");
assert_eq!(field(&counts, "hits"), "0");
assert_eq!(field(&counts, "misses"), "12");
assert_eq!(field(&counts, "buffers"), "0");
// Twelve files is under `INTERLEAVE_ABOVE`, so the scan is one shot and
// nothing is published mid-way.
assert_eq!(field(&counts, "publishes"), "0");
assert_eq!(field(&stages, "since_start"), field(&stages, "since_start"));
// And the index it left is those twelve packages.
assert_eq!(field(&memory, "index_files"), "12");
assert_eq!(field(&memory, "cache_entries"), "0", "no storage path, so no store");
}
#[test]
fn a_warm_second_session_reports_every_file_as_a_hit() {
// The one claim the whole warm-scan column rests on: `hits` counts
// records served for exactly these bytes, and `misses` counts the parses.
let tree = trace_tree("tracewarm", 9);
let storage = std::env::temp_dir().join(format!("lucisv_trace_store_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&storage);
let cold = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
let cold_lines = scan_lines(&cold);
let cold_counts = line_of(&cold_lines, "counts");
assert_eq!(field(&cold_counts, "hits"), "0");
assert_eq!(field(&cold_counts, "misses"), "9");
assert_eq!(field(&cold_counts, "records"), "9", "a cold scan writes every record through");
drop(cold);
let warm = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
let warm_lines = scan_lines(&warm);
let warm_counts = line_of(&warm_lines, "counts");
assert_eq!(field(&warm_counts, "hits"), "9", "the same bytes, so every lookup hits");
assert_eq!(field(&warm_counts, "misses"), "0");
assert_eq!(field(&warm_counts, "records"), "0", "a hit writes nothing back");
let warm_memory = line_of(&warm_lines, "memory");
assert_eq!(field(&warm_memory, "cache_entries"), "9");
assert!(number(&warm_counts, "decoded_kib") >= 0.0);
drop(warm);
let _ = std::fs::remove_dir_all(&storage);
}
#[test]
fn the_stages_add_up_to_the_scan_they_describe() {
// The tolerance claim: what the trace attributes must be most of the scan
// and can never be more than all of it. The slack is the loop itself —
// the progress callbacks, the per-file word `Vec`, the staging pushes —
// which is deliberately unattributed rather than silently folded into a
// neighbouring stage.
let tree = trace_tree("tracesums", 40);
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let stages = line_of(&scan_lines(&session), "stages");
let total = number(&stages, "total");
let named = [
"discovery",
"order",
// Since 2026-09-08 a scan reads a file's text at the step that indexes
// it, so what `discovery` used to spend on reading the whole scope is
// this stage instead — and a list without it accounts for a fifth of
// the scan (`docs/features/perf5-p4/README.md` §P4b3).
"read",
"cache_open",
"lookup",
"decode",
"parse",
"encode",
"store_write",
"publish_absorb",
"publish_candidates",
"publish_includes",
"publish_overlay",
"gone",
"absorb",
"compact",
"candidates",
"includes",
"overlay",
];
let sum: f64 = named.iter().map(|key| number(&stages, key)).sum();
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
assert!(sum >= total * 0.5, "the stages must account for most of it: {sum} of {total}");
}
#[test]
fn a_rescan_is_a_second_scan_with_its_own_three_lines() {
// A session pays for more than one scan — the startup scan runs at the
// default settings and whatever the client then says can ask for another
// (`docs/features/perf5-p4/README.md`, the two-scan startup). Each gets
// its own numbered triple so no reader adds two scans together.
let tree = trace_tree("tracerescan", 8);
let mut session = Session::verbose_wide(vec![tree.path.clone()], None);
let first = scan_lines(&session);
assert_eq!(first.len(), 3, "one scan, three lines: {first:#?}");
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": {
"index": { "scope": "workspace" },
"exclude": ["**/t000.sv"],
} } }),
);
let second = scan_lines(&session);
assert_eq!(second.len(), 3, "the rescan says the same three things: {second:#?}");
for line in &second {
assert!(line.starts_with("timing: scan 2 "), "{line}");
}
let counts = line_of(&second, "counts");
assert_eq!(field(&counts, "read"), "7", "the exclusion is one file fewer");
}
/// A `--verbose` session at the **default** settings, against a client that
/// cannot be asked for its settings at all — the shape every pre-2026-08-27
/// editor starts in, and the one the startup staging leaves untouched
/// (`server/startup.rs`). There is nothing to wait for, so the startup scan
/// runs immediately at the defaults: with no buffer open its folder scope is
/// empty and so is its work list.
fn verbose_default(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
let (server_end, client) = Connection::memory();
let startup = Startup {
abilities: ClientAbilities::default(),
client: ClientSettings::default(),
storage,
verbose: true,
queued: Vec::new(),
wait: Duration::ZERO,
};
let server = Server::started(server_end, roots, startup);
Session { server, client }
}
/// Ask for `lucisv.index.scope: "workspace"`, which is the rescan the pulled
/// configuration asks for in a real session.
fn widen_to_the_workspace(session: &mut Session) {
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "index": { "scope": "workspace" } } } }),
);
}
#[test]
fn a_startup_scan_with_no_files_opens_no_store_and_a_warm_rescan_rewrites_none() {
// §P4b, both halves, over the real dispatch.
//
// **(b1)** the startup scan indexes nothing, so it opens nothing: warm it
// used to read a 44 MiB store and rewrite it byte-identically, 184 ms of
// a 1.33 s start, for a scan with no files in it. **(a)** the configured
// rescan behind it hits every record, appends nothing, and so would
// rewrite the store it just read into itself — which it no longer does.
let tree = trace_tree("traceemptyscan", 9);
let storage = std::env::temp_dir().join(format!("lucisv_trace_empty_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&storage);
let store = storage.join("index-cache");
// Cold: scan 1 is empty and touches nothing, scan 2 fills the store.
let mut cold = verbose_default(vec![tree.path.clone()], Some(storage.clone()));
let first = line_of(&scan_lines(&cold), "counts");
assert_eq!(field(&first, "read"), "0", "premise: the startup scan indexes nothing");
assert_eq!(field(&first, "opens"), "0", "and so reads no store");
assert_eq!(field(&first, "compactions"), "0", "and rewrites none");
assert!(!store.exists(), "a scan with no files does not even create one");
widen_to_the_workspace(&mut cold);
let filled = line_of(&scan_lines(&cold), "counts");
assert_eq!(field(&filled, "read"), "9", "the configured rescan indexes the tree");
assert_eq!(field(&filled, "opens"), "1", "which does open the store");
assert_eq!(field(&filled, "records"), "9");
assert_eq!(field(&filled, "compactions"), "1", "a session that appended must rewrite");
drop(cold);
let bytes = std::fs::read(&store).expect("a store");
let stamp = std::fs::metadata(&store).expect("meta").modified().expect("mtime");
// Warm: the same two scans, and neither writes a byte — with a buffer
// open, which is the shape a real session has. An open buffer is indexed
// from its own analysis and writes its record through on every scan, and
// that write-through is what would otherwise put a duplicate line in the
// store and owe the rewrite back.
let mut warm = verbose_default(vec![tree.path.clone()], Some(storage.clone()));
let empty = line_of(&scan_lines(&warm), "counts");
assert_eq!(field(&empty, "read"), "0");
assert_eq!(field(&empty, "opens"), "0", "still no store read for a scan with no files");
assert_eq!(field(&empty, "compactions"), "0");
let opened = tree.path.join("t000.sv");
let text = std::fs::read_to_string(&opened).expect("read");
warm.open(&opened, &text);
let _ = scan_lines(&warm);
widen_to_the_workspace(&mut warm);
let warmed = line_of(&scan_lines(&warm), "counts");
assert_eq!(field(&warmed, "hits"), "8", "every file but the buffer came out of the store");
assert_eq!(field(&warmed, "buffers"), "1", "premise: the buffer indexes itself");
assert_eq!(field(&warmed, "repeats"), "1", "and its record was already in the store");
assert_eq!(field(&warmed, "records"), "0", "so nothing was appended");
assert_eq!(field(&warmed, "opens"), "1", "the store was read once, not twice");
assert_eq!(field(&warmed, "compactions"), "0", "and the rewrite would have been identical");
drop(warm);
assert_eq!(std::fs::read(&store).expect("a store"), bytes, "not one byte of the store moved");
assert_eq!(
std::fs::metadata(&store).expect("meta").modified().expect("mtime"),
stamp,
"and the file was not touched at all"
);
let _ = std::fs::remove_dir_all(&storage);
}
@@ -26,12 +26,18 @@ fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() {
}
#[test]
fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
// `Server::new` calls `register_watchers` and then
// `request_configuration`, in that order — this pins it on the actual
// wire rather than trusting the call order in the source. Every
// outgoing request's id is `lucisv-{n}` off one monotonically
// increasing counter, so the numeric suffix *is* the send order.
fn the_startup_pull_is_the_first_thing_on_the_wire() {
// **Amended 2026-09-08 (§P4b2).** This used to pin the opposite order:
// `Server::new` registered the watchers and *then* asked for the
// settings, because the startup scan ran in front of both and the
// answer could not have changed it. Staging the scan reverses that —
// the pull is now the first thing a session sends, because the scan is
// waiting on its answer to know which scope to run at
// (`server/startup.rs`). The claim the test makes is unchanged in kind:
// the order is pinned on the actual wire rather than trusted from the
// call order in the source. Every outgoing request's id is `lucisv-{n}`
// off one monotonically increasing counter, so the numeric suffix *is*
// the send order.
// QA (2026-08-27): pinned per the dev's own review checklist item
// ("verify on the wire").
let tree = Tree::new("pulloraftwatch");
@@ -46,7 +52,8 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
};
let watchers = index_of(RegisterCapability::METHOD);
let pull = index_of(WorkspaceConfiguration::METHOD);
assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}");
assert_eq!(pull, 0, "the pull precedes everything, watchers included: {sent:#?}");
assert!(pull < watchers, "including the watcher registration: {sent:#?}");
let numeric_suffix = |request: &Request| -> u32 {
request
@@ -57,9 +64,10 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
.parse()
.unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id))
};
assert_eq!(numeric_suffix(&sent[pull]), 0, "and it takes the first id: {sent:#?}");
assert!(
numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]),
"the pull's id must be issued after the watcher registration's: {sent:#?}"
numeric_suffix(&sent[pull]) < numeric_suffix(&sent[watchers]),
"the watcher registration's id must be issued after the pull's: {sent:#?}"
);
}
@@ -0,0 +1,529 @@
//! The staged startup (`server/startup.rs`): the settings pull goes out
//! first, the one scan runs at the scope the answer decided, and a client
//! that never answers is bounded rather than waited on for ever.
//!
//! Eight claims, one test each, all on the wire: one scan for a client that
//! answers, the bounded fallback and the late answer's ordinary rescan for
//! one that does not, a `didOpen` that beats the answer folded into that one
//! scan (its own file first in the work list), a request that beats it
//! answered *inside* the scan rather than after it, a client that cannot be
//! asked at all left exactly as it was, and a settings answer stranded behind
//! a held request taken back out of it.
//!
//! Two of them are §P4b3's (`docs/features/perf5-p4/README.md`): the request
//! that beats the answer is answered **from the user's own folder** rather
//! than off the alphabet, whichever of the two the `didOpen` and the answer
//! arrives first.
use std::time::Instant;
use super::scan::{positions, symbol_request};
use super::scan_trace::{field, is_trace_line, line_of, trace_tree};
use super::*;
/// A client that answers `workspace/configuration` and is told what a scan
/// spent its time on.
fn pulling() -> ClientAbilities {
ClientAbilities { configuration: true, ..Default::default() }
}
/// A client that also renders the indexing bar, so the mid-scan ordering of
/// an answer is observable.
fn pulling_with_a_bar() -> ClientAbilities {
ClientAbilities { configuration: true, work_done_progress: true, ..Default::default() }
}
/// The client's answer to the startup settings pull.
///
/// The id is `lucisv-0` because the pull is the **first** request a staged
/// session makes of its client: `stage_for_configuration` runs before the
/// scan, and therefore before the progress `create`, the watcher
/// registration and the lens refresh that used to be issued ahead of it.
/// `send_request` numbers off one counter that only ever goes up, so that
/// first id is a fact about the order, not a guess.
fn configuration_answer(section: Value) -> Message {
Message::Response(Response::new_ok(
RequestId::from("lucisv-0".to_string()),
serde_json::json!([section]),
))
}
/// `lucisv.index.scope: "workspace"` — the answer that used to cost a whole
/// second scan, plus the per-file log that makes the work list's order
/// readable.
fn the_whole_workspace() -> Value {
serde_json::json!({ "index": { "scope": "workspace", "logFiles": true } })
}
/// A `textDocument/didOpen` over the wire, as the client sends it.
fn did_open(path: &Path, text: &str) -> Message {
Message::Notification(Notification::new(
DidOpenTextDocument::METHOD.to_string(),
serde_json::json!({
"textDocument": {
"uri": path_to_uri(path).expect("uri"),
"languageId": "systemverilog",
"version": 1,
"text": text,
}
}),
))
}
/// Every `timing: scan …` trace line among `messages` — [`scan_lines`] over
/// a drain that has already happened, because a drain is destructive and
/// these tests ask two questions of one session.
fn trace_lines(messages: &[Message]) -> Vec<String> {
messages
.iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == LogMessage::METHOD => {
let params: LogMessageParams =
serde_json::from_value(n.params.clone()).expect("log message params");
Some(params.message)
}
_ => None,
})
.filter(|text| is_trace_line(text))
.collect()
}
/// Every log line, trace lines included — where the per-file `indexing:`
/// and `analyzed:` lines are read from.
fn log_lines(messages: &[Message]) -> Vec<String> {
messages
.iter()
.filter_map(|message| match message {
Message::Notification(n) if n.method == LogMessage::METHOD => {
let params: LogMessageParams =
serde_json::from_value(n.params.clone()).expect("log message params");
Some(params.message)
}
_ => None,
})
.collect()
}
/// The methods of the requests the server made, in send order.
fn asked(messages: &[Message]) -> Vec<String> {
messages
.iter()
.filter_map(|message| match message {
Message::Request(request) => Some(request.method.clone()),
_ => None,
})
.collect()
}
#[test]
fn a_client_that_answers_pays_one_scan_at_the_scope_it_asked_for() {
// The whole of the change, in one assertion. Before 2026-09-08 this
// session ran **two** scans: an empty one at the default folder scope,
// because nothing could be known about the client's settings until the
// pull it had not yet been sent came back, and then the configured
// rescan behind it. Now the pull goes first and there is one scan.
let tree = trace_tree("stagedone", 9);
let session = Session::staged(
vec![tree.path.clone()],
pulling(),
true,
CONFIGURATION_WAIT,
vec![configuration_answer(the_whole_workspace())],
);
let said = session.drain();
let lines = trace_lines(&said);
assert_eq!(lines.len(), 3, "one scan, three trace lines: {lines:#?}");
for line in &lines {
assert!(line.starts_with("timing: scan 1 "), "no second scan ran: {line}");
assert!(line.contains("whole"), "and it is the startup scan: {line}");
}
let counts = line_of(&lines, "counts");
assert_eq!(field(&counts, "read"), "9", "the one scan read the configured scope");
assert_eq!(session.server.workspace.index().files().len(), 9);
// And the pull really did go out ahead of everything else the startup
// sends — the order the id in `configuration_answer` depends on.
let methods = asked(&said);
assert_eq!(
methods.first().map(String::as_str),
Some(WorkspaceConfiguration::METHOD),
"the settings pull is the first thing a staged session asks: {methods:#?}"
);
}
#[test]
fn a_client_that_never_answers_is_bounded_and_then_scanned_at_the_defaults() {
// The fallback, and the shipped bound it is measured against. Two
// seconds is not a budget — the round trip is single-digit
// milliseconds — it is what a client that advertised the capability and
// then says nothing costs, once, before the workspace is indexed anyway.
assert_eq!(
CONFIGURATION_WAIT,
Duration::from_secs(2),
"the shipped bound, which no test may quietly move"
);
let tree = trace_tree("stagednever", 9);
let bound = Duration::from_millis(120);
let began = Instant::now();
let mut session = Session::staged(vec![tree.path.clone()], pulling(), true, bound, Vec::new());
let waited = began.elapsed();
assert!(waited >= bound, "the bound is waited out, not skipped: {waited:?}");
let said = session.drain();
let lines = trace_lines(&said);
assert_eq!(lines.len(), 3, "one scan, not none and not two: {lines:#?}");
let counts = line_of(&lines, "counts");
assert_eq!(
field(&counts, "read"),
"0",
"at the defaults — the folder scope, which with no buffer open is empty"
);
let (id, _) = {
let asked: Vec<&Message> = said
.iter()
.filter(
|m| matches!(m, Message::Request(r) if r.method == WorkspaceConfiguration::METHOD),
)
.collect();
assert_eq!(asked.len(), 1, "asked once, not once per retry: {asked:#?}");
let Message::Request(request) = asked[0] else { unreachable!("filtered above") };
(request.id.clone(), request.params.clone())
};
// The late answer is an ordinary settings change: it costs the one
// rescan a changed scope has always cost, and — this is the order
// contract, unchanged — a request behind it in the same burst is held
// rather than answered off the half-updated index.
let answer =
Message::Response(Response::new_ok(id, serde_json::json!([the_whole_workspace()])));
session.batch(vec![answer, symbol_request(7, "t000")]);
let said = session.drain();
let lines = trace_lines(&said);
assert_eq!(lines.len(), 3, "the late answer's rescan, and only it: {lines:#?}");
for line in &lines {
assert!(line.starts_with("timing: scan 2 "), "the second scan of the session: {line}");
}
assert_eq!(field(&line_of(&lines, "counts"), "read"), "9", "which indexed the whole tree");
let rescanned = said
.iter()
.rposition(|message| match message {
Message::Notification(n) if n.method == LogMessage::METHOD => {
n.params["message"].as_str().is_some_and(|text| text.starts_with("timing: scan 2 "))
}
_ => false,
})
.expect("the rescan traced itself");
let answered = positions(&said, 7).1.expect("the request behind it is still answered");
assert!(
rescanned < answered,
"the request waits the rescan out rather than being answered off the index it was \
sent into: {said:#?}"
);
}
#[test]
fn a_did_open_that_beats_the_answer_is_folded_into_the_one_scan_and_indexed_first() {
// A `didOpen` arriving while the settings are in flight widens the
// folder scope, which before this would have been its own scan. Staged,
// there is nothing to widen *into* yet: the buffer is installed, the one
// scan that follows resolves the scope with it in place, and
// `open_first` puts the user's own file at the head of its work list.
let tree = trace_tree("stagedopen", 9);
let opened = tree.path.join("t005.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let session = Session::staged(
vec![tree.path.clone()],
pulling(),
true,
CONFIGURATION_WAIT,
vec![did_open(&opened, &text), configuration_answer(the_whole_workspace())],
);
let said = session.drain();
let lines = trace_lines(&said);
assert_eq!(lines.len(), 3, "the widen is the scan, not a scan of its own: {lines:#?}");
for line in &lines {
assert!(line.starts_with("timing: scan 1 "), "{line}");
}
let counts = line_of(&lines, "counts");
assert_eq!(field(&counts, "read"), "9", "the configured scope, in one pass");
assert_eq!(field(&counts, "buffers"), "1", "with the buffer indexed from its own analysis");
// Open first: the per-file log the answer switched on names the work
// list in order, and the user's file is at the head of it.
let files: Vec<String> = log_lines(&said)
.into_iter()
.filter(|line| line.starts_with("indexing: ") || line.starts_with("analyzed: "))
.collect();
let first = files.first().expect("the scan logged its files");
assert!(
first.ends_with("t005.sv"),
"the open buffer is indexed first, not when the alphabet reaches it: {files:#?}"
);
// And the buffer's diagnostics were published against the finished
// index — the debt `started` pays at the end of construction.
let uri = path_to_uri(&opened).expect("uri");
let published: Vec<&Message> = said
.iter()
.filter(|m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD))
.collect();
assert!(
published.iter().any(|message| {
let Message::Notification(n) = message else { return false };
n.params["uri"] == serde_json::json!(uri)
}),
"the opened buffer is published: {published:#?}"
);
}
#[test]
fn a_request_that_beats_the_answer_is_answered_inside_the_startup_scan() {
// The regression §P4b named, closed. A definition sent before the
// settings answer used to be held behind the *configured rescan* —
// `must_wait`'s first clause — and waited the whole of it out, which on
// opentitan was 0.9 s warm. Staged, the scan it waits for is the
// **startup** scan: nothing was queued ahead of it, the session has no
// prior index and therefore no `gone`, and it is answered mid-way off
// the published prefix exactly as a request arriving during that scan
// is. The only ordering a test can check without a stopwatch is that
// the response goes out before the bar comes down.
let tree = trace_tree("stagedrequest", INTERLEAVE_ABOVE + 6);
let opened = tree.path.join("t005.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let uri = path_to_uri(&opened).expect("uri");
let definition = Message::Request(Request::new(
RequestId::from(7),
GotoDefinition::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 1, "character": 13 },
}),
));
let session = Session::staged(
vec![tree.path.clone()],
pulling_with_a_bar(),
false,
CONFIGURATION_WAIT,
vec![
configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })),
did_open(&opened, &text),
definition,
],
);
let said = session.drain();
let (ended, answered) = positions(&said, 7);
let answered = answered.expect("the definition is answered at all");
let ended = ended.expect("the bar comes down");
assert!(answered < ended, "answered inside the scan, not after it: {said:#?}");
// And it is a real, coherent answer — the buffer's own `localparam K`,
// read off the prefix `open_first` put that file at the head of.
let Some(Message::Response(response)) = said.get(answered) else {
unreachable!("positions found a response there")
};
let found = response.response_result.clone().expect("a result, not a failure");
assert_eq!(found[0]["range"]["start"]["line"], 1, "{found}");
assert_eq!(found[0]["uri"], serde_json::json!(uri), "{found}");
// One scan still, and it finished: nothing was traded for the latency
// but the completeness of that one answer.
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6);
}
/// opentitan's shape in miniature: a testbench two folders below its block,
/// the module it instantiates in that block's `rtl/`, and enough unrelated
/// files ahead of both in the alphabet that a scan reaching them first would
/// have nothing useful to answer with.
fn a_block_and_a_crowd(tag: &str, padding: usize) -> Tree {
let tree = Tree::new(tag);
tree.write("ip/aes/rtl/aes.sv", "module aes;\n localparam K = 1;\nendmodule\n");
tree.write("ip/aes/dv/tb/tb.sv", "module tb;\n aes dut ();\nendmodule\n");
for n in 0..padding {
tree.package(&format!("crowd/p{n:03}.sv"), &format!("p{n:03}"));
}
tree
}
#[test]
fn a_request_that_beats_the_answer_is_answered_from_the_users_own_folder() {
// **The §P4b2 regression, closed.** Staging made the first useful answer
// of a workspace-scoped session unimodal — and *empty*: the request was
// drained at the first interleave point, off a prefix holding the user's
// own buffer and nothing else, so the module it named was not in it yet.
// The work list now leads with the buffer's own **folder** and the drain
// waits for that folder, which is the answer the widen used to give
// (`docs/features/perf5-p4/README.md` §P4b3).
//
// `crowd/` sorts before `ip/`, so under plain path order the scan would
// reach 70 irrelevant files before `aes.sv` — this answer cannot come
// from the alphabet.
let tree = a_block_and_a_crowd("stagedfolderfirst", INTERLEAVE_ABOVE + 6);
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let definition = Message::Request(Request::new(
RequestId::from(7),
GotoDefinition::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
"position": { "line": 1, "character": 3 },
}),
));
let session = Session::staged(
vec![tree.path.clone()],
pulling_with_a_bar(),
false,
CONFIGURATION_WAIT,
vec![
configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })),
did_open(&opened, &text),
definition,
],
);
let said = session.drain();
let (ended, answered) = positions(&said, 7);
let answered = answered.expect("the definition is answered at all");
assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}");
let Some(Message::Response(response)) = said.get(answered) else {
unreachable!("positions found a response there")
};
let found = response.response_result.clone().expect("a result, not a failure");
assert_eq!(found.as_array().map(Vec::len), Some(1), "one location, not none: {found}");
assert_eq!(
found[0]["uri"],
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
"the module in the folder next door, which is what the user asked about: {found}"
);
// One scan still, and it finished over the whole workspace: the folder
// bought the answer's quality, not a smaller index.
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 8);
}
#[test]
fn a_did_open_answered_mid_scan_pulls_its_folder_in_front_of_the_request_behind_it() {
// **The case the opentitan measurement found, and the one an editor
// really produces.** The client's reader answers `workspace/configuration`
// from its own thread, so the answer usually beats the editor's `didOpen`:
// the scan begins with *no* buffer open, its work list is the plain
// alphabet, and the `didOpen` and the definition behind it arrive at an
// interleave point some way into it. Before this the definition was
// answered off that alphabet's prefix and came back `[]`.
//
// Now the burst's `didOpen` holds what is behind it (`Server::head_owed`),
// the work list is re-ordered around the buffer it installed, and the
// definition is answered once that folder has been indexed — which is
// exactly what the widen this `didOpen` used to trigger made it wait for.
//
// A client that cannot be asked for settings is the shortest way to a scan
// that has already started when the burst lands: nothing is staged, and
// the wide scope is given up front.
let tree = a_block_and_a_crowd("midscanopen", INTERLEAVE_ABOVE + 6);
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let definition = Message::Request(Request::new(
RequestId::from(7),
GotoDefinition::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
"position": { "line": 1, "character": 3 },
}),
));
let session = Session::started_behind(
vec![tree.path.clone()],
watching_progress(),
wide_ish(),
Vec::new(),
vec![did_open(&opened, &text), definition],
);
let said = session.drain();
let (ended, answered) = positions(&said, 7);
let answered = answered.expect("the definition is answered at all");
assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}");
let Some(Message::Response(response)) = said.get(answered) else {
unreachable!("positions found a response there")
};
let found = response.response_result.clone().expect("a result, not a failure");
assert_eq!(found.as_array().map(Vec::len), Some(1), "one location, not none: {found}");
assert_eq!(
found[0]["uri"],
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
"the module in the folder next door: {found}"
);
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 8);
}
#[test]
fn a_client_that_cannot_be_asked_scans_at_once_exactly_as_it_always_did() {
// The other half of the gate. A client that never advertised
// `workspace/configuration` is only ever *pushed* settings, so there is
// nothing to wait for: the scan runs immediately at the defaults, and
// the trace lines say what they said before staging existed. The bound
// is the shipped one, so a session that waited on it would take two
// seconds — the elapsed check is what proves the gate rather than the
// bound.
let tree = trace_tree("stagednoconfig", 9);
let began = Instant::now();
let session = Session::staged(
vec![tree.path.clone()],
ClientAbilities::default(),
true,
CONFIGURATION_WAIT,
Vec::new(),
);
let took = began.elapsed();
assert!(took < Duration::from_secs(1), "nothing was waited for: {took:?}");
let said = session.drain();
assert!(asked(&said).is_empty(), "nothing is asked of this client: {said:#?}");
let lines = trace_lines(&said);
assert_eq!(lines.len(), 3, "one startup scan: {lines:#?}");
let counts = line_of(&lines, "counts");
assert_eq!(field(&counts, "read"), "0", "at the defaults, as it always was");
assert_eq!(field(&counts, "opens"), "0", "and §P4b's deferred store open is untouched");
assert_eq!(field(&counts, "compactions"), "0");
}
#[test]
fn an_answer_behind_a_held_request_is_not_stranded_for_the_whole_bound() {
// **A defect this lane measured before it shipped** (2026-09-08). The
// editor's opening burst is `didOpen` then a request, and the client's
// reader can answer the settings pull into that same burst. The request
// must wait — there is no index yet — and `process_batch`'s order rule
// takes *everything behind it* into `held` with it, the answer included.
// The wait then saw the pull still outstanding and blocked the whole
// bound: one warm opentitan session in three took 2.1 s to its first
// useful answer instead of 0.39 s. The answer is taken back out;
// everything else in the burst keeps its place.
let tree = trace_tree("stagedstranded", 9);
let opened = tree.path.join("t005.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let bound = Duration::from_secs(30);
let began = Instant::now();
let session = Session::staged(
vec![tree.path.clone()],
pulling(),
true,
bound,
vec![
did_open(&opened, &text),
symbol_request(7, "t000"),
configuration_answer(the_whole_workspace()),
],
);
let took = began.elapsed();
assert!(took < Duration::from_secs(5), "the bound was not waited out: {took:?}");
let said = session.drain();
let lines = trace_lines(&said);
assert_eq!(lines.len(), 3, "one scan, at the answered scope: {lines:#?}");
assert_eq!(field(&line_of(&lines, "counts"), "read"), "9");
// And the request is neither lost nor answered off an empty index: nine
// files are under `INTERLEAVE_ABOVE`, so this scan answers nothing
// mid-way and the request is still waiting for `run` to take it — which
// is the order rule it was held for, working exactly as it does for a
// short startup scan with nothing staged.
assert_eq!(positions(&said, 7).1, None, "a short scan answers nothing mid-way: {said:#?}");
assert_eq!(session.server.held.len(), 1, "and the request is still owed an answer");
}
+8
View File
@@ -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
File diff suppressed because it is too large. Load diff
+297
View File
@@ -0,0 +1,297 @@
//! One workspace scan in flight: the work list it took, the text and the
//! records it has gathered so far, and what it reports about itself as it
//! runs.
//!
//! Split out of `state.rs` on 2026-09-08, as a pure move, when the lazy read
//! gave the scan three more things to carry (`docs/features/perf5-p4/README.md`
//! §P4b3). [`Workspace`](super::Workspace) drives it — `begin_scan` builds
//! one, `scan_step` advances it, `finish_scan` lands it — so the fields are
//! `pub(super)` and visible exactly where they were before the move: inside
//! `crate::state` and nowhere else.
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use vlog_semantic::FileFacts;
use crate::includes::Include;
use crate::scan_order::{self, WorkList};
use crate::scan_trace::{self, ScanTrace};
/// A `Scope` resolved: which files one index rebuild works from, and the text
/// of the ones it already holds.
///
/// **Nothing on disk has been read.** Until 2026-09-08 this carried every
/// in-scope file's text, read in one pass before the first file was indexed —
/// 34 MiB and ~293 ms on OpenTitan, held for the whole life of the scan and
/// spent before any request could be answered. A file's text is now read at
/// the step that indexes it and let go again
/// (`docs/features/perf5-p4/README.md` §P4b3). An **open buffer's** text is
/// still taken here, with the analysis beside it, because the two must
/// describe the same bytes and the buffer may be edited while the scan runs.
pub(super) struct Sources {
/// Every in-scope file, in scope order: the walked ones the cap and the
/// open buffers left, then the buffers' own paths.
pub(super) files: Vec<PathBuf>,
/// The text of each open buffer among `files`, as it was when the scope
/// was resolved.
pub(super) buffered: HashMap<PathBuf, String>,
/// What the open buffers among `files` already know about themselves.
pub(super) analyzed: Analyzed,
pub(super) incdirs: Vec<PathBuf>,
pub(super) warnings: Vec<String>,
}
/// The index facts and the completion words of the entries `texts` took from an
/// **open buffer**, read off the analysis that buffer already holds.
///
/// Both maps are filled in the same loop that lets a buffer override the disk
/// copy, so an entry here is always the analysis of exactly the text beside it
/// in `texts` — the two cannot describe different bytes. A file that is not an
/// open buffer appears in neither map and is parsed and lexed as it always was.
#[derive(Default)]
pub(super) struct Analyzed {
pub(super) facts: HashMap<PathBuf, FileFacts>,
pub(super) words: HashMap<PathBuf, Vec<String>>,
}
/// Whether a caller of `collect_sources` wants [`Analyzed`] filled in.
///
/// An index rebuild does — it is what it indexes the open buffers from. A
/// refactoring reads the texts and nothing else, and reading a record off every
/// open buffer for it would be work nothing looks at.
#[derive(PartialEq, Eq)]
pub(super) enum HeldAnalyses {
Wanted,
Unused,
}
/// One workspace scan in flight: the work list it took when it began, and how
/// far through it the workspace has got.
///
/// A value rather than a loop inside [`Workspace::rebuild_index_with`] because
/// the server answers the client's messages *between* two files of a scan
/// (`docs/features/scan-interleave/README.md`), and a message it answers needs
/// the very workspace the scan is feeding — which a callback called from
/// inside a `&mut self` loop can never be handed. Splitting the loop is what
/// puts the scan's state somewhere the message can be answered around.
pub struct Scan {
/// Whether this scan rebuilds the index or only folds newly-in-scope files
/// into it. The whole difference is in [`Workspace::finish_scan`]; every
/// step in between is the same code.
pub(super) kind: ScanKind,
/// Every file this scan indexes, in the order it indexes them: the open
/// buffers' own files, then the rest of their folders, then the rest in
/// path order ([`crate::scan_order`]). For a widen that is the
/// newly-in-scope files plus the open buffers, not the whole scope.
///
/// **Paths, not texts.** A file's text is read at the step that indexes
/// it; see [`Workspace::scan_step`].
pub(super) work: Vec<PathBuf>,
/// How many files at the front of `work` are the user's own
/// neighbourhood — see [`Scan::neighbourhood_indexed`].
pub(super) head: usize,
/// The text of each open buffer among `work`, taken when the work list
/// was, so it describes the same bytes as that buffer's entry in
/// `analyzed` however the buffer is edited while the scan runs.
pub(super) buffered: HashMap<PathBuf, String>,
/// What each file taken so far `` `include``s, read off the text at its
/// own step. Staged for the same reason `words` is: the include graph is
/// built once at the end and once per mid-scan publish, and by then the
/// text is gone.
pub(super) includes: HashMap<PathBuf, Vec<Include>>,
/// Files of `work` whose text could not be read when their step came, and
/// which therefore contribute nothing at all. Empty in every ordinary
/// scan: a file has to leave the disk between the walk and its own step.
/// Named so that the scan can leave it out of everything it lands —
/// `collect_sources` used to drop such a file before the work list
/// existed, and a whole scan must still take it *out* of the index.
pub(super) unread: Vec<PathBuf>,
/// Every file that is in scope once this scan lands, kept flat so the
/// include graph's known-file table can be relearned from a slice. Which
/// files *exist* is settled the moment the scope is resolved, so this never
/// moves while the scan runs — reordering the tail of `work` does not
/// reorder a set. Equal to `work`'s paths for a whole scan; for a widen it
/// is the index's files plus `work`'s.
pub(super) paths: Vec<PathBuf>,
/// What this scan takes *out* of the index, known before it starts. Empty
/// for a whole scan, which works out what left the scope from its own work
/// list once it has one ([`Workspace::finish_scan`]).
pub(super) gone: Vec<PathBuf>,
/// What the open buffers among `work` already knew about themselves, taken
/// from as each of them is reached.
pub(super) analyzed: Analyzed,
pub(super) incdirs: Vec<PathBuf>,
pub(super) warnings: Vec<String>,
/// How many of `work` have been indexed.
pub(super) at: usize,
/// The records taken since the last publish, and which files of `work`
/// they came from. Staged rather than merged because a merge is a pass
/// over the whole index — see [`vlog_semantic::WorkspaceIndex::absorb`].
pub(super) staged: Vec<FileFacts>,
pub(super) staged_at: Vec<usize>,
/// The completion words of every file taken so far, which the tables built
/// when the scan ends are assembled from.
pub(super) words: HashMap<PathBuf, Vec<String>>,
/// How many files the size cap kept out, and how many came from the
/// persistent cache instead of a parse. Facts about this scan, so they
/// live on it — the end message names both.
pub(super) skipped: usize,
pub(super) cached: usize,
/// What this scan spent its time on, when `--verbose` asked. Off, it is a
/// bag of zeroes nobody reads (`crate::scan_trace`).
pub(super) trace: ScanTrace,
}
/// Which of the two shapes a [`Scan`] is.
///
/// One enum rather than two `finish` methods so a caller cannot pair the wrong
/// ending with a scan: the scan itself says how it must be landed.
#[derive(PartialEq, Eq)]
pub(super) enum ScanKind {
/// Every in-scope file, and whatever the index holds that the work list
/// does not name has left the scope.
Whole,
/// Only the files a scope widen brought in, folded into the index beside
/// what is already there (`docs/features/index-scope/README.md`).
Widen,
}
impl Scan {
/// How many files the size cap kept out of this scan.
pub fn skipped(&self) -> usize {
self.skipped
}
/// How many files came from the persistent cache instead of being parsed.
pub fn cached(&self) -> usize {
self.cached
}
/// How many files this scan will index — known before the first parse,
/// which is what lets the caller decide whether the scan is long enough to
/// be worth answering messages in the middle of.
pub fn total(&self) -> usize {
self.work.len()
}
/// Whether this scan has stepped every file of the user's own
/// neighbourhood — the open buffers and the folders they raise to
/// ([`crate::scan_order`]).
///
/// **What a request held for the startup scan waits for.** A mid-scan
/// answer reads the published prefix, and a prefix holding the user's own
/// buffer and the alphabet after it names nothing they asked about: the
/// first useful answer of a workspace-scoped session was measurably
/// *empty* (`docs/features/perf5-p4/README.md` §P4b2). Waiting for the
/// neighbourhood makes it the answer the folder scope would have given,
/// which is what it was before the startup scan was staged. Requests that
/// arrive after that are answered at every interleave point as they always
/// were, and a scan with no neighbourhood (nothing open, an `untitled:`
/// buffer, or a folder covering the workspace) has `head` 0 and answers at
/// the first one.
pub fn neighbourhood_indexed(&self) -> bool {
self.at >= self.head
}
/// The text of one file of this scan's work list, at the moment its step
/// comes — `None` when it cannot be read.
///
/// An open buffer's is the copy taken when the work list was, and it is
/// *taken*: a scan indexes each file once, so holding it afterwards would
/// be holding a second copy of a buffer the workspace already has. Every
/// other file is read from disk here and nowhere else in the scan.
pub(super) fn take_text(&mut self, path: &Path) -> Option<String> {
if let Some(text) = self.buffered.remove(path) {
return Some(text);
}
let reading = self.trace.now();
let text = fs::read_to_string(path).ok()?;
scan_trace::count_read();
self.trace.saw_read(text.len(), reading);
Some(text)
}
/// The files this scan has not reached yet, for a caller that wants to
/// re-order them ([`Scan::reorder`]).
pub fn remaining(&self) -> Vec<PathBuf> {
self.work[self.at.min(self.work.len())..].to_vec()
}
/// Put `ordered` — [`Scan::remaining`] ranked again — back as what is left
/// to index, and take its head segment as the new neighbourhood.
///
/// The open-first rule, applied to a buffer opened *after* the work list
/// was taken: a `didOpen` answered mid-scan puts that file and the folder
/// around it next rather than leaving the user waiting for the alphabet to
/// reach them. Reordering the tail cannot change the finished index —
/// records are merged in path order whatever order they were taken in
/// ([`vlog_semantic::IndexBuilder`]) — so this is a latency decision and
/// nothing more.
pub fn reorder(&mut self, ordered: WorkList) {
let at = self.at.min(self.work.len());
self.work.truncate(at);
self.work.extend(ordered.files);
// What is left to wait for, bounded against the whole scan rather than
// against the tail it was ranked from
// ([`crate::scan_order::worth_waiting`]), and then placed: the
// neighbourhood ends that many files past where the scan has got to.
self.head = match scan_order::worth_waiting(ordered.head, self.work.len()) {
0 => 0,
pending => at + pending,
};
}
}
/// What each of `taken` `` `include``s, as [`IncludeGraph`] wants it.
///
/// Borrowed, never cloned: the lists were read at each file's own step and the
/// graph only reads them again ([`crate::includes::IncludeGraph::from_includes`]).
///
/// A free function rather than a method because the two callers hold the map
/// differently — a mid-scan publish still has the whole [`Scan`], and the two
/// `finish` paths have taken it apart.
pub(super) fn included<'a>(
includes: &'a HashMap<PathBuf, Vec<Include>>,
taken: &'a [PathBuf],
) -> Vec<(&'a Path, &'a [Include])> {
taken
.iter()
.map(|path| (path.as_path(), includes.get(path).map(Vec::as_slice).unwrap_or(&[])))
.collect()
}
/// What an index rebuild reports about itself as it runs.
///
/// This module speaks no protocol, so an event carries numbers and paths and
/// nothing that reads like a message; `server.rs` turns them into a progress
/// report and a log line (`docs/features/indexing-ux/README.md`).
pub enum IndexEvent<'a> {
/// One file is about to be parsed into the index: how many were parsed
/// before it, how many there are in all, and which one it is. `done`
/// counts from 0, so the file being reported is number `done + 1` of
/// `total`.
Parsing { done: usize, total: usize, path: &'a Path },
/// One file went into the index from the persistent cache instead of
/// being parsed. The same three numbers [`IndexEvent::Parsing`] carries,
/// because it is the same file of the same work list — it is *how* it got
/// there that differs, and a user watching a rescan fly through a
/// thousand files deserves to be told why.
Cached { done: usize, total: usize, path: &'a Path },
/// One file went into the index from the analysis an **open buffer**
/// already holds — the parse this server did when the buffer was last
/// opened or changed — instead of being parsed again. The same three
/// numbers the other two carry, for the same reason.
///
/// Its own variant rather than [`IndexEvent::Cached`] so that "from cache"
/// keeps meaning the persistent store and nothing else
/// (`docs/features/index-persistence/README.md`): a buffer's own analysis
/// is in memory, is there whether that store exists or not, and is right
/// even when the buffer has unsaved edits — which is exactly when a
/// content-keyed store has nothing to offer.
Analyzed { done: usize, total: usize, path: &'a Path },
/// A walked file was skipped without being read, because it is bigger
/// than the size cap in force.
Skipped { path: &'a Path, size: u64, cap: u64 },
}
+102
View File
@@ -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);
}
+6
View File
@@ -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);
+17 -2
View File
@@ -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),
+41 -6
View File
@@ -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)
}
+49 -6
View File
@@ -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);
+10 -1
View File
@@ -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 }
}
}
+86 -25
View File
@@ -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("}")])
}
}
+15 -4
View File
@@ -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;
+17 -2
View File
@@ -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);
}
+154 -3
View File
@@ -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`
+39 -1
View File
@@ -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()
+10 -1
View File
@@ -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) => {
+305 -1
View File
@@ -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,10 +11,120 @@
//! 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_parser::defines::collect_defines;
use vlog_parser::token::Token;
use vlog_parser::LineIndex;
use vlog_semantic::{analyze, FileFacts, IndexBuilder, SymbolKind, WorkspaceIndex};
use crate::context::ModuleInterface;
use crate::visit::walk_items;
use crate::ParsedSource;
/// Every package one file declares, with the names it exports — `None` for a
/// package this file alone cannot answer for.
///
/// The text-taking form, for a caller that has not parsed: exactly one
/// [`ParsedSource::parse`] followed by [`package_exports_in`], so the two can
/// only ever give the same answer.
pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
let parsed = ParsedSource::parse(src);
package_exports_in(path, parsed.file(), parsed.tokens(), src)
}
/// [`package_exports`] over a parse the caller **already has** — `file` and
/// `tokens` from one [`ParsedSource::parse`] of `src`.
///
/// 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.
///
/// Two things make this cheap enough for the CLI to run over a whole project
/// (take 5 §P3, `docs/features/perf5-p3/README.md`). The index is built from
/// the caller's parse rather than from the text, so the file is lexed and
/// parsed once for this and for the interface census together; and a file
/// whose tree holds **no package item** never reaches the index at all — nine
/// files in ten on opentitan `hw/ip`. The gate reads the AST, never the text:
/// a `package` inside a string or a comment is not a declaration, and a file
/// that says nothing about packages must cost nothing.
pub fn package_exports_in(
path: &Path,
file: &SourceFile,
tokens: &[Token],
src: &str,
) -> Vec<(String, Option<Vec<String>>)> {
if !declares_a_package(file) {
return Vec::new();
}
let index = one_file_index(path, file, tokens, 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()
}
/// Whether this tree holds a `package` item anywhere, which is the gate on
/// building an index for the file at all.
///
/// Deliberately a **superset** of "declares a package unit": `walk_items`
/// descends into every container, while only a package item bound in the file
/// scope becomes a unit the index records. Answering `true` too often costs
/// an index; answering `false` too often would lose a package, so the walk
/// errs the one way it may.
///
/// A **fragment** parse — a file that is the bare middle of something, so its
/// items list is empty and its content hangs off `SourceFile::fragment` —
/// `walk_items` does not descend into, and is never gated out. No fragment
/// shape can hold a package (they are statements, enum members and cover
/// items, and a file opening with `package` is never re-read as one), but the
/// gate does not rest on that.
fn declares_a_package(file: &SourceFile) -> bool {
if file.fragment.is_some() {
return true;
}
let mut found = false;
walk_items(file, &mut |item| {
found |= matches!(item.kind, ItemKind::Package { .. });
});
found
}
/// The one-file index [`WorkspaceIndex::build`] would make of this file,
/// built from the caller's parse instead of from its text.
///
/// `build` is `IndexBuilder::add_file` + `finish`, and `add_file` is
/// `add_facts(FileFacts::of(path, src))`. `FileFacts::of` parses, analyses and
/// reads the record off; [`FileFacts::from_analysis`] is that same read-off
/// with the parse handed in. So this is `build` with the lex and the parse it
/// would have done deleted — pinned by the equality test below, not by the
/// reading of two functions.
fn one_file_index(path: &Path, file: &SourceFile, tokens: &[Token], src: &str) -> WorkspaceIndex {
let defines = collect_defines(tokens);
let sem = analyze(file, src);
let lines = LineIndex::new(src);
let facts =
FileFacts::from_analysis(path.to_path_buf(), file, &defines, &sem, src, &lines, tokens);
let mut builder = IndexBuilder::new();
builder.add_facts(facts);
builder.finish()
}
/// Every module, interface and program the file declares, with what it
/// exposes. `None` for a unit whose header cannot be read whole.
@@ -180,3 +291,196 @@ mod tests {
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
}
}
/// The package half: every fixture answers what a one-file `WorkspaceIndex`
/// built from the file's **text** answers, and a file with no package item
/// never builds one (take 5 §P3).
#[cfg(test)]
mod package_tests {
use super::*;
/// The construction §P3 replaced, kept here as the thing to be equal to:
/// a one-file index built from the text, queried exactly as
/// [`package_exports_in`] queries the index it builds from a parse.
fn from_text(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 shape the census can meet, named so a failure says which.
///
/// The list is the §P3 brief's: no package, one, two, a wildcard export,
/// a named re-export, a package behind a directive, a package after a
/// module, text that does not lex, a parse error inside a package body, a
/// class in a package, the word `package` in a string and in a comment,
/// and one name declared twice in the same file.
fn fixtures() -> Vec<(&'static str, &'static str)> {
vec![
("no package", "module m ();\n wire a;\nendmodule\n"),
(
"one package",
"package p;\n localparam int A = 1;\n typedef logic [1:0] t;\n\
endpackage\n",
),
(
"two packages",
"package p;\n localparam int A = 1;\nendpackage\n\
package q;\n localparam int B = 2;\nendpackage\n",
),
(
"a wildcard export of itself",
"package p;\n localparam int A = 1;\n export *::*;\nendpackage\n",
),
(
"a wildcard export of another package",
"package p;\n import q::*;\n localparam int A = 1;\n export q::*;\n\
endpackage\n",
),
(
"a named re-export",
"package p;\n import q::x;\n localparam int A = 1;\n export q::x;\n\
endpackage\n",
),
(
"a package behind a directive",
"`ifdef USE_PKG\npackage p;\n localparam int A = 1;\nendpackage\n`endif\n",
),
(
"a package after a module",
"module m ();\nendmodule\npackage p;\n localparam int A = 1;\nendpackage\n",
),
("text that does not lex", "module m;\n wire a = \"unterminated\nendmodule\n"),
(
"a parse error inside the package",
"package p;\n localparam int A = 1;\n @@@ ;\n localparam int B = 2;\n\
endpackage\n",
),
(
"a class in a package",
"package p;\n class c;\n int field;\n endclass\n\
endpackage\n",
),
(
"the word package in a string",
"module m ();\n initial $display(\"package p; endpackage\");\nendmodule\n",
),
(
"the word package in a comment",
"// package p; endpackage\nmodule m ();\nendmodule\n",
),
(
"one name declared twice",
"package p;\n localparam int A = 1;\nendpackage\n\
package p;\n localparam int B = 2;\nendpackage\n",
),
("an empty file", ""),
]
}
#[test]
fn every_fixture_answers_what_a_text_built_index_answers() {
for (name, src) in fixtures() {
let path = Path::new("/w/f.sv");
assert_eq!(package_exports(path, src), from_text(path, src), "{name}");
}
}
#[test]
fn the_parsed_form_and_the_text_form_agree() {
for (name, src) in fixtures() {
let path = Path::new("/w/f.sv");
let parsed = ParsedSource::parse(src);
assert_eq!(
package_exports_in(path, parsed.file(), parsed.tokens(), src),
package_exports(path, src),
"{name}"
);
}
}
/// The gate is the whole saving, so it is asserted directly rather than
/// inferred from an equal answer: exactly the fixtures that write a
/// `package` item reach the index.
#[test]
fn only_a_package_item_opens_the_gate() {
let gated_out = [
"no package",
"text that does not lex",
"the word package in a string",
"the word package in a comment",
"an empty file",
];
for (name, src) in fixtures() {
let opens = declares_a_package(ParsedSource::parse(src).file());
assert_eq!(opens, !gated_out.contains(&name), "{name}");
}
}
/// A file that does not lex really is one, or the fixture above tests
/// nothing about the lex-error path.
#[test]
fn the_unlexable_fixture_does_not_lex() {
let src = fixtures()
.into_iter()
.find(|(name, _)| *name == "text that does not lex")
.map(|(_, src)| src)
.unwrap_or_default();
assert!(ParsedSource::parse(src).lex_error().is_some(), "{src:?}");
}
/// The answers themselves, not only their equality to the old
/// construction: a file with no package says nothing, a plain package is
/// a list, and a re-export is unknowable.
#[test]
fn the_answers_are_the_conservative_ones() {
let path = Path::new("/w/f.sv");
assert!(package_exports(path, "module m ();\nendmodule\n").is_empty());
let plain = package_exports(path, "package p;\n localparam int A = 1;\nendpackage\n");
assert_eq!(plain.len(), 1);
assert_eq!(plain[0].0, "p");
assert_eq!(plain[0].1.as_deref(), Some(["A".to_string()].as_slice()));
let wildcard = package_exports(
path,
"package p;\n localparam int A = 1;\n export q::*;\nendpackage\n",
);
assert_eq!(wildcard, vec![("p".to_string(), None)], "a re-export is unknowable");
}
/// One name declared twice **in one file** — the `` `ifdef``-copied
/// package — answers with the *first* declaration's members, not with
/// `None`. That is what the one-file index has always said and this lane
/// changes nothing about it; the `None` the CLI's census produces is the
/// *cross-file* rule, applied by `Census::of`'s merge when two files each
/// contribute an entry for one name.
///
/// Pinned here so a later change to either construction has to notice it.
#[test]
fn a_name_declared_twice_in_one_file_answers_with_the_first() {
let path = Path::new("/w/f.sv");
let first = package_exports(
path,
"package p;\n localparam int A = 1;\nendpackage\n\
package p;\n localparam int B = 2;\nendpackage\n",
);
assert_eq!(first, vec![("p".to_string(), Some(vec!["A".to_string()]))]);
let swapped = package_exports(
path,
"package p;\n localparam int B = 2;\nendpackage\n\
package p;\n localparam int A = 1;\nendpackage\n",
);
assert_eq!(swapped, vec![("p".to_string(), Some(vec!["B".to_string()]))]);
}
}
+4 -1
View File
@@ -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, package_exports_in};
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};
+1
View File
@@ -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,
+1
View File
@@ -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);
}
}
+2 -2
View File
@@ -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(_)
+13
View File
@@ -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)]
+51
View File
@@ -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.
+3
View File
@@ -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::*;
+93 -2
View File
@@ -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
+173
View File
@@ -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>,
}
+39 -2
View File
@@ -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`
+3 -3
View File
@@ -52,9 +52,9 @@ struct RawLexer<'a> {
/// Multi-character operators, longest first so greedy matching works.
const OPERATORS: &[&str] = &[
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "**", "==",
"!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=",
"%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "->>", "**",
"==", "!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=",
"/=", "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
];
const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
+1
View File
@@ -10,6 +10,7 @@ pub mod lexer;
pub mod line_index;
pub mod parser;
pub mod span;
pub mod stats;
pub mod token;
pub use lexer::{tokenize, LexError};
+5 -1
View File
@@ -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`,
+44 -6
View File
@@ -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("(");
+13 -3
View File
@@ -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`.
+4
View File
@@ -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;
@@ -299,6 +301,7 @@ struct Rewind {
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
/// instead of returning `Err`.
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
crate::stats::count_parse();
Parser::new(tokens, source, false).parse_source_file()
}
@@ -315,6 +318,7 @@ pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
/// parses of the same over-deep input overflow at the same depth.
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
crate::stats::count_parse();
let mut p = Parser::new(tokens, source, true);
match p.parse_source_file() {
Ok(file) => (file, p.diagnostics),
+72 -19
View File
@@ -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> {
+16 -3
View File
@@ -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 })
}
}
+38 -5
View File
@@ -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("(");
+28 -6
View File
@@ -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]
+78 -3
View File
@@ -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.
+15 -1
View File
@@ -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
+39
View File
@@ -0,0 +1,39 @@
//! How much parsing this thread has done — a work counter, not a timer.
//!
//! A `textDocument/codeAction` used to parse the same buffer five times, and
//! the only honest way to prove that it no longer does is to count the parses
//! rather than to time them (take 5 §P1,
//! `docs/features/perf5-p1/README.md`). A stopwatch assertion on a 1.3 MB
//! buffer is a flake; a count is not.
//!
//! **Per thread, deliberately.** A process-wide counter would be unusable as
//! an assertion, because `cargo test` runs tests in parallel and every other
//! test in the binary would be adding to it; and it would answer the wrong
//! question anyway, since what a caller wants to know is what *this* request
//! did. A request is answered on one thread, so a thread-local count is that
//! number exactly. It costs one non-atomic add per whole-file parse.
use std::cell::Cell;
thread_local! {
static PARSES: Cell<u64> = const { Cell::new(0) };
}
/// How many whole-file parses this thread has run.
///
/// Counted in [`crate::parse`] and [`crate::parse_tolerant`], which is every
/// way a whole file is parsed: [`crate::parse_source`] and
/// [`crate::parse_source_tolerant`] both funnel through them. A *lex* failure
/// parses nothing and is not counted; neither is a fragment read (macro
/// expansion), which re-reads a token slice rather than a file.
///
/// The count is monotone and never reset, so a caller measures a *delta*
/// across the work it is asking about.
pub fn parses() -> u64 {
PARSES.with(Cell::get)
}
/// Count one whole-file parse.
pub(crate) fn count_parse() {
PARSES.with(|parses| parses.set(parses.get() + 1));
}
+1
View File
@@ -257,6 +257,7 @@ keywords![
"pure",
"extern",
"rand",
"randsequence",
"randc",
"local",
"protected",
+77 -1
View File
@@ -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
+296
View File
@@ -0,0 +1,296 @@
//! The state after the edits: the index the verifier compares against, and
//! one watched file's print of it.
//!
//! Both used to be "do it all again". The after-index was a whole
//! `WorkspaceIndex::build` over every in-scope file, of which an edit changes
//! two or three; the after-print of an *unedited* watched file was a fresh
//! parse and analysis of text nothing had touched. Take 5 §P2c replaced the
//! first with the before-index plus the edited files' absorbed records, and
//! the second with the analysis the before-pass already made, re-resolved
//! against the new index.
//!
//! **Nothing the verifier compares changed.** The prints are the same prints,
//! built by the same `print`, over the same watched set; what changed is where
//! their inputs come from. The tests below are the proof that the inputs are
//! the same inputs — including on edits crafted to make an incremental index
//! disagree with a rebuilt one.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_semantic::{resolve_external, FileFacts, Semantics, WorkspaceIndex};
use super::{print, Print, Shifts};
use crate::scope::Scope;
/// The workspace index as it would be after the edits, so that a cross-file
/// capture is caught exactly the way an in-file one is — **and** the one new
/// analysis of each edited file, which is also its after-print's.
///
/// The before-index already holds a record per in-scope file, and an edit
/// changes at most a handful of them. So this is the before-index with the
/// edited files' new records absorbed, and not one unedited file re-read:
/// `WorkspaceIndex::absorb` promises "the index a full build over the
/// resulting record set would have produced" (`docs/topo.md` §3), and every
/// edited path is one the index already holds, so no file id moves either.
/// One `absorb` of every edited record rather than an `update_facts` per
/// record: both promise that same equality, and `absorb`'s single whole merge
/// **measured faster** than the per-file restricted merges, which walk the
/// same records with a name-set lookup at every declaration (tail rename
/// 37 ms against 53; see the feature README's §P2c entry).
/// That equality is what the verifier depends on and what
/// `an_absorbed_after_index_is_the_index_a_rebuild_would_give` pins, on
/// crafted adversarial edits as well as on ordinary ones (take 5 §P2c).
///
/// Each edited file is parsed **once**, here, and the analysis that parse
/// produced is handed back for the after-print rather than being made again.
pub(super) fn after_index(
scope: &Scope,
edited: &[(PathBuf, String)],
) -> (WorkspaceIndex, Vec<(PathBuf, Semantics)>) {
let mut records = Vec::with_capacity(edited.len());
let mut analyses = Vec::with_capacity(edited.len());
for (path, text) in edited {
let (facts, semantics) = FileFacts::analyzed(path.clone(), text);
records.push(facts);
analyses.push((path.clone(), semantics));
}
let mut index = scope.index().clone();
index.absorb(records, &[]);
(index, analyses)
}
/// One watched file's after-print: from the edited file's own new analysis
/// when the edits touched it, and otherwise from the analysis the before-pass
/// computed, re-resolved against the after-index.
pub(super) fn after_print(
scope: &Scope,
i: usize,
path: &Path,
index: &WorkspaceIndex,
edited: &[(PathBuf, Semantics)],
excluded: &[TextRange],
) -> Option<Print> {
match edited.iter().find(|(edited_path, _)| edited_path == path) {
Some((_, semantics)) => {
let external = resolve_external(semantics, index);
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
}
None => {
let (semantics, external) = scope.against(i, index)?;
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::apply;
use crate::TextEdit;
/// What a whole `WorkspaceIndex::build` over the edited texts gives — the
/// thing the absorbed index has to equal, and what §P2c replaced.
fn rebuilt(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
let sources: Vec<(PathBuf, &str)> = (0..scope.len())
.filter_map(|i| {
let (path, text) = (scope.path(i)?, scope.text(i)?);
let text = edited
.iter()
.find(|(edited_path, _)| edited_path == path)
.map_or(text, |(_, edited_text)| edited_text.as_str());
Some((path.to_path_buf(), text))
})
.collect();
WorkspaceIndex::build(sources)
}
/// Every query the verifier's prints reach the index through, for one
/// name — so "the same index" is checked at the level the checks use it
/// and not only through the fingerprint.
fn answers(index: &WorkspaceIndex, name: &str) -> String {
let mut out = String::new();
for def in index.units(name) {
out.push_str(&format!(
"unit {} {:?} {}..{}\n",
def.file.0, def.kind, def.name_span.start, def.name_span.end
));
for site in index.references_to(def) {
out.push_str(&format!(
" ref {} {}..{}\n",
site.file.0, site.name_span.start, site.name_span.end
));
}
}
for edge in index.instantiations_of(name) {
out.push_str(&format!("inst {} {}\n", edge.file.0, edge.owner.name));
}
for (unit, def) in index.hierarchical_declarations(name) {
out.push_str(&format!(
"hier {unit} {} {}..{}\n",
def.file.0, def.name_span.start, def.name_span.end
));
}
for symbol in index.workspace_symbols(name) {
out.push_str(&format!("sym {} {:?}\n", symbol.name, symbol.container));
}
out
}
/// One (workspace, edit) case: build a scope, apply the edits, and assert
/// the absorbed after-index is the index a rebuild would give.
fn absorbing_equals_rebuilding(
files: &[(&str, &str)],
edits: &[(&str, &str, &str)],
names: &[&str],
) {
let sources: Vec<(PathBuf, String)> =
files.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
let scope = Scope::build(&sources);
let mut edited: Vec<(PathBuf, String)> = Vec::new();
for (path, from, to) in edits {
let i = scope.index_of(Path::new(path)).expect("the edited file is in scope");
let text = scope.text(i).expect("its text");
let at = text.find(from).expect("the edited text is there") as u32;
let edit = TextEdit {
range: TextRange::new(at, at + from.len() as u32),
new_text: (*to).to_string(),
};
edited.push((PathBuf::from(*path), apply(text, std::slice::from_ref(&edit))));
}
let (absorbed, analyses) = after_index(&scope, &edited);
let built = rebuilt(&scope, &edited);
assert_eq!(absorbed.fingerprint(), built.fingerprint(), "{files:?} / {edits:?}");
assert_eq!(absorbed.files(), built.files(), "the file ids moved");
assert_eq!(absorbed.files(), scope.index().files(), "an absorb over held paths keeps ids");
for name in names {
assert_eq!(answers(&absorbed, name), answers(&built, name), "`{name}` differs");
}
assert_eq!(analyses.len(), edited.len(), "one new analysis per edited file");
}
const SUB: &str = "module sub (input logic clk, output logic q);\n wire sig;\nendmodule\n";
const TOP: &str = "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign sig = u_sub.sig;\nendmodule\n";
const PKG: &str = "package pkg;\n localparam int SIG = 1;\nendpackage\n";
const USER: &str = "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n";
fn workspace() -> [(&'static str, &'static str); 4] {
[("/w/sub.sv", SUB), ("/w/top.sv", TOP), ("/w/pkg.sv", PKG), ("/w/user.sv", USER)]
}
#[test]
fn an_absorbed_after_index_is_the_index_a_rebuild_would_give() {
// An ordinary rename edit, in one file and in two.
absorbing_equals_rebuilding(
&workspace(),
&[("/w/top.sv", "logic sig;", "logic sg;")],
&["sig", "sg", "top", "sub"],
);
absorbing_equals_rebuilding(
&workspace(),
&[("/w/sub.sv", "wire sig;", "wire sg;"), ("/w/top.sv", "u_sub.sig", "u_sub.sg")],
&["sig", "sg", "sub"],
);
// A file that **gains** a declaration another file can name.
absorbing_equals_rebuilding(
&workspace(),
&[(
"/w/pkg.sv",
"localparam int SIG = 1;",
"localparam int SIG = 1;\n localparam int X = 2;",
)],
&["SIG", "X", "pkg"],
);
// A file that **loses** one — the use in `user.sv` is left dangling,
// and neither index may hide that.
absorbing_equals_rebuilding(
&workspace(),
&[("/w/pkg.sv", "localparam int SIG = 1;", "")],
&["SIG", "pkg"],
);
// An edit that changes what **another** file resolves to: the package
// is renamed, so `user.sv`'s import points at nothing.
absorbing_equals_rebuilding(
&workspace(),
&[("/w/pkg.sv", "package pkg;", "package pkq;")],
&["pkg", "pkq", "SIG"],
);
// An edited **package**, plus the re-export chain that reads it.
const A: &str = "package a_pkg;\n localparam int V = 1;\nendpackage\n";
const B: &str = "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n";
const C: &str = "module c;\n localparam int W = b_pkg::V;\nendmodule\n";
let chain = [("/w/a.sv", A), ("/w/b.sv", B), ("/w/c.sv", C)];
absorbing_equals_rebuilding(
&chain,
&[("/w/a.sv", "localparam int V = 1;", "localparam int V2 = 1;")],
&["V", "V2", "a_pkg", "b_pkg"],
);
absorbing_equals_rebuilding(
&chain,
&[("/w/b.sv", "export a_pkg::*;", "")],
&["V", "a_pkg", "b_pkg"],
);
// A module that stops being instantiated, and one that starts.
absorbing_equals_rebuilding(
&workspace(),
&[("/w/top.sv", "sub u_sub", "other u_sub")],
&["sub", "other", "top"],
);
// An edit that makes a file stop lexing: it contributes nothing, and
// both indexes must agree that it contributes nothing.
absorbing_equals_rebuilding(
&workspace(),
&[("/w/sub.sv", "wire sig;", "wire \"sig;")],
&["sig", "sub"],
);
}
/// **Attack 3 — an after-index whose file ids shifted.** The absorbed
/// index keeps ids because every edited path is one it already holds, but
/// the print comparison must not *depend* on that: a `Def` names a file by
/// id, and an id is a position in a path-sorted list that any added file
/// renumbers. So the print resolves every id back to a **path** before
/// comparing, and this pins it — the same file's print against two indexes
/// whose ids differ by one everywhere must be the same print.
#[test]
fn a_print_names_paths_so_shifted_file_ids_cannot_change_it() {
let sources: Vec<(PathBuf, String)> =
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
let mut scope = Scope::build(&sources);
// An index over the same four files plus one that sorts *first*, so
// every original file's id is one higher in it.
let mut shifted: Vec<(PathBuf, &str)> =
sources.iter().map(|(p, t)| (p.clone(), t.as_str())).collect();
shifted.insert(0, (PathBuf::from("/w/aaa.sv"), "module aaa; endmodule\n"));
let shifted = WorkspaceIndex::build(shifted);
assert_eq!(
shifted.file_id(Path::new("/w/pkg.sv")).map(|f| f.0),
scope.index().file_id(Path::new("/w/pkg.sv")).map(|f| f.0 + 1),
"the ids really do shift"
);
let i = scope.index_of(Path::new("/w/user.sv")).expect("user.sv is in scope");
assert!(scope.analysis(i).is_some(), "its analysis is what a before-pass computes");
let path = scope.path(i).expect("its path");
let held = after_print(&scope, i, path, scope.index(), &[], &[]).expect("a print");
let moved = after_print(&scope, i, path, &shifted, &[], &[]).expect("a print");
assert_eq!(held, moved, "a print must not read a file id");
}
/// Absorbing over a path the index already holds moves no file id — the
/// property the after-print's path lookups and the `Def`s inside a print
/// both stand on.
#[test]
fn absorbing_an_edited_file_keeps_every_file_id() {
let sources: Vec<(PathBuf, String)> =
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
let scope = Scope::build(&sources);
let before: Vec<PathBuf> = scope.index().files().to_vec();
let edited = vec![(PathBuf::from("/w/pkg.sv"), PKG.replace("SIG", "SIGNAL"))];
let (after, _) = after_index(&scope, &edited);
assert_eq!(after.files(), before.as_slice());
for (id, path) in before.iter().enumerate() {
assert_eq!(after.file_id(path), Some(vlog_semantic::FileId(id as u32)));
}
}
}
+929
View File
@@ -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 => &nothing,
};
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 &param.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, &params);
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()
}
+665
View File
@@ -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, &region.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."
)
}
+530
View File
@@ -0,0 +1,530 @@
//! 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::span::TextRange;
use vlog_parser::{parse_source_tolerant, ParseDiagnostic};
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);
extract_site_in(&tree, &diagnostics, text, start, end)
}
/// [`extract_site`] over a parse the caller already has.
///
/// The same answer, refusal on parse diagnostics included — `diagnostics`
/// must be `tree`'s own list, and `text` the bytes both were built from
/// (`Region::read` copies item text out by span). Take 5 §P1b; see
/// `docs/features/perf5-p1/README.md`.
pub fn extract_site_in(
tree: &SourceFile,
diagnostics: &[ParseDiagnostic],
text: &str,
start: u32,
end: u32,
) -> Option<ExtractSite> {
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 &region.items {
collect_instantiated(item, &mut units);
}
for import in &region.module.imports {
for path in &import.paths {
push(&mut units, path.pkg.text.clone());
}
}
for item in &region.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, &region)?;
}
let semantics = analyze(&tree, text);
if let Some(path) = flow::hierarchical_escape(text, &semantics, &region) {
return Err(hierarchical(&path));
}
let flow = flow::read(&scope, text, &semantics, &region)?;
let packages = boundary::packages(&tree);
let crossing =
Crossing::read(text, &semantics, &region, &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, &region.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}.")
}
+209
View File
@@ -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`.";
+384
View File
@@ -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, &param.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(&param.prefix);
out.push_str(&param.name);
if !param.default.is_empty() {
out.push_str(" = ");
out.push_str(&param.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.")
}
Loaded 100 of 236 files, more files were not shown because too many files have changed in this diff. Show more