Compare commits

...
86 Commits
Author SHA1 Message Date
lucio b12e0cc2c4 Release 0.52.0 — performance take 5, the review round
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 36s
release / build-and-publish (push) Successful in 7m2s
2026-09-09 00:42:39 -05:00
lucio 01843eb75a Review round closed (§61.6): perf README entry for the five lanes, the review's and the tracker's status lines 2026-09-09 00:41:34 -05:00
lucio 5e02142a8f Review round §61.5 (R3b/R3c): the rename's scope stage split (the parser is two thirds of it, a third spent on files never analysed) and facts reuse under a content-hash tie — a closed file's record is reused only when the handed bytes hash to what the store entry was written for, record and hash from one place, never the workspace index; tail rename 380 → 314 ms (−21 % against the review's baseline), the duplicate-module refusal 2.05 s → 0.7 s, 36 rows and 1 750 warning sentences byte-identical, check/ untouched 2026-09-09 00:41:34 -05:00
lucio 07ef771a35 Review round §61.4 (R4): a fixed-arrival probe showed a publish costs the size of the index (a whole-index merge per burst); a scan now publishes at most once per 512 files with the waiting drain exempt — publication −78 to −88 %, loaded scans −48 to −65 %, median wait 112 → 2 ms warm at the same offered load; an empty navigation answer mid-scan is deferred to the next publish or scan end (unsettled answers 0 everywhere); a cancel naming a deferred request answers it cancelled (lead fix for QA's finding); HEAD_WALK_MAX pinned
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 36s
2026-09-08 22:38:56 -05:00
lucio eb54042032 Review round §61.3 (R2a/R2b): the walk hands on the length it already has (collect_files_with) and a subtree walk carries the ancestor ignore stack down (collect_files_below); a workspace start walks, steps and publishes the open buffer's folders before discovering the rest (state/discover.rs, one scan, every file once, bounded to today's path otherwise); first useful answer 266 → 78 ms cold and 301 → 115 warm, correct in every session, warm settle under 1 s, store byte-identical, RSS down; one stopwatch assertion in a trace test dropped by the lead
ci / checks (push) Successful in 1m9s
ci / corpus (push) Successful in 33s
2026-09-08 20:48:41 -05:00
lucio a1c77c053f Review round §61.2 (R1a/R1b): one lint pass per document revision shared by the diagnostics publish and quick-fix discovery, keyed by value on every input of lint_with (waiver contents included) and cleared by every index mutation's overlay refresh; a --verbose codeaction stage trace first showed the 23 ms is three semantic rules and the first-after-edit is the flush; pinmux menu 22.6 → 1.0 ms, queued definition 22.4 → 0.8, publish and memory unchanged
ci / checks (push) Successful in 1m10s
ci / corpus (push) Successful in 35s
2026-09-08 18:26:44 -05:00
lucio 51cbfd27df Review round §61.1 (R3a): an engine-owned rename preflight refuses from the request buffer alone — a cursor with no symbol went from 2.0 s and 3 975 parses to 0.34 ms and none, sentence and precedence byte-identical; index-answered refusals stay on the slow road (a wrong rename refusal is terminal); the extract preflight was proven redundant and not shipped
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 32s
2026-09-08 16:48:05 -05:00
lucio e13ae4c89b TODO §61: the take-5 review round sequenced into lanes 61.1–61.6 with gates
ci / checks (push) Successful in 1m28s
ci / corpus (push) Successful in 42s
2026-09-08 15:24:03 -05:00
lucio b2bb912bbb docs: independent performance review of 0.51.0 (Codex, 2026-09-08) — paired rerun confirms the take-5 numbers; four follow-up items with gates; evidence preserved 2026-09-08 15:24:03 -05:00
lucio 126a6bcdac TODO §60.5: 0.51.0 verified — perf take 5 closed
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 32s
2026-09-08 04:47:12 -05:00
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
lucioandClaude Fable 5.1 ce2f7190ed Release 0.46.0 — expand .* and convert ports to ANSI
release / build-and-publish (push) Successful in 6m17s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00
lucioandClaude Fable 5.1 aa479cf701 Convert ports to ANSI: a Verilog-2001 header merged with its body declarations, and a verifier that never drops a comment or an attribute
TODO §51 (docs/features/ansi-conversion), the second §8 refactoring.

`vlog_refactor::convert_to_ansi` (ports/ansi.rs, ports/merge.rs): for a
`PortList::NonAnsi` module, each header name gains its direction, net or
variable type, signing and packed dims from the body declarations that
describe it, merged per IEEE 1800 §23.2.2.2 (`output b; reg [7:0] b;`
→ `output reg [7:0] b`), as insertions around the untouched name so no
reference anchor moves; the absorbed declarations are deleted with their
comments carried onto the ports. Twenty-three refusals, each a sentence
(port expressions, disagreeing ranges, initialisers, directives, a
comment that would have to move into a one-line list, an attributed
declaration). Code action `lucisv: convert ports to ANSI (N ports)` and
command `lucisv.convertToAnsi`.

Review rework (QA's two HIGHs, invariant 4): the verifier's comment rule
is now `never_dropped` over comments and attribute instances alike —
`has ≥ had`, `wrote ≤ gone` unless the text is the one generated
placeholder, `has == had − gone + wrote` — with masked-corruption attack
tests, re-attacked by QA (30-plus pairs, a neutering pass).

Neither the corpus nor opentitan holds a non-ANSI module; acceptance is
by round trip (ANSI → 2001 → ANSI, same ports/types in order) over five
corpus modules and 290 of 291 opentitan candidates (the one failure is
kmac_reduced_tb.sv's pre-existing trailing-comma parse error). 0 of 854
corpus files differ from 0.45.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00
lucioandClaude Fable 5.1 d9ed2c447a Expand .*: a wildcard connection written out as the named connections it stands for
TODO §50 (docs/features/expand-wildcard), the first §8 refactoring.

`vlog_refactor::expand_wildcard` (ports/expand.rs): at the cursor's
instantiation, every port not explicitly connected becomes `.p(p)` when a
same-named net, variable or port is declared in the instance's scope
(generate block → parents → module; IEEE 1800 §23.3.2.4 read strictly —
a parameter, genvar, type, instance or tf argument does not bind) and
`.p()` plus a warning otherwise, in declaration order, replacing the
`.*` element through the ports engine's splice and verifier. Refusals:
no `.*`, two, a positional list, a `bind` directive, a multi-instance
statement, a parse diagnostic in either file, compiler directives in
either list, an unknown or twice-declared module, and a `.*` that binds
nothing. Server: the lazy code action `lucisv: expand .* (N connections)`
and the command `lucisv.expandWildcard`; a title-rewrite bug in the lazy
offer path (`counted`) fixed on the way. Corpus: 11 of 21 sites expand
(the rest refused honestly); opentitan `hw/`: 9 of 66 (50 are `bind`),
each verified, two surfacing real FPV-wrapper drift. 0 of 854 corpus
files differ. Dev-dependency vlog_refactor → vlog_formatter (tests).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 15:03:11 -05:00
lucioandClaude Fable 5.1 1da0a303cc Release 0.45.0 — type spans, package re-exports, hierarchical tails
ci / checks (push) Successful in 1m14s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m25s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 f476c31483 Cross-file instance-member tail: a module's hierarchical surface, read only behind an instance head; rename edits the tail
TODO §49 (docs/features/hierarchical-tail). Closes topo §2.9-23 and
comment-slots finding 2. The first dev was cut off by an outage with the
library half complete; a second finished the tests, README and gates.

`Surface { Connection, Hierarchical }` on `Resolution::ExternalCandidate`
and `MemberSite::Unit`, set by `resolve.rs::head_surface` for an instance
head. `workspace/hierarchy.rs`: `surface_of` (the export rule, re-ruled)
and the two surface-taking reads; the index keeps two disjoint tables —
`members` (connection: ports, parameters; byte-identical to before for
every existing reader) and `hier_members` (nets, variables, instances) —
and a hierarchical read consults the connection table first, so a port
has one record. `FACTS_FORMAT` 18 → 19. `assign w = u_x.sig;` in another
file now resolves to `sub`'s `wire sig`; rename edits both files (nested
`u_a.u_b.sig` included); the §2.9-20 warning is retired for a resolved
tail; a generate-scoped net is still refused honestly. Completion after
`u_x.` in an expression lists the hierarchical surface; a connection
list's does not.

Census: single-file numbers unmoved; 12 939 connection + 5 239
hierarchical-only members; 335 corpus references newly resolve, 514 over
opentitan `hw/` (20 sampled by QA, all genuine). 0 of 860 corpus files
differ. Also: §50/§51 planned, §55 (state.rs size) filed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 9ef1058059 Package re-exports as real references: bound halves, RX facts, the member walk through re-exports
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 1m52s
TODO §48 (docs/features/package-reexports). Closes topo §2.9-16 and
dpi-export's request (a).

`bind_export_path` records `export pkg::item` as a `Target::Package` use
and a `Target::UnitMember` use, with no scope import (a re-export brings
nothing into the exporting scope, IEEE 1800 §26.6). `FileFacts` gains the
`RX` group (`FACTS_FORMAT` 17 → 18): per package its re-export edges
(package, source, item|*), with `export *::*` expanded into the package's
own imports at record time. `workspace/reexport.rs`: the member lookup
and listing follow re-exports transitively with a visited set, layered
over `own_chain`/`own_members` so the walk cannot recurse into itself;
`Affected::exporters` keeps one-file updates exact and `fingerprint()`
shows the edges. Definition, hover, completion after `pkg::`, references
and rename all read the one edge. Census 103 870 → 103 875 references
(the corpus's two package export lines), 0 unplaced; 0 of 860 corpus
files differ. opentitan: `spi_device_pkg::SramDepth`, reached only
through a re-export, resolves.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 10:41:54 -05:00
lucioandClaude Fable 5.1 4d59e80568 Type-name spans on the AST; vlog_semantic/src/scan.rs retired
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 33s
TODO §47 (docs/features/type-name-spans). Closes topo §2.9-2.

`DataType` carries `name_start` (a `u32` in its existing padding, so
`Expr` stays at its 96-byte pin) and derives `name_span()` and
`segments()` — the `::`/`.` split from the span's own text, with a
leading escaped identifier read to its terminator first. Five parser
construction sites set it; an implicit type gets the empty range at the
position its name would have had. `StmtKind::Disable { name, name_span }`.
The binder walks `ty.segments()` and verifies every segment's range
against the source before recording it (`exact_or_empty`); a segment that
does not read back is recorded with the empty range, never dropped, so
the census's `unplaced` counter is the alarm a join regression would
move (review rework of QA's MEDIUM). `scan.rs` deleted; `bind_data_type`
lost its `window` and ten call sites their window arithmetic.

Census unchanged in every field (860 files, 27 486 symbols, 103 870
references, 1 197 unresolved, 0 unplaced); 0 of 860 corpus files differ;
200/200 opentitan definition/hover/typeDefinition answers identical.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 09:24:19 -05:00
lucioandClaude Fable 5.1 859742ac84 TODO: §48 package re-exports and §49 cross-file instance-member tail planned
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:58:30 -05:00
lucioandClaude Fable 5.1 66f38987ac Release 0.44.0 — opening a file no longer stalls the editor
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m22s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 8145a67be6 The didOpen delay: undriven-net asks the workspace census last, not once per declaration
TODO §46 (docs/features/didopen-cost). Closes take-3 finding §8.4 (§44b).

Measured first: on opentitan the open of a 42 192-line file cost
1 745 ms, of which the lint pass was 1 654 ms and `undriven-net` alone
1 608 ms — the rule asked `WorkspaceIndex::files_mentioning` (a walk over
all 3 976 indexed files) once per declaration, ahead of the local guards
that silence almost all of them. Six lines reordered so the oracle is
asked last, as `unused-signal` always did: same findings, same order
(pinned by a counting-oracle unit test that fails on a revert, and shown
byte-identical against 0.43.0 over a crafted workspace and four opentitan
IPs). didOpen → next request: 1 742 → 117 ms on the largest file,
51–95 → 5–8 ms on typical IPs, the same on every keystroke flush. No
debounce added; three wire-level pins with a debug-build bound.

Docs: take-3 §8.4 annotated, docs/perf/README.md entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 f7956060b3 Small items, round 4: the editor's unknown rule name said once, a warning channel for the walk, inline aggregate override arguments, comment slots inside delay lists
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 32s
TODO §45 (docs/features/small-items-4). Closes topo §2.9-17, 29, 30 and
adds the delay-list bar to §2.9-22.

45.1 `settings::rules` records every dropped `lucisv.lint.select`/`ignore`
name as `lucisv.lint.<setting>: unknown rule: <name>`; `apply_settings`
logs what the previous settings value did not already say — once per
(setting, name), re-armed by a changed list.
45.2 `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink: an
unreadable directory, an unreadable `.gitignore` and a dangling source
link are warned about and the walk continues; the CLI prints
`warning: <path>: <message>` on stderr before the report with the exit
code unchanged, the server logs once per scan through `report_scope`.
45.3 `parse_expr_or_type` accepts a `struct`/`union`/`enum` head as a
type argument, so `m #(.T(struct packed { logic a; })) u ();` parses and
`instantiation_plan` emits a one-line `parameter type` aggregate default.
45.4 Comment slots for `#(1:2:3)` and gate delay lists
(`MinTypMaxComments`, `DelayValue`, `ContAssign`/`GateInstantiation`/
`GateInstance` slots); `EXPECTED_RTL_GAPS` 374 → 419 at zero failures.
Review rework (QA's MEDIUM): a line comment after a gate instance's `,`
now ends the line, the next instance one level in.

Byte-identity vs 0.43.0: 0 of 820 corpus files and 0 opentitan outcomes
differ.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 07:12:54 -05:00
lucioandClaude Fable 5.1 f302b471a7 TODO: loop 2 order from the owner's twelve rulings; §45 and §46 planned; manual acceptance checklist
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 30s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 05:50:45 -05:00
lucioandClaude Fable 5.1 7aedfe2554 docs: performance take 3 on opentitan — 0.43.0 vs take 2 vs 0.39.0
ci / checks (push) Successful in 51s
ci / corpus (push) Successful in 28s
TODO §40 (owner request). Every take-2 row re-measured over the wire and
by CLI sweep, three tries each, no instrumentation added. Headlines: the
lazy codeAction is 11.8× on the cursor-move path (200.7 → 24.0 ms at the
128-file fan-out, 39.2 → 5.2 ms on `aes`), the default-scope didOpen is
1 731 → 1 082 ms cold, completion at 0–1 chars 14.8–19.4 → 2.3–3.2 ms;
nothing else moved since 0.39.0. Per-file outcome diff 0.39.0 → 0.43.0
is exactly the three predicted files. Two findings filed as §44
candidates: the eager codeAction path 1.35–1.40× slower than take 2, and
an in-scope didOpen delaying the next request by 21–51 ms.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 03:24:24 -05:00
lucioandClaude Fable 5.1 73799f3d53 Release 0.43.0 — the repository analysis's three findings
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 6m27s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 ec9ec42276 Walker cycle policy by directory identity, and comment slots around a net delay's #
TODO §43 (docs/features/walk-cycles). Closes topo §2.9-8 and §2.9-27 and
repository-analysis finding 3; §2.9-30 filed.

43.1 `lucisv_core::walk::Walk` keeps a `visited` set keyed on `(dev, ino)`
(the canonical path off unix): each directory is entered once, a symlink
to one already entered is skipped, one not yet entered is followed once,
a dangling directory link is skipped. A dangling link that names a source
file is still handed on, so the front end's "no such file" error survives
(review ruling on QA's finding). Both front ends share the walk unchanged
in signature; a cyclic workspace indexes and a cyclic tree formats, each
file once.

43.2 `NetDelay::{before_hash, after_hash}`: the gaps around `#` have
slots, printed inline; the `#SKIP` in net_delay_position.cases is live
and the RTL gap fuzzer covers the construct (374 gaps, 0 failures).

Byte-identity vs 0.42.0: 0 of 820 corpus files differ. On opentitan the
only per-file change is §41's dedup reporting a same-directory symlink
alias once.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 4b2dad87fe One lint-configuration contract for project and editor: the server picks the editor's selection when set, else the project's, and logs rejected project entries once
TODO §42 (docs/features/lint-config-contract). Closes topo §2.9-28 and
repository-analysis finding 2.

`enabled_rules(settings, project, has_oracle)`: rung 2 is
`lucisv.lint.select` when non-empty else `[lint] select`, rung 5 the same
for `ignore` — the CLI's `pick` applied to the editor — so one buffer
linted two ways is linted the same way (asserted equal over the wire for
three configurations). `lint::project`: `ProjectLint` read from the
`Discovery` result `configured` already computes (no extra read per
pass); an unknown rule name in a project list is dropped and said rather
than silently emptying the selection. `ConfigProblems`/`ProblemLog`:
rejected `[lint.<rule>]` options, unknown names and bad `[lint] waivers`
lines are logged once per (config file, entry) in `lucisv check`'s
wording, re-armed when the config's lint content changes; the buffer
keeps linting with the entry dropped.

Docs applied: README, the linter guide, configuration.md, the analysis,
topo (28 struck; 29 filed for the editor-side unknown-name silence), site
rebuilt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 01:45:48 -05:00
lucioandClaude Fable 5.1 3b08c0753c Same-target atomic writers: exclusive per-operation temps, mode before bytes, CLI dedup by canonical identity
TODO §41 (docs/features/atomic-write-coordination). Closes topo §2.9-26
and repository-analysis finding 1.

`atomic::write_atomic` names its temp `.{name}.{pid}.{n}.lucisv-tmp` with
a per-process counter and opens it create-new (O_EXCL), retrying a used
name up to 32 times; on unix the temp is created 0600 when a target
exists and takes the target's mode through the open handle before the
bytes are written, so a 0600 file never has a readable moment. The CLI's
`dedup` keys on the canonical path when the file exists, so a symlink
alias reaches one worker; the reported path is the first spelling. Two
processes on one target remain last-writer-wins (rename is atomic, the
formatter idempotent), stated in the module doc. The audit's probe is a
test: 0 write errors in 200 calls.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:40:48 -05:00
lucioandClaude Fable 5.1 972bd1cff1 Release 0.42.0 — external waiver files and the two vendor shapes
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m28s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:03:07 -05:00
lucioandClaude Fable 5.1 8a92e79fc0 External waiver files: Verible's format from lucisv.toml, --waiver-file and the editor, union with inline waivers, honoured by quick fixes
TODO §39 (docs/features/waiver-files). Closes §4's last waiver item.

`vlog_linter::waiver_file`: `waive --rule=<rule> [--line=N|N-M]
[--location=<pattern>]`, `#` comments, BOM tolerated; `--location` is
the `--exclude` matcher (`lucisv_core::walk::is_excluded`, a new
vlog_linter → lucisv_core edge), a regex-looking pattern refused by
name. `lint_with(ctx, rules, external)` applies inline and external
waivers as a union and reports which external directives fired;
`lucisv check` reports the dead ones under `unused-waiver` at the
waiver file's line after the whole run. Discovery: `[lint] waivers`
(relative to the toml), `--waiver-file` (repeatable), `lucisv.lint.waivers`
(first workspace root); bad lines fail the CLI run with file:line and
are dropped and logged once by the server.

Review rework (QA's HIGH): the server's code-action path now lints with
the buffer's `LintRun` — its enabled rules and external waivers — so a
quick fix is never offered, nor applied by fix-on-save, for a waived
finding.

Docs: Waivers sections in README and the linter guide, cli and
configuration rows, topo edge, site rebuilt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:03:07 -05:00
lucioandClaude Fable 5.1 f6f18de10d docs: repository analysis audit at v0.41.0 — README architecture, topo facts (codec 17, handshakes 26–28), site guides and rebuilt dist
Written by the owner's audit process on 2026-09-04; committed by the lead
unchanged. Findings 1–3 are planned as TODO §41–§43.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 23:37:55 -05:00
lucioandClaude Fable 5.1 d5abf81563 The two §11 parser skips: rival unit headers across an ifdef/else split as one verbatim unit, a net delay accepted after the type
TODO §38 (docs/features/parser-skips). Closes the jtag_if.sv and
SimDTM.sv skips from the §11 sweep.

38.1 `Parser::at_rival_header`: in a module/interface/program body, a
continuing directive at the unit's own entry level followed by the same
keyword and name is a header written twice across the arms, not a
nested unit. The error routes into the existing conditional split
(`at_split_conditional` now fires on a rival as well as an open
bracket; `scan_split_extent` runs to the unit's real closer, counting
nested units of the same kind), so the whole unit is one Verbatim item
in both modes. jtag_if.sv now formats (body verbatim, the standing
directive-split trade).

38.2 `DataDecl::delay: Option<NetDelay { expr, after_type }>`: a net
delay is accepted before or after the type (IEEE 1800 §6.7 puts it
after), never both, and printed where it was written. SimDTM.sv now
formats; its four `#0.1` lines come back byte-identical.

Byte-identity vs 0.41.0: 0 of 820 corpus files differ; over 2 554
opentitan files exactly the two named files change outcome.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 23:06:37 -05:00
lucioandClaude Fable 5.1 97aa2fefd8 Release 0.41.0 — code actions off the fan-out
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m13s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 18:15:40 -05:00
lucioandClaude Fable 5.1 9604753b6c Lazy codeAction/resolve for the port refactorings, definitions from the index, the inlayHint zero ruled correct
TODO §37 (docs/features/lazy-code-action). Closes the four §10 lines.

37.1 For a client whose resolveSupport lists "edit", the port actions are
offered over the buffer plus the instantiated module's declaration alone
(`ports::offers`, `offer_sources`), carrying `data {uri, position,
title}` and no edit; `codeAction/resolve` (`ports::resolve`) re-runs the
eager path and returns the matching action, matched on the title minus
its count phrase, erroring when the action is gone or the buffer is on
the large-file path. Clients without resolve support get today's eager
answer. Offer flat at ~55 µs from a 3- to a 128-file fan-out where the
eager path was linear; ~4.5 ms vs ~77 ms over the wire on opentitan's
128-file case.

37.2 The inlayHint zero at the default scope is correct: the hinted
module (`pins_if`) is declared outside what the scope reaches, and
definition/hover answer nothing there either. Pinned, not changed.

37.3 `locate::definition_location`: an index-only Location for a closed
file's file-scope declaration from its recorded `DeclPositions`; nav and
workspace symbols routed through it (0.4 µs vs 28 µs). Open buffers keep
the file-read path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 18:15:40 -05:00
lucioandClaude Fable 5.1 797ef86d47 Release 0.40.0 — two parser residues and atomic writes
release / build-and-publish (push) Successful in 6m11s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 17:08:53 -05:00
lucioandClaude Fable 5.1 a30dda167a Small items, round 3: a bare begin block recovered as a generate block, the half-typed #( override lookahead, atomic in-place writes
TODO §36 (docs/features/small-items-3). Closes topo §2.9-24 and §2.9-25
and the §1 atomic-writes item.

36.1 `ItemKind::GenBlock(Box<GenBlock>)`: in tolerant mode a `begin … end`
at module scope or straight inside a generate region is parsed as an
unnamed generate block with a diagnostic at the keyword, so the items
inside and after it survive; strict mode is untouched. Consumers walk
its items; `module-begin-block`, `v2001-generate-begin` and
`mismatched-labels` read the node. The formatter's `gen_block` is split
by a pure extraction into `begin_block`. One server test that parsed a
3 000-deep begin nest on libtest's thread now runs on PARSE_STACK_SIZE.

36.2 `Parser::value_runs_into_next_instance`, a tolerant-mode lookahead
in `parse_connection`: an unclosed `.NAME(` whose value would swallow
the next instance as a call fails the element instead; `recover_element`
takes the bracket the element stopped on before skipping so the skip
stays at the list's level. The balanced-parens spelling stays greedy.

36.3 `lucisv_core::atomic::write_atomic`: sibling temp file + rename,
permissions preserved, symlink target replaced, read-only target
refused as `fs::write` refused it; used by format, `check --fix` and
the cache.

Also: TODO housekeeping (QA lines of §27–§35 ticked as recorded in
their QA logs; the §27 P6 line and the sva-bodies README checkbox
annotated as delivered by §29), topo §2.9-24/25 struck.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 17:08:53 -05:00
lucioandClaude Fable 5 0757503fd1 Release 0.39.0 — the rest of Verible's rules (73 in all)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 30s
release / build-and-publish (push) Successful in 6m18s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 05:03:37 -05:00
lucio 6a0af26fdf Merge branch 'lint-3' 2026-09-04 04:56:52 -05:00
lucioandClaude Fable 5 8adb6c8ac1 Linter expansion, wave 3: the remaining nineteen Verible rules, forbidden-macro, void-cast's forbidden calls, and the e2e options case
TODO section 35 (54 -> 73 rules: every rule in Verible's published
list but forbid-implicit-declarations).
module-begin-block, legacy-generate-region, legacy-genvar-declaration,
v2001-generate-begin, explicit-function-lifetime,
explicit-task-lifetime (both exempt out-of-body definitions after a
census showed 948 of 960 findings were exactly that shape),
positive-meaning-parameter-name, suggest-parentheses (safe fix,
truth-tabled), unpacked-dimensions-range-ordering, uvm-macro-semicolon,
create-object-name-match, numeric-format-string-style,
macro-string-concatenation, disable-statement, forbidden-macro,
endif-comment (safe fix), forbid-line-continuations, dff-name-style,
proper-parameter-declaration. Verible's forbidden-symbol is the
source-file name of invalid-system-task-function (read in its
rule .cc), so it is that rule's symbols option, nothing fires twice;
void-cast gains forbidden_calls. Shared readers: walk_items_scoped,
exprs.rs, preproc.rs. A checked-in e2e case drives lucisv.lint.options
over the wire. Two rules fire on an error leaf because the parser
refuses a module-scope begin/end and a bare generate begin - filed as
docs/topo.md 2.9-25.
3 695 tests / 48 binaries; corpus 814/820 byte-identical to 0.38.0;
opentitan default-set census 1 053 -> 1 169, the arithmetic balancing
to the six default-on additions; timing unchanged.

docs/features/linter-expansion-3/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:55:10 -05:00
lucioandClaude Fable 5 fbee290a0a docs: topo — linter-expansion-1/2/3 rows; §2.9-25 filed (module-scope begin/end and bare generate begin refused rather than recovered)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:31:36 -05:00
lucioandClaude Fable 5 b1b3cad09b TODO §35 planned: linter expansion wave 3 — the remaining twenty Verible rules, forbidden-* lists, the e2e options case
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:55 -05:00
lucioandClaude Fable 5 a896e0dff0 Release 0.38.0 — lint rule options and the Style family
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 11m24s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:03 -05:00
lucioandClaude Fable 5 0cb398bcd9 merge follow-up: §34's port walkers read ANSI port lists through ListElem::ok (§32's error elements)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:39:00 -05:00
lucio 17697b9d77 Merge branch 'lint-2' 2026-09-04 03:36:59 -05:00
lucioandClaude Fable 5 5e5813a2a9 Linter expansion, wave 2: per-rule options end to end, options on the naming rules, and eighteen Style rules
TODO section 34 (36 -> 54 rules).
Options: OptionSpec/OptionKind/OptionValue/RuleOptions in vlog_linter
with one validator behind both front ends - [lint.<rule>] tables in
lucisv.toml (accepted now; stored raw by lucisv_core::config, resolved
per file by the CLI with <config>:<line> on the first bad entry) and
the editor's lucisv.lint.options object (bad entries logged and
dropped) - precedence editor > toml > default key by key, --rules-doc
listing every option. A small anchored regex engine of our own: a
Thompson-NFA simulation, linear in pattern x name by construction
(QA's first cut found the backtracking matcher exponential on (a*)*b),
unknown escapes refused by name through both doors, a 71-row table
verified against CPython. The four naming rules take Verible's option
spellings with defaults that keep today's verdicts byte-identical.
Eighteen Style rules, one file each with true positives and near-
misses: line-length (the formatter's width), posix-eof (safe fix),
forbid-consecutive-null-statements (safe fix), generate-label and
generate-label-prefix, package-filename, one-module-per-file (off),
signal/interface/macro/constraint/parameter-type-name-style,
port-name-suffix (off), banned-declared-name-patterns (off),
typedef-enums, typedef-structs-unions (allow_anonymous_nested defaults
true here - opentitan's 3 159 findings were all generated register
packages, and its own config disables the rule), always-comb (unsafe
fix), explicit-begin (off, Verible's eleven enables). Four rules ask
parsed_cleanly() first after a census showed error-recovered UVM files
rebound as generate blocks. package.json regenerated (drift test).
3 549 tests / 48 binaries; corpus 814/820 byte-identical; naming-rule
finding lists identical to 0.36.0; opentitan check timing unchanged.

docs/features/linter-expansion-2/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:36:59 -05:00
lucioandClaude Fable 5 bafc1b425b docs: header-recovery QA follow-up — the fuzz sweep's time-based guard kill isolated; no hang (max single parse 38 ms over the whole file)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:25:52 -05:00
lucioandClaude Fable 5 8c61570a04 tools/guard.sh: keep the command's stdin (a backgrounded job got /dev/null, silently emptying stdin-fed lucisv runs)
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 31s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:09:29 -05:00
lucioandClaude Fable 5 7c4bdbcfea Release 0.37.0 — error recovery inside headers and lists
ci / checks (push) Successful in 1m8s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 9m43s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:08:47 -05:00
lucioandClaude Fable 5 e902af37c5 docs: topo — header-recovery row, §2.9-24 filed (half-typed #( override that reads as a call)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:08:47 -05:00
lucio 4ba6eafa2d Merge branch 'wip-header-recovery'
# Conflicts:
#	crates/vlog_linter/src/visit.rs
2026-09-04 03:01:49 -05:00
lucioandClaude Fable 5 747ae02b0e Error recovery inside headers and lists: error elements, a list-local bracket-seeded sync that cannot stall, headers keep their node
TODO section 32 (coverage_gaps M10).
A typo inside a port list, parameter list, tf-port list, connection
list or a for/if/while/case header no longer destroys the enclosing
module or function. The four list element types and ExprKind gain an
Error(RawText) element; element_or_recover records the diagnostic and
skips to a list-local sync set (',' ')' ';' or a line change) with the
bracket counter seeded from the list's own opener, and list_ends ends
any list whose iteration left the cursor unmoved - the structural
guarantee that closes the non-advancing loop which exhausted memory on
the first cut. Headers are infallible in tolerant mode: the node keeps
its name, the typed elements and its body, so the body binds in the
right scope and there is no orphaned closer; recovery declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs and strict parity holds (550 fixtures and all 814 strict-parsing
corpus files, Debug-equal). Pins per shape with exact counts; server
pins: document symbols and scoped completion survive a broken header,
one diagnostic, the three validity probes keep their verdicts.
Census over the corpus truncated at each midpoint: error nodes 622 ->
555, diagnostics 1 702 -> 1 826 (surviving modules now report their
missing endmodule). parse_tolerant timing within noise. 3 259 tests on
this branch (0.35.0 + 15 pins); corpus 814/820 byte-identical.

docs/features/header-recovery/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 02:58:24 -05:00
lucioandClaude Fable 5 ffbb29ddbb Release 0.36.1 — 0.36.0 with its release notes (that tag never published: no CHANGELOG section)
ci / checks (push) Successful in 1m8s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 11m34s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 02:42:32 -05:00
lucioandClaude Fable 5 f1d44a2a0c WIP checkpoint, §32 paused 2026-09-03 — runaway root cause fixed (list_ends on an unmoved cursor), strict parity restored; 32.1–32.5 done, 32.6 half, 32.7 + gates not run
Root cause of the 100 GB crash: a non-ANSI port loop took its trailing
comma from the element, an error element never got that far, the next
iteration failed on the same comma, consumed nothing and pushed another
empty error element - an allocating spin. Fix is structural: list_ends
ends the list whenever the cursor has not moved since the iteration
began; the two loops that read their own separator also eat it after an
error element. Truncate-anywhere + delete-any-character pass under
tools/guard.sh -m 4. Strict parity: element_or_recover declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs. cargo test -p vlog_parser 365 + 26 + 31 / 0 failed; workspace
suite NOT re-run since the last fixes. Not done: completion pin + the
three validity probes (32.6), measurements (32.7), README amendments,
coverage_gaps M10, TODO ticks, every gate. Handshake: three
vlog_linter arms (visit.rs walk_param_ports, signals.rs connection
loops) live in the earlier commit 6a15594.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:28:33 -07:00
lucioandClaude Fable 5 10b63e665d docs: linter-expansion-1 review — opentitan lint timing re-measured at merge (no difference vs 0.35.0)
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 27s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:01:24 -07:00
lucioandClaude Fable 5 a648561f63 TODO §34 planned in detail: per-rule lint options end to end, options on the naming rules, the first eighteen Style rules; the rest deferred to §35
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:00:45 -07:00
lucioandClaude Fable 5 6a15594ae8 WIP §32 header recovery — DO NOT MERGE: half-finished; a fuzz test loops without advancing and exhausts memory (crashed the machine 2026-09-03)
Checkpoint of the interrupted dev work (rate limit) so master stays
clean. Known state: a_half_typed_instantiation_is_one_error_node
(expected to invert) and tolerant_parse_equals_strict_parse_on_valid_
sources FAIL; the error_recovery test binary exceeds 6 GB under
tools/guard.sh (a non-advancing recovery loop under the delete-any-
character / truncate fuzzers). Resume in a worktree of this branch,
under tools/guard.sh, fixing the advance guarantee first.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:48:28 -07:00
459 changed files with 94104 additions and 3955 deletions

No files matched your search

+1
View File
@@ -7,3 +7,4 @@
.DS_Store
/.zcode
/.claude
__pycache__/
+520
View File
@@ -4,6 +4,526 @@ 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.52.0 — 2026-09-09
### Performance take 5 — the review round
An independent review of 0.51.0 (`docs/performance_take5_review.md`)
named four remaining costs with gates; all four are implemented and
measured (`docs/perf/README.md`, the 2026-09-08 review-round entry).
Behaviour is unchanged everywhere the suites and byte-identity gates can
see; two pre-existing gaps the round found are filed, not hidden.
- **A rename refuses cheaply.** A cursor with no symbol used to read,
parse and index every file in the workspace before refusing (2 s on
opentitan); an engine-owned preflight now refuses from the request
buffer alone in 0.3 ms with the same sentence and precedence. Refusals
the workspace index would have to answer stay on the slow road, because
a wrong rename refusal is terminal.
- **One lint pass per buffer revision.** The diagnostics publish and the
quick-fix discovery share one result, keyed by value on every input
(rule set, options, width, tab width, waiver *contents*) and cleared by
every index change; a cursor move on a 42 000-line file costs 1 ms
instead of 23, and the navigation queued behind it likewise.
- **The first answer after opening a file.** A workspace start now
walks, indexes and publishes the open file's own folders before it
discovers the rest of the workspace, one scan, every file once: the
first go-to-definition answers in about 80 ms cold and 115 ms warm,
correct every session, and a warm start settles under one second.
- **Scans under load.** A scan publishes at most once per 512 files
instead of once per burst of requests (a publish costs the size of the
index): at the same offered load the median request wait falls from
112 ms to 2 ms and the scan finishes about twice as fast. An empty
navigation answer computed while the index is still growing is no
longer an answer — it is asked again at the next publish or at the
scan's end — and a cancel for such a request is honoured where it
lands.
- **Rename reuses the index's own records.** For the files a rename
selects but never analyses, the engine now takes the index cache's
record instead of parsing, and only when the file's bytes hash to what
that record was written for. The hierarchical-tail rename falls from
380 to 314 ms, the duplicate-module refusal from 2 s to 0.7 s; every
edit and every warning byte-identical.
- The CLI is unchanged in this release.
## 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
- **Expand `.*`.** A wildcard connection is written out as the named
connections it stands for, in the module's declaration order, through
the port engine's splice and verifier. The wildcard rule is read
strictly (IEEE 1800 §23.3.2.4): a same-named net, variable or port
binds; a parameter, genvar, type or instance does not, and that port
becomes `.p()` with a warning naming it. Refused inside a `bind`
directive, on a positional list, on two `.*`, or when a file does not
parse. Code action `lucisv: expand .* (N connections)` and command
`lucisv.expandWildcard`.
- **Convert ports to ANSI.** A Verilog-2001 header with body
declarations becomes an ANSI header (`output b; reg [7:0] b;` →
`output reg [7:0] b`, every merge of §23.2.2.2), the absorbed
declarations deleted and their comments carried onto the ports. The
edit inserts around each header name so nothing that referenced the
port moves; twenty-three shapes are refused with a sentence rather
than guessed (port expressions, disagreeing ranges, initialisers,
directives, a comment that would have to move into a one-line list).
Code action `lucisv: convert ports to ANSI (N ports)` and command
`lucisv.convertToAnsi`.
- **The refactoring verifier's comment rule is stricter, and covers
attributes.** Every comment and every `(* … *)` attribute a file had it
still has, by exact text and count; a piece a deletion covers is
written back exactly as many times as it was deleted, and an edit may
not duplicate one nothing touched — which also catches a comment
rewritten, truncated or duplicated. Ships with masked-corruption
attack tests, re-attacked by QA.
## 0.45.0 — 2026-09-05
### Cross-file semantics: type spans, re-exports, hierarchical tails
- **Type names carry spans.** Every `DataType` and `disable` target knows
its range on the AST; the semantic crate's text scanner (`scan.rs`) is
deleted. Definition and hover on a type name land exactly, `pkg::t`
selecting `t`; a segment the source spells differently from the
parser's join is recorded with an empty range rather than guessed.
- **Package re-exports are real references.** `export pkg::item;` and
`export pkg::*;` bind both halves, the index records each package's
re-exports, and definition, hover, completion after `pkg::`, references
and rename follow them transitively. On opentitan a name reached only
through `export spi_device_reg_pkg::SramDepth;` now resolves.
- **Renaming an internal net edits its hierarchical uses in other files.**
A module now has a hierarchical surface (nets, variables, instances)
read only behind an instance head — `assign w = u_x.sig;` in another
file renames with `sig`'s declaration, nested `u_a.u_b.sig` included —
while connection lists still see ports and parameters only. Completion
after `u_x.` in an expression lists the hierarchical members. Over
opentitan's `hw/`, 514 hierarchical references resolve that did not
before; a rename that now reaches one more file costs one more file's
read.
- The index facts format is 19; stores written by earlier releases are
rebuilt on first use.
## 0.44.0 — 2026-09-05
### Opening a file no longer stalls the editor
- **`undriven-net` asked the workspace census once per declaration**,
ahead of the local guards that silence almost every one, so a
`didOpen` — and every keystroke flush — of a large file paid a walk
over every indexed file thousands of times. Asked last now, the way
its twin `unused-signal` always did. Opening opentitan's 42 192-line
`pinmux_reg_top.sv` at workspace scope: 1 742 ms → 117 ms; typical
IP files 51–95 ms → 5–8 ms. Same findings in the same order.
- **Walk warnings.** An unreadable directory, an unreadable `.gitignore`
or a dangling source-file symlink no longer fails a run: the CLI
prints `warning: <path>: <message>` on stderr before the report with
the exit code unchanged, and the server logs once per scan.
- **A typo in `lucisv.lint.select` or `ignore`** is logged once
(`lucisv.lint.select: unknown rule: <name>`) instead of silently
emptying the selection.
- **Inline aggregate types as parameter-override arguments**
(`m #(.T(struct packed { logic a; })) u ();`) parse, format and are
emitted by the instantiation skeleton.
- **Comment slots inside delay lists** (`#( /*a*/ 1 : 2 : 3 )`, gate
`#(rise, fall)`), and a line comment after a gate instance's comma
now ends the line.
## 0.43.0 — 2026-09-05
### The repository analysis's three findings
- **Atomic writers cannot collide.** In-place writes use an exclusive,
per-operation temp file (`.{name}.{pid}.{n}.lucisv-tmp`, created
0600 when a target exists and given the target's mode before the bytes
land); the CLI deduplicates its inputs by canonical identity, so a
symlink alias of a file reaches one worker and is reported once. Two
processes on one target remain last-writer-wins, which the formatter's
idempotence makes safe.
- **One lint-configuration contract.** The editor now honours a project's
`[lint] select` and `[lint] ignore` the way the CLI honours its flags:
`lucisv.lint.select` when set, else the project's, key by key, with the
editor-only severity switches and per-rule toggles applied over whichever
stands. A project entry the server cannot use — a rejected `[lint.<rule>]`
option, an unknown rule name, a bad waiver directive — is logged once with
file and line in `lucisv check`'s wording and dropped; the buffer keeps
linting. The CLI's and the server's rule lists are asserted equal over
the wire.
- **Directory walks terminate on symlink cycles.** Each directory is
entered once by identity; a link to a directory already entered is
skipped, one not yet entered is followed once, a dangling directory link
is skipped and a dangling source-file link is still reported. Both the
CLI and the server's index scan.
- A comment before a net delay's `#` (`wire /* c */ #5 w;`) now formats.
## 0.42.0 — 2026-09-05
### External waiver files, and the two vendor shapes the sweep skipped
- **External waiver files** in Verible's format: `waive --rule=<rule>
[--line=N|N-M] [--location=<pattern>]`, `#` comments. Read from
`[lint] waivers` in `lucisv.toml`, `lucisv check --waiver-file` (repeatable)
and the editor setting `lucisv.lint.waivers`; the three add up.
`--location` is an `--exclude`-style pattern, not a regex, and a
regex-looking one is refused by name. Union with inline waivers; unused
external waivers are reported under `unused-waiver` at their line of the
waiver file by `lucisv check`, after the whole run. The editor's quick
fixes and fix-on-save honour external waivers too.
- **Rival module/interface headers across an `ifdef`/`else`** (opentitan's
`jtag_if.sv`) now parse: the unit is kept verbatim as a whole, the
standing directive-split trade, instead of nesting and losing its
closer.
- **A net delay after the type** (`wire [31:0] #0.1 x = y;`, where the LRM
puts it) is accepted and printed where it was written.
- Documentation: the repository analysis audit's README and site rewrite
(architecture across all eight crates, topo facts at codec 17) is
committed; its three findings are planned as TODO §41–§43.
## 0.41.0 — 2026-09-04
### Code actions off the fan-out
- **Lazy port refactorings.** For a client that supports
`codeAction/resolve` (VS Code does), the port actions are offered from
the buffer and the instantiated module's declaration alone, and the
edit is computed when the action is picked. The request VS Code sends
on nearly every cursor move no longer reads the module's fan-out:
flat at ~55 µs in-process from a 3-file to a 128-file fan-out, where
it was linear (15 ms at 128). A resolve for an action that no longer
applies is an error, not an empty edit. Clients without resolve
support get the edit up front, as before.
- **Definitions from the index.** `textDocument/definition` and
workspace symbols for a file-scope declaration in a closed file now
build the location from the positions the index already records
instead of reading the file: 0.4 µs against 28 µs per answer.
- **inlayHint at the default scope**: investigated, not changed. The
hints missing at that scope belong to a module declared outside what
the scope reaches; definition and hover say the same. A scope
question, recorded in the feature README.
## 0.40.0 — 2026-09-04
### Two parser residues and atomic writes
- **A bare `begin … end` at module scope, or straight inside
`generate … endgenerate`, is recovered** in error-tolerant mode as an
unnamed generate block (`ItemKind::GenBlock`) with a diagnostic at the
keyword, instead of being refused and taking the rest of the unit with
it. The items inside and after the block are now visible to the
editor and to every lint rule; `module-begin-block`,
`v2001-generate-begin` and `mismatched-labels` read the node. Strict
parsing is unchanged, so the formatter still refuses the file exactly
as before.
- **A half-typed `#(` override or connection whose value would read as
the next instance** (`sub #(.W(8), .DEPTH(` ⏎ `u0 (.a(x));`) now costs
one error element: `.W(8)` survives, `u0` is an instance with its
connections, one diagnostic on the unclosed `(`. The balanced-parens
spelling stays ambiguous and is still parsed greedily, by design.
- **In-place writes are atomic.** `lucisv format`, `lucisv check --fix`
and the cache write a sibling temp file and rename it over the target,
so a crash or a full disk never leaves a source file truncated. The
target's permissions are kept, a symlink's *target* is what gets
replaced, and a read-only file is refused as it always was.
## 0.39.0 — 2026-09-04
### The rest of Verible's rules
Nineteen more rules bring lucisv to **73** — every rule in Verible's
published list except the one that needs a compiler. New: `module-begin-
block`, `legacy-generate-region`, `legacy-genvar-declaration`,
`v2001-generate-begin`, `explicit-function-lifetime`,
`explicit-task-lifetime`, `positive-meaning-parameter-name`,
`suggest-parentheses` (safe fix), `unpacked-dimensions-range-ordering`,
`uvm-macro-semicolon`, `create-object-name-match`,
`numeric-format-string-style`, `macro-string-concatenation`,
`disable-statement`, `forbidden-macro` (`macros` option),
`endif-comment` (safe fix), `forbid-line-continuations`,
`dff-name-style`, `proper-parameter-declaration`.
`invalid-system-task-function` gains a `symbols` option (Verible's
"forbidden-symbol" is the same rule); `void-cast` gains
`forbidden_calls`. The two lifetime rules deliberately exempt an
out-of-body method definition (`function cls::f()`), which is where
almost every finding on a UVM tree would otherwise land. Each rule's
documentation cites the Verible rule and default it follows.
## 0.38.0 — 2026-09-04
### Lint rule options, and the Style family
**Per-rule options.** A rule that takes options can be configured in
`lucisv.toml` (`[lint.line-length] length = 120`,
`[lint.signal-name-style] style_regex = "[a-z_0-9]+"`) and from the
editor (`lucisv.lint.options`, one object keyed by rule). Both doors run
one validator: a bad key, kind, range or pattern fails `lucisv check`
naming the file and line, and is logged and dropped in the editor so a
typo cannot switch a rule off. Editor options win over `lucisv.toml`,
key by key. `--rules-doc` lists every option with its kind and default.
Patterns use a small built-in regex dialect (literals, `.`, classes,
groups, alternation, `* + ?`, `\d \w \s`), whole-name anchored, run as
a linear-time automaton so no pattern can slow a lint run; anything
outside the dialect is refused by name.
**Eighteen new Style rules** (54 in all): `line-length` (the
formatter's width), `posix-eof` (safe fix), `forbid-consecutive-null-
statements` (safe fix), `generate-label`, `generate-label-prefix`,
`package-filename`, `one-module-per-file` (off), `signal-name-style`
(off), `interface-name-style`, `macro-name-style`,
`constraint-name-style`, `parameter-type-name-style` (off),
`port-name-suffix` (off), `banned-declared-name-patterns` (off),
`typedef-enums`, `typedef-structs-unions`, `always-comb` (unsafe fix),
`explicit-begin` (off). The four existing naming rules take Verible's
option spellings. `typedef-structs-unions` allows a nested anonymous
aggregate by default — a deliberate divergence from Verible, because
every one of its 3 159 findings on opentitan was a generated register
package; `allow_anonymous_nested = false` restores the stricter reading.
Every rule's toggle in VS Code is regenerated from the registry.
## 0.37.0 — 2026-09-04
### Typing a header no longer loses the module
While you type a port list, a parameter list, a function's argument
list, an instantiation's connections, or the header of a `for`/`if`/
`while`/`case`, the editor used to lose the whole surrounding module or
function: its body re-parsed at file scope, its symbols vanished from
the outline and from completion, and the orphaned `endmodule` produced a
second error. Recovery now happens inside the list: the element that
failed becomes an error element, the ones you already typed stay, the
header keeps its node, and the body binds in the right scope. One
diagnostic per typo. The strict parse (what the formatter uses) is
untouched, so every corpus file formats byte for byte as before.
Measured over the corpus with every file cut in half: error nodes fall
by 11 %; diagnostics rise by 7 % because a module whose header was cut
now survives to report its missing `endmodule` instead of vanishing
into one error node. Known gap: a half-typed `#(` override whose value
can read as a call still collapses its instantiation (filed).
## 0.36.1 — 2026-09-04
The 0.36.0 tag never published: its release commit shipped without a
CHANGELOG section (the release chain's draft lived in a session
scratchpad that a crash had wiped), and the release workflow refuses a
version without notes, as designed. 0.36.1 is 0.36.0 plus these notes.
## 0.36.0 — 2026-09-03
### The linter grows up: severities, per-rule toggles, and 19 new rules
Every lint rule now has a **severity** — `error` (would likely fail to
compile or elaborate, or silently mis-synthesize), `warning` (a probable
bug) or `style` — printed in `lucisv check` output
(`FILE:LINE:COL: warning: message [rule]`), carried in the JSON output,
mapped to red / yellow / blue in the editor, and shown in
`--rules-doc`, which now groups rules by class. `--select`, `--ignore`
and `[lint]` in `lucisv.toml` accept a severity word (`--ignore style`).
**Editor toggles.** VS Code settings gain three master switches
(`lucisv.lint.severity.error`, `.warning`, `.style`) and one setting per
rule (`lucisv.lint.rules.<rule>`: `default` / `on` / `off`), generated
from the rule registry so the list can never drift. Precedence, top to
bottom: defaults → `select` → severity switches → per-rule settings →
`ignore`. Changing any of them re-checks every open file.
**New rules — Error**: `mismatched-labels`, `duplicate-declaration`,
`undeclared-identifier` (with a project; silent for names that come
from macros, `` `include``d fragments or hierarchical paths),
`unknown-port`, `unknown-parameter`.
**New rules — Warning**: `forbid-defparam`, `invalid-system-task-function`,
`truncated-numeric-literal`, `undersized-binary-literal` (safe fix pads),
`suspicious-semicolon`, `packed-dimensions-range-ordering`, `module-port`,
`module-parameter`, `explicit-function-task-parameter-type`,
`plusarg-assignment`, `instance-shadowing`, `forbid-negative-array-dim`,
`void-cast`, `incomplete-assignment` (latch inference in `always_comb`).
Verible equivalents are named in each rule's documentation; defaults
follow Verible's except where the doc says why not. Existing rules
re-classified: `multiply-driven` and `wire-reg-mixup` are errors.
Measured on opentitan: every false-positive class found was closed with
a test; `lucisv check` over its `hw/` tree runs in the same time as
0.35.0.
## 0.35.0 — 2026-09-02
### Format fences reach statements and class bodies
+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
+10 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.36.0"
version = "0.52.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.36.0"
version = "0.52.0"
[[package]]
name = "lucisv_server"
version = "0.36.0"
version = "0.52.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,15 +248,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.36.0"
version = "0.52.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.36.0"
version = "0.52.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
@@ -264,19 +265,20 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.36.0"
version = "0.52.0"
[[package]]
name = "vlog_refactor"
version = "0.36.0"
version = "0.52.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
]
[[package]]
name = "vlog_semantic"
version = "0.36.0"
version = "0.52.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.36.0"
version = "0.52.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+252 -22
View File
@@ -2,6 +2,12 @@
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
Start with the [repository analysis](docs/repository-analysis.md) for a code-based
assessment and [dependency topology](docs/topo.md) for interfaces and change
impact. The [documentation site source](docs/site/README.md) contains usage
guides and references; [CHANGELOG.md](CHANGELOG.md) records releases, and
[TODO.md](TODO.md) tracks work in progress.
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
layout conventions and lint ergonomics borrowed from
@@ -80,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
@@ -91,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
@@ -106,6 +115,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
git's "already-tracked files are never ignored" rule. See
`docs/features/parallel-files/README.md` for the exact subset.
Directory walks enter each directory once by identity, so symlink cycles
terminate. Inputs resolving to one canonical file path are processed once.
Unreadable directories or `.gitignore` files and dangling source links found
during a walk warn on stderr and are skipped without changing the exit code;
a missing explicitly named input is still an error.
## Configuration
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
@@ -158,11 +173,16 @@ 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]`, multi-line arrays, string
escapes) is a hard error naming the file and line — exit 2, with nothing
written. This is deliberate:
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.
## Linting
@@ -242,6 +262,11 @@ makes an editor's red squiggle worth believing.
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
| `undriven-net` † | warning | — | everything read is driven by something |
| `unused-signal` † | warning | — | no net or variable nothing uses |
| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` |
| `forbidden-macro` | warning | — | no macro on the project's forbidden list |
| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) |
| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) |
| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) |
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
| `empty-item` | style | safe | no `;` standing where an item belongs |
@@ -251,7 +276,40 @@ makes an editor's red squiggle worth believing.
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
| `line-length` | style | — | no line wider than the width the formatter uses |
| `posix-eof` | style | safe | the file ends with a newline |
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
| `generate-label` | style | — | every generate block carries a `: label` |
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
| `package-filename` | style | — | a one-package file is named after its package |
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
| `one-module-per-file` | style | — | one `module` per file (off by default) |
| `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 |
| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized |
| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` |
| `module-begin-block` | style | — | no `begin`/`end` at module scope |
| `v2001-generate-begin` | style | — | no bare `begin` in a generate region |
| `forbid-line-continuations` | style | — | no `\` breaking a string literal |
| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) |
| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) |
| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) |
| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) |
| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) |
| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) |
† On by default when lucisv can see a project (a multi-file CLI run or the
language server), and off for a single file or stdin unless `--select` names
@@ -266,11 +324,77 @@ its default, its fix and the paragraph saying why it exists — generated from
the registry, so it can never be out of date.
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
that cannot change what the code means), `--unsafe-fixes` widens that to the
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
`always_comb`, which is a different block at time zero and makes a second
driver of its outputs an error — right nearly always, and not lucisv's call to
make without being asked. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Rule options
A rule can be configured in a `[lint.<rule-name>]` table:
```toml
[lint]
ignore = ["typedef-structs-unions"]
[lint.line-length]
length = 120 # the linter's limit, if not the formatter's
[lint.generate-label-prefix]
prefix = ["g_", "gen_"] # the label prefixes this project writes
[lint.parameter-name-style]
localparam_style = "CamelCase" # Verible's own default, stricter than ours
[lint.signal-name-style]
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
```
The keys are Verible's wherever it has the same option, so a `.rules.verible`
file translates word for word. An option nobody sets reads the default
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
value of the wrong kind, an integer out of range or a pattern that does not
compile **fails the run**, naming the config file and the line — a typo in a
lint setting is not something to guess at.
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
against the **whole** name, so `^`/`$` are accepted and redundant.
Everything else is **refused when the option is read, by name**: counted
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
worse than an error you can read.
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
length whatever shape the pattern has: no pattern can make `lucisv check` — or
an editor session — hang.
From an editor the same options are one object, `lucisv.lint.options`:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": false }
}
```
There the precedence is **the editor's value, then the `lucisv.toml`, then the
rule's default — key by key**: a project can set two options and one user
override the third without losing the others. (This is the opposite order to
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
formatting has a byte-exact contract with CI, and which findings you are shown
in your own editor is yours to choose.) A bad entry there is *ignored* and
reported in the lucisv log rather than fatal, so one typo cannot leave a
session with no diagnostics.
### Waivers
```systemverilog
@@ -284,13 +408,61 @@ wire a; // lucisv: waive no-tabs suppresses that rule on this line
works unedited — including waivers naming Verible rules lucisv has not
implemented, which are ignored rather than reported. A waiver of lucisv's own
that suppresses nothing, names an unknown rule or is malformed is reported
under `unused-waiver`. External waiver files are not supported. Full rules:
under `unused-waiver`.
Findings can also be suppressed from **outside** the RTL, in Verible's
waiver-file format — one directive per line, `#` comments and blank lines
ignored:
```text
# every line of every file
waive --rule=no-tabs
# one line, or a range with both ends included
waive --rule=line-length --line=12
waive --rule=line-length --line=12-20
# only the files a pattern names
waive --rule=no-tabs --location=legacy/top.sv
```
`--rule` is required and names exactly one rule (a severity word is not
accepted). `--line` is 1-based. `--location` is matched the way an
`--exclude` pattern is — `*` within one path component, a pattern with `/`
matching a path suffix, one without matching the file name at any depth — and
**not** as a regular expression; a pattern that looks like one (`.*`, `\.`,
`[…]`) is an error naming the difference.
Waiver files come from three places, and they add up: `lucisv check
--waiver-file <path>` (repeatable, relative to the working directory),
`waivers` under `[lint]` in `lucisv.toml` (relative to that file; read by the
CLI and the editor), and the editor setting `lucisv.lint.waivers` (relative to
the first workspace folder). External and inline waivers are a union: a
finding either covers is suppressed, and one both cover leaves neither
reported as dead. A missing file or an unparsable directive fails `lucisv
check` with `<file>:<line>: <message>` and exit 2; in an editor the bad line
is dropped and the rest of the file applies, and the bad line is written once
to the lucisv log whether the file was named by the editor setting or by
`lucisv.toml`. Unused external waivers
are reported under `unused-waiver` at their line of the waiver file, by
`lucisv check` only and only after the whole run.
Both front ends read the same configuration, and the editor's settings play
the role the CLI's flags play: `lucisv.lint.select` when it is set, else
`[lint] select` from the buffer's `lucisv.toml`, else the default set — and
the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
`lucisv.lint.rules.*` have no project counterpart and apply over whichever
selection stands. Project per-rule options are read by both front ends. A
project entry lucisv cannot use — an unknown rule name in `[lint]
select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
file or a directive that does not parse — fails `lucisv check` with
`<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
once to the lucisv log in the same words, and everything lucisv did
understand still lints the buffer. Full rules:
`docs/features/linter-core/README.md`.
## Architecture (the ruff mapping)
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
generic pretty-printing IR, language formatting rules, and a thin CLI:
The eight-crate workspace separates source syntax, reusable engines, project
inputs, and the CLI/LSP front ends. The formatter follows ruff's separation
of document layout from language rules:
| This repo | ruff equivalent | Role |
|---|---|---|
@@ -298,7 +470,20 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
| `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/lucisv` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
| `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 |
`vlog_parser` and `lucisv_core` have no dependencies. The formatter depends
only on the parser; semantic analysis also depends only on the parser.
Linting consumes the parser, semantics and `lucisv_core` (for the one
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
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 and refactor’s formatter dependencies used only by tests.
Key ideas carried over from ruff/prettier:
@@ -311,8 +496,15 @@ Key ideas carried over from ruff/prettier:
lists, expressions, concatenations) is a `Group`: it renders on one line if
it fits within the line limit, otherwise it breaks one-element-per-line.
A comment inside a group forces it to break.
- **Idempotency as a hard invariant.** The test suite formats every fixture
twice and asserts a fixed point.
- **Verification on every formatting call.** The engine re-lexes input and
output and compares normalized tokens, including comments. It then parses
and formats the output again and requires a fixed point. Either check can
reject the result; the caller retains the original file. This is a lexical
safety net, not compiler elaboration or a proof of hardware equivalence.
- **Two parsing modes.** Formatting uses strict parsing. Linting and the
editor use tolerant parsing: failed elements become error leaves while
valid siblings remain available for analysis. A lexer failure is still
all-or-nothing. Neither mode performs cross-file macro expansion.
## Style
@@ -431,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`
@@ -668,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
@@ -709,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
@@ -768,8 +986,11 @@ vim.lsp.enable('lucisv')
**Which files the server indexes.** A filelist if the project has one — the
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
(a path, absolute or relative to the workspace folder) — and then exactly the
files it names. Otherwise the workspace folder, walked as the CLI walks it;
and with no folder open at all, the current file's own directory. Open buffers
files it names. Otherwise the default `lucisv.index.scope = "folder"` starts
from open-file folders, widens by `lucisv.index.scopeDepth` (default 2), and stays bounded by
the workspace roots; `"workspace"` walks the full roots. With no folder open,
the server stays in the current file's directory: depth 0 scans it flat; a
positive depth walks its descendants but never climbs to a parent. Open buffers
are always indexed on top. A filelist that cannot be read warns and falls back
to the folder walk, so the index is never silently empty.
@@ -800,11 +1021,20 @@ expected; no PRs or review required.
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo test # unit + snapshot + idempotency tests
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
```
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
expected outputs only for intentional formatting changes with
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
Table-driven cases live in `crates/vlog_formatter/tests/cases/`; lint cases
live in `crates/vlog_linter/tests/cases/`. All tests, fuzzers, and corpus/tree
sweeps must run through `tools/guard.sh` (8 GiB RSS / 30 minutes by default),
as required by [CLAUDE.md](CLAUDE.md). A guard kill is a finding, not a reason
to increase the limit. Documentation build instructions are in
[docs/site/README.md](docs/site/README.md).
## Install and releases
+2994 -69
View File
File diff suppressed because it is too large. Load diff
+61 -2
View File
@@ -71,6 +71,12 @@ pub struct Options {
pub select: Vec<String>,
/// `check` only: rules to drop from whatever `--select` left.
pub ignore: Vec<String>,
/// `check` only: external waiver files, relative to the current
/// directory. They *add* to whatever `[lint] waivers` in a `lucisv.toml`
/// names — a waiver file suppresses findings and can only ever suppress
/// fewer of them by being left out, so there is nothing here for a
/// command line flag to override.
pub waiver_files: Vec<String>,
/// `check` only: print the generated rule reference and exit, reading no
/// file at all.
pub rules_doc: bool,
@@ -100,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
}
@@ -203,6 +215,9 @@ CHECK OPTIONS (`lucisv check` only):
--fix apply safe fixes and write the files back
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
one yet, so today this changes nothing)
--waiver-file <PATH> read waiver directives from this file; may be
repeated, and adds to whatever `[lint] waivers`
in a lucisv.toml already names
--rules-doc print the rule reference — every rule, what it
reports and whether it has a fix — as Markdown on
stdout and exit 0. Generated from the registry, so
@@ -215,6 +230,31 @@ CHECK OPTIONS (`lucisv check` only):
accepted in place of `lucisv:`. A waiver that suppresses nothing is
reported under the `unused-waiver` rule.
WAIVER FILES:
Findings can also be suppressed from outside the RTL, in Verible's waiver
file format — one directive per line, `#` comments and blank lines ignored:
waive --rule=<rule> every line of every file
waive --rule=<rule> --line=12 one line
waive --rule=<rule> --line=12-20 a range, both ends included
waive --rule=<rule> --location=legacy.sv the files that pattern names
`--rule` is required and names one rule (a severity word is not accepted);
`--line` is 1-based and a range includes both ends; `--location` is matched
the way an `--exclude` pattern is — `*` within one path component, a
pattern with `/` against a path suffix and one without against the file
name. Unlike Verible's, it is **not** a regular expression, and a pattern
that looks like one is an error rather than a silent mismatch.
lucisv reads `--waiver-file <PATH>` (relative to the current directory) and
every path in `waivers` under `[lint]` in a `lucisv.toml` (relative to that
file). An external waiver and an inline one are a union: a finding either
covers is suppressed, and neither is then reported as dead. A file that
does not exist, or a directive that does not parse, fails the run with
`<file>:<line>: message` and exit 2. An external waiver that suppressed
nothing anywhere in the run is reported under `unused-waiver`, at the line
of the waiver file it was written on.
IGNORE FILES:
While walking a directory, lucisv reads a `.gitignore` in every directory it
enters and skips what it names; a deeper file overrides a shallower one and
@@ -250,8 +290,11 @@ CONFIGURATION:
read by lucisv-server only — the CLI reads a filelist only when `-f` names
one, so `lucisv rtl/` always means the directory it was given). One table
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
`--select`/`--ignore` semantics). A command line flag overrides the file's
corresponding key; the other keys still apply.
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
paths, resolved against the config file's own directory). A command line
flag overrides the file's corresponding key; the other keys still apply —
`--waiver-file` is the exception, and adds to `waivers` rather than
replacing it.
RANGE FORMATTING:
`--lines` formats one construct at a time: an item whose lines meet a range
@@ -298,6 +341,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
unsafe_fixes: false,
select: Vec::new(),
ignore: Vec::new(),
waiver_files: Vec::new(),
rules_doc: false,
inputs: Vec::new(),
filelists: Vec::new(),
@@ -378,6 +422,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--ignore requires a value")?;
opts.ignore.extend(split_rules(&v));
}
"--waiver-file" => {
let v = args.next().ok_or("--waiver-file requires a value")?;
opts.waiver_files.push(v);
}
"--rules-doc" => opts.rules_doc = true,
"-h" | "--help" => {
print_help();
@@ -444,6 +492,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
(opts.output_format != OutputFormat::Text, "--output-format"),
(!opts.select.is_empty(), "--select"),
(!opts.ignore.is_empty(), "--ignore"),
(!opts.waiver_files.is_empty(), "--waiver-file"),
(opts.rules_doc, "--rules-doc"),
];
let format_only = [
@@ -614,6 +663,16 @@ mod tests {
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
}
#[test]
fn waiver_files_are_collected_in_order_and_are_lint_only() {
let opts = parse(&["check", "--waiver-file", "a.waiver", "--waiver-file", "b", "rtl"])
.expect("parsed");
assert_eq!(opts.waiver_files, vec!["a.waiver", "b"]);
assert!(parse(&["check", "rtl"]).unwrap().waiver_files.is_empty());
assert!(parse(&["check", "--waiver-file"]).is_err(), "a value is required");
assert!(parse(&["--waiver-file", "a.waiver", "rtl"]).is_err(), "not a formatter flag");
}
#[test]
fn rules_doc_is_the_one_check_that_needs_no_input() {
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
+297 -66
View File
@@ -9,12 +9,16 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use lucisv_core::atomic::write_atomic;
use lucisv_core::config::FileConfig;
use rayon::prelude::*;
use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::words;
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
use vlog_linter::{
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
Violation, WaiverUse,
};
use vlog_parser::LineIndex;
use crate::args::{Options, OutputFormat};
@@ -31,6 +35,9 @@ pub struct Job {
path: PathBuf,
config: Config,
rules: Vec<&'static dyn Rule>,
/// What this file's `lucisv.toml` configured about each rule, validated
/// against the registry when the run was planned.
options: RuleOptions,
}
/// A whole `lucisv check` run: what to lint, and what the project says about
@@ -40,6 +47,15 @@ pub struct Plan {
/// The project's identifier census, built when at least one selected rule
/// asks for a workspace and there is more than one file to ask about.
census: Option<Census>,
/// Every external waiver file the run reads, applied to every job.
///
/// One set for the whole run rather than one per file, because a
/// `--location` pattern names files and a waiver is only *unused* when no
/// file in the run matched it — a question only the whole run can answer.
external: ExternalWaivers,
/// Every rule name any job in the run has switched on, for deciding which
/// external waivers never had a chance to fire.
enabled: Vec<&'static str>,
}
/// How many of the run's files write each identifier down.
@@ -55,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 {
@@ -65,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.
@@ -106,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.
@@ -118,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
@@ -142,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.
@@ -157,18 +227,98 @@ impl MentionOracle for Elsewhere<'_> {
/// already says about itself.
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
let workspace = gathered.len() > 1;
let external = external_waivers(opts, gathered.iter().map(|(_, _, file)| file))?;
let mut jobs = Vec::with_capacity(gathered.len());
for (path, config, file_config) in gathered {
let select = pick(&opts.select, file_config.lint_select.as_deref());
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, workspace)
.map_err(|e| format!("{}: {e}", path.display()))?;
jobs.push(Job { path, config, rules });
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));
Ok(Plan { jobs, census })
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();
enabled.dedup();
Ok(Plan { jobs, census, external, enabled })
}
/// The run's external waiver files, read once each: `--waiver-file` in flag
/// order, then every `[lint] waivers` entry of a config file governing an
/// input.
///
/// The two **add up** rather than override: a waiver file only ever suppresses
/// findings, so there is nothing for a command line to take back. A file named
/// twice over — the flag and a `lucisv.toml`, or one `lucisv.toml` governing
/// five hundred files — is read once, or its directives would each be reported
/// unused as many times as the file was read.
///
/// A file that cannot be read, or a directive that does not parse, fails the
/// run naming the file and the line, exactly as a bad `[lint.<rule>]` entry
/// does and for the same reason: a user wrote it and is watching.
pub fn external_waivers<'a>(
opts: &Options,
configs: impl Iterator<Item = &'a FileConfig>,
) -> Result<ExternalWaivers, String> {
let mut paths: Vec<PathBuf> = opts.waiver_files.iter().map(PathBuf::from).collect();
for config in configs {
for path in config.lint_waivers.iter().flatten() {
paths.push(path.clone());
}
}
let mut read: Vec<PathBuf> = Vec::new();
let mut waivers = ExternalWaivers::default();
for path in paths {
// Compared canonically, because the flag's path is relative to the
// working directory and a `lucisv.toml`'s is absolute: the same file
// named both ways is still one file, and reading it twice would report
// each of its dead directives twice. Only the *comparison* is
// canonical — the path a diagnostic names stays the one written.
let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if read.contains(&key) {
continue;
}
let (file, problems) = ExternalWaivers::read(&path)?;
if let Some(problem) = problems.first() {
return Err(problem.clone());
}
waivers.absorb(file);
read.push(key);
}
Ok(waivers)
}
/// The `[lint.<rule>]` entries of one file's config, resolved against the
/// registry.
///
/// The names and the values are checked **here**, where the registry is, and
/// the first bad entry fails the run naming the config file and the line it
/// was written on — the same treatment a bad `[lint] select` name gets, and
/// for the same reason: a user typed it and is watching.
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
let mut options = RuleOptions::new();
for entry in &file_config.lint_options {
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
let file = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
// The rule is named as well as the option: the table header two
// lines up says which rule it is, and an error a user reads out
// of a CI log has no table header beside it.
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
})?;
}
Ok(options)
}
/// Whether this rule reads the census's **interface** half, which costs a
@@ -185,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() {
@@ -203,20 +359,51 @@ struct Report {
violations: Vec<Violation>,
/// Violations whose fix was applied and written back.
fixed: usize,
/// Which of the run's external waivers suppressed something in this file.
/// Merged across every file before the dead ones are reported.
used: WaiverUse,
/// Set when the file could not be fully checked: unreadable, unwritable,
/// or — because the lexer is all-or-nothing — unlexable, in which case
/// only the text-level rules saw it.
error: Option<String>,
}
/// Everything one file's lint pass reads besides the file itself.
///
/// One value rather than six parameters: every function below the driver
/// needs the same set, and the `--fix` loop passes it down another level
/// again.
struct Pass<'a> {
config: &'a Config,
rules: &'a [&'static dyn Rule],
options: &'a RuleOptions,
census: Option<&'a Census>,
/// The run's external waiver files. Empty unless `--waiver-file` or a
/// `[lint] waivers` named one, and then costing nothing.
external: &'a ExternalWaivers,
}
/// Lints every gathered file and reports. Exit 1 if anything is left over,
/// 2 if a file could not be read, written, or lexed.
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
let mut reports: Vec<Report> = plan
.jobs
.par_iter()
.map(|job| check_one(&job.path, &job.config, opts, &job.rules, plan.census.as_ref()))
.map(|job| {
let pass = Pass {
config: &job.config,
rules: &job.rules,
options: &job.options,
census: plan.census.as_ref(),
external: &plan.external,
};
check_one(&job.path, opts, &pass)
})
.collect();
// The dead external waivers are found once every file has been linted,
// and reported against the waiver file, which then sorts in among the
// sources like any other path.
reports.extend(dead_waivers(&plan.external, &reports, &plan.enabled));
// Diagnostics are printed sorted by path, then by position within the
// file (`lint` already sorts those), so a run over a directory reads
// top to bottom whatever order the walk or the worker pool produced.
@@ -224,6 +411,37 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
finish(opts, reports)
}
/// The `unused-waiver` reports for external waivers no file in the run used.
///
/// **After the whole run**, which is the whole reason this is the CLI's job
/// and not the linter's: a `--location` pattern may match a file the run has
/// not reached yet, so a waiver is only dead once every file has been asked.
fn dead_waivers(
external: &ExternalWaivers,
reports: &[Report],
enabled: &[&'static str],
) -> Vec<Report> {
if external.is_empty() {
return Vec::new();
}
let mut used = WaiverUse::default();
for report in reports {
used.merge(&report.used);
}
external
.unused(&used, enabled)
.into_iter()
.map(|dead| Report {
path: dead.path.display().to_string(),
index: LineIndex::new(&dead.text),
violations: dead.violations,
fixed: 0,
used: WaiverUse::default(),
error: None,
})
.collect()
}
/// Lints a buffer piped in on stdin. `--stdin-filename` names it, and is
/// what the rules that need a file name see.
pub fn check_stdin(
@@ -231,31 +449,35 @@ pub fn check_stdin(
src: &str,
config: &Config,
rules: &[&'static dyn Rule],
options: &RuleOptions,
external: &ExternalWaivers,
) -> ExitCode {
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
let (violations, lex_error) = run_rules(src, path, config, rules, None);
let pass = Pass { config, rules, options, census: None, external };
let (violations, used, lex_error) = run_rules(src, path, &pass);
// Nothing is ever written back for stdin, so `--fix` has nothing to do
// here; the violations are reported as they are.
let error = lex_error.map(|e| format!("{name}: {e}"));
let report = Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error };
finish(opts, vec![report])
let report =
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, used, error };
// One buffer is a whole run too, so a waiver that covered nothing in it is
// as dead as one that covered nothing in a directory.
let names: Vec<&'static str> = rules.iter().map(|rule| rule.name()).collect();
let mut reports = vec![report];
reports.extend(dead_waivers(external, &reports, &names));
finish(opts, reports)
}
/// Lints one file, optionally fixing it, and never panics out of its worker.
fn check_one(
file: &Path,
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> Report {
fn check_one(file: &Path, opts: &Options, pass: &Pass) -> Report {
let path = file.display().to_string();
let failed = |error: String| Report {
path: path.clone(),
index: LineIndex::new(""),
violations: Vec::new(),
fixed: 0,
used: WaiverUse::default(),
error: Some(error),
};
@@ -265,20 +487,19 @@ fn check_one(
};
let outcome = crate::catch_panic(|| {
if opts.fix {
fix_source(&src, file, config, opts, rules, census)
fix_source(&src, file, opts, pass)
} else {
let (violations, lex_error) =
run_rules(&src, Some(file.to_path_buf()), config, rules, census);
(violations, None, 0, lex_error)
let (violations, used, lex_error) = run_rules(&src, Some(file.to_path_buf()), pass);
(violations, used, None, 0, lex_error)
}
});
let (violations, rewritten, fixed, lex_error) = match outcome {
let (violations, used, rewritten, fixed, lex_error) = match outcome {
Ok(outcome) => outcome,
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
};
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
if let Some(text) = rewritten {
if let Err(e) = std::fs::write(file, &text) {
if let Err(e) = write_atomic(file, text.as_bytes()) {
return failed(format!("{path}: {e}"));
}
}
@@ -287,20 +508,20 @@ fn check_one(
// so the file must not pass as checked. It is an error (exit 2), exactly
// as `lucisv format` treats the same file.
let error = lex_error.map(|e| format!("{path}: {e}"));
Report { path, index, violations, fixed, error }
Report { path, index, violations, fixed, used, error }
}
/// Runs the rules over one text. The second half of the answer is the lex
/// error when the text does not lex — rendered `line:col: message`, ready
/// for a path prefix — because a file with no tokens was only text-linted
/// and must be reported as an error, not passed off as clean.
/// Runs the rules over one text, reporting which external waivers fired. The
/// last part of the answer is the lex error when the text does not lex —
/// rendered `line:col: message`, ready for a path prefix — because a file with
/// no tokens was only text-linted and must be reported as an error, not passed
/// off as clean.
fn run_rules(
src: &str,
path: Option<PathBuf>,
config: &Config,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>) {
pass: &Pass,
) -> (Vec<Violation>, WaiverUse, Option<String>) {
let Pass { config, rules, options, census, external } = *pass;
// One parse per file (TODO §4): the products are built here, once, and
// lent to the context. Under `--fix` each *round* re-enters through this
// function with rewritten text — that re-parse is inherent (the old
@@ -313,13 +534,19 @@ fn run_rules(
// census so a signal never counts as mentioned by its own declaration.
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
// The indent width the formatter would use is also the width a tab
// expands to, so `--indent 4` fixes tabs into four spaces.
let ctx = parsed.context(path).with_tab_width(config.indent_width);
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
// it would wrap to is the width `line-length` holds the file to.
let ctx = parsed
.context(path)
.with_tab_width(config.indent_width)
.with_line_length(config.max_width)
.with_options(options);
let ctx = match &elsewhere {
Some(elsewhere) => ctx.with_oracle(elsewhere),
None => ctx,
};
(lint(&ctx, rules), lex_error)
let (violations, used) = lint_with(&ctx, rules, external);
(violations, used, lex_error)
}
/// The violations whose fix may be applied: everything except a fix that
@@ -358,15 +585,15 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
fn fix_source(
src: &str,
file: &Path,
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
pass: &Pass,
) -> (Vec<Violation>, WaiverUse, Option<String>, usize, Option<String>) {
let mut text = src.to_string();
let mut fixed = 0;
let (mut violations, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, census);
let mut used = WaiverUse::default();
let (mut violations, mut round_used, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), pass);
used.merge(&round_used);
for _ in 0..MAX_FIX_ROUNDS {
let round =
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
@@ -375,10 +602,14 @@ fn fix_source(
}
fixed += round.applied;
text = round.output;
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules, census);
(violations, round_used, lex_error) = run_rules(&text, Some(file.to_path_buf()), pass);
// A waiver that covered a finding in an earlier round did its job even
// though the fix then removed the finding, so usage accumulates over
// the rounds rather than being the last round's.
used.merge(&round_used);
}
let rewritten = (text != src).then_some(text);
(violations, rewritten, fixed, lex_error)
(violations, used, rewritten, fixed, lex_error)
}
/// Prints the run and turns it into an exit code.
+86 -12
View File
@@ -27,6 +27,7 @@ use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
@@ -98,7 +99,7 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
if opts.is_stdin() {
let config = match stdin_config(opts) {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -120,7 +121,24 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules);
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it exactly as `[lint] select` does.
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
Ok(external) => external,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -140,7 +158,7 @@ fn run_check(opts: &Options) -> ExitCode {
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let config = match stdin_config(opts) {
let (config, _file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -299,7 +317,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
} else if opts.check {
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
} else if let Err(e) = std::fs::write(file, &out) {
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
} else {
// The bytes now on disk are formatted, so they are what the cache
@@ -315,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
@@ -348,7 +371,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String>
return Err(format!("--lines needs a file, not a directory: {input}"));
}
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
// The walk's own warnings — an unreadable directory, a source file
// that is only a broken link — go to stderr as they are found, before
// the report and exactly as a filelist's do. A warning is not a
// failure: the exit code is the formatting's alone.
let mut warn = |w| eprintln!("warning: {w}");
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
}
// Filelists come after the command line's own inputs, in flag order: they
// add files, they never replace or reorder what was named directly.
@@ -397,13 +425,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut seen = HashSet::new();
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
}
/// The key two spellings of one file share: the file's canonical path when it
/// is there, and the lexical fold when it is not.
///
/// Canonical means symlinks resolved, which is the only way to see that
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
/// target otherwise, each rewriting what the other just wrote. A path with no
/// file behind it has no canonical form, and the lexical fold is then the
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
/// deliberately left unresolved, so this is only ever a dedup key and never
/// the path lucisv reports.
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
@@ -421,13 +461,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// The settings for a buffer piped in on stdin: discovery anchors on
/// `--stdin-filename`'s directory when given, else on the current one.
fn stdin_config(opts: &Options) -> Result<Config, String> {
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
Ok(opts.config_with(&file))
Ok((opts.config_with(&file), file))
}
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
@@ -581,6 +624,37 @@ mod tests {
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
}
#[cfg(unix)]
#[test]
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
// A directory walk lists `b.sv` as a file of its own; lexically the
// two names share nothing, and two workers would rewrite one file.
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let real = dir.join("a.sv");
let link = dir.join("b.sv");
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
// Whichever spelling comes first is the one kept and reported.
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
// And a `..` detour through the same link is still the same file.
std::fs::create_dir(dir.join("sub")).expect("sub dir");
let detour = dir.join("sub/../b.sv");
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
// A file that is not there has no canonical path: the key is lexical,
// which still folds `.` and `..`, and two missing files stay two.
let gone = dir.join("gone.sv");
let same = dir.join("./sub/../gone.sv");
let other = dir.join("other.sv");
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
+488 -12
View File
@@ -136,6 +136,57 @@ fn formats_files_in_place() {
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
}
/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv`
/// used to put two workers on one file: two report lines for one file, and
/// two writers racing to replace it. It is one file now, named once.
#[cfg(unix)]
#[test]
fn a_symlink_and_its_target_are_one_file() {
let dir = TempDir::new("alias");
dir.write("a.sv", UNFORMATTED);
std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 1, "one file, one line: {named:?}");
assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}");
assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out));
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out));
assert_eq!(dir.read("a.sv"), FORMATTED);
assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it");
assert!(
std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(),
"the link was not replaced by a copy"
);
}
/// A directory that links back into itself. Before the walk kept a visited
/// set (`docs/features/walk-cycles/README.md`) this run recursed until the
/// OS refused the path; now each directory is entered once, so each file is
/// named once — under the first spelling that reaches it.
#[cfg(unix)]
#[test]
fn a_symlink_cycle_terminates_and_names_each_file_once() {
let dir = TempDir::new("cycle");
dir.write("rtl/a.sv", UNFORMATTED);
dir.write("rtl/sub/b.sv", UNFORMATTED);
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level down.
std::os::unix::fs::symlink("../rtl", dir.path.join("rtl/self")).expect("symlink");
std::os::unix::fs::symlink("..", dir.path.join("rtl/sub/up")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 2, "two files, two lines: {named:?}");
assert!(stderr(&out).contains("2 files would be reformatted"), "{}", stderr(&out));
}
#[test]
fn check_reports_without_writing() {
let dir = TempDir::new("check");
@@ -935,6 +986,89 @@ fn check_honors_inline_waivers_and_reports_dead_ones() {
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
}
/// Two tabbed lines, one of which a waiver file's `--line` covers.
const TABBED: &str = "module foo;\n\twire a;\n\twire b;\nendmodule\n";
/// `--waiver-file`: the suppression, the flag repeated, and the dead directive
/// reported at the waiver file's own line. TODO §39.
#[test]
fn check_reads_external_waiver_files() {
let dir = TempDir::new("check-waiver-file");
let path = dir.write("foo.sv", TABBED);
let one = dir.write("one.waiver", "# just line 2\nwaive --rule=no-tabs --line=2\n");
let out = run(&["check", "--waiver-file", &one, &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert_eq!(stdout(&out).lines().count(), 1, "one tab left: {}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "{}", stdout(&out));
// A second file adds to the first rather than replacing it, and both are
// then used, so neither is reported.
let two = dir.write("two.waiver", "waive --rule=no-tabs --line=3 --location=foo.sv\n");
let out = run(&["check", "--waiver-file", &one, "--waiver-file", &two, &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
// A directive that covered nothing is reported against the waiver file.
let dead = dir.write("dead.waiver", "waive --rule=no-tabs --location=elsewhere.sv\n");
let out = run(&["check", "--waiver-file", &dead, &path]);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("dead.waiver:1:1: style: unused waiver for `no-tabs`"), "{text}");
assert!(text.contains("[unused-waiver]"), "{text}");
}
/// The `[lint] waivers` key, and that `--waiver-file` adds to it. TODO §39.
#[test]
fn check_reads_the_waiver_files_a_config_file_names() {
let dir = TempDir::new("check-waiver-toml");
let path = dir.write("rtl/foo.sv", TABBED);
dir.write("lucisv.toml", "[lint]\nwaivers = [ \"project.waiver\" ]\n");
dir.write("project.waiver", "waive --rule=no-tabs --line=2\n");
// Relative to the config file, not to the working directory.
let out = run_raw(&["check", "--no-cache", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "only line 3 survives: {}", stdout(&out));
let extra = dir.write("extra.waiver", "waive --rule=no-tabs --line=3\n");
let out = run_raw(&["check", "--no-cache", "--waiver-file", &extra, &path]);
assert_eq!(code(&out), 0, "the two lists add up: {}", stdout(&out));
// `--no-config` drops the config file's list with everything else in it.
let out = run_raw(&["check", "--no-cache", "--no-config", &path]);
assert_eq!(code(&out), 1);
assert_eq!(stdout(&out).lines().count(), 2, "both tabs are back: {}", stdout(&out));
}
/// A waiver file that cannot be read, or that has a line that does not parse,
/// fails the run with `<file>:<line>: message` and exit 2. TODO §39.
#[test]
fn a_broken_waiver_file_fails_the_run() {
let dir = TempDir::new("check-waiver-bad");
let path = dir.write("foo.sv", TABBED);
let out = run(&["check", "--waiver-file", &dir.write("x.waiver", "hush\n"), &path]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("x.waiver:1: expected a `waive` directive"), "{}", stderr(&out));
let bad = dir.write("y.waiver", "# fine\nwaive --rule=no-such-rule\n");
let out = run(&["check", "--waiver-file", &bad, &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("y.waiver:2: unknown rule"), "{}", stderr(&out));
let regexy = dir.write("z.waiver", "waive --rule=no-tabs --location=.*foo.sv\n");
let out = run(&["check", "--waiver-file", &regexy, &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("looks like a regular expression"), "{}", stderr(&out));
let out = run(&[
"check",
"--waiver-file",
&dir.path.join("gone.waiver").display().to_string(),
&path,
]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("gone.waiver:"), "{}", stderr(&out));
}
#[test]
fn check_reads_stdin_and_names_it() {
let out = run_with_stdin(&["check", "--stdin-filename", "rtl/z.sv", "-"], LINTY);
@@ -1133,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]
@@ -1229,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));
@@ -1254,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");
@@ -1263,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));
@@ -1863,16 +2060,81 @@ fn an_unknown_rule_in_the_lint_table_is_an_error() {
assert_eq!(code(&out), 2);
}
/// Per-rule tables are named rather than silently ignored, so a user who
/// writes one finds out it does nothing yet.
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
/// with it — §34.0's headline claim, end to end through the real binary.
#[test]
fn a_per_rule_lint_table_is_refused_by_name() {
fn a_per_rule_lint_table_changes_the_verdict() {
let dir = TempDir::new("lint-per-rule");
dir.write("dut.sv", DUT);
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
dir.write("m.sv", &wide);
let out = run(&["check", &dir.root()]);
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the option raised the limit");
assert_eq!(code(&out), 0);
}
/// A bad entry fails the run naming the config file and the line, which is
/// what tells a user *where* to fix it.
#[test]
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
let dir = TempDir::new("lint-bad-option");
dir.write("m.sv", "module m;\nendmodule\n");
for (config, wanted) in [
("[lint.line-length]\nlength = 10\n", "must be between"),
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
// An escape from another dialect must be refused rather than read
// as a literal, which would silently judge the wrong names (QA,
// 2026-09-04).
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
] {
dir.write("lucisv.toml", config);
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains(wanted), "{config:?}: {text}");
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
assert_eq!(code(&out), 2, "{config:?}");
}
// Every one of them names the rule as well as the option, so an error
// read out of a CI log stands on its own.
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
let text = stderr(&run(&["check", &dir.root()]));
assert!(text.contains("rule `line-length`"), "{text}");
assert!(text.contains("`length` must be between"), "{text}");
}
/// The width `line-length` holds a file to is the width the formatter is
/// configured with, so the two halves of lucisv cannot disagree.
#[test]
fn line_length_follows_the_formatters_width() {
let dir = TempDir::new("lint-width");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
dir.write("m.sv", &wide);
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
dir.write("lucisv.toml", "line-length = 80\n");
let from_config = run(&["check", &dir.root()]);
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
}
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
#[test]
fn a_stdin_buffer_reads_the_rule_options_too() {
let dir = TempDir::new("lint-stdin-options");
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
@@ -1947,3 +2209,217 @@ fn rules_doc_refuses_files_and_belongs_to_check() {
stderr(&out)
);
}
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
/// A tree with the two things the walk can only warn about: a directory it
/// cannot read, and a source file that is only a broken link.
#[cfg(unix)]
fn unwalkable_tree(tag: &str) -> TempDir {
use std::os::unix::fs::{symlink, PermissionsExt};
let dir = TempDir::new(tag);
dir.write("a.sv", UNFORMATTED);
dir.write("z/late.sv", UNFORMATTED);
dir.write("locked/hidden.sv", UNFORMATTED);
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
dir
}
#[cfg(unix)]
fn lock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
}
#[cfg(unix)]
fn unlock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
// The finding TODO §45.2 closes: one permission-denied directory used to
// propagate `read_dir`'s error and fail the whole run.
let dir = unwalkable_tree("walk-warn");
let out = run(&[&dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
let said = stderr(&out);
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
assert!(said.contains("locked"), "{said}");
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
}
#[test]
#[cfg(unix)]
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
let dir = unwalkable_tree("walk-warn-check");
let out = run(&["--check", &dir.root()]);
unlock(&dir);
// `--check` answers on formatting alone: two files would be reformatted.
assert_eq!(code(&out), 1, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
// And with nothing left to reformat the run is clean, warnings and all.
dir.write("a.sv", FORMATTED);
dir.write("z/late.sv", FORMATTED);
lock(&dir);
let out = run(&["--check", &dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
// The walk drops the link; a path the user typed is not walked at all, so
// "no such file or directory" is still what naming one gets.
let dir = TempDir::new("walk-warn-named");
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
let out = run(&[&named]);
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}"
);
}
+451
View File
@@ -0,0 +1,451 @@
//! Replacing a file's contents without ever leaving it half written.
//!
//! `fs::write` truncates the target and then writes into it, so a crash, a
//! full disk or a `^C` between the two leaves the user's source truncated —
//! and lucisv's first invariant is that it never corrupts code. Every
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
//! gets the bytes, and a `rename` over the target publishes them in one step
//! that either happened or did not.
//!
//! Two threads of one process may write one target: the temp names carry a
//! per-process counter as well as the pid and are created with `O_EXCL`, so
//! each writer owns its own file and neither can see the other's bytes.
//!
//! Two *processes* writing one target are not coordinated, and deliberately
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
//! discarded whole — never merged. Both processes formatted the same input
//! and `format` is idempotent, so whichever rename lands last leaves the
//! file complete and correctly formatted. A lock would buy nothing and would
//! be one more thing to leave behind after a `^C`.
//!
//! See `docs/features/small-items-3/README.md` and
//! `docs/features/atomic-write-coordination/README.md`.
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Writes `bytes` to `path`, replacing whatever was there in one step.
///
/// A temp file beside the target takes the bytes, inherits the target's
/// permissions when there is a target, and is renamed onto it — `rename` is
/// atomic within a directory on every platform lucisv ships to, so a reader
/// sees either the old file or the new one and never a truncated one. A
/// failure anywhere after the temp exists removes it before returning.
///
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
/// writer in this process will be given, and the file is created with
/// `create_new`, so a name that somehow exists is an error and not a shared
/// file. Two threads writing one target therefore both succeed, and the
/// target ends up holding one thread's whole buffer.
///
/// A symlinked target is resolved first: `fs::write` writes *through* a
/// symlink, so replacing the link itself would silently redirect it at a new
/// file and leave the real one stale. The canonical path is what gets
/// replaced, which is also what makes the temp land on the target's own
/// filesystem — `rename` cannot cross one.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let perms = target_permissions(&target);
// A rename replaces a file whatever its mode, so a read-only target would
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
// a file someone made read-only is asking not to be rewritten in place.
if perms.as_ref().is_some_and(fs::Permissions::readonly) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is read-only", path.display()),
));
}
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
drop(file);
if let Err(e) = fs::rename(&tmp, &target) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// How many temp names one write tries before giving up.
///
/// A name is only ever handed out once per process, so a collision means a
/// leftover from a *previous* process that crashed mid-write and whose pid
/// this process now has. A handful of those may sit in one directory; a
/// hundred is a directory to clean up by hand, not a race to retry through.
const TEMP_ATTEMPTS: u32 = 32;
/// Creates the temp file, exclusively, and returns it with its path.
///
/// `replacing` says there is a target whose mode the temp is about to take.
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
/// not revoke a descriptor someone already opened, so the only way a private
/// file's replacement can never be read by anyone else is for the temp to be
/// private from the moment it exists. With no target there is no earlier mode
/// to honour and the umask decides, as `fs::write` would.
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
if replacing {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
#[cfg(not(unix))]
let _ = replacing;
for _ in 0..TEMP_ATTEMPTS {
let tmp = temp_path(target)?;
match opts.open(&tmp) {
Ok(file) => return Ok((tmp, file)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
))
}
/// Puts the target's mode on the temp, then the bytes in it.
///
/// The order is the point on unix: a 0600 target's replacement must not spend
/// even an instant holding the file's contents under the umask's broader
/// bits. Chmod does not close the handle opened before it, so a mode without
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
/// takes a path rather than a handle and the mode goes on after the bytes,
/// which is the order this always had.
fn fill_temp(
file: &mut File,
tmp: &Path,
perms: Option<fs::Permissions>,
bytes: &[u8],
) -> io::Result<()> {
if cfg!(unix) {
copy_mode(file, perms);
file.write_all(bytes)
} else {
file.write_all(bytes)?;
if let Some(perms) = perms {
let _ = fs::set_permissions(tmp, perms);
}
Ok(())
}
}
/// Puts the target's mode on the temp through its open handle, which is what
/// lets it happen while the temp is still empty. No target means no earlier
/// mode to honour, and the umask's stands.
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
if let Some(perms) = perms {
let _ = file.set_permissions(perms);
}
}
/// The mode the temp must end up with: a file someone made executable, or
/// private, keeps its bits, because the temp was created with the process
/// umask (or 0600) and not with the target's. `None` means there is no target
/// — a new file, which takes the umask as `fs::write` would.
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
fs::metadata(target).ok().map(|m| m.permissions())
}
/// Names handed out by [`temp_path`], one per call for the life of the
/// process. Wrapping after 2^64 names is not a scenario.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// The temp file's path: hidden, in the target's own directory, and stamped
/// with the process id and a per-process counter — the pid keeps two lucisv
/// runs apart, the counter keeps two threads of one run apart, and together
/// they mean no two writers anywhere are ever given the same name.
fn temp_path(target: &Path) -> io::Result<PathBuf> {
let dir = target.parent().unwrap_or_else(|| Path::new("."));
let name = target
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let mut tmp = std::ffi::OsString::from(".");
tmp.push(name);
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
Ok(dir.join(tmp))
}
#[cfg(test)]
mod tests {
use super::*;
/// A directory that removes itself, the way `cache.rs`'s own tests have
/// one — no dependency, and no leftovers under `target/`.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"lucisv-atomic-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
/// Every name in the directory, so a test can say what is *not* there.
fn names(&self) -> Vec<String> {
let mut out: Vec<String> = fs::read_dir(&self.path)
.expect("read dir")
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
out.sort();
out
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn the_bytes_land_and_no_temp_file_is_left_behind() {
let dir = TempDir::new("plain");
let file = dir.file("a.sv");
fs::write(&file, "old\n").expect("seed");
write_atomic(&file, b"new\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
}
#[test]
fn a_file_that_does_not_exist_yet_is_created() {
let dir = TempDir::new("create");
let file = dir.file("new.sv");
write_atomic(&file, b"hello\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
}
#[test]
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
// A directory standing where the file should be: the write succeeds,
// the rename cannot.
let dir = TempDir::new("dirtarget");
let target = dir.file("occupied");
fs::create_dir(&target).expect("create dir");
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
assert!(err.to_string().len() > 1, "{err}");
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
}
#[test]
fn writing_the_same_path_twice_leaves_one_file() {
let dir = TempDir::new("twice");
let file = dir.file("a.sv");
write_atomic(&file, b"one\n").expect("write");
write_atomic(&file, b"two\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
}
#[cfg(unix)]
#[test]
fn the_targets_permissions_are_preserved() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("modes");
for mode in [0o600, 0o755] {
let file = dir.file(&format!("m{mode:o}.sv"));
fs::write(&file, "old\n").expect("seed");
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
write_atomic(&file, b"new\n").expect("write");
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
assert_eq!(got, mode, "mode {mode:o} was not preserved");
}
}
#[cfg(unix)]
#[test]
fn a_read_only_target_is_refused_and_left_alone() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("readonly");
let file = dir.file("ro.sv");
fs::write(&file, "old\n").expect("seed");
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
}
#[cfg(unix)]
#[test]
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
let dir = TempDir::new("symlink");
let real = dir.file("real.sv");
let link = dir.file("link.sv");
fs::write(&real, "old\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
write_atomic(&link, b"new\n").expect("write");
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
assert!(
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
"the link is still a link"
);
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
}
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
/// used to produce 100 write errors in 200 calls: both threads derived
/// the same temp name from the target and the pid, so one deleted the
/// other's file under it. Now every writer owns its own temp, so every
/// call succeeds and the target holds one writer's whole buffer.
#[test]
fn two_threads_writing_one_target_never_collide() {
const MIB: usize = 1024 * 1024;
const ROUNDS: usize = 100;
let dir = TempDir::new("race");
let file = dir.file("a.sv");
fs::write(&file, "seed\n").expect("seed");
// Three parties: the two writers and this thread, which inspects the
// target between rounds. Nobody starts a round until everyone has
// finished the last one.
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
let writers: Vec<_> = (*b"ab")
.into_iter()
.map(|tag| {
let (path, start, done) = (file.clone(), start.clone(), done.clone());
std::thread::spawn(move || {
let bytes = vec![tag; MIB];
let mut errors = Vec::new();
for _ in 0..ROUNDS {
start.wait();
if let Err(e) = write_atomic(&path, &bytes) {
errors.push(e.to_string());
}
done.wait();
}
errors
})
})
.collect();
for round in 0..ROUNDS {
start.wait();
done.wait();
let got = fs::read(&file).expect("read");
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
let tag = got[0];
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
}
let errors: Vec<String> =
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
assert!(
errors.is_empty(),
"{} write errors in {} calls: {errors:?}",
errors.len(),
2 * ROUNDS
);
}
#[test]
fn every_thread_gets_its_own_temp_name() {
const PER_THREAD: usize = 200;
let dir = TempDir::new("names");
let target = dir.file("a.sv");
let threads: Vec<_> = (0..4)
.map(|_| {
let target = target.clone();
std::thread::spawn(move || {
(0..PER_THREAD)
.map(|_| temp_path(&target).expect("temp name"))
.collect::<Vec<_>>()
})
})
.collect();
let names: Vec<PathBuf> =
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
}
/// The mode goes on while the temp is still empty, so a 0600 file's
/// replacement never holds its contents under the umask's wider bits.
#[cfg(unix)]
#[test]
fn the_temp_takes_the_targets_mode_before_any_bytes() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("modewindow");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let perms = target_permissions(&target);
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
// Born private, before any mode is copied onto it: an fd opened by
// someone else in this instant would not see the bytes to come.
assert_eq!(
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
0o600,
"the temp was created readable by others"
);
copy_mode(&file, perms.clone());
let meta = fs::metadata(&tmp).expect("stat");
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
// And the chmod does not close the door on the handle opened before it.
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
let _ = fs::remove_file(&tmp);
}
/// The same window seen from outside, through a real `write_atomic`: a
/// big enough buffer that the temp is usually observable while it is
/// being filled. It asserts about what it sees and never about seeing it,
/// so a scheduler that hides the window cannot fail the test.
#[cfg(unix)]
#[test]
fn a_temp_seen_mid_write_is_never_world_readable() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("window");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let path = target.clone();
let writer = std::thread::spawn(move || {
let bytes = vec![b'x'; 8 * 1024 * 1024];
write_atomic(&path, &bytes)
});
while !writer.is_finished() {
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
continue;
}
let Ok(meta) = entry.metadata() else { continue };
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"a temp for a 0600 target was readable by others"
);
}
}
writer.join().expect("writer thread").expect("write");
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
}
}
+96 -24
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.
@@ -87,10 +90,7 @@ impl Cache {
if !ignore.exists() {
let _ = std::fs::write(&ignore, "*\n");
}
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
}
/// The file's text: one line per entry, sorted by path so that two
@@ -107,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
@@ -140,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)
@@ -204,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]
@@ -237,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");
@@ -257,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}"
);
}
@@ -280,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:?}");
@@ -298,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,
@@ -397,7 +469,7 @@ mod tests {
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".tmp"))
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
}
+325 -24
View File
@@ -1,8 +1,9 @@
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a small config file needs is supported (comments, `key = int`,
//! `key = "string"`, `key = ["a", "b"]`, and the single table `[lint]`);
//! everything else is rejected by name rather than ignored. See
//! `key = "string"`, `key = ["a", "b"]`, the table `[lint]` and the per-rule
//! `[lint.<rule>]` tables); everything else is rejected by name rather than
//! ignored. See
//! `docs/features/config-discovery/README.md` for the grammar and the
//! reasoning behind not taking a TOML dependency.
@@ -29,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
@@ -36,6 +41,43 @@ pub struct FileConfig {
pub lint_select: Option<Vec<String>>,
/// `[lint] ignore`: rules dropped from whatever `select` left.
pub lint_ignore: Option<Vec<String>>,
/// `[lint] waivers`: external waiver files, in the order written.
///
/// Like [`FileConfig::filelist`], these name *other files*: [`parse`]
/// records them exactly as written and [`Discovery`] resolves each one
/// against the config file's own directory, so every `FileConfig` a
/// `Discovery` hands out carries usable paths. Nothing here reads them —
/// their contents name lint rules, and this crate does not know the rule
/// registry any more than it does for `select`.
pub lint_waivers: Option<Vec<PathBuf>>,
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
/// order.
///
/// Neither the rule names nor the option names or their values are
/// checked here — this crate does not know the rule registry, exactly as
/// it does not know which rule names `select` may hold. `lucisv check`
/// resolves them against `vlog_linter`'s specs and fails the run naming
/// this file and the line, which is what [`LintOption::line`] is for.
pub lint_options: Vec<LintOption>,
/// The config file these settings were read from, when they were read
/// from one. `parse` leaves it unset — it is handed text, not a path —
/// and [`Discovery`] fills it in, so an error about an entry can name the
/// file the user has to edit.
pub source: Option<PathBuf>,
}
/// One `key = value` written under a `[lint.<rule>]` table, as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintOption {
/// The rule named by the table header.
pub rule: String,
/// The option key.
pub key: String,
/// The value's text, comment stripped, quotes and all — the linter's own
/// parser reads it, because only it knows what kind the key takes.
pub raw: String,
/// 1-based line the entry was written on.
pub line: usize,
}
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
@@ -45,36 +87,62 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
// Editors on some platforms prepend a BOM; it would otherwise garble
// key matching on line 1 into an `unknown key` with invisible cause.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
// Which table the keys below belong to. There is exactly one table, so
// this is a flag rather than a path: `[lint]` opens it and nothing closes
// it, which is TOML's own rule.
let mut in_lint = false;
// Which table the keys below belong to: the top level until a header
// opens one, and then that one until the next header. Nothing closes a
// table, which is TOML's own rule.
let mut table = Table::Top;
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
parse_entry(line, &mut config, &mut in_lint).map_err(|e| format!("{}: {e}", index + 1))?;
parse_entry(line, &mut config, &mut table, index + 1)
.map_err(|e| format!("{}: {e}", index + 1))?;
}
Ok(config)
}
fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Result<(), String> {
/// The table whose keys are being read.
enum Table {
/// Before any header: the formatter's own keys.
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),
}
fn parse_entry(
line: &str,
config: &mut FileConfig,
table: &mut Table,
number: usize,
) -> Result<(), String> {
if line.starts_with('[') {
// `[lint]` is the one table lucisv reads. `[lint.<rule>]` — per-rule
// settings — is named in the error rather than ignored, so a user who
// writes one finds out it is not supported yet instead of wondering
// why it did nothing (topo §2.9-4 keeps the per-rule half open).
// `[lint]` carries `select`/`ignore`/`waivers`; `[lint.<rule>]` carries that
// rule's options, which are stored raw and checked by whoever knows
// the registry.
if line == "[lint]" {
*in_lint = true;
*table = Table::Lint;
return Ok(());
}
if line.starts_with("[lint.") {
return Err(format!(
"per-rule lint settings (`{line}`) are not supported yet; `[lint]` takes `select` and `ignore`"
));
if line == "[format]" {
*table = Table::Format;
return Ok(());
}
return Err(format!("unknown table `{line}` (the only table is `[lint]`)"));
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>]`"));
}
*table = Table::Rule(rule.to_string());
return Ok(());
}
return Err(format!(
"unknown table `{line}` \
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
));
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
@@ -83,8 +151,11 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
if value.is_empty() {
return Err(format!("`{key}` has no value"));
}
if *in_lint {
return parse_lint_entry(key, value, config);
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 => {}
}
match key {
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
@@ -105,18 +176,59 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
and select, ignore under `[lint]`)"
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" {
if config.lint_waivers.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.lint_waivers = Some(parse_array(value)?.into_iter().map(PathBuf::from).collect());
return Ok(());
}
let slot = match key {
"select" => &mut config.lint_select,
"ignore" => &mut config.lint_ignore,
_ => {
return Err(format!("unknown key `{key}` under `[lint]` (known keys: select, ignore)"))
return Err(format!(
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
))
}
};
if slot.is_some() {
@@ -126,6 +238,26 @@ fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(
Ok(())
}
/// One `key = value` of a `[lint.<rule>]` table, kept as written.
fn parse_rule_entry(
rule: &str,
key: &str,
value: &str,
config: &mut FileConfig,
line: usize,
) -> Result<(), String> {
if config.lint_options.iter().any(|held| held.rule == rule && held.key == key) {
return Err(format!("duplicate key `{key}` under `[lint.{rule}]`"));
}
config.lint_options.push(LintOption {
rule: rule.to_string(),
key: key.to_string(),
raw: value.to_string(),
line,
});
Ok(())
}
fn set_int(
slot: &mut Option<usize>,
key: &str,
@@ -288,10 +420,18 @@ fn load(path: &Path) -> Result<FileConfig, String> {
// `filelist` is the one value that names another file, so it is resolved
// here — against the config file's own directory, which `parse` cannot
// know. An absolute path is left alone (`join` already does that).
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
if let Some(filelist) = config.filelist.take() {
let dir = path.parent().unwrap_or(Path::new("."));
config.filelist = Some(dir.join(filelist));
}
// `[lint] waivers` names other files the same way, and is resolved the
// same way: against the config file's directory, an absolute path left
// alone by `join`.
if let Some(waivers) = config.lint_waivers.take() {
config.lint_waivers = Some(waivers.into_iter().map(|file| dir.join(file)).collect());
}
// So an error about a `[lint.<rule>]` entry can name the file to edit.
config.source = Some(path.to_path_buf());
Ok(config)
}
@@ -355,6 +495,34 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// `[lint] waivers` names other files, so it resolves the way `filelist`
/// does: against the config file's own directory, absolute paths left
/// alone. See `docs/features/waiver-files/README.md`.
#[test]
fn lint_waivers_are_a_list_resolved_against_the_config_files_directory() {
assert_eq!(
ok("[lint]\nwaivers = [ \"a.waiver\", \"deep/b.waiver\" ]").lint_waivers,
Some(vec![PathBuf::from("a.waiver"), PathBuf::from("deep/b.waiver")])
);
assert_eq!(
ok("[lint]\nselect = [\"no-tabs\"]").lint_waivers,
None,
"absent unless written"
);
assert!(err("[lint]\nwaivers = \"a.waiver\"").contains("multi-line arrays"));
assert!(err("[lint]\nwaivers = []\nwaivers = []").contains("duplicate key `waivers`"));
assert!(err("[lint]\nwaiver = []").contains("unknown key `waiver` under `[lint]`"));
let tree = TempTree::new();
tree.write("lucisv.toml", "[lint]\nwaivers = [ \"rtl/a.waiver\", \"/opt/b.waiver\" ]\n");
let deep = tree.write("a/b/x.sv", "");
let found = Discovery::new(true).for_file(&deep).unwrap();
assert_eq!(
found.lint_waivers,
Some(vec![tree.path.join("rtl/a.waiver"), PathBuf::from("/opt/b.waiver")])
);
}
#[test]
fn an_empty_file_sets_nothing() {
assert_eq!(ok(""), FileConfig::default());
@@ -425,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]
@@ -451,7 +678,8 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn the_lint_table_rejects_what_it_does_not_support() {
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
assert!(err("[lint.no-tabs]\nseverity = \"error\"").contains("per-rule lint settings"));
assert!(err("[lint.]\nx = 1").contains("not a rule table"));
assert!(err("[lint.a.b]\nx = 1").contains("not a rule table"));
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
// A key before any table still belongs to the top level.
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
@@ -462,6 +690,79 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// The per-rule tables: stored exactly as written, because this crate
/// has no idea what a rule is or what its options take.
#[test]
fn a_rule_table_keeps_its_entries_as_written() {
let config = parse(
"[lint]\nignore = [\"no-tabs\"]\n\n\
[lint.line-length]\nlength = 120\n\n\
[lint.signal-name-style]\nstyle_regex = \"[a-z_0-9]+\" # ours\n",
)
.expect("parses");
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
let entries: Vec<(&str, &str, &str, usize)> = config
.lint_options
.iter()
.map(|o| (o.rule.as_str(), o.key.as_str(), o.raw.as_str(), o.line))
.collect();
assert_eq!(
entries,
vec![
("line-length", "length", "120", 5),
("signal-name-style", "style_regex", "\"[a-z_0-9]+\"", 8),
]
);
}
/// A backslash is legal in an option value and refused in a top-level
/// string: the linter's own parser reads the former, and a pattern is the
/// one value that needs them.
#[test]
fn a_rule_option_value_is_not_string_checked_here() {
let config =
parse("[lint.signal-name-style]\nstyle_regex = \"[a-z]\\d+\"\n").expect("parses");
assert_eq!(config.lint_options[0].raw, "\"[a-z]\\d+\"");
assert!(err("exclude = [\"a\\d\"]").contains("escapes"), "still refused up here");
}
#[test]
fn a_rule_table_rejects_a_repeated_key_and_a_bad_header() {
assert!(err("[lint.line-length]\nlength = 1\nlength = 2")
.contains("duplicate key `length` under `[lint.line-length]`"));
// The same key under two different rules is two different options.
let config = parse(
"[lint.enum-name-style]\nstyle_regex = \"a\"\n\
[lint.module-name-style]\nstyle_regex = \"b\"\n",
)
.expect("parses");
assert_eq!(config.lint_options.len(), 2);
assert!(err("[lint.a b]\nx = 1").contains("not a rule table"));
}
/// Nothing closes a table: the keys after a rule header belong to it
/// until the next header, and a formatter key written there is that
/// rule's option as far as this parser is concerned.
#[test]
fn a_rule_table_runs_until_the_next_header() {
let config =
parse("indent = 4\n[lint.line-length]\nlength = 120\nindent = 8\n").expect("parses");
assert_eq!(config.indent, Some(4));
assert_eq!(config.lint_options.len(), 2);
assert_eq!(config.lint_options[1].key, "indent");
}
#[test]
fn a_config_file_records_where_it_came_from() {
let tree = TempTree::new();
let written = tree.write("lucisv.toml", "[lint.line-length]\nlength = 120\n");
let file = tree.write("x.sv", "");
let found = Discovery::new(true).for_file(&file).expect("reads");
assert_eq!(found.source.as_deref(), Some(written.as_path()));
// `parse` alone has no path to record.
assert_eq!(parse("indent = 4").expect("parses").source, None);
}
/// A throwaway directory tree under the system temp dir.
struct TempTree {
path: PathBuf,
+4 -1
View File
@@ -6,11 +6,14 @@
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
//! `cache` answers the third question of the same family — whether a file
//! needs to be processed at all, and `filelist` answers the first one the way
//! an EDA project already does, from a `.f` file. See
//! an EDA project already does, from a `.f` file. `atomic` is the one write
//! path all of them share: nothing here ever truncates a file it is
//! replacing. See
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
pub mod atomic;
pub mod cache;
pub mod config;
pub mod filelist;
+659 -25
View File
@@ -2,6 +2,7 @@
//! `.gitignore` subset documented in
//! `docs/features/parallel-files/README.md`.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// File extensions lucisv formats when walking a directory.
@@ -10,79 +11,323 @@ pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
/// The name of the per-directory ignore file that is honoured by default.
const GITIGNORE: &str = ".gitignore";
/// Something the walk could not do and went on regardless: a directory it
/// could not read, an ignore file it could not open, a source file that is
/// only a broken link.
///
/// The walk's warning channel exists because none of these is worth failing a
/// run over — one unreadable directory used to drop every file already found
/// — and because a silent skip loses the user the fact entirely. Rendering is
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
/// the server logs the same text once per scan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Warning {
/// What could not be used.
pub path: PathBuf,
/// Why, in the operating system's own words where there are any.
pub message: String,
}
impl std::fmt::Display for Warning {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.path.display(), self.message)
}
}
/// Adds `input` to `files`: the file itself, or every Verilog file under
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
/// to directory walks only — a path named on the command line is always
/// formatted.
///
/// `warn` is called once for everything the walk skipped and wants said; see
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
/// user's own typo, and the run has nothing to do.
pub fn collect_files(
input: &str,
exclude: &[String],
gitignore: bool,
files: &mut Vec<PathBuf>,
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
collect_files_with(input, exclude, gitignore, &mut |path, _| files.push(path), warn)
}
/// [`collect_files`] with the size the walk already read handed on beside each
/// path.
///
/// The same walk, the same order, the same warnings — the only difference is
/// where a file goes when it is found. A directory walk already calls
/// `metadata` on every entry to answer "directory?", so the length is a field
/// of a struct it holds anyway; a caller that has to know how big a file is —
/// the server's `lucisv.index.maxFileSize` cap — would otherwise ask the
/// filesystem the same question a second time, once per file.
/// `docs/features/perf5r-first-answer/README.md` measured that second `stat`
/// at 6.9 ms of a 165 ms discovery over 3 976 files — small, because the walk
/// has just warmed every one of those inodes, and 3 976 system calls that buy
/// a number already in hand all the same.
///
/// **`None` means the walk did not look.** `input` naming a file rather than a
/// directory is handed straight over, exactly as [`collect_files`] hands it
/// over, with no `metadata` call added to a path that never needed one — so a
/// caller that wants a size there asks for it itself. Every path a *directory
/// walk* yields carries `Some`.
pub fn collect_files_with(
input: &str,
exclude: &[String],
gitignore: bool,
found: &mut dyn FnMut(PathBuf, Option<u64>),
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let path = Path::new(input);
if path.is_dir() {
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
let mut walk = Walk {
exclude,
gitignore,
ignores: Vec::new(),
rel: Vec::new(),
visited: HashSet::new(),
found,
warn,
};
walk.dir(path);
} else if path.is_file() {
files.push(path.to_path_buf());
found(path.to_path_buf(), None);
} else {
return Err(format!("{input}: no such file or directory"));
}
Ok(())
}
/// [`collect_files_with`] over `input`, which lies **under** `root`, finding
/// exactly what a walk of `root` would have found there.
///
/// The difference from walking `input` directly is the `.gitignore` files
/// between the two. A walk reads ignore rules from its own starting directory
/// downwards, so `collect_files_with("<root>/hw/ip/aes")` never sees the rule
/// `<root>/.gitignore` writes about `hw/ip/aes/gen/` — and a caller walking a
/// subtree *of a scope whose rung is the root* would then index files that
/// scope excludes. This one walks the ancestor chain first: it reads each
/// ancestor's `.gitignore` onto the stack with the depth it belongs at, and it
/// stops without yielding anything when one of those ancestors is itself
/// ignored or excluded — because a walk of `root` would never have descended
/// into it.
///
/// `input` not being under `root` is the caller's mistake and is answered the
/// way a walk of an unknown path is: nothing found, and no error, since there
/// is no ancestor chain to apply.
///
/// Everything else is [`collect_files_with`]: the same order, the same cycle
/// guard, the same warnings, the same lengths.
pub fn collect_files_below(
root: &Path,
input: &Path,
exclude: &[String],
gitignore: bool,
found: &mut dyn FnMut(PathBuf, Option<u64>),
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let Ok(below) = input.strip_prefix(root) else { return Ok(()) };
if !input.is_dir() {
return Err(format!("{}: no such file or directory", input.display()));
}
let mut walk = Walk {
exclude,
gitignore,
ignores: Vec::new(),
rel: Vec::new(),
visited: HashSet::new(),
found,
warn,
};
// The root's own `.gitignore` sits at depth 0, exactly where a walk of the
// root would have put it.
walk.push_ignore(root);
let mut here = root.to_path_buf();
let names: Vec<String> = below.iter().map(|name| name.to_string_lossy().into_owned()).collect();
for (at, name) in names.iter().enumerate() {
here.push(name);
if is_excluded(&here, exclude) {
return Ok(());
}
walk.rel.push(name.clone());
if is_ignored(&walk.ignores, &walk.rel, true) {
return Ok(());
}
// Not `input`'s own — `Walk::dir` pushes that one itself, and pushing
// it twice would apply its rules at two different depths.
if at + 1 < names.len() {
walk.push_ignore(&here);
}
}
walk.dir(input);
Ok(())
}
/// How a directory is recognised as one the walk has already entered. Two
/// names for the same directory — a symlink and its target, or two symlinks
/// pointing at one place — must map to the same identity, or a cycle has no
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
/// elsewhere it is the canonical path, which resolves symlinks the same way
/// at the cost of a real path lookup.
#[cfg(unix)]
type DirId = (u64, u64);
#[cfg(not(unix))]
type DirId = PathBuf;
/// The identity of the directory at `path`, or `None` when it cannot be
/// read — a dangling symlink, or a directory that vanished mid-walk.
#[cfg(unix)]
fn dir_id(path: &Path) -> Option<DirId> {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(path).ok()?;
Some((meta.dev(), meta.ino()))
}
#[cfg(not(unix))]
fn dir_id(path: &Path) -> Option<DirId> {
std::fs::canonicalize(path).ok()
}
/// True when `path` names one of the source files lucisv formats.
fn is_source(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
}
/// One directory walk. `rel` is the path of the directory currently being
/// read, in components relative to the walk root, which is what
/// `.gitignore` rules are matched against; `ignores` is the stack of
/// ignore files seen from the root down to it.
/// ignore files seen from the root down to it; `visited` is every directory
/// already entered, by identity rather than by spelling.
struct Walk<'a> {
exclude: &'a [String],
gitignore: bool,
ignores: Vec<Ignore>,
rel: Vec<String>,
files: &'a mut Vec<PathBuf>,
visited: HashSet<DirId>,
/// Where a source file goes when the walk finds one, with the length the
/// walk's own `metadata` call already read.
found: &'a mut dyn FnMut(PathBuf, Option<u64>),
warn: &'a mut dyn FnMut(Warning),
}
impl Walk<'_> {
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
let pushed = self.push_ignore(dir)?;
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
fn dir(&mut self, dir: &Path) {
if !self.enter(dir) {
return;
}
let pushed = self.push_ignore(dir);
self.entries(dir);
if pushed {
self.ignores.pop();
}
}
/// One directory's entries, in name order. A directory that cannot be read
/// — the permission-denied one somewhere under the start — is said and
/// skipped: everything already found stays found and the walk goes on,
/// which is the whole reason this channel exists.
fn entries(&mut self, dir: &Path) {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) => return self.say(dir, e.to_string()),
};
let mut entries = Vec::new();
for entry in read {
match entry {
Ok(entry) => entries.push(entry),
Err(e) => self.say(dir, e.to_string()),
}
}
entries.sort_by_key(|e| e.path());
for entry in entries {
let path = entry.path();
if is_excluded(&path, self.exclude) {
continue;
}
let is_dir = path.is_dir();
// One `metadata` call per entry, exactly as before — it follows
// symlinks, so it answers "directory?" for a symlinked directory
// the way `is_dir()` did. A dangling symlink has no metadata at
// all. One that *names a source file* is warned about and dropped:
// §43's QA was right that a silent skip loses the user the fact,
// and §45.2 gives that fact a home of its own rather than handing
// the path on to fail as "no such file" in the front end. One that
// names anything else was never going to be read, and is skipped
// as quietly as it always was.
let Ok(meta) = std::fs::metadata(&path) else {
if is_source(&path) {
let why = broken_link_reason(&path);
self.say(&path, why);
}
continue;
};
self.rel.push(entry.file_name().to_string_lossy().into_owned());
if !is_ignored(&self.ignores, &self.rel, is_dir) {
if is_dir {
self.dir(&path)?;
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
if EXTENSIONS.contains(&ext) {
self.files.push(path);
}
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
if meta.is_dir() {
self.dir(&path);
} else if meta.is_file() && is_source(&path) {
// The length comes off the `metadata` above — the same
// call that answered "directory?" — so a caller wanting it
// costs the walk nothing at all.
(self.found)(path, Some(meta.len()));
}
}
self.rel.pop();
}
if pushed {
self.ignores.pop();
}
Ok(())
}
/// Hand one warning to the front end.
fn say(&mut self, path: &Path, message: String) {
(self.warn)(Warning { path: path.to_path_buf(), message });
}
/// Records `dir` as entered, and answers whether it had not been entered
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
/// a directory the walk is already inside, and following either is the
/// cycle that only ends when the OS refuses a path. A symlink to a
/// directory the walk has *not* seen is followed once, so
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
/// one target contributes nothing further, and the files are reported
/// under the first spelling that reached them.
///
/// A directory whose identity cannot be read is not entered.
fn enter(&mut self, dir: &Path) -> bool {
dir_id(dir).is_some_and(|id| self.visited.insert(id))
}
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
/// Returns whether anything was pushed, so `dir` can pop it again.
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
///
/// An ignore file that cannot be read is said and ignored, for the same
/// reason an unreadable directory is: the walk that finds too much is a
/// better failure than the walk that finds nothing.
fn push_ignore(&mut self, dir: &Path) -> bool {
let path = dir.join(GITIGNORE);
if !self.gitignore || !path.is_file() {
return Ok(false);
return false;
}
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
self.ignores.push(Ignore { base: self.rel.len(), rules });
Ok(true)
match std::fs::read_to_string(&path) {
Ok(text) => {
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
true
}
Err(e) => {
self.say(&path, e.to_string());
false
}
}
}
}
/// Why a directory entry has no metadata, said the way a person would.
///
/// A broken symbolic link is what this is nearly always about, and naming it
/// as one is worth more than the bare `No such file or directory` the follow
/// produced; anything else keeps the operating system's own words.
fn broken_link_reason(path: &Path) -> String {
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
Ok(_) => "cannot be read".to_string(),
Err(e) => e.to_string(),
}
}
@@ -214,6 +459,8 @@ fn glob_component(pattern: &str, name: &str) -> bool {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::sync::atomic::{AtomicUsize, Ordering};
fn excluded(path: &str, pattern: &str) -> bool {
is_excluded(Path::new(path), &[pattern.to_string()])
@@ -320,6 +567,393 @@ mod tests {
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
}
// ------------------------------------------------------------------
// Symlink cycles — `docs/features/walk-cycles/README.md`
//
// Every test below builds a real tree with real symlinks, because the
// question is what the filesystem answers, not what a mock does. Each
// one would run until the OS refused a path before the visited set.
// ------------------------------------------------------------------
/// A throwaway directory tree under the system temp dir, removed on
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
/// a tree with a cycle in it is cleaned up like any other.
#[cfg(unix)]
struct TempTree {
path: PathBuf,
}
#[cfg(unix)]
impl TempTree {
fn new(tag: &str) -> TempTree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempTree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::fs::write(&path, text).expect("write");
}
/// A source file with enough in it to be worth finding.
fn source(&self, rel: &str) {
self.write(rel, "module m;\nendmodule\n");
}
/// Set `rel`'s permission bits. `0o000` is how a test builds the
/// directory the walk cannot read; the test puts them back so the
/// temp tree can be removed.
fn chmod(&self, rel: &str, mode: u32) {
use std::os::unix::fs::PermissionsExt;
let path = self.path.join(rel);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
.expect("set permissions");
}
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
/// directory — the spelling a checked-in symlink actually uses.
fn link(&self, rel: &str, target: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::os::unix::fs::symlink(target, &path).expect("symlink");
}
/// The walk from `rel` (empty for the root), as sorted paths
/// relative to the tree root. Warnings are dropped; the tests that
/// care about them call [`TempTree::warned`].
fn walk(&self, rel: &str) -> Vec<String> {
self.walked(rel).0
}
/// The same, plus what the walk said, each warning's path made
/// relative to the tree root so the assertions read.
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
self.walked(rel)
}
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
let mut files = Vec::new();
let mut warnings = Vec::new();
collect_files(
start.to_str().expect("utf-8 temp path"),
&[],
true,
&mut files,
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
)
.expect("the walk finishes");
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
out.sort();
warnings.sort();
(out, warnings)
}
fn rel_of(&self, path: &Path) -> String {
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
}
}
#[test]
#[cfg(unix)]
fn a_directory_linking_to_itself_is_entered_once() {
let tree = TempTree::new("selfloop");
tree.source("a/x.sv");
tree.link("a/loop", "../a");
assert_eq!(tree.walk(""), ["a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
let tree = TempTree::new("uplink");
tree.source("root.sv");
tree.source("a/x.sv");
tree.link("a/up", "..");
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
// root, which the walk has not seen yet and so does enter — once.
// Its own `a` is the directory already being walked, and stops.
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn two_links_to_one_directory_yield_its_files_once() {
let tree = TempTree::new("twolinks");
tree.source("shared/x.sv");
// Sorted after `shared`, so the real directory is the spelling that
// reaches the file first; whichever name wins, the file is reported
// exactly once.
tree.link("z1", "shared");
tree.link("z2", "shared");
assert_eq!(tree.walk(""), ["shared/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
let tree = TempTree::new("sibling");
tree.source("shared/rtl/x.sv");
tree.link("proj/rtl", "../shared/rtl");
// The `rtl -> ../shared/rtl` of a real checkout: the target is
// outside the walk, so the link is the only way to it.
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
// §43's review kept the dangling source link in the file list so the
// front end's "no such file" error survived. TODO §45.2 reverses that
// on purpose: the warning is now the error's home, so the link is said
// once here and never reaches the formatter. A dangling link that
// names no source file was never going to be read and stays silent.
let tree = TempTree::new("dangling");
tree.source("a/x.sv");
tree.link("a/gone.sv", "nowhere.sv");
tree.link("a/gonedir", "nowhere");
let (files, warnings) = tree.warned("");
assert_eq!(files, ["a/x.sv"]);
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
// The finding this channel exists for: one permission-denied directory
// used to propagate `read_dir`'s error out of the whole walk, dropping
// every file already found and failing the run.
let tree = TempTree::new("unreadable");
tree.source("a.sv");
tree.source("locked/hidden.sv");
tree.source("z/late.sv");
tree.chmod("locked", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod("locked", 0o755);
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
}
#[test]
#[cfg(unix)]
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
let tree = TempTree::new("lockedignore");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.chmod(".gitignore", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod(".gitignore", 0o644);
assert_eq!(files, ["keep.sv"]);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
}
#[test]
#[cfg(unix)]
fn a_clean_walk_says_nothing() {
let tree = TempTree::new("quiet");
tree.source("a/x.sv");
tree.source("b/y.sv");
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
}
#[test]
#[cfg(unix)]
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
let tree = TempTree::new("ignoredcycle");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.source("build/y.sv");
tree.link("build/loop", "../build");
assert_eq!(tree.walk(""), ["keep.sv"]);
}
// ------------------------------------------------------------------
// The metadata hand-off — `docs/features/perf5r-first-answer/README.md`
// ------------------------------------------------------------------
/// Every path `collect_files_with` yields under `rel`, with its length.
#[cfg(unix)]
fn walked_with(tree: &TempTree, rel: &str) -> Vec<(String, Option<u64>)> {
let start = if rel.is_empty() { tree.path.clone() } else { tree.path.join(rel) };
let mut out = Vec::new();
collect_files_with(
start.to_str().expect("utf-8 temp path"),
&[],
true,
&mut |path, len| out.push((tree.rel_of(&path), len)),
&mut |_| {},
)
.expect("the walk finishes");
out
}
#[test]
#[cfg(unix)]
fn the_metadata_entry_yields_exactly_the_paths_the_plain_one_does() {
// The claim the server's cap rests on: `collect_files` is
// `collect_files_with` with the length thrown away, so the two cannot
// disagree about which files exist — not about order, not about
// `.gitignore`, not about a symlink cycle, not about a broken link.
let tree = TempTree::new("handoffsame");
tree.write(".gitignore", "build\n");
tree.source("a.sv");
tree.source("rtl/b.sv");
tree.source("rtl/deep/c.svh");
tree.source("build/hidden.sv");
tree.write("rtl/notsource.txt", "x");
tree.link("rtl/loop", "..");
tree.link("rtl/dangling.sv", "nowhere.sv");
let mut plain = Vec::new();
collect_files(tree.path.to_str().expect("utf-8"), &[], true, &mut plain, &mut |_| {})
.expect("the walk finishes");
let plain: Vec<String> = plain.iter().map(|p| tree.rel_of(p)).collect();
let handed: Vec<String> =
walked_with(&tree, "").into_iter().map(|(path, _)| path).collect();
assert_eq!(plain, handed, "the same paths in the same order, byte for byte");
}
#[test]
#[cfg(unix)]
fn a_walked_file_carries_the_length_the_walk_already_read() {
let tree = TempTree::new("handofflen");
tree.write("small.sv", "module m;\nendmodule\n");
tree.write("big.sv", &"// pad\n".repeat(500));
let found = walked_with(&tree, "");
let sizes: Vec<(String, Option<u64>)> = found;
assert_eq!(
sizes,
[("big.sv".to_string(), Some(3_500)), ("small.sv".to_string(), Some(20))],
"the length is the file's own, not a guess"
);
}
#[test]
#[cfg(unix)]
fn a_path_named_directly_is_handed_over_without_a_stat() {
// `None` is the walk saying it did not look — the file was named, not
// walked to, and adding a `metadata` call for it would be a cost
// `collect_files` never paid.
let tree = TempTree::new("handoffnamed");
tree.source("one.sv");
let found = walked_with(&tree, "one.sv");
assert_eq!(found, [("one.sv".to_string(), None)]);
}
/// What `collect_files_below(root, root/rel)` finds, relative to the tree.
#[cfg(unix)]
fn below(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
let mut out = Vec::new();
collect_files_below(
&tree.path,
&tree.path.join(rel),
&patterns,
true,
&mut |path, _| out.push(tree.rel_of(&path)),
&mut |_| {},
)
.expect("the walk finishes");
out.sort();
out
}
/// What a walk of the whole tree finds under `rel` — the answer `below`
/// has to reproduce.
#[cfg(unix)]
fn whole_under(tree: &TempTree, rel: &str, exclude: &[&str]) -> Vec<String> {
let patterns: Vec<String> = exclude.iter().map(|p| p.to_string()).collect();
let mut out = Vec::new();
collect_files(tree.path.to_str().expect("utf-8"), &patterns, true, &mut out, &mut |_| {})
.expect("the walk finishes");
let prefix = format!("{rel}/");
let mut under: Vec<String> =
out.iter().map(|p| tree.rel_of(p)).filter(|p| p.starts_with(&prefix)).collect();
under.sort();
under
}
#[test]
#[cfg(unix)]
fn a_walk_that_starts_below_a_root_still_obeys_that_roots_gitignore() {
// The whole reason `collect_files_below` exists. Starting the walk at
// `hw/ip/aes` loses every rule written above it, and a scope whose
// rung *is* the root would then index files that scope excludes.
let tree = TempTree::new("belowignore");
tree.write(".gitignore", "gen/\n*_generated.sv\n");
tree.write("hw/.gitignore", "vendor/\n");
tree.source("hw/ip/aes/rtl/aes.sv");
tree.source("hw/ip/aes/rtl/aes_generated.sv");
tree.source("hw/ip/aes/gen/made.sv");
tree.source("hw/ip/aes/vendor/third.sv");
tree.source("hw/ip/aes/dv/tb.sv");
let seen = below(&tree, "hw/ip/aes", &[]);
assert_eq!(seen, ["hw/ip/aes/dv/tb.sv", "hw/ip/aes/rtl/aes.sv"]);
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
}
#[test]
#[cfg(unix)]
fn a_directory_the_root_walk_never_entered_yields_nothing_below_it() {
// An ancestor the root's own rules ignore is an ancestor the root walk
// never descended into, so nothing under it is in scope however
// directly it is named.
let tree = TempTree::new("belowblocked");
tree.write(".gitignore", "hw/vendor/\n");
tree.source("hw/vendor/ip/aes/aes.sv");
tree.source("hw/ip/aes/aes.sv");
assert!(below(&tree, "hw/vendor/ip/aes", &[]).is_empty());
assert_eq!(below(&tree, "hw/ip/aes", &[]), ["hw/ip/aes/aes.sv"]);
// An excluded ancestor is the same answer by the other filter.
assert!(below(&tree, "hw/ip/aes", &["ip"]).is_empty());
}
#[test]
#[cfg(unix)]
fn a_negation_below_the_root_still_wins_over_the_root_rule() {
// The precedence a root walk gives — deeper file last, so its `!` line
// re-includes — must survive the ancestor chain being pre-loaded.
let tree = TempTree::new("belownegate");
tree.write(".gitignore", "*.sv\n");
tree.write("hw/ip/aes/.gitignore", "!keep.sv\n");
tree.source("hw/ip/aes/keep.sv");
tree.source("hw/ip/aes/drop.sv");
let seen = below(&tree, "hw/ip/aes", &[]);
assert_eq!(seen, ["hw/ip/aes/keep.sv"]);
assert_eq!(seen, whole_under(&tree, "hw/ip/aes", &[]), "the root walk agrees");
}
#[test]
#[cfg(unix)]
fn a_start_that_is_not_under_the_root_finds_nothing() {
let tree = TempTree::new("belowoutside");
tree.source("a/x.sv");
let mut out = Vec::new();
collect_files_below(
&tree.path.join("a"),
&tree.path,
&[],
true,
&mut |path, _| out.push(path),
&mut |_| {},
)
.expect("no error, nothing found");
assert!(out.is_empty());
}
#[test]
fn unsupported_syntax_degrades_to_plain_globbing() {
// `**` is just two stars inside one component; documented.
+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)
+81 -13
View File
@@ -14,6 +14,7 @@ use lsp_types::{
use vlog_linter::{apply_fixes, rule_by_name, Applicability, Violation};
use crate::convert::Positions;
use crate::lint::LintRun;
use crate::state::Document;
/// The kind of the fix-everything action, namespaced under `source.fixAll` so
@@ -27,23 +28,41 @@ pub const FIX_ALL: &str = "source.fixAll.lucisv";
/// client, because a fix-on-save request asks for `source.fixAll.lucisv` alone
/// and computing every quick fix for it would be work nobody reads.
pub fn code_actions(
run: &LintRun,
uri: &Uri,
doc: &Document,
range: Range,
only: Option<&[CodeActionKind]>,
tab_width: usize,
) -> Vec<CodeActionOrCommand> {
let violations = crate::lint::fixable(run, doc);
// Timed apart from the lint pass that found them: a menu that is slow
// because it *renders* a thousand fixes is a different problem from one
// that is slow because it found them (review round §R1b).
let actions = crate::lint_trace::stage(crate::lint_trace::Stage::Serialize, || {
offered(uri, doc, range, only, &violations)
});
crate::lint_trace::saw_actions(actions.len());
actions
}
/// The quick fixes and the fix-all action `only` asks for, built from
/// violations already found.
fn offered(
uri: &Uri,
doc: &Document,
range: Range,
only: Option<&[CodeActionKind]>,
violations: &[Violation],
) -> Vec<CodeActionOrCommand> {
let positions = doc.positions();
let violations = crate::lint::fixable(doc, tab_width);
let mut actions = Vec::new();
if wanted(only, &CodeActionKind::QUICKFIX) {
let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range));
actions.extend(quick.map(CodeActionOrCommand::CodeAction));
}
if wanted(only, &CodeActionKind::new(FIX_ALL)) {
actions.extend(
fix_all(uri, doc, &positions, &violations).map(CodeActionOrCommand::CodeAction),
);
actions
.extend(fix_all(uri, doc, &positions, violations).map(CodeActionOrCommand::CodeAction));
}
actions
}
@@ -131,6 +150,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.
@@ -170,7 +201,7 @@ mod tests {
fn actions_of(ws: &Workspace) -> Vec<CodeAction> {
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
code_actions(&uri(), doc, whole, None, 2)
code_actions(&LintRun::default(), &uri(), doc, whole, None)
.into_iter()
.map(|a| match a {
CodeActionOrCommand::CodeAction(action) => action,
@@ -248,7 +279,13 @@ mod tests {
start: Position { line: 1, character: 0 },
end: Position { line: 1, character: 0 },
};
let actions = code_actions(&uri(), doc, line1, Some(&[CodeActionKind::QUICKFIX]), 2);
let actions = code_actions(
&LintRun::default(),
&uri(),
doc,
line1,
Some(&[CodeActionKind::QUICKFIX]),
);
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
}
@@ -320,14 +357,19 @@ mod tests {
start: Position { line: fenced_line, character: 0 },
end: Position { line: fenced_line, character: 0 },
};
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
let actions =
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]));
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
// The unfenced tab one line further down still has one.
let at = Range {
start: Position { line: 4, character: 0 },
end: Position { line: 4, character: 0 },
};
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
assert_eq!(
code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]),)
.len(),
1
);
}
#[test]
@@ -370,14 +412,14 @@ mod tests {
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2);
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only));
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
// `source` is a prefix filter for `source.fixAll.lucisv`.
let source = [CodeActionKind::SOURCE];
assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1);
assert_eq!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source)).len(), 1);
// And an unrelated filter selects nothing.
let refactor = [CodeActionKind::REFACTOR];
assert!(code_actions(&uri(), doc, whole, Some(&refactor), 2).is_empty());
assert!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor)).is_empty());
}
#[test]
@@ -386,7 +428,13 @@ mod tests {
let ws = workspace(text);
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let actions = code_actions(&uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), 4);
let actions = code_actions(
&LintRun::default().with_tab_width(4),
&uri(),
doc,
whole,
Some(&[CodeActionKind::QUICKFIX]),
);
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
}
@@ -407,4 +455,24 @@ mod tests {
assert!(out.contains("é 🎉"), "comments are never dropped: {out:?}");
assert_eq!(out, "module m;\n // é 🎉 wire a;\nendmodule\n");
}
#[test]
fn an_externally_waived_finding_gets_no_quick_fix_and_fix_all_leaves_it() {
// §39 QA's HIGH: `fixable` used `default_rules()` and no waivers, so
// fix-on-save rewrote a line a checked-in waiver file had waived.
let src = "module m;\n\twire a;\nendmodule\n";
let ws = workspace(src);
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let waived = LintRun::default()
.with_waivers(std::path::Path::new("team.waiver"), "waive --rule=no-tabs\n");
assert!(
code_actions(&waived, &uri(), doc, whole, None).is_empty(),
"no quick fix and no fix-all for a waived finding"
);
assert!(
!code_actions(&LintRun::default(), &uri(), doc, whole, None).is_empty(),
"the same buffer without the waiver is fixable"
);
}
}
+61 -3
View File
@@ -14,7 +14,7 @@ use std::collections::HashSet;
use lsp_types::CompletionResponse;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{MemberSite, Semantics, SymbolKind, WorkspaceIndex};
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
use super::site::balanced;
use super::tiers::innermost_scope;
@@ -168,6 +168,14 @@ fn members_at(
site: &MemberSite,
) -> Vec<Member> {
let mut members = Members::new();
// A cross-file site says which surface its own tail resolution reads, and
// the list follows it: behind `u_x.` in an *expression* that is the
// module's hierarchical surface — its nets, variables and instances as
// well as its ports and parameters — which is exactly what the in-file
// `MemberSite::Scope` half above offers for an instance this file
// declares. A connection list's `.` never arrives here; it is
// `connection_members` below, and it is the connection surface.
let mut surface = Surface::Connection;
let base = match site {
MemberSite::Scope(scope) => {
let (scopes, base) = semantics.member_scopes(*scope);
@@ -181,10 +189,13 @@ fn members_at(
// overlay's own inheritance chase does.
base.map(|path| last_segment(&path).to_string())
}
MemberSite::Unit(unit) => Some(unit.clone()),
MemberSite::Unit { path, surface: reads } => {
surface = *reads;
Some(path.clone())
}
};
if let Some(unit) = base {
for (name, def) in index.members_of_chain(&unit) {
for (name, def) in index.members_of_chain_in(&unit, surface) {
members.push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
@@ -983,6 +994,53 @@ endmodule
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
/// *expression* the list is the module's **hierarchical** surface — its
/// nets, its variables and its instances as well as its ports and its
/// parameters — because that is what a hierarchical path may name and
/// exactly what the tail resolution will find, so every item offered is
/// an item hover and go-to-definition answer. Behind the `.` of a
/// **connection list** it is the connection surface and nothing more:
/// `.internal(w)` is not a legal connection, and an item the resolution
/// could not find is a wrong answer rather than a generous one.
#[test]
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
let hierarchical = {
let tree = Tree::new("hiersurface_expr");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(
hierarchical,
vec!["clk", "counter", "internal", "u_leaf"],
"the port and the three hierarchical-only members"
);
let connection = {
let tree = Tree::new("hiersurface_conn");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
+41 -31
View File
@@ -528,39 +528,49 @@ mod tests {
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// anywhere near its header — right after its name, or on one of its
/// ports — is not indexed as a `Module` unit **at all**.
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
/// at the very first line (no `[def]` to anchor on) before the whitelist
/// walk ever runs, and completion's module tier — which sources its
/// candidate names from the same table — never offers the module in the
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
/// completion-core one: it is filed in `docs/features/completion-core/
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
/// outside this round's touched files. The two "attribute" shapes this QA
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
/// because both sides of that comparison fall back to the same whole-file
/// parse, which this test makes explicit rather than leaving it as an
/// unremarked side effect of the pin.
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
for module in ["attributed", "port_attributed"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units(module).is_empty(),
"{module}: if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(
module_header(&index, module, text).is_none(),
"{module}: no unit to anchor on"
);
}
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
@@ -513,6 +513,20 @@ endmodule
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
@@ -896,6 +910,30 @@ endmodule
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
+31
View File
@@ -156,6 +156,37 @@ mod tests {
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
}
/// The user-visible contract of header recovery (TODO §32), pinned where
/// the user meets it: a typo in a port list costs **one** diagnostic, and
/// the module around it survives whole — its name, the ports typed before
/// and after the typo, and its body all still in the outline.
///
/// Before this round the same buffer published two errors (the header, and
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
/// the outline had no module in it at all.
#[test]
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 1, "{diags:#?}");
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
// The missing-closer pass explains a *parse* failure; there is no
// unclosed block here, so it must add nothing.
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
let symbols = crate::symbols::document_symbols(doc);
assert_eq!(symbols.len(), 1, "the module is still in the outline");
assert_eq!(symbols[0].name, "m");
let children = symbols[0].children.as_ref().expect("module contents");
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
assert!(names.contains(&"b"), "the port after it: {names:?}");
assert!(names.contains(&"ok"), "the body: {names:?}");
}
#[test]
fn a_lex_error_gets_a_visible_range() {
// The lexer gives up at end of file, which a trailing newline makes
+466
View File
@@ -0,0 +1,466 @@
//! 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,
};
// No preflight here, and the take 5 review round (§61.1) is why: every
// refusal one could take is already taken before a scope is built. The
// `site_at` gate above **is** `extract_site_in`, which returns `None` on a
// parse diagnostic and on every `Region::read` refusal, so neither can
// reach the engine; and `extract_module` checks the new name and the
// occupied target as its own first two statements, ahead of
// `Extraction::plan`. The 805 ms at `aes_wrap.sv` is none of those — it is
// `boundary::Crossing::read`, which needs the instantiated modules' port
// directions and so needs the scope. See
// `docs/features/perf5r-preflight/README.md`.
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));
}
// ------------------------------------------------------------------
// Where the extract refusals are actually taken (take 5 review §3 item 5,
// TODO §61.1). No preflight was added — every refusal below is already
// reached before a scope exists, and these pin that it stays so.
// ------------------------------------------------------------------
fn run(
ws: &Workspace,
uri: &Uri,
range: Range,
name: &str,
create: bool,
) -> Result<(), String> {
let arguments = vec![
serde_json::to_value(uri).expect("uri"),
serde_json::to_value(range).expect("range"),
Value::String(name.to_string()),
];
execute(ws, &arguments, create).map(|_| ())
}
/// A bad new name is refused by `extract_module`'s own first statement,
/// and a selection covering no whole item is refused by the `site_at` gate
/// — neither reaches `Extraction::plan`, so neither builds a scope.
#[test]
fn the_cheap_refusals_reach_the_wire_in_the_engines_words() {
let tree = Tree::new("preflightrefusals");
let (ws, uri) = opened(&tree);
let bad = run(&ws, &uri, selection(), "1bad", true).expect_err("a bad name");
assert!(bad.contains("plain SystemVerilog identifier"), "{bad}");
// Half of `assign s = a + b;`, which covers no whole item.
let partial = Range {
start: Position { line: 6, character: 6 },
end: Position { line: 6, character: 19 },
};
assert_eq!(
run(&ws, &uri, partial, "sum", true),
Err(NOTHING.to_string()),
"the `site_at` gate answers a partial selection before the engine is asked"
);
}
/// A file already sitting where the new module would go is refused before
/// `Extraction::plan`, and the question is asked of the source set the
/// engine was handed rather than of the disk behind its back.
#[test]
fn an_occupied_target_is_refused_with_the_engines_sentence() {
let tree = Tree::new("preflightoccupied");
tree.write("sum.sv", "module sum;\nendmodule\n");
let (ws, uri) = opened(&tree);
let refusal = run(&ws, &uri, selection(), "sum", true).expect_err("occupied");
assert!(refusal.contains("there is already a"), "{refusal}");
assert!(refusal.contains("sum.sv"), "and it names the file: {refusal}");
// Into the same file nothing is occupied, so the early check passes
// and the engine refuses for its own, later reason: the workspace
// already declares that name — an index question, answered by the
// stage that owns the index.
let deferred = run(&ws, &uri, selection(), "sum", false).expect_err("already declared");
assert!(deferred.contains("the workspace already declares"), "{deferred}");
}
/// The control: a whole, movable item still extracts.
#[test]
fn a_whole_movable_selection_still_extracts() {
let tree = Tree::new("preflightok");
let (ws, uri) = opened(&tree);
assert!(run(&ws, &uri, selection(), "sum", true).is_ok());
}
}
+40
View File
@@ -0,0 +1,40 @@
//! 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))
}
/// Whether the answer is already in hand — asked *before* [`of`], so a
/// `--verbose` trace can say whether this request paid the parse or read the
/// memo (review round §R1b, `crate::lint_trace`). Decides nothing.
pub fn held(doc: &Document) -> bool {
doc.fences.get().is_some()
}
+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] {
+488 -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
@@ -123,6 +215,28 @@ impl IndexCache {
self.dir.as_deref()
}
/// The entry that asserts *exactly these bytes*, if there is one.
///
/// The one place the record and the key it is filed under are read
/// together: an entry holds the FNV-1a of the bytes its facts were read
/// off, and this is the only comparison anything in the server makes
/// against it. Both readers below go through here, so "the store answers
/// for this text" means one thing in a scan and in a refactoring alike.
fn entry_for(&self, path: &Path, text: &str) -> Option<&Entry> {
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()))
}
/// [`IndexCache::facts_for`] asked by something that is **not** a scan.
///
/// The same question, the same entry, the same answer — but the work is
/// not counted into [`IndexCache::work`], because that counter is what a
/// scan's own trace subtracts to say what *it* did. A refactoring reading
/// records between two scans would otherwise show up as decodes the next
/// scan never made (review round §R3b, `crate::state::Workspace::known_facts`).
pub fn facts_now(&self, path: &Path, text: &str) -> Option<FileFacts> {
FileFacts::decode(&self.entry_for(path, text)?.facts)
}
/// The facts a previous session read off this exact text, if it did.
///
/// The hash is of the text the server is about to index — an open buffer's
@@ -133,11 +247,27 @@ 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.entry_for(path, text);
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 +279,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 +324,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 +564,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
@@ -507,6 +734,42 @@ mod tests {
assert!(reopened.facts_for(Path::new("/nowhere.sv"), M).is_none());
}
/// **The R3b tie, both ways.** `facts_now` is the same content key
/// `facts_for` is — a record answers for the bytes it was read off and for
/// no others — and it leaves the scan's own work counters alone.
///
/// The stale case is the one that matters: a record written from one text
/// must never be handed to a refactoring reading a different text, because
/// the refactoring would index it as that file's facts and edit against an
/// index describing bytes nobody has.
#[test]
fn a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work() {
let dir = TempDir::new("factsnow");
let file = dir.file("m.sv", M);
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.record(&facts(&file, M), M);
cache.compact();
let reopened = IndexCache::open(Some(dir.path.clone()));
let before = reopened.work();
assert_eq!(reopened.facts_now(&file, M), Some(facts(&file, M)), "these bytes");
// Every way the bytes can differ, and the wrong path too.
const EDITED: &str = "module m;\n sub u ();\n wire added;\nendmodule\n";
assert!(reopened.facts_now(&file, EDITED).is_none(), "a stale record must not be served");
assert!(reopened.facts_now(&file, "").is_none(), "nor an empty buffer's");
assert!(reopened.facts_now(&file, &M[..M.len() - 1]).is_none(), "nor one byte short");
assert!(reopened.facts_now(Path::new("/nowhere.sv"), M).is_none(), "nor another path's");
let after = reopened.work();
assert_eq!(
(after.hits, after.misses, after.decode_ns, after.lookup_ns),
(before.hits, before.misses, before.decode_ns, before.lookup_ns),
"a refactoring's reads are not a scan's work"
);
// The counted reader, asked the same questions, answers the same way.
assert_eq!(reopened.facts_for(&file, M), reopened.facts_now(&file, M));
assert_eq!(reopened.facts_for(&file, EDITED), reopened.facts_now(&file, EDITED));
}
#[test]
fn a_record_survives_a_session_that_never_compacted() {
// The crash case: records are written through as they are made, so a
@@ -720,6 +983,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,
+120 -4
View File
@@ -22,7 +22,7 @@
use std::collections::HashMap;
use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::ast::{Connection, Connections, Expr, Instance, Instantiation, ListElem};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
@@ -84,6 +84,13 @@ enum Kind {
/// name is written somewhere in the same list.
fn param_sites(inst: &Instantiation) -> Vec<Site> {
let Some(params) = &inst.params else { return Vec::new() };
// A list a tolerant parse recovered inside gets no hints either: which
// parameter a position names is exactly what the skipped text decides, so
// any hint here would be a guess, and a wrong hint is worse than none.
if params.iter().any(ListElem::is_error) {
return Vec::new();
}
let params: Vec<&Connection> = params.iter().filter_map(ListElem::ok).collect();
if params.iter().any(|param| !param.name.is_empty()) {
return Vec::new();
}
@@ -99,7 +106,16 @@ fn param_sites(inst: &Instantiation) -> Vec<Site> {
/// instance: the connections are the module's ports either way.
fn port_sites(instance: &Instance) -> Vec<Site> {
let Connections::Ordered(conns) = &instance.conns else { return Vec::new() };
conns.iter().enumerate().filter_map(|(index, conn)| site(index, conn.expr.as_ref())).collect()
// As in `param_sites`: a recovered list's positions are a guess.
if conns.iter().any(ListElem::is_error) {
return Vec::new();
}
conns
.iter()
.filter_map(ListElem::ok)
.enumerate()
.filter_map(|(index, conn)| site(index, conn.expr.as_ref()))
.collect()
}
/// A site at the start of `expr`, or nothing for an omitted position
@@ -542,10 +558,23 @@ endmodule
assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉");
}
/// A buffer mid-edit still hints where the *positions* are known, and
/// stops where they are not.
///
/// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n`
/// used to fail to parse at all, so there was nothing to hint from. Now
/// the instantiation survives with both positional connections, and both
/// are at the index they were written at, so both are hinted. The second
/// half is the rule that replaces "does not parse": a list the parser
/// *recovered* inside holds text nobody can index, so `port_sites` and
/// `param_sites` decline the whole list rather than mislabel what follows
/// the hole.
#[test]
fn a_buffer_that_does_not_parse_hints_nothing_rather_than_guessing() {
fn a_truncated_list_hints_and_a_recovered_one_does_not() {
let top = "module top;\n sub u1 (clk, rst_n\n";
assert!(hints_of("broken", top).is_empty());
assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]);
let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n";
assert!(hints_of("recovered", holed).is_empty());
}
#[test]
@@ -563,6 +592,7 @@ endmodule
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let insts = instantiations::sites(&tree.items);
let params = insts[0].inst.params.as_ref().expect("a `#( ... )`");
let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect();
assert_eq!(params[0].name, "", "`8` names nothing");
assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does");
}
@@ -725,6 +755,92 @@ endmodule
assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]);
}
// ------------------------------------------------------------------
// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8)
// ------------------------------------------------------------------
/// An opentitan-shaped tree: an IP block with its RTL and its testbench,
/// and a shared library folder outside that block. Opening
/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to
/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is
/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against
/// `hw/dv/sv/common_ifs/pins_if.sv`.
fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) {
const TB: &str =
"module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n";
let tree = Tree::new(name);
fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs");
fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs");
fs::create_dir_all(tree.path.join("dv/common")).expect("dirs");
tree.write("ip/aes/rtl/sub.sv", SUB);
tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n");
let tb = tree.write("ip/aes/dv/tb/tb.sv", TB);
let mut ws = Workspace::default();
// The shipped default: no `index.scope`, `scopeDepth` 2.
ws.set_client_settings(crate::settings::ClientSettings::default());
ws.adopt_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&tb).expect("uri");
ws.set_document(uri.clone(), TB.to_string());
ws.rebuild_index();
(tree, ws, uri, TB)
}
#[test]
fn the_default_scope_hints_a_module_the_didopen_widen_reached() {
// `performance_take2.md` §4b measured 0 hints at the default scope
// where the workspace scope gives 4, and §8 filed it as a correctness
// gap. It is not one: the hints that scope answers are exactly the
// instantiations whose module the widen reached.
let (tree, ws, uri, _) = default_scoped("default_scope");
assert!(
ws.index().files().iter().any(|f| f.ends_with("sub.sv")),
"the widen reached the block's own RTL: {:?}",
ws.index().files()
);
assert!(
!ws.index().files().iter().any(|f| f.ends_with("far.sv")),
"and not the library folder beside it"
);
let hints = inlay_hints(&ws, &uri, everything());
let labels: Vec<String> = hints
.into_iter()
.map(|h| {
let InlayHintLabel::String(s) = h.label else { panic!("string") };
s
})
.collect();
assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted");
drop(tree);
}
#[test]
fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() {
// The other half of the same finding: the `far` instantiation gets no
// hints — and go-to-definition and hover give nothing for it either.
// The zero is the scope's, not this module's; inlay uses the same
// `module_definition` lookup its neighbours do.
let (tree, ws, uri, tb) = default_scoped("out_of_scope");
let hints = inlay_hints(&ws, &uri, everything());
assert!(
hints.iter().all(|hint| hint.position.line != 2),
"nothing on the `far` line: {hints:#?}"
);
let far = tb.find("far u_far").expect("the instantiation") as u32;
assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer");
assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover");
// And the moment the scope reaches it, all three answer.
let mut wide = Workspace::default();
wide.open_whole_workspace(vec![tree.path.clone()]);
wide.set_document(uri.clone(), tb.to_string());
let hints = inlay_hints(&wide, &uri, everything());
assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}");
assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1);
}
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
/// timing assertions in a shared CI runner are flaky by nature. Run with
/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`.
+40 -4
View File
@@ -575,6 +575,7 @@ mod tests {
use crate::uri::path_to_uri;
use std::path::PathBuf;
use std::str::FromStr;
use vlog_parser::PARSE_STACK_SIZE;
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
/// No files on disk: nothing here reads the index.
@@ -1081,10 +1082,31 @@ endmodule
// A trailing newline, so this test isolates depth from the separate
// true-end-of-file `Eof`-adjacency case pinned above.
text.push_str("initial begin\n");
let (ws, uri, position) = asking(&text, "initial begin");
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
let items = inline_completions(&ws, &uri, position);
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
// Opening the document *parses* it, and since §36.1 a bare `begin` at
// item scope is a generate block the tolerant parser descends into —
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
// MiB of stack in a debug build. That is exactly what
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
// parse is given it (`main.rs`), libtest's own thread is not, so the
// body runs on one of its own. Nothing here is about the inline path,
// which still never recurses.
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
.spawn(move || {
let (ws, uri, position) = asking(&text, "initial begin");
assert!(
!ws.document(&uri).expect("open").tokens.is_empty(),
"the lexer never recurses"
);
let items = inline_completions(&ws, &uri, position);
assert!(
items.is_some(),
"the innermost, truly unclosed `begin` still offers its `end`"
);
})
.expect("spawn")
.join()
.expect("the inline path crashed");
}
#[test]
@@ -1894,6 +1916,20 @@ sub #(
}
}
/// The premise the "the accepted text must parse" probe above rests on:
/// the probe can still fail. Header recovery (TODO §32) widened what a
/// tolerant parse reads — a half-typed connection list is now a recovered
/// instantiation rather than a dead item — so the probe is only worth
/// asking while text that does not parse still says so.
#[test]
fn the_accepted_text_probe_still_reports_text_that_does_not_parse() {
let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n";
assert!(
!vlog_parser::parse_source_tolerant(probe).1.is_empty(),
"recovery must not make a broken instantiation look clean"
);
}
#[test]
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
let top = "module top;\n bare \nendmodule\n";
+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));
}
}
+1
View File
@@ -144,6 +144,7 @@ fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
ItemKind::Task(t) => task_pairs(t, out),
ItemKind::Clocking(c) => clocking_pairs(c, out),
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
ItemKind::GenIf(g) => gen_if_pairs(g, out),
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
ItemKind::GenCase(g) => {
+598 -39
View File
@@ -10,19 +10,34 @@
//! table `lucisv.toml` now carries. See
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
//!
//! Since §42 the two halves of that selection are one contract: the editor's
//! settings play the role the CLI's flags play, and the project's `[lint]`
//! table is what stands when the editor says nothing —
//! `docs/features/lint-config-contract/README.md`, and [`project`] for the
//! project's half.
mod project;
pub use project::{ConfigProblems, ProblemLog, ProjectLint};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use lucisv_core::config::FileConfig;
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
Severity, Violation,
default_rules, lint_with, workspace_rules, Exports, ExternalWaivers, LintContext,
MentionOracle, ModuleInterface, Rule, RuleOptions, Severity, Violation,
};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
use crate::convert::Positions;
use crate::diagnostics::SOURCE;
use crate::lint_snapshot::{Key, Slot};
use crate::lint_trace::{self, Fences, Reuse, Stage};
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
@@ -35,14 +50,65 @@ use crate::state::{Document, Workspace};
pub struct LintRun<'a> {
rules: Vec<&'static dyn Rule>,
oracle: Option<IndexMentions<'a>>,
/// What the buffer's `lucisv.toml` and the editor's settings configured
/// about each rule, merged. Empty means every rule reads its own default.
options: RuleOptions,
/// The width `line-length` holds this buffer to — the width the formatter
/// would wrap it to, so the two halves of lucisv cannot disagree.
line_length: usize,
/// The width a `no-tabs` fix writes where a tab was — the same ladder
/// `format::indent_width` walks, read off the `FileConfig` this pass
/// already discovered.
///
/// On the run rather than passed to [`fixable`] since the review round's
/// §R1a: the diagnostics pass and the quick-fix pass must build the *same*
/// `LintContext` to share one snapshot. Nothing published moves — the
/// width reaches only `no-tabs`' fix *text*, and the diagnostics path
/// never reads a fix.
tab_width: usize,
/// The external waiver files in force for this buffer, from its
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
/// configured, and then costing the pass nothing.
external: ExternalWaivers,
/// Those files' paths and contents, in the order they were read — the
/// snapshot key's row 7. Empty when no waiver file is configured.
///
/// **Written in the same step as `external`**, by `waiver_files` and by
/// `with_waivers` and by nothing else, so a run can never carry a waiver
/// its key cannot see. A run whose key missed a waiver would offer a fix
/// for a finding the waiver had silenced, which is the stale-fix failure
/// this whole key exists to prevent.
waiver_texts: Vec<(PathBuf, String)>,
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
/// (config file, message) — and never fatal here: §42.2.
problems: ConfigProblems,
}
impl Default for LintRun<'_> {
fn default() -> LintRun<'static> {
LintRun { rules: default_rules(), oracle: None }
LintRun {
rules: default_rules(),
oracle: None,
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
tab_width: DEFAULT_TAB_WIDTH,
external: ExternalWaivers::default(),
waiver_texts: Vec::new(),
problems: ConfigProblems::default(),
}
}
}
/// The width a buffer is held to when neither its `lucisv.toml` nor the
/// editor says otherwise — `vlog_formatter::Config`'s own default.
const DEFAULT_LINE_LENGTH: usize = 100;
/// The indent width a buffer's fixes are written at when neither its
/// `lucisv.toml` nor the editor says otherwise — `vlog_formatter::Config`'s
/// own default, which is what `format::indent_width` falls back to.
const DEFAULT_TAB_WIDTH: usize = 2;
impl<'a> LintRun<'a> {
/// The pass this workspace's settings and index describe for one buffer.
///
@@ -53,17 +119,67 @@ impl<'a> LintRun<'a> {
/// cross-file evidence behind them, which is the false-positive mode this
/// whole round exists to close.
pub fn for_document(ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
LintRun { rules, oracle }
// Two stages, so `--verbose` can say which of them the request spent
// its milliseconds in: everything read from disk, then everything
// decided from what was read (review round §R1b, `crate::lint_trace`).
let found = lint_trace::stage(Stage::Config, || Discovered::read(ws, doc));
lint_trace::saw_config(found.file.source.is_some(), found.texts.len());
lint_trace::stage(Stage::Build, || found.into_run(ws, doc))
}
/// What this buffer's `lucisv.toml` asked for and did not get, for a
/// caller that can tell the user about it.
pub fn config_problems(&self) -> &ConfigProblems {
&self.problems
}
/// A run carrying this waiver file — for the tests that pin what a waiver
/// keeps out of the code actions.
///
/// Takes the file's **text**, not a parsed `ExternalWaivers`, for the same
/// reason `waiver_files` returns both: the waivers a run lints with and
/// the texts its snapshot key holds must be written in one step, or a run
/// could carry waivers its key cannot see. The bad-line messages are
/// dropped here; the caller asserts about them itself where it cares.
#[cfg(test)]
pub(crate) fn with_waivers(mut self, path: &Path, text: &str) -> Self {
self.external.absorb(ExternalWaivers::parse(path, text).0);
self.waiver_texts.push((path.to_path_buf(), text.to_string()));
self
}
/// A run whose fixes are written at this indent width — for the tests
/// that pin what a `no-tabs` fix writes. The server itself reads the
/// width off the buffer's own configuration in [`Discovered::read`].
#[cfg(test)]
pub(crate) fn with_tab_width(mut self, tab_width: usize) -> Self {
self.tab_width = tab_width;
self
}
/// What this run would lint with, as the snapshot compares it.
///
/// Every field is an argument of the `lint_with` call it guards; the
/// buffer itself and the workspace index are settled by identity and by
/// `Document::refresh_overlay` instead. The feature README's table is the
/// whole argument.
fn key(&self) -> Key {
Key {
rules: self.rules.iter().map(|rule| rule.name()).collect(),
options: self.options.clone(),
line_length: self.line_length,
tab_width: self.tab_width,
has_oracle: self.oracle.is_some(),
waivers: self.waiver_texts.clone(),
}
}
/// This run's context over a buffer's own parse products.
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
let ctx = context(doc);
let ctx = context(doc)
.with_options(&self.options)
.with_line_length(self.line_length)
.with_tab_width(self.tab_width);
match &self.oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
@@ -71,32 +187,250 @@ impl<'a> LintRun<'a> {
}
}
/// Which rules a buffer is linted with, given what the editor's settings say.
/// Everything one lint pass reads **from disk**: the `lucisv.toml` governing
/// the buffer, what its `[lint]` table said, and the external waiver files in
/// force.
///
/// Split out of [`LintRun::for_document`] so the I/O has a name and a stage of
/// its own on the `--verbose` channel — "config read plus lint" was as far as
/// take 5 §P1 could attribute the pinmux menu's 23 ms, and that is two
/// answers. Nothing about *what* is read changed: the calls below are
/// `for_document`'s own, in its own order, so the messages a config problem
/// produces arrive in the order §42.2 fixed.
struct Discovered {
options: RuleOptions,
line_length: usize,
tab_width: usize,
file: FileConfig,
project: ProjectLint,
external: ExternalWaivers,
/// Each waiver file's path and the text it was parsed from — the
/// snapshot key's only I/O-derived field.
texts: Vec<(PathBuf, String)>,
messages: Vec<String>,
}
impl Discovered {
/// One discovery for the whole pass: the selection, the options, the
/// width, the indent and the waiver paths all read the same `FileConfig`,
/// so reading the project's rules costs no extra stat and no extra open.
fn read(ws: &Workspace, doc: &Document) -> Discovered {
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
let (project, bad_names) = ProjectLint::read(&file);
messages.extend(bad_names);
let (mut external, bad_waivers, mut texts) = waiver_files(&project_waivers(&file));
messages.extend(bad_waivers);
// The editor's own waiver files are read separately and their
// problems dropped: `notification::apply_settings` already said them
// once, where the setting arrived.
let editor = waiver_files(&editor_waivers(ws.client_settings(), ws.roots()));
external.absorb(editor.0);
texts.extend(editor.2);
// `format::indent_width` stays the one authority on the indent ladder
// (`lucisv.toml` > `lucisv.indent` > the formatter's default): reading
// it here rather than spelling the ladder a second time costs a second
// `Discovery` walk, which the R1b trace measures at hundredths of a
// millisecond against a 21 ms pass.
let tab_width = crate::format::indent_width(doc.path.as_deref(), ws.client_settings());
Discovered { options, line_length, tab_width, file, project, external, texts, messages }
}
/// What this buffer's index and settings make of it: the census oracle and
/// the rule ladder, neither of which touches the filesystem.
fn into_run<'a>(self, ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let oracle = workspace.then_some(IndexMentions { index, own });
let rules = enabled_rules(ws.client_settings(), &self.project, workspace);
let problems = ConfigProblems::new(&self.file, self.messages);
LintRun {
rules,
oracle,
options: self.options,
line_length: self.line_length,
tab_width: self.tab_width,
external: self.external,
waiver_texts: self.texts,
problems,
}
}
}
/// The per-rule options and the line width governing one buffer.
///
/// **Precedence for an option, highest first: the editor, then the buffer's
/// `lucisv.toml`, then the rule's own default — key by key**, so a project
/// that sets two options and a user who overrides one keep the other. This is
/// deliberately the *opposite* order to `format::settings_for`, where a
/// checked-in `lucisv.toml` outranks the editor: formatting has a byte-exact
/// contract with CI that a user's editor must not break, while a lint option
/// changes which findings that user is shown in their own editor and is
/// theirs to set. §34.0(d).
///
/// The **width** follows the formatting ladder instead, because it is not a
/// lint setting at all: it is the width the formatter would wrap this buffer
/// to, read the same way `format::settings_for` reads it, so a line lucisv
/// wrote is never a line lucisv calls too long. `line-length`'s own `length`
/// option still beats it — that is the rule's own business, and the rule
/// applies it.
///
/// The config file is read here, per pass, exactly as `format::discover`
/// reads it per formatting request: a `lucisv.toml` edited while the server
/// runs takes effect at the next publish, and the read is a few stats beside
/// a parse and an analysis the same pass already paid for.
fn configured(
client: &ClientSettings,
doc: &Document,
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
let file = doc
.path
.as_deref()
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
.unwrap_or_default();
let mut options = RuleOptions::new();
let mut problems = Vec::new();
for entry in &file.lint_options {
// A broken entry in the file is dropped rather than fatal — an editor
// cannot fail a run — but it is *said*, in the words `lucisv check`
// fails with, once per (config file, entry): §42.2. Silently dropping
// it left a user's option doing nothing with nothing to read about it.
if let Err(problem) = options.set_raw(&entry.rule, &entry.key, &entry.raw) {
let source = file
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
problems.push(format!("{source}:{}: rule `{}` {problem}", entry.line, entry.rule));
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
(options, width, file, problems)
}
/// The waiver files governing one buffer: its `lucisv.toml`'s `[lint] waivers`
/// first, then `lucisv.lint.waivers` from the editor.
///
/// The two **add up**, the way they do on the command line — a waiver file
/// only ever suppresses findings, so there is nothing here for one list to
/// take back from the other. A relative setting path is resolved against the
/// first workspace root, exactly as `lucisv.filelist` is; a `lucisv.toml`'s
/// paths were already resolved against that file's own directory.
pub fn waiver_paths(client: &ClientSettings, roots: &[PathBuf], file: &FileConfig) -> Vec<PathBuf> {
let mut paths = project_waivers(file);
paths.extend(editor_waivers(client, roots));
paths
}
/// The `[lint] waivers` of one config file, already resolved by `Discovery`
/// against that file's own directory.
///
/// Read apart from the editor's since §42.2, because a problem in one of
/// *these* is the project's and belongs in the output channel with the
/// `lucisv.toml` that named it, while a problem in the editor's was already
/// said where the setting arrived.
fn project_waivers(file: &FileConfig) -> Vec<PathBuf> {
file.lint_waivers.iter().flatten().cloned().collect()
}
/// The waiver files `lucisv.lint.waivers` names, a relative one anchored at
/// the first workspace root exactly as `lucisv.filelist` is.
fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
client
.lint_waivers
.iter()
.map(|setting| {
let path = Path::new(setting);
match roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
}
})
.collect()
}
/// Those files, read: the waivers and one message per file or line that could
/// not be used.
///
/// **Nothing here is fatal.** A push arrives on a socket and a bad path in it
/// must never cost a user every diagnostic in their file — this module's
/// standing rule, and `settings::rule_options`'. The messages are logged once,
/// when the settings arrive (`server::notification::apply_settings`); the lint
/// pass, which runs on every keystroke, drops them silently rather than
/// logging the same line a hundred times.
pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
let (waivers, problems, _) = waiver_files(paths);
(waivers, problems)
}
/// [`external_waivers`], keeping each file's **text** as well.
///
/// The text is what the lint snapshot's key holds (review round §R1a): a
/// waiver file is not watched — `watch::SOURCE_GLOB` covers sources and the
/// filelist alone — so comparing its contents is the only thing that ever
/// notices one being rewritten under a running server.
///
/// One read, not two. `ExternalWaivers::read` is `read_to_string` followed by
/// `ExternalWaivers::parse`, and both halves are public, so the bytes are
/// taken once and handed to the parser; the sentence an unreadable file
/// produces is `read`'s own, byte for byte.
fn waiver_files(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>, Vec<(PathBuf, String)>) {
let mut waivers = ExternalWaivers::default();
let mut problems = Vec::new();
let mut texts = Vec::new();
for path in paths {
match std::fs::read_to_string(path) {
Ok(text) => {
let (file, bad) = ExternalWaivers::parse(path, &text);
problems.extend(bad);
waivers.absorb(file);
texts.push((path.clone(), text));
}
Err(problem) => problems.push(format!("{}: {problem}", path.display())),
}
}
(waivers, problems, texts)
}
/// Which rules a buffer is linted with, given what the editor's settings and
/// the buffer's own `lucisv.toml` say.
///
/// **The one ladder**, top rung last — every rung may undo the one above it:
///
/// 1. the base set is what the rules themselves declare: `default_on`, plus
/// the `needs_workspace` rules when `has_oracle`;
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
/// `--select` replaces it on the command line;
/// `--select` replaces it on the command line; when the editor names
/// nothing, the project's `[lint] select` replaces it instead — the flag
/// when there is one, else the file, which is `lucisv check`'s own `pick`;
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
/// that class;
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
/// one rule — the per-rule word beats the class word, which is what makes
/// "all style off except `no-tabs`" expressible;
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
/// one a user reaches for when nothing else worked.
/// one a user reaches for when nothing else worked; when the editor names
/// nothing there either, the project's `[lint] ignore` removes instead.
///
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
let base = if settings.lint_select.is_empty() {
/// Rungs 3 and 4 are the **editor's alone**: a `lucisv.toml` has no such
/// keys, and the command line has no such flags. Rungs 2 and 5 are decided
/// independently — a project that selects and a user who only ignores keep
/// both halves. Every list accepts a severity word wherever a rule name fits,
/// the project's as much as the editor's.
pub fn enabled_rules(
settings: &ClientSettings,
project: &ProjectLint,
has_oracle: bool,
) -> Vec<&'static dyn Rule> {
let select = pick(&settings.lint_select, &project.select);
let base = if select.is_empty() {
if has_oracle {
workspace_rules()
} else {
default_rules()
}
} else {
named(&settings.lint_select)
named(select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
@@ -115,12 +449,22 @@ pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'stati
on.remove(rule.name());
}
}
for rule in named(&settings.lint_ignore) {
for rule in named(pick(&settings.lint_ignore, &project.ignore)) {
on.remove(rule.name());
}
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
}
/// The editor's list when it said anything, else the project's — the twin of
/// `lucisv/src/lint.rs`'s `pick`, which is the whole of §42's contract.
fn pick<'a>(editor: &'a [String], project: &'a [String]) -> &'a [String] {
if editor.is_empty() {
project
} else {
editor
}
}
/// Every rule a list of `--select`-style words names, unknown words skipped —
/// they were already dropped when the settings were parsed, and a name that
/// survived that filter always resolves.
@@ -179,6 +523,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
@@ -199,16 +555,48 @@ fn context(doc: &Document) -> LintContext<'_> {
///
/// This is the diagnostics path, which never looks at a fix, so the width a
/// `no-tabs` fix would expand a tab to is left at the linter's own default.
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
lint(&run.context(doc), &run.rules)
/// The external waivers apply here exactly as the inline ones do, as a union.
/// Which of them *fired* is discarded: only a whole run can tell whether a
/// waiver was dead, and a server never has one — it lints the buffers a user
/// happens to have open. `lucisv check` is what reports an unused external
/// waiver; see `docs/features/waiver-files/README.md`.
pub fn violations_in(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
found(doc, run)
}
/// The findings a code action may offer a fix for, with their fixes built for
/// `tab_width`.
/// The one place `vlog_linter::lint_with` is called for an open buffer.
///
/// The code-action path passes the indent width of the `lucisv.toml` governing
/// the buffer, so a quick fix that replaces a tab writes exactly what `lucisv`
/// would have written there.
/// One place, so there is one snapshot to read (review round §R1a) and one
/// site that says on the `--verbose` channel what a pass ran, what it found,
/// and whether it ran at all. Both doors — the diagnostics publish and
/// quick-fix discovery — arrive here with the *same* context, which is why the
/// tab width lives on the [`LintRun`] rather than being handed to [`fixable`].
fn found(doc: &Document, run: &LintRun) -> Arc<[Violation]> {
let key = run.key();
let (violations, hit) = lint_trace::stage(Stage::Lint, || {
snapshot(doc).read_or(&key, || lint_with(&run.context(doc), &run.rules, &run.external).0)
});
let reuse = if hit { Reuse::Hit } else { Reuse::Miss };
lint_trace::saw_lint(run.rules.len(), violations.len(), reuse);
violations
}
/// The slot this buffer's findings are kept in.
///
/// A field on the `Document`, so it is dropped with the buffer and cannot
/// outlive the text it was computed from: `Workspace::set_document` builds a
/// new `Document` for every flushed change. One per open document and nothing
/// else — no map, no eviction, no second analysis cache.
fn snapshot(doc: &Document) -> &Slot {
&doc.lint
}
/// The findings a code action may offer a fix for.
///
/// The fixes are written at the run's own indent width — the `lucisv.toml`
/// governing the buffer, else `lucisv.indent`, else the formatter's default —
/// so a quick fix that replaces a tab writes exactly what `lucisv` would have
/// written there.
///
/// A finding whose fix would edit bytes inside a `// verilog_format: off`
/// region is dropped here, so the editor keeps the same promise `lucisv check
@@ -217,15 +605,39 @@ pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
/// just has no lightbulb. Which bytes count as fenced is
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
/// `docs/features/shared-fence-filter/README.md`.
pub fn fixable(doc: &Document, tab_width: usize) -> Vec<Violation> {
let found = lint(&context(doc).with_tab_width(tab_width), &default_rules());
// 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()
pub fn fixable(run: &LintRun, doc: &Document) -> Arc<[Violation]> {
// The buffer's own run: its enabled rules and its external waiver files,
// so a fix is never offered — nor applied by fix-on-save — for a finding
// the diagnostics pass would not have shown. Found by §39's QA: with
// `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a
// line a checked-in waiver file had waived.
let violations = found(doc, run);
// 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 !violations.iter().any(|violation| violation.fix.is_some()) {
lint_trace::saw_fences(Fences::Skipped);
return violations;
}
// 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 held = crate::fences::held(doc);
let regions = lint_trace::stage(Stage::Fence, || crate::fences::of(doc));
lint_trace::saw_fences(if held { Fences::Memo } else { Fences::Computed });
// The snapshot's own findings when the fence drops nothing, which is every
// buffer with no `// lucisv: off` region in it: the filter would be the
// identity, and copying the findings to prove it would undo the reuse.
if !violations.iter().any(|violation| fix_touches_fence(violation, regions)) {
return violations;
}
violations.iter().filter(|v| !fix_touches_fence(v, regions)).cloned().collect()
}
/// True when a violation carries a fix any edit of which lands in a fenced
@@ -302,6 +714,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");
@@ -392,7 +821,7 @@ mod tests {
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
let offered = fixable(doc, 2);
let offered = fixable(&LintRun::default(), doc);
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
let free = text.find("\twire b").expect("the unfenced tab") as u32;
assert_eq!(offered[0].span.start, free);
@@ -412,7 +841,7 @@ mod tests {
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
"still reported"
);
assert!(fixable(doc, 2).is_empty(), "and still not fixable");
assert!(fixable(&LintRun::default(), doc).is_empty(), "and still not fixable");
}
#[test]
@@ -491,8 +920,14 @@ mod tests {
/// be true of the result).
#[test]
fn the_enabled_rules_ladder_is_the_documented_one() {
// The project's half of the ladder is `lint::project`'s own table
// test; this one holds it empty, which is the editor-only ladder
// §33.1 wrote.
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
enabled_rules(settings, &ProjectLint::default(), oracle)
.into_iter()
.map(|rule| rule.name())
.collect()
};
let with = |f: &dyn Fn(&mut ClientSettings)| {
let mut settings = ClientSettings::default();
@@ -654,7 +1089,7 @@ mod tests {
#[test]
fn an_unfenced_file_offers_every_fix() {
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
assert_eq!(fixable(ws.document(&uri).expect("open"), 2).len(), 1);
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open")).len(), 1);
}
#[test]
@@ -662,9 +1097,133 @@ mod tests {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
for width in [2usize, 4] {
let found = fixable(doc, width);
let found = fixable(&LintRun::default().with_tab_width(width), doc);
let fix = found[0].fix.as_ref().expect("no-tabs offers a fix");
assert_eq!(fix.edits[0].1, " ".repeat(width));
}
}
/// The two waiver lists add up, and only the setting's relative paths are
/// anchored at the first root — a `lucisv.toml`'s were resolved against
/// that file's own directory before they got here. TODO §39.
#[test]
fn the_config_files_waivers_come_first_and_the_settings_are_rooted() {
let file = FileConfig {
lint_waivers: Some(vec![PathBuf::from("/proj/rtl/project.waiver")]),
..Default::default()
};
let client = ClientSettings {
lint_waivers: vec!["team.waiver".to_string(), "/etc/global.waiver".to_string()],
..Default::default()
};
let roots = vec![PathBuf::from("/work/top")];
assert_eq!(
waiver_paths(&client, &roots, &file),
vec![
PathBuf::from("/proj/rtl/project.waiver"),
PathBuf::from("/work/top/team.waiver"),
PathBuf::from("/etc/global.waiver"),
]
);
// With no root at all a relative path is left as written rather than
// guessed at, exactly as `filelist_path` leaves it.
assert_eq!(
waiver_paths(&client, &[], &FileConfig::default()),
vec![PathBuf::from("team.waiver"), PathBuf::from("/etc/global.waiver")]
);
assert!(waiver_paths(&ClientSettings::default(), &roots, &FileConfig::default()).is_empty());
}
/// The run's indent width is the formatter's own ladder, read through
/// `format::indent_width` rather than spelled a second time — pinned at
/// each rung, because the width is a fix's bytes and this lane moved
/// where it is read (review round §R1a).
#[test]
fn the_runs_tab_width_is_the_formatters_own_ladder() {
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_indent", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("m.sv"), "module m;\n\twire a;\nendmodule\n").expect("write");
let path = dir.join("m.sv");
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
// Rung by rung: the built-in default, the editor's setting, and a
// `lucisv.toml` that outranks it.
let rungs: Vec<(Option<&str>, Option<usize>, usize)> = vec![
(None, None, 2),
(None, Some(8), 8),
(Some("indent = 4\n"), Some(8), 4),
(Some("indent = 3\n"), None, 3),
];
for (toml, editor, want) in rungs {
match toml {
Some(text) => std::fs::write(dir.join("lucisv.toml"), text).expect("write"),
None => {
let _ = std::fs::remove_file(dir.join("lucisv.toml"));
}
}
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { indent: editor, ..Default::default() });
ws.set_document(uri.clone(), "module m;\n\twire a;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
assert_eq!(run.tab_width, want, "toml={toml:?} editor={editor:?}");
assert_eq!(
run.tab_width,
crate::format::indent_width(Some(&path), ws.client_settings()),
"the two readings of the ladder agree"
);
assert_eq!(
fixable(&run, doc)[0].fix.as_ref().expect("a fix").edits[0].1,
" ".repeat(want)
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// The snapshot is a memo and not a second implementation: what it hands
/// back is what a pass computed from scratch would have, violation for
/// violation, and both doors get the same object.
#[test]
fn a_reused_snapshot_is_what_a_fresh_pass_would_have_found() {
let (ws, uri) = doc_of("module m;\n\twire a; \nendmodule\n");
let doc = ws.document(&uri).expect("open");
let run = LintRun::default();
let fresh: Vec<Violation> = lint_with(&run.context(doc), &run.rules, &run.external).0;
let first = violations_in(doc, &run);
let second = fixable(&run, doc);
assert!(Arc::ptr_eq(&first, &second), "the diagnostics and the fixes are one pass");
assert_eq!(first.len(), fresh.len(), "{fresh:#?}");
for (held, made) in first.iter().zip(&fresh) {
assert_eq!(
(held.rule, held.span, &held.message),
(made.rule, made.span, &made.message)
);
assert_eq!(
held.fix.as_ref().map(|fix| &fix.edits),
made.fix.as_ref().map(|fix| &fix.edits),
"the fix bytes are the fresh pass's too"
);
}
}
/// A waiver file that is missing, and one with a bad line, are both
/// described rather than fatal — and the good directives of the second
/// still apply. TODO §39.
#[test]
fn a_bad_waiver_file_is_described_and_its_good_directives_still_apply() {
let dir = std::env::temp_dir().join(format!("lucisv_waiver_paths_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let good = dir.join("good.waiver");
std::fs::write(&good, "waive --rule=no-tabs\nwaive --rule=nope\n").expect("write");
let (waivers, problems) = external_waivers(&[good.clone(), dir.join("missing.waiver")]);
assert!(!waivers.is_empty(), "the good directive survived its neighbour");
assert_eq!(problems.len(), 2, "{problems:?}");
assert!(problems[0].contains("good.waiver:2: unknown rule `nope`"), "{problems:?}");
assert!(problems[1].contains("missing.waiver"), "{problems:?}");
let _ = std::fs::remove_dir_all(&dir);
}
}
+398
View File
@@ -0,0 +1,398 @@
//! What a buffer's `lucisv.toml` says about linting, and what could not be
//! used from it.
//!
//! The contract (§42): **the editor's settings play the role the CLI's flags
//! play**. `lucisv check` picks the flag when one was given and the project
//! file otherwise (`lucisv/src/lint.rs`'s `pick`); the server picks
//! `lucisv.lint.select` when it is non-empty and `[lint] select` otherwise,
//! key by key, so one buffer linted two ways is linted the same way. See
//! `docs/features/lint-config-contract/README.md`.
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeSet, HashMap};
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use lucisv_core::config::FileConfig;
/// The selection a buffer's `lucisv.toml` carries: `[lint] select` and
/// `[lint] ignore`, exactly as `--select` and `--ignore` carry them.
///
/// [`ProjectLint::default`] — both lists empty — is a buffer with no config
/// file, or one whose `[lint]` table says nothing about rules: the editor's
/// settings and the base set then decide everything, which is what this
/// server did before §42.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ProjectLint {
/// `[lint] select`: run exactly these rules, replacing the base set —
/// unless the editor named some, which outranks it.
pub select: Vec<String>,
/// `[lint] ignore`: rules dropped from whatever `select` left — unless
/// the editor named some.
pub ignore: Vec<String>,
}
impl ProjectLint {
/// One config file's selection, with every name the registry does not
/// know dropped and reported.
///
/// `lucisv check` *fails the run* over an unknown name, which an editor
/// cannot do — but it must not silently obey a typo either: a
/// `select = ["no-tab"]` taken at face value would resolve to no rules at
/// all and blank the file's squiggles, which reads as "lucisv is happy"
/// rather than "lucisv could not understand your config". So the name is
/// dropped, said once, and the rest of the list still applies; a `select`
/// left empty by the dropping falls back to the base set.
pub fn read(file: &FileConfig) -> (ProjectLint, Vec<String>) {
let mut problems = Vec::new();
let select = known(file, "select", file.lint_select.as_deref(), &mut problems);
let ignore = known(file, "ignore", file.lint_ignore.as_deref(), &mut problems);
(ProjectLint { select, ignore }, problems)
}
}
/// The names of one `[lint]` list that name something, the others reported.
fn known(
file: &FileConfig,
key: &str,
list: Option<&[String]>,
problems: &mut Vec<String>,
) -> Vec<String> {
let mut kept = Vec::new();
for name in list.unwrap_or(&[]) {
if vlog_linter::rules_named(name).is_some() {
kept.push(name.clone());
} else {
// No line number: `lucisv_core::config` records one per
// `[lint.<rule>]` entry, because those are checked one by one,
// and the list keys are one value each.
problems.push(format!("{}: [lint] {key}: unknown rule: {name}", source_of(file)));
}
}
kept
}
/// The config file's path as an error should name it.
fn source_of(file: &FileConfig) -> String {
file.source.as_ref().map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string())
}
/// What one buffer's `lucisv.toml` asked for and did not get: a
/// `[lint.<rule>]` entry the registry refused, a name in `[lint] select` that
/// is not a rule, a `[lint] waivers` file that is not there or holds a
/// directive that does not parse.
///
/// Every message is written the way `lucisv check` writes it —
/// `<file>:<line>: <message>` — so the same mistake reads the same in CI and
/// in an editor's output channel. **Nothing here is fatal**: the entry is
/// dropped and the buffer is still linted with everything that was
/// understood, because a server cannot fail a run the way a command can.
#[derive(Debug, Default, Clone)]
pub struct ConfigProblems {
/// The config file they came from. `None` — no config file was found —
/// means there is nothing to complain about and `messages` is empty.
source: Option<PathBuf>,
/// A stamp of that file's lint content, so an edited config gets a fresh
/// hearing: see [`ProblemLog`].
stamp: u64,
/// The messages, in file order.
messages: Vec<String>,
}
impl ConfigProblems {
/// The problems found in this config file.
pub fn new(file: &FileConfig, messages: Vec<String>) -> ConfigProblems {
ConfigProblems { source: file.source.clone(), stamp: stamp_of(file), messages }
}
/// Whether anything at all could not be used.
pub fn is_empty(&self) -> bool {
self.messages.is_empty()
}
}
/// A stamp over everything in a config file that [`ConfigProblems`] can be
/// about, so that editing the file re-arms the report and editing a source
/// beside it does not.
///
/// A hash rather than a modification time: the file is re-read on every lint
/// pass anyway (`configured`), and a hash of what was parsed cannot be fooled
/// by a filesystem whose timestamps are coarse.
fn stamp_of(file: &FileConfig) -> u64 {
let mut hasher = DefaultHasher::new();
file.lint_select.hash(&mut hasher);
file.lint_ignore.hash(&mut hasher);
file.lint_waivers.hash(&mut hasher);
for entry in &file.lint_options {
entry.rule.hash(&mut hasher);
entry.key.hash(&mut hasher);
entry.raw.hash(&mut hasher);
entry.line.hash(&mut hasher);
}
hasher.finish()
}
/// Which config problems have already been said, so each is said **once**.
///
/// Once per (config file, message), not once per lint pass: the pass runs on
/// every keystroke and every index rebuild, and a hundred copies of one line
/// in the output channel is not a report, it is noise. The editor-settings
/// path has said its own problems once since §34 — this is the same promise
/// for the file a project checks in.
///
/// A config file whose lint content changed clears its own memo, so a user
/// who edits `lucisv.toml` and gets it wrong again is told again. The memo is
/// keyed by path, so it holds one small entry per config file a session ever
/// linted through.
#[derive(Debug, Default)]
pub struct ProblemLog {
said: HashMap<PathBuf, Said>,
}
/// One config file's memo: the content it was taken under, and what was said.
#[derive(Debug, Default)]
struct Said {
stamp: u64,
messages: BTreeSet<String>,
}
impl ProblemLog {
/// The messages that have not been said yet for this config file, marked
/// as said. An empty answer means the user has already been told.
pub fn unsaid(&mut self, problems: &ConfigProblems) -> Vec<String> {
let Some(source) = problems.source.clone() else { return Vec::new() };
if problems.is_empty() {
return Vec::new();
}
let said = self.said.entry(source).or_default();
if said.stamp != problems.stamp {
said.stamp = problems.stamp;
said.messages.clear();
}
problems
.messages
.iter()
.filter(|message| said.messages.insert((*message).clone()))
.cloned()
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
use lsp_types::Uri;
use std::str::FromStr;
use vlog_linter::Severity;
fn config(text: &str) -> FileConfig {
let mut file = lucisv_core::config::parse(text).expect("the config parses");
file.source = Some(PathBuf::from("/rtl/lucisv.toml"));
file
}
fn names(settings: &ClientSettings, project: &ProjectLint, oracle: bool) -> Vec<&'static str> {
super::super::enabled_rules(settings, project, oracle)
.into_iter()
.map(|rule| rule.name())
.collect()
}
fn editor(select: &[&str], ignore: &[&str]) -> ClientSettings {
ClientSettings {
lint_select: select.iter().map(|s| (*s).to_string()).collect(),
lint_ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
..ClientSettings::default()
}
}
fn project(select: &[&str], ignore: &[&str]) -> ProjectLint {
ProjectLint {
select: select.iter().map(|s| (*s).to_string()).collect(),
ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
}
}
/// §42.1's table: every combination of {toml select, editor select} ×
/// {toml ignore, editor ignore}, against the ladder. The editor's list
/// wins when it says anything, the project's is used when it does not,
/// and the two keys are decided **independently** — the CLI's `pick`,
/// applied twice.
#[test]
fn the_editor_outranks_the_project_key_by_key() {
// Four rules stand in for the whole registry: two the project may
// name and two the editor may, so a row's answer says which list was
// consulted rather than which happened to be shorter.
// (toml select, editor select, toml ignore, editor ignore, expected).
type Row = (
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
);
let rows: [Row; 8] = [
// (toml select, editor select, toml ignore, editor ignore) => rules
(&[], &[], &[], &[], &[]),
(&["no-tabs"], &[], &[], &[], &["no-tabs"]),
(&[], &["no-tabs"], &[], &[], &["no-tabs"]),
(&["module-name-style"], &["no-tabs"], &[], &[], &["no-tabs"]),
(&["no-tabs", "module-name-style"], &[], &["no-tabs"], &[], &["module-name-style"]),
(&["no-tabs", "module-name-style"], &[], &[], &["no-tabs"], &["module-name-style"]),
(
&["no-tabs", "module-name-style"],
&[],
&["module-name-style"],
&["no-tabs"],
&["module-name-style"],
),
(
&["module-name-style"],
&["no-tabs", "module-name-style"],
&["no-tabs"],
&["module-name-style"],
&["no-tabs"],
),
];
for (toml_select, ed_select, toml_ignore, ed_ignore, want) in rows {
let settings = editor(ed_select, ed_ignore);
let from_file = project(toml_select, toml_ignore);
let got = names(&settings, &from_file, false);
if want.is_empty() {
// The empty row is the base set, which is too long to spell.
assert_eq!(
got,
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>(),
"neither list said anything, so the base set stands"
);
} else {
assert_eq!(
got, want,
"{toml_select:?} {ed_select:?} {toml_ignore:?} {ed_ignore:?}"
);
}
}
}
/// A severity word stands for its whole class in the toml's lists exactly
/// as it does in the editor's, and as `--select style` does.
#[test]
fn a_severity_word_works_in_the_projects_lists_too() {
let styled = names(&ClientSettings::default(), &project(&["style"], &[]), true);
assert!(!styled.is_empty());
assert!(styled
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
let quiet = names(&ClientSettings::default(), &project(&[], &["style"]), true);
assert!(!quiet.is_empty());
assert!(quiet
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
}
/// A rung 3 or 4 switch is the editor's alone, and still applies over a
/// selection the project made.
#[test]
fn the_editor_only_rungs_still_apply_over_a_project_selection() {
let mut settings = ClientSettings::default();
settings.lint_severity.insert(Severity::Style, false);
let from_file = project(&["no-tabs", "wire-reg-mixup"], &[]);
assert_eq!(
names(&settings, &from_file, false),
vec!["wire-reg-mixup"],
"the class switch removes the project's style rule"
);
settings.lint_rules.insert("no-tabs".to_string(), true);
assert_eq!(
names(&settings, &from_file, false),
vec!["no-tabs", "wire-reg-mixup"],
"and the per-rule word puts it back"
);
}
/// A name the registry does not know is dropped and reported — the run
/// `lucisv check` would have failed keeps going here with what was
/// understood.
#[test]
fn an_unknown_name_in_the_projects_list_is_dropped_and_said() {
let (from_file, problems) =
ProjectLint::read(&config("[lint]\nselect = [\"no-tab\", \"no-tabs\"]\n"));
assert_eq!(from_file.select, vec!["no-tabs"]);
assert_eq!(problems, vec!["/rtl/lucisv.toml: [lint] select: unknown rule: no-tab"]);
assert_eq!(names(&ClientSettings::default(), &from_file, false), vec!["no-tabs"]);
// Every name unknown leaves the list empty, which is the base set —
// the safe direction: some rules rather than none.
let (none, problems) = ProjectLint::read(&config("[lint]\nselect = [\"nope\"]\n"));
assert!(none.select.is_empty());
assert_eq!(problems.len(), 1);
assert_eq!(
names(&ClientSettings::default(), &none, false),
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
}
/// §42.2: a `[lint.<rule>]` entry the registry refuses is reported once,
/// however many lint passes run, and the buffer keeps being linted.
#[test]
fn a_rejected_option_is_said_once_and_the_lint_still_runs() {
let dir = std::env::temp_dir()
.join(format!("lucisv_lint_project_{}_rejected", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = \"wide\"\n")
.expect("write config");
let path = dir.join("m.sv");
let text = "module m;\n\twire a;\nendmodule\n";
std::fs::write(&path, text).expect("write source");
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let mut log = ProblemLog::default();
let mut said = Vec::new();
for _ in 0..3 {
let doc: &Document = ws.document(&uri).expect("open");
let run = super::super::LintRun::for_document(&ws, doc);
// The lint still runs: the tab is still a finding.
assert!(
super::super::violations_in(doc, &run).iter().any(|v| v.rule == "no-tabs"),
"the buffer is still linted with the entry dropped"
);
said.extend(log.unsaid(run.config_problems()));
}
assert_eq!(said.len(), 1, "said once across three passes: {said:#?}");
let expected = format!("{}:2: rule `line-length` ", dir.join("lucisv.toml").display());
assert!(said[0].starts_with(&expected), "the wording `lucisv check` prints: {}", said[0]);
let _ = std::fs::remove_dir_all(&dir);
}
/// An edited config gets a fresh hearing: the memo is keyed by the file's
/// lint content, so the same mistake made again after a change is said
/// again.
#[test]
fn an_edited_config_re_arms_the_report() {
let first = config("[lint.line-length]\nlength = \"wide\"\n");
let problems = ConfigProblems::new(&first, vec!["/rtl/lucisv.toml:2: bad".to_string()]);
let mut log = ProblemLog::default();
assert_eq!(log.unsaid(&problems).len(), 1);
assert!(log.unsaid(&problems).is_empty(), "and not twice");
// Same message, different file content: the user has been editing.
let edited = config("# a comment\n[lint.line-length]\nlength = \"wide\"\n");
let again = ConfigProblems::new(&edited, vec!["/rtl/lucisv.toml:3: bad".to_string()]);
assert_eq!(log.unsaid(&again).len(), 1, "a changed config is heard again");
// A buffer with no config file has nothing to report.
let nowhere = ConfigProblems::new(&FileConfig::default(), vec!["never".to_string()]);
assert!(log.unsaid(&nowhere).is_empty());
}
}
+245
View File
@@ -0,0 +1,245 @@
//! One lint pass's findings, kept for as long as they are still the answer.
//!
//! Take 5 **review** round §R1a (`docs/features/perf5r-lint-snapshot/README.md`,
//! `docs/performance_take5_review.md` §1). A `textDocument/codeAction` on
//! `pinmux_reg_top.sv` spends **21 of its 22 ms in `lint_with`**, and the first
//! request after an edit runs that pass **twice** on one revision — once to
//! publish diagnostics, once to discover quick fixes. This module is what lets
//! the second one read the first one's answer.
//!
//! **The whole design is in [`Key`].** A snapshot is legitimate only while
//! every input of `lint_with(ctx, rules, external)` is what it was, and the
//! key is those inputs *by value* — no hash, no mtime, no generation number,
//! so "could this offer a stale fix?" is a question about `PartialEq` and not
//! about collision probability. What the key deliberately does **not** carry
//! is the two things identity already settles:
//!
//! * the **buffer** — a [`Slot`] is a field on the `Document`, and
//! `Workspace::set_document` builds a new `Document` for every flushed
//! change, so a slot cannot outlive the text it was computed from (the
//! argument `crate::fences` already rests on);
//! * the **workspace index** the census oracle reads — every index mutation in
//! `state/mod.rs` ends by calling `Document::refresh_overlay` on every open
//! buffer, and that is where the slot is cleared.
//!
//! The invalidation table in the feature README has one row per input, the
//! mechanism for each, and the test that flips it.
//!
//! **Bounded by construction:** one slot per open document, holding that
//! document's own violations, dropped with the `Document` on `didClose`. There
//! is no map, no eviction policy and no second unbounded analysis cache.
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use vlog_linter::{RuleOptions, Violation};
/// Everything a lint result depends on that is **not** settled by the
/// `Document`'s own identity.
///
/// Compared by value, field by field. Every field is an argument of the
/// `lint_with` call it guards, which is what makes the list complete: see the
/// feature README's table, which derives it from that call's signature.
#[derive(Debug, Clone, PartialEq)]
pub struct Key {
/// The enabled rules' names, in registry order — the whole of what the
/// `lucisv.lint.*` ladder and the project's `[lint]` table decided.
pub rules: Vec<&'static str>,
/// The merged per-rule options: the buffer's `lucisv.toml` overlaid with
/// the editor's `lucisv.lint.options`.
pub options: RuleOptions,
/// The width `line-length` holds this buffer to.
pub line_length: usize,
/// The width a `no-tabs` fix writes. It changes a fix's *text* and
/// nothing else, but a fix's text is what a user applies.
pub tab_width: usize,
/// Whether the pass had a census to ask. The oracle's *answers* are
/// covered by `refresh_overlay`; whether there is one at all is decided
/// from the index's file count, which can move without any one file's
/// facts moving.
pub has_oracle: bool,
/// Every external waiver file in force, path and **contents**, in the
/// order they were read.
///
/// The contents, not a digest and not an mtime: a waiver file is not
/// watched (`watch::SOURCE_GLOB` covers sources and the filelist alone),
/// so the only thing that ever notices a rewritten one is this
/// comparison. The text is already in hand — the pass read it to parse
/// it — so keeping it costs a copy per open document and no I/O.
pub waivers: Vec<(PathBuf, String)>,
}
/// One document's lint snapshot: the key it was computed under, and what it
/// found.
struct Held {
key: Key,
violations: Arc<[Violation]>,
}
/// The snapshot slot a `Document` carries.
///
/// A `Mutex` rather than a `RefCell` so a `Document` stays `Sync` exactly as
/// its `OnceLock` fence memo leaves it; the lock is uncontended (one message
/// loop) and is never held across the pass itself.
#[derive(Default)]
pub struct Slot(Mutex<Option<Held>>);
impl Slot {
/// An empty slot — what every `Document` is built with.
pub fn new() -> Slot {
Slot(Mutex::new(None))
}
/// Forget whatever is held.
///
/// Called from `Document::refresh_overlay`, which is the one place a
/// `Document` is told the workspace index moved. Dropping here rather
/// than keying on an index generation is deliberate: the four call sites
/// that mutate the index all end in that loop, so there is no way for the
/// index to move without this running, and no counter to keep in step.
pub fn clear(&mut self) {
if let Ok(mut held) = self.0.lock() {
*held = None;
}
}
/// The violations for `key`, computing them when what is held is for
/// anything else.
///
/// Returns `(violations, answered_from_the_snapshot)`. A poisoned lock —
/// which this server has no way to produce, having one message loop and no
/// panicking library code — degrades to computing every time rather than
/// to an error a user would see.
pub fn read_or(
&self,
key: &Key,
compute: impl FnOnce() -> Vec<Violation>,
) -> (Arc<[Violation]>, bool) {
if let Ok(held) = self.0.lock() {
if let Some(held) = held.as_ref().filter(|held| held.key == *key) {
return (Arc::clone(&held.violations), true);
}
}
// Computed with the lock released: `lint_with` is the expensive part
// and it reads nothing this slot owns.
let violations: Arc<[Violation]> = compute().into();
if let Ok(mut held) = self.0.lock() {
*held = Some(Held { key: key.clone(), violations: Arc::clone(&violations) });
}
(violations, false)
}
/// Whether anything is held at all — for the tests that assert a slot was
/// filled, or was not.
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.0.lock().map_or(true, |held| held.is_none())
}
}
impl std::fmt::Debug for Slot {
/// Says whether a snapshot is held and nothing about it: a `Document`'s
/// `Debug` must not print a thousand violations.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let held = self.0.lock().map(|held| held.is_some()).unwrap_or(false);
f.debug_tuple("Slot").field(&held).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::TextRange;
fn key() -> Key {
Key {
rules: vec!["no-tabs"],
options: RuleOptions::new(),
line_length: 100,
tab_width: 2,
has_oracle: false,
waivers: Vec::new(),
}
}
fn violation(message: &str) -> Violation {
Violation::new("no-tabs", message, TextRange::new(0, 1))
}
/// The second ask for the same key does not compute, and answers with the
/// same findings.
#[test]
fn a_matching_key_answers_without_computing() {
let slot = Slot::new();
let (first, hit) = slot.read_or(&key(), || vec![violation("one")]);
assert!(!hit, "an empty slot cannot hit");
let (again, hit) = slot.read_or(&key(), || panic!("must not recompute"));
assert!(hit);
assert_eq!(again.len(), 1);
assert_eq!(again[0].message, first[0].message);
}
/// Every field of the key is load-bearing: change any one and the pass
/// runs again. This is the table's row set in miniature — the per-input
/// server tests assert the same thing through the real doors.
#[test]
fn every_field_of_the_key_forces_a_recompute() {
let mut options = RuleOptions::new();
options.set_raw("line-length", "length", "80").expect("a real option");
let changes: Vec<(&str, Key)> = vec![
("rules", Key { rules: vec!["no-tabs", "posix-eof"], ..key() }),
("options", Key { options, ..key() }),
("line_length", Key { line_length: 120, ..key() }),
("tab_width", Key { tab_width: 4, ..key() }),
("has_oracle", Key { has_oracle: true, ..key() }),
(
"waivers",
Key {
waivers: vec![(PathBuf::from("/w.waiver"), "waive --rule=no-tabs\n".into())],
..key()
},
),
];
for (what, moved) in changes {
let slot = Slot::new();
slot.read_or(&key(), || vec![violation("old")]);
let (found, hit) = slot.read_or(&moved, || vec![violation("new")]);
assert!(!hit, "{what} did not invalidate the snapshot");
assert_eq!(found[0].message, "new", "{what} answered stale");
// ... and the new answer is what is held afterwards, so the stale
// one cannot come back on the next request.
let (again, hit) = slot.read_or(&moved, || panic!("must not recompute"));
assert!(hit);
assert_eq!(again[0].message, "new", "{what} left the old answer held");
}
}
/// A waiver file rewritten to the same length with different bytes is a
/// different key: the contents are compared, not a size or a time.
#[test]
fn a_waiver_rewritten_in_place_is_a_different_key() {
let one = |text: &str| Key {
waivers: vec![(PathBuf::from("/w.waiver"), text.to_string())],
..key()
};
let slot = Slot::new();
slot.read_or(&one("waive --rule=no-tabs\n"), || vec![violation("old")]);
let (found, hit) =
slot.read_or(&one("waive --rule=posix-eof\n"), || vec![violation("new")]);
assert!(!hit, "same length, different bytes");
assert_eq!(found[0].message, "new");
}
/// Clearing is what `refresh_overlay` does when the index moves.
#[test]
fn clearing_forces_the_next_pass_to_compute() {
let mut slot = Slot::new();
slot.read_or(&key(), || vec![violation("old")]);
assert!(!slot.is_empty());
slot.clear();
assert!(slot.is_empty());
let (found, hit) = slot.read_or(&key(), || vec![violation("new")]);
assert!(!hit, "a cleared slot cannot hit");
assert_eq!(found[0].message, "new");
}
}
+400
View File
@@ -0,0 +1,400 @@
//! Where a lint-answering request's milliseconds went.
//!
//! Take 5 **review** round §R1b (`docs/performance_take5_review.md` §1,
//! `docs/features/perf5r-lint-snapshot/README.md`). The review's own note is
//! that the pinmux code-action menu costs **25 ms of which 23 is quickfix**,
//! and that the first request after a one-character edit costs **136 ms** —
//! but "config read plus lint" was as far as the previous lane could
//! attribute it, and *config read plus lint* is two answers, not one. This
//! module splits the request into the five stages a reader can act on:
//!
//! | stage | what it is |
//! |---|---|
//! | `config` | `Discovery::for_file`, `ProjectLint::read` and every waiver file read |
//! | `build` | the rest of [`crate::lint::LintRun::for_document`] — the oracle, the rule ladder |
//! | `lint` | `vlog_linter::lint_with`, and how many times it ran |
//! | `fence` | `crate::fences::of` — computed, taken from the memo, or skipped |
//! | `serialize` | turning violations into `CodeAction`s |
//!
//! and reports the **flush** — the debounced `Document` rebuild `answer_request`
//! performs before any handler runs — as its own group, with the diagnostics
//! pass that publishes inside it split the same five ways. That separation is
//! the review's item 4: if the dirty-buffer stage dominates the 136 ms, a lint
//! cache alone cannot fix it, and only a number can say.
//!
//! **Nothing here decides anything.** A trace is armed by
//! [`crate::server`]'s request wrapper when `--verbose` asked for one, written
//! as the request runs, logged once and dropped.
//!
//! Off is the shipped state and costs **one thread-local `Cell<bool>` read**
//! per traced site — no clock read, no allocation, no line — which is the same
//! bargain `Server::timer` makes for the rest of `docs/features/verbose-timing/`.
//!
//! Per thread, deliberately, for `vlog_parser::stats`' reason: a request is
//! answered on one thread, so a thread-local accumulator is that request's
//! number exactly, and `cargo test`'s parallel binaries cannot add to each
//! other's.
use std::cell::{Cell, RefCell};
use std::time::{Duration, Instant};
/// One stage of a lint-answering request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
/// Reading the project's configuration: the `lucisv.toml` discovery walk,
/// its `[lint]` table, and the external waiver files.
Config,
/// The rest of the `LintRun`: the census oracle and the rule ladder.
Build,
/// `vlog_linter::lint_with` itself.
Lint,
/// The formatter's fenced-region answer.
Fence,
/// Turning violations into what goes on the wire.
Serialize,
}
impl Stage {
/// The name this stage is counted under in the `timing:` line.
fn label(self) -> &'static str {
match self {
Stage::Config => "config",
Stage::Build => "build",
Stage::Lint => "lint",
Stage::Fence => "fence",
Stage::Serialize => "serialize",
}
}
/// Every stage, in the order a request passes through them — so a line
/// always carries the same fields whether or not a stage ran.
const ALL: [Stage; 5] =
[Stage::Config, Stage::Build, Stage::Lint, Stage::Fence, Stage::Serialize];
}
/// What the fence filter did, when a pass reached it at all.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Fences {
/// No finding carried a fix, so the filter would have been the identity
/// and was not asked (take 5 §P1a).
#[default]
Skipped,
/// `protected_regions` parsed the buffer for this `Document`.
Computed,
/// The `Document`'s memo answered (take 5 §P1b).
Memo,
}
impl Fences {
fn label(self) -> &'static str {
match self {
Fences::Skipped => "skipped",
Fences::Computed => "computed",
Fences::Memo => "memo",
}
}
}
/// Whether a lint pass was answered from the snapshot (review round §R1a).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Reuse {
/// No pass ran.
#[default]
None,
/// The `Document` held no snapshot, or held one for other inputs.
Miss,
/// The snapshot matched and `lint_with` did not run.
Hit,
}
impl Reuse {
fn label(self) -> &'static str {
match self {
Reuse::None => "none",
Reuse::Miss => "miss",
Reuse::Hit => "hit",
}
}
/// A hit only survives while every pass hit: one recompute in a request
/// is a miss for that request, which is what a reader wants to know.
fn saw(self, other: Reuse) -> Reuse {
match (self, other) {
(Reuse::Miss, _) | (_, Reuse::Miss) => Reuse::Miss,
(Reuse::Hit, _) | (_, Reuse::Hit) => Reuse::Hit,
_ => Reuse::None,
}
}
}
/// One group of stages: the flush's, or the handler's own.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Group {
ms: [f64; Stage::ALL.len()],
/// How many times `lint_with` ran in this group.
passes: u32,
/// How many violations the last pass found.
violations: usize,
/// How many rules that pass ran.
rules: usize,
/// How many actions were serialized.
actions: usize,
/// How many waiver files were read from disk.
waivers: usize,
/// Whether a `lucisv.toml` was found and read.
toml: bool,
fences: Fences,
reuse: Reuse,
}
impl Group {
/// The `const` form `thread_local!`'s initializer needs; `Default` is not
/// callable there.
const EMPTY: Group = Group {
ms: [0.0; Stage::ALL.len()],
passes: 0,
violations: 0,
rules: 0,
actions: 0,
waivers: 0,
toml: false,
fences: Fences::Skipped,
reuse: Reuse::None,
};
fn add(&mut self, stage: Stage, took: Duration) {
self.ms[stage as usize] += took.as_secs_f64() * 1_000.0;
}
/// This group's fields, in the `key=value` shape `tools/perf` parses.
fn fields(&self) -> String {
let stages: Vec<String> = Stage::ALL
.iter()
.map(|stage| format!("{}={:.2}ms", stage.label(), self.ms[*stage as usize]))
.collect();
format!(
"{} passes={} rules={} violations={} actions={} waivers={} toml={} fences={} \
snapshot={}",
stages.join(" "),
self.passes,
self.rules,
self.violations,
self.actions,
self.waivers,
self.toml,
self.fences.label(),
self.reuse.label(),
)
}
}
/// One request's trace: what the flush cost, and what the handler cost.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Trace {
/// The stages the debounced `Document` rebuild and its diagnostics
/// publish passed through, closed by [`close_flush`].
pub flush: Group,
/// How long the whole flush took, publish included.
pub flush_ms: f64,
/// Buffers the flush rebuilt.
pub flush_buffers: usize,
/// Whole-file parses the flush performed (`vlog_parser::stats`).
pub flush_parses: u64,
/// The handler's own stages.
pub action: Group,
}
impl Trace {
/// Whether this request touched the lint path at all. A trace that did
/// not is not worth a line.
pub fn is_empty(&self) -> bool {
self.flush == Group::default() && self.action == Group::default() && self.flush_buffers == 0
}
/// The whole trace as one `timing:`-style fragment.
pub fn line(&self) -> String {
format!(
"flush{{wall={:.2}ms buffers={} parses={} {}}} action{{{}}}",
self.flush_ms,
self.flush_buffers,
self.flush_parses,
self.flush.fields(),
self.action.fields(),
)
}
}
thread_local! {
/// One branch is the whole of what verbose-off costs at a traced site.
static ARMED: Cell<bool> = const { Cell::new(false) };
static TRACE: RefCell<Trace> = const { RefCell::new(Trace {
flush: Group::EMPTY,
flush_ms: 0.0,
flush_buffers: 0,
flush_parses: 0,
action: Group::EMPTY,
}) };
/// Which group the stages recorded right now belong to.
static IN_FLUSH: Cell<bool> = const { Cell::new(true) };
}
/// Start a fresh trace for one request. Called by the request wrapper when
/// `--verbose` asked for timing, and by nothing else.
pub fn arm() {
ARMED.set(true);
IN_FLUSH.set(true);
TRACE.with_borrow_mut(|trace| *trace = Trace::default());
}
/// Whether a trace is being written — the one branch a caller checks before
/// reading a clock of its own.
pub fn armed() -> bool {
ARMED.get()
}
/// Stop tracing and return what was written, or `None` when nothing armed it.
pub fn disarm() -> Option<Trace> {
if !ARMED.replace(false) {
return None;
}
Some(TRACE.with_borrow(Clone::clone))
}
/// Close the flush group: everything recorded from here on is the handler's.
///
/// `parses` is the `vlog_parser::stats::parses()` delta across the flush and
/// `buffers` is how many dirty buffers it rebuilt, so the `Document` rebuild
/// is readable beside the diagnostics pass that follows it.
pub fn close_flush(took: Duration, buffers: usize, parses: u64) {
if !ARMED.get() {
return;
}
TRACE.with_borrow_mut(|trace| {
trace.flush_ms = took.as_secs_f64() * 1_000.0;
trace.flush_buffers = buffers;
trace.flush_parses = parses;
});
IN_FLUSH.set(false);
}
/// Run `work`, counting what it took against `stage`.
///
/// Untimed and unallocated when nothing armed a trace, which is every session
/// but a `--verbose` one.
pub fn stage<T>(stage: Stage, work: impl FnOnce() -> T) -> T {
if !ARMED.get() {
return work();
}
let started = Instant::now();
let out = work();
let took = started.elapsed();
group(|held| held.add(stage, took));
out
}
/// Record what a lint pass ran and found.
pub fn saw_lint(rules: usize, violations: usize, reuse: Reuse) {
group(|held| {
held.passes += 1;
held.rules = rules;
held.violations = violations;
held.reuse = held.reuse.saw(reuse);
});
}
/// Record what the configuration read found: a `lucisv.toml`, and how many
/// waiver files it and the editor's settings between them named.
pub fn saw_config(toml: bool, waivers: usize) {
group(|held| {
held.toml |= toml;
held.waivers += waivers;
});
}
/// Record what the fence filter did.
pub fn saw_fences(fences: Fences) {
group(|held| held.fences = fences);
}
/// Record how many actions were put on the wire.
pub fn saw_actions(actions: usize) {
group(|held| held.actions += actions);
}
/// Apply `write` to whichever group is being filled, or to nothing at all.
fn group(write: impl FnOnce(&mut Group)) {
if !ARMED.get() {
return;
}
let flushing = IN_FLUSH.get();
TRACE.with_borrow_mut(|trace| {
write(if flushing { &mut trace.flush } else { &mut trace.action })
});
}
#[cfg(test)]
mod tests {
use super::*;
/// Nothing is written when nothing armed a trace — the shipped state.
#[test]
fn an_unarmed_trace_records_nothing_and_returns_the_work() {
assert_eq!(disarm(), None);
assert_eq!(stage(Stage::Lint, || 7), 7);
saw_lint(3, 4, Reuse::Miss);
assert_eq!(disarm(), None, "still nothing to say");
}
/// The two groups are kept apart, and `close_flush` is what separates
/// them: a stage before it is the flush's, one after it the handler's.
#[test]
fn close_flush_divides_the_request_into_its_two_halves() {
arm();
saw_lint(9, 100, Reuse::Miss);
close_flush(Duration::from_millis(110), 1, 1);
saw_lint(9, 100, Reuse::Hit);
saw_actions(2);
saw_fences(Fences::Memo);
let trace = disarm().expect("armed");
assert_eq!(trace.flush.passes, 1);
assert_eq!(trace.flush.violations, 100);
assert_eq!(trace.flush.actions, 0, "the flush serializes nothing");
assert_eq!(trace.flush_buffers, 1);
assert_eq!(trace.flush_parses, 1);
assert!((trace.flush_ms - 110.0).abs() < 5.0, "{}", trace.flush_ms);
assert_eq!(trace.action.passes, 1);
assert_eq!(trace.action.actions, 2);
assert_eq!(trace.action.fences, Fences::Memo);
assert_eq!(trace.action.reuse, Reuse::Hit);
assert_eq!(disarm(), None, "disarming twice says nothing twice");
}
/// One recompute in a request is a miss for that request: a reader asking
/// "did this menu re-lint?" must not be told "hit" because the second
/// pass reused what the first one had just computed.
#[test]
fn a_single_recompute_makes_the_whole_request_a_miss() {
arm();
close_flush(Duration::ZERO, 0, 0);
saw_lint(9, 100, Reuse::Hit);
saw_lint(9, 100, Reuse::Miss);
assert_eq!(disarm().expect("armed").action.reuse, Reuse::Miss);
}
/// Every stage is named in the line whether or not it ran, so a reader
/// (and `tools/perf/phases_r1.py`) always parses the same fields.
#[test]
fn the_line_names_every_stage_in_both_groups() {
arm();
stage(Stage::Config, || {});
close_flush(Duration::from_millis(1), 1, 1);
stage(Stage::Lint, || {});
let line = disarm().expect("armed").line();
for stage in Stage::ALL {
assert_eq!(line.matches(&format!("{}=", stage.label())).count(), 2, "{line}");
}
assert!(line.contains("buffers=1"), "{line}");
assert!(line.contains("snapshot=none"), "{line}");
assert!(!line.contains(" "), "no empty field: {line}");
}
}
+236 -1
View File
@@ -7,11 +7,18 @@
//! buffer's own line index when there is one, and otherwise through
//! `Workspace::file_view`, which reads a closed file at most once per
//! generation of it rather than once per question about it.
//!
//! One span never needs that read at all: a **file-scope declaration**'s own
//! name, whose client-side range the index recorded when the file was scanned
//! ([`vlog_semantic::DeclPositions`]). [`definition_location`] is that path,
//! and it is what `textDocument/definition` and `workspace/symbol` answer
//! from — see `docs/features/lazy-code-action/README.md`.
use std::path::Path;
use lsp_types::Location;
use lsp_types::{Location, Position, Range};
use vlog_parser::TextRange;
use vlog_semantic::{Def, Utf16Range};
use crate::convert::Positions;
use crate::state::Workspace;
@@ -27,6 +34,40 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
}
/// Where an **indexed** declaration is written — its name's own range.
///
/// The index converted that range to client positions while it was scanning
/// the file ([`vlog_semantic::DeclLines::positions`]), so pointing an editor
/// at a module nobody has open is a map lookup rather than a file read: the
/// same eight numbers, computed once at index time instead of once per
/// question. Only **file-scope** declarations carry them; a member (a port, a
/// parameter, a class field) records none and falls through to
/// [`location`]'s read, which is the whole reason this is a separate function
/// rather than a change inside that one.
///
/// **An open buffer keeps the read.** Its text may have moved since it was
/// indexed, and every other answer about that buffer is computed against the
/// text it holds now; answering this one from the index instead would make
/// go-to-definition disagree with the document symbols beside it.
pub fn definition_location(ws: &Workspace, path: &Path, def: &Def) -> Option<Location> {
if ws.document_for_path(path).is_none() {
if let Some(recorded) = def.lines.positions {
return Some(Location { uri: path_to_uri(path)?, range: range(recorded.name) });
}
}
location(ws, path, def.name_span)
}
/// An index-recorded range as the protocol's own — the same four numbers,
/// both already counted in UTF-16 code units by the file's own
/// `LineIndex::utf16_position`, which is the converter `Positions` uses too.
fn range(recorded: Utf16Range) -> Range {
Range {
start: Position { line: recorded.start.line, character: recorded.start.character },
end: Position { line: recorded.end.line, character: recorded.end.character },
}
}
/// The 1-based line a byte offset falls on, for hover text that names a file
/// and a line rather than jumping to it.
///
@@ -49,3 +90,197 @@ pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
pub fn display_name(path: &Path) -> String {
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
}
#[cfg(test)]
mod tests {
use super::*;
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_locate_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
/// Write a file as **bytes**, so a test can put a BOM or CRLF in one.
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text.as_bytes()).expect("write");
path
}
/// An indexed workspace over everything written so far.
fn indexed(&self) -> Workspace {
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![self.path.clone()]);
ws
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
/// The one declaration of `name` in the index, and the file it is in.
fn only_def<'w>(ws: &'w Workspace, name: &str) -> (&'w Def, &'w Path) {
let index = ws.index();
let [def] = index.units(name) else { panic!("exactly one `{name}`") };
(def, index.path(def.file).expect("a path"))
}
#[test]
fn a_file_scope_definition_is_located_without_reading_its_file() {
let tree = Tree::new("no_read");
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
let ws = tree.indexed();
let (def, path) = only_def(&ws, "sub");
let indexed = definition_location(&ws, path, def).expect("a location");
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
// Only now, so the comparison cannot be what filled the cache.
let read = location(&ws, path, def.name_span).expect("a location");
assert_eq!(indexed, read);
assert_eq!(ws.held_views().len(), 1, "the file-read path really does read one");
}
#[test]
fn the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom() {
// Everything that has ever made a UTF-16 conversion disagree, in one
// file: a BOM at offset 0, CRLF line endings, a two-byte character, a
// three-byte one, and an astral character that is *two* UTF-16 code
// units on its own.
let tree = Tree::new("encodings");
tree.write(
"wide.sv",
"\u{feff}// é ✓ 𝛼𝛽 — a comment\r\n\
// 𝟘𝟙𝟚 more\r\n\
module wide (\r\n input logic clk\r\n);\r\nendmodule\r\n",
);
let ws = tree.indexed();
let (def, path) = only_def(&ws, "wide");
let indexed = definition_location(&ws, path, def).expect("a location");
assert!(ws.held_views().is_empty(), "still no read");
let read = location(&ws, path, def.name_span).expect("a location");
assert_eq!(indexed, read, "the index-only range must be the file-read one");
// And it really is the name, not the line: `module ` is seven UTF-16
// units into line 2 (0-based), whatever the lines above it hold.
assert_eq!(indexed.range.start.line, 2);
assert_eq!(indexed.range.start.character, 7);
assert_eq!(indexed.range.end.character, 11);
}
#[test]
fn an_open_buffer_still_answers_from_the_buffer() {
// The index saw the file on disk; the buffer has since gained a line
// above the declaration, and has not been re-indexed. An indexed span
// is stale either way — the byte offset is the disk file's — and what
// this pins is that the *conversion* is unchanged by this round: the
// buffer's own line index, exactly as before, so go-to-definition and
// the document symbols beside it still agree with each other.
let tree = Tree::new("open_buffer");
let path = tree.write("sub.sv", "module sub;\nendmodule\n");
let mut ws = tree.indexed();
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "// typed since\nmodule sub;\nendmodule\n".to_string());
let (def, path) = only_def(&ws, "sub");
let located = definition_location(&ws, path, def).expect("a location");
assert_eq!(
located,
location(&ws, path, def.name_span).expect("a location"),
"an open buffer takes the file-read path, index positions or not"
);
assert_eq!(located.range.start.line, 0, "byte 7 of the buffer, not of the index's file");
assert!(ws.held_views().is_empty(), "an open buffer is never viewed");
}
#[test]
fn a_member_keeps_the_file_read_path() {
// Members carry no `DeclPositions` — see `DeclLines` — so the fallback
// is not decoration: it is the only answer for a port.
let tree = Tree::new("member");
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
let ws = tree.indexed();
let index = ws.index();
let [port] = index.member("sub", "clk") else { panic!("one `clk`") };
assert!(port.lines.positions.is_none(), "a member records no client positions");
let path = index.path(port.file).expect("a path");
assert_eq!(
definition_location(&ws, path, port),
location(&ws, path, port.name_span),
"and the fallback answers exactly what it always did"
);
assert_eq!(ws.held_views().len(), 1, "which cost the read");
}
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server --bin lucisv-server locate::tests::defining -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
fn defining_over_a_real_project() {
// TODO §37.3's own number, beside the code it measures rather than in
// `perf.rs` — the precedent `perf::mean`'s `pub(crate)` exists for.
// Two columns over the same corpus and the same targets: converting an
// indexed span by reading its file, and reading it off the index.
// **Read-only** — the corpus is opened, never written.
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
return;
};
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
});
let started = std::time::Instant::now();
ws.open_whole_workspace(vec![PathBuf::from(&root)]);
let scan = started.elapsed();
// The targets: modules the corpus instantiates somewhere, whose single
// declaration the index can name — what an F12 on an instantiation
// lands on, and each in a different file.
let names: Vec<String> =
ws.index().instantiations().map(|(name, _)| name.to_string()).collect();
let targets: Vec<(PathBuf, vlog_semantic::Def)> = names
.iter()
.filter_map(|name| {
let path = vlog_refactor::module_definition(ws.index(), name).ok()?;
let [def] = ws.index().units(name) else { return None };
def.lines.positions.is_some().then(|| (path.to_path_buf(), def.clone()))
})
.take(200)
.collect();
let indexed = crate::perf::mean(5, || {
for (path, def) in &targets {
std::hint::black_box(definition_location(&ws, path, def));
}
});
let read = crate::perf::mean(5, || {
for (path, def) in &targets {
std::hint::black_box(location(&ws, path, def.name_span));
}
});
let each = targets.len().max(1) as u32;
eprintln!(
"definition over {} indexed files of {root} (scan {scan:?}), {} targets:\n \
index-only {indexed:?}, file-read {read:?} — {:?} vs {:?} per definition",
ws.index().files().len(),
targets.len(),
indexed / each,
read / each,
);
}
}
+162 -9
View File
@@ -13,21 +13,28 @@ 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 lint_snapshot;
mod lint_trace;
mod locate;
mod module_select;
mod nav;
mod on_type;
mod pairs;
@@ -35,6 +42,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 +69,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;
@@ -126,6 +137,8 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
configuration: configuration_support(&params),
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)?)?;
@@ -259,10 +272,18 @@ 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(),
// Every action is returned complete; there is nothing to resolve.
resolve_provider: None,
// The quick fixes are complete when they are offered; the port
// refactorings are not, for a client that can ask
// (`docs/features/lazy-code-action/README.md`). Advertised
// unconditionally because the server can always answer a resolve
// — including for an action that already carries its edit, which
// it hands straight back.
resolve_provider: Some(true),
})),
// The port refactorings. `lucisv.addPort` needs a declaration typed by
// the user, which no code action can carry, and a Vim user has no
@@ -391,10 +412,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
@@ -499,6 +523,50 @@ fn snippet_support(params: &InitializeParams) -> bool {
.unwrap_or(false)
}
/// Whether the client can fetch a code action's `edit` after the fact —
/// `textDocument.codeAction.resolveSupport.properties` listing `"edit"`.
///
/// The property list is the capability: a client that can resolve `title`
/// alone cannot be offered an action without its edit, so nothing short of
/// `"edit"` counts. A client that says nothing gets every action complete, as
/// every client did before this was read
/// (`docs/features/lazy-code-action/README.md`).
fn code_action_resolve_support(params: &InitializeParams) -> bool {
params
.capabilities
.text_document
.as_ref()
.and_then(|text_document| text_document.code_action.as_ref())
.and_then(|code_action| code_action.resolve_support.as_ref())
.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
@@ -1148,6 +1216,91 @@ mod tests {
assert!(kinds.contains(&CodeActionKind::QUICKFIX));
assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL)));
assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS)));
assert_eq!(
options.resolve_provider,
Some(true),
"the port refactorings are offered without their edits to a client that can ask"
);
}
#[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::{
ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities,
TextDocumentClientCapabilities,
};
assert!(
!code_action_resolve_support(&InitializeParams::default()),
"silence means the whole edit up front"
);
let saying = |properties: &[&str]| InitializeParams {
capabilities: ClientCapabilities {
text_document: Some(TextDocumentClientCapabilities {
code_action: Some(CodeActionClientCapabilities {
resolve_support: Some(CodeActionCapabilityResolveSupport {
properties: properties.iter().map(|p| p.to_string()).collect(),
}),
..Default::default()
}),
..Default::default()
}),
..Default::default()
},
..Default::default()
};
assert!(code_action_resolve_support(&saying(&["edit"])));
assert!(code_action_resolve_support(&saying(&["documentation", "edit"])));
assert!(
!code_action_resolve_support(&saying(&["documentation"])),
"resolving anything but the edit is no use to us"
);
assert!(!code_action_resolve_support(&saying(&[])));
}
#[test]
+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());
}
}
+79 -2
View File
@@ -7,7 +7,7 @@ use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId
use crate::convert::Positions;
use crate::includes;
use crate::locate::location;
use crate::locate::{definition_location, location};
use crate::state::{Document, Workspace};
use crate::uri::path_to_uri;
@@ -60,7 +60,9 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
.iter()
.filter_map(|def| {
let path = ws.index().path(def.file)?;
location(ws, path, def.name_span)
// A file-scope declaration's range is already in the index, so
// the jump costs no read of the file it lands in.
definition_location(ws, path, def)
})
.collect(),
None => Vec::new(),
@@ -550,6 +552,51 @@ mod tests {
assert_eq!(locations[0].range.start.line, 1);
}
/// A qualified type name is two references, each addressable on its own
/// half: the parser spans `pkg::t` and `DataType::segments` splits it, so
/// F12 on the *item* lands on the typedef rather than on the package.
#[test]
fn a_scoped_type_name_jumps_from_its_item_half() {
let text = "\
package pkg;
typedef logic [1:0] t;
endpackage
module m;
pkg::t x;
endmodule
";
let (ws, uri) = document(text);
let item = definition(&ws, &uri, at(text, "pkg::t x") + 5);
assert_eq!(item.len(), 1, "the typedef");
assert_eq!(item[0].range.start.line, 1, "the `typedef ... t;` line");
assert_eq!(item[0].range.start.character, 22, "the name `t`, not the keyword");
let unit = definition(&ws, &uri, at(text, "pkg::t x"));
assert_eq!(unit.len(), 1, "the package");
assert_eq!(unit[0].range.start.line, 0);
}
/// `bus_if.mp bus` — the interface is the type, so the head range is what
/// F12 answers from; the modport tail is a member of it.
#[test]
fn an_interface_port_type_jumps_from_its_head() {
let text = "\
interface bus_if;
logic clk;
modport mp (input clk);
endinterface
module m (bus_if.mp bus);
endmodule
";
let (ws, uri) = document(text);
let head = definition(&ws, &uri, at(text, "bus_if.mp bus") + 2);
assert_eq!(head.len(), 1, "the interface");
assert_eq!(head[0].range.start.line, 0);
assert_eq!(head[0].range.start.character, 10, "the interface name");
let tail = definition(&ws, &uri, at(text, "bus_if.mp bus") + 7);
assert_eq!(tail.len(), 1, "the modport");
assert_eq!(tail[0].range.start.line, 2);
}
#[test]
fn a_macro_use_jumps_to_its_define_in_the_same_file() {
let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n";
@@ -691,6 +738,36 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_cross_file_definition_reads_no_file() {
// The jump above, asked again for what it *costs*: the target module's
// range is in the index (`DeclPositions`), so nothing opens `sub.sv`.
// Pinned through the view cache, which is where a read would land.
let dir = temp_dir("no_read");
let sub = dir.join("sub.sv");
fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write");
let top_path = dir.join("top.sv");
let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
fs::write(&top_path, top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), top_text.to_string());
let locations = definition(&ws, &uri, at(top_text, "sub u_sub"));
assert_eq!(locations.len(), 1);
assert_eq!(locations[0].range.start.character, 7, "and it is still the right answer");
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
// `workspace/symbol` answers the same way, over the same index.
let hits = crate::symbols::workspace_symbols(&ws, "sub");
assert!(hits.iter().any(|hit| hit.name == "sub"), "{hits:#?}");
assert!(ws.held_views().is_empty(), "nor did the symbol search");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn an_ambiguous_workspace_name_returns_every_location() {
let dir = temp_dir("ambig");
+24 -8
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
@@ -1022,6 +1022,14 @@ fn a_code_action_at_an_instantiation_before_and_after() {
let after = mean(20, || {
black_box(crate::ports::code_actions(&ws, &uri, black_box(offset)));
});
// TODO §37.1's column: the *offer* a client that can resolve receives,
// which reads the buffer and — at an instantiation — one more file,
// whatever the fan-out is. The edit is computed by `resolve`, which is the
// `after` column above, once, when the user clicks.
let position = ws.document(&uri).expect("open").positions().position(offset);
let offer = mean(20, || {
black_box(crate::ports::offers(&ws, &uri, black_box(position), black_box(offset)));
});
let read = mean(3, || {
black_box(ws.sources());
});
@@ -1035,9 +1043,10 @@ fn a_code_action_at_an_instantiation_before_and_after() {
});
// A measurement of an answer that was not given is worthless.
assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1);
assert_eq!(crate::ports::offers(&ws, &uri, position, offset).len(), 1);
eprintln!(
"codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \
whole workspace {before:?}, fan-out {after:?} \
whole workspace {before:?}, fan-out {after:?}, offer {offer:?} \
(`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})",
ws.index().files().len()
);
@@ -1111,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 —
@@ -1121,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());
@@ -1129,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!(
+738 -10
View File
@@ -1,5 +1,5 @@
//! The port refactorings on the wire: `textDocument/codeAction` for the two
//! that need no typing, and `workspace/executeCommand` for all three.
//! The port refactorings on the wire: `textDocument/codeAction` for the four
//! that need no typing, and `workspace/executeCommand` for all five.
//!
//! Protocol only. Every edit is computed by `vlog_refactor` over the same file
//! set the workspace index was built from; this module turns the result into a
@@ -8,10 +8,18 @@
//!
//! **Why commands as well as code actions.** Adding a port needs a
//! declaration typed by the user, and a code action carries no input — so
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`
//! and `lucisv.propagatePorts` take a position and exist for the same reason a
//! Vim user has no lightbulb: a command works everywhere a keybinding does.
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`,
//! `lucisv.propagatePorts`, `lucisv.expandWildcard` and `lucisv.convertToAnsi`
//! take a position and exist for the same reason a Vim user has no lightbulb:
//! a command works everywhere a keybinding does.
//! See `docs/features/refactor-ports/README.md`.
//!
//! **Two shapes of code action.** A client that can resolve is *offered*
//! actions with no edit ([`offers`]) and asks for the edit when the user picks
//! one ([`resolve`]); a client that cannot gets the edit up front
//! ([`code_actions`]). The offer reads one or two files whatever the module's
//! fan-out is, which is the whole point — see
//! `docs/features/lazy-code-action/README.md`.
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
#![allow(clippy::mutable_key_type)]
@@ -22,12 +30,13 @@ use std::path::{Path, PathBuf};
use lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
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
@@ -40,14 +49,48 @@ pub const ADD_PORT: &str = "lucisv.addPort";
pub const REMOVE_PORT: &str = "lucisv.removePort";
/// Connect an instantiation's missing ports: `[uri, position]`.
pub const PROPAGATE_PORTS: &str = "lucisv.propagatePorts";
/// Write out the `.*` at a position: `[uri, position]`.
pub const EXPAND_WILDCARD: &str = "lucisv.expandWildcard";
/// Rewrite the non-ANSI header at a position ANSI-style: `[uri, position]`.
pub const CONVERT_TO_ANSI: &str = "lucisv.convertToAnsi";
/// Every command this server executes.
pub fn commands() -> Vec<String> {
vec![ADD_PORT.to_string(), REMOVE_PORT.to_string(), PROPAGATE_PORTS.to_string()]
vec![
ADD_PORT.to_string(),
REMOVE_PORT.to_string(),
PROPAGATE_PORTS.to_string(),
EXPAND_WILDCARD.to_string(),
CONVERT_TO_ANSI.to_string(),
]
}
/// The port actions available at a position, each carrying its own computed
/// edit — nothing to resolve, and nothing offered that would be refused.
///
/// What a client without `codeAction/resolve` gets, and what [`resolve`]
/// re-runs to answer one that has. It reads the module's whole fan-out
/// ([`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() };
@@ -57,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();
}
@@ -76,7 +119,227 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
.collect()
}
/// Run one of the three commands, or say why it cannot run.
/// What a lazily-offered action carries in place of its edit: enough to ask
/// the same question again when the user picks it.
///
/// The position rather than the offset, because that is what the client
/// speaks and what the buffer it will be re-read against is indexed by.
#[derive(Serialize, Deserialize)]
struct Offer {
uri: Uri,
position: Position,
title: String,
}
/// The sentence a resolve that finds nothing answers with. Not a silent empty
/// edit: an action that has stopped applying is news, and applying nothing
/// while saying nothing is how a user comes to distrust the lightbulb.
const GONE: &str = "the action is no longer available.";
/// A resolve of something this server never offered.
const NOT_OURS: &str = "this code action carries no lucisv port refactoring to resolve.";
/// The port actions available at a position, **without their edits** — the
/// offer a client that can `codeAction/resolve` is sent.
///
/// The question "is there an action here at all" is answered over the buffer
/// itself plus, for a cursor on an instantiation, the instantiated module's
/// own declaration ([`offer_sources`]) — one or two files, whatever the
/// module's fan-out is. The edits those two files produce are thrown away;
/// [`resolve`] computes the real one over the whole fan-out when the user
/// clicks.
///
/// **The count in the title comes from the index**, since the fan-out has not
/// been read: [`instances_of`] counts every *instance* the index has seen of
/// the module, so `sub u1(), u2();` counts two. The eager title counts the
/// instances the plan really rewrites, which is the same number except where
/// the index cannot know — an unsaved buffer's new instantiation, a
/// file-scope instantiation site (which records no edge), an instance
/// connecting with `.*`. The two are therefore matched on the part of the
/// title *before* that count; see [`key`].
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) = doc.path.clone() else { return Vec::new() };
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
// resolve would then decline.
if modules.is_empty() || modules.iter().any(|name| declared_twice(ws, name)) {
return Vec::new();
}
let sources = offer_sources(ws, &path, &doc.text, &modules);
offered(doc, &sources, &path, offset)
.into_iter()
.map(|offer| {
let title = counted(ws, offer.title, &modules);
let data =
serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() })
.ok();
CodeActionOrCommand::CodeAction(CodeAction {
title,
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
data,
..Default::default()
})
})
.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.
///
/// The second is the same two steps `inlay.rs`'s `Plans::read` takes — the
/// index says which file declares the module, and that one file is read —
/// and it is what lets the engine answer "this instantiation is missing
/// ports" without any file that *instantiates* the module. A cursor on a port
/// declaration names its own module, whose declaring file is the buffer
/// itself, so that case reads nothing at all.
///
/// `pub(crate)` for the test that pins exactly this set.
pub(crate) fn offer_sources(
ws: &Workspace,
path: &Path,
text: &str,
modules: &[String],
) -> Vec<(PathBuf, String)> {
let mut sources = vec![(path.to_path_buf(), text.to_string())];
for name in modules {
let Ok(declared_in) = vlog_refactor::module_definition(ws.index(), name) 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));
}
}
sources
}
/// The edit for one offered action, computed now that the user has picked it.
///
/// Today's eager answer at the offer's own position, narrowed to the action
/// whose title the client is holding. An action already carrying its edit is
/// returned untouched — a client may resolve anything it likes, and the quick
/// fixes in `code_action.rs` are complete when they are offered.
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 `codeAction/resolve` carries a `CodeAction`, not a `textDocument`, so
// the large-file fast path's gate (which reads the URI out of the params)
// never sees this request. A buffer that has grown past the threshold
// since it was offered an action is refused here instead: the fast path's
// whole contract is that a large buffer is never parsed, and one stale
// lightbulb is not a reason to break it.
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) if key(&found.title) == key(&offer.title) => {
Some(found)
}
_ => None,
})
.map(|mut resolved| {
resolved.data = action.data;
resolved
})
.ok_or_else(|| GONE.to_string())
}
/// An action's identity: its title without the count phrase the offer and the
/// eager path can honestly disagree about.
///
/// `"lucisv: remove port `rst` (updates 3 instantiations)"` keys as
/// ``"lucisv: remove port `rst`"``; a title with no such suffix
/// (`"lucisv: connect 1 missing port"`, whose count is the cursor's own file's
/// and therefore exact) keys as itself. An escaped identifier cannot contain a
/// space, so `" ("` never occurs inside a port name.
fn key(title: &str) -> &str {
title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")).map_or(title, |(head, _)| head)
}
/// An offered title with the workspace's own instantiation count in it,
/// replacing the one the offer's one or two files could see.
///
/// Only a title whose count *is* an instantiation census is recounted:
/// `lucisv: expand .* (3 connections)` counts the connections one wildcard
/// becomes, which the offer's own two files already know exactly and no index
/// lookup could improve (`vlog_refactor::is_sites_phrase`).
fn counted(ws: &Workspace, title: String, modules: &[String]) -> String {
let Some((head, phrase)) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" ("))
else {
return title;
};
if !vlog_refactor::is_sites_phrase(phrase) {
return title;
}
let sites = modules.iter().map(|name| instances_of(ws, name)).sum();
format!("{head} ({})", vlog_refactor::sites_phrase(sites))
}
/// Every instance of `name` the index has seen. An edge is one written
/// statement, so its instances are counted rather than the edges themselves —
/// `sub u1 (), u2 ();` is two connection lists to rewrite and the title says
/// two.
fn instances_of(ws: &Workspace, name: &str) -> usize {
ws.index().instantiations_of(name).iter().map(|edge| edge.instances.len()).sum()
}
/// Whether the index holds more than one declaration of `name` a module
/// reference could mean — the ambiguity `vlog_refactor::module_definition`
/// refuses to guess between, and the one the engine refuses a refactoring
/// over.
fn declared_twice(ws: &Workspace, name: &str) -> bool {
ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1
}
/// Run one of the five commands, or say why it cannot run.
///
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
/// it reaches the editor is `server.rs`'s business: it is pushed as a
@@ -122,10 +385,23 @@ pub fn execute(
let sources = sources_at(ws, &path, offset);
vlog_refactor::propagate_ports(&sources, &path, offset)?
}
EXPAND_WILDCARD => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, EXPAND_WILDCARD)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::expand_wildcard(&sources, &path, offset)?
}
CONVERT_TO_ANSI => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, CONVERT_TO_ANSI)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::convert_to_ansi(&sources, &path, offset)?
}
// The instantiation skeleton is not a port refactoring and computes
// its own `WorkspaceEdit`, but `server.rs` routes every non-lens
// `workspace/executeCommand` through here — this is the one place an
// edit-producing command is handed to `Server::deliver`.
crate::imports::ORGANIZE_IMPORTS => return crate::imports::execute(ws, arguments),
crate::instantiate::INSTANTIATE => {
return crate::instantiate::execute(ws, arguments).map(|edit| (edit, Vec::new()))
}
@@ -809,6 +1085,322 @@ mod tests {
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
}
// ------------------------------------------------------------------
// the lazy offer and its resolve (TODO §37.1)
// ------------------------------------------------------------------
/// The offer a client that can resolve receives at `offset`.
fn offered(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
let position = ws.document(uri).expect("an open document").positions().position(offset);
offers(ws, uri, position, offset)
}
/// One action's title and kind — what a lightbulb draws, and all an offer
/// promises.
fn menu(actions: &[CodeActionOrCommand]) -> Vec<(String, Option<String>)> {
actions
.iter()
.map(|action| {
let CodeActionOrCommand::CodeAction(action) = action else {
return ("a command".to_string(), None);
};
(action.title.clone(), action.kind.as_ref().map(|k| k.as_str().to_string()))
})
.collect()
}
/// The one action an offer holds.
fn only(actions: &[CodeActionOrCommand]) -> &CodeAction {
let [CodeActionOrCommand::CodeAction(action)] = actions else {
panic!("exactly one action, got {actions:#?}")
};
action
}
#[test]
fn the_lazy_offer_names_exactly_what_the_eager_one_names() {
let tree = Tree::new("lazy_menu");
let mut ws = crowded(&tree, 40);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let lazy = offered(&ws, &sub_uri, offset);
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &sub_uri, offset)));
assert_eq!(
menu(&lazy)[0].0,
"lucisv: remove port `rst` (updates 3 instantiations)",
"counted from the index, and it agrees with the plan's own count"
);
let action = only(&lazy);
assert!(action.edit.is_none(), "an offer carries no edit");
assert!(action.data.is_some(), "it carries what resolve needs instead");
}
#[test]
fn the_offer_reads_the_buffer_and_at_most_the_declaring_file() {
// The pin `the_files_a_code_action_reads_are_the_modules_own_fan_out`
// is to the eager path; this is the same question asked of the offer,
// through the set it hands the engine. Neither the 40 noise files nor
// — and this is the point — any of the three instantiating tops.
let tree = Tree::new("lazy_reads");
let mut ws = crowded(&tree, 40);
let sub = tree.path.join("sub.sv");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
assert_eq!(ws.sources().len(), 44, "the whole workspace");
assert_eq!(ws.module_sources(&sub, &["sub".to_string()]).len(), 4, "the eager fan-out");
// A cursor on a port declaration: the module is the buffer's own.
let read = offer_sources(&ws, &sub, SUB, &["sub".to_string()]);
let names: Vec<String> = read
.iter()
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
.collect();
assert_eq!(names, ["sub.sv"], "one file, and it is the buffer itself");
// A cursor on an instantiation: the buffer, plus the one file the
// index says declares the module.
let top = tree.path.join("top0.sv");
let top_text = std::fs::read_to_string(&top).expect("read");
let read = offer_sources(&ws, &top, &top_text, &["sub".to_string()]);
let mut names: Vec<String> = read
.iter()
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
.collect();
names.sort();
assert_eq!(names, ["sub.sv", "top0.sv"], "and never top1, top2 or a noise file");
}
#[test]
fn a_resolved_action_carries_the_eager_edit_at_a_port_declaration() {
let tree = Tree::new("resolve_port");
let mut ws = crowded(&tree, 40);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let resolved = resolve(&ws, only(&offered(&ws, &sub_uri, offset)).clone()).expect("edit");
let eager = only(&code_actions(&ws, &sub_uri, offset)).clone();
assert_eq!(resolved.title, eager.title);
assert_eq!(resolved.kind, eager.kind);
assert_eq!(resolved.edit, eager.edit, "the same WorkspaceEdit, to the byte");
assert!(resolved.data.is_some(), "the offer's own data survives the round trip");
}
#[test]
fn a_resolved_action_carries_the_eager_edit_at_an_instantiation() {
// The other cursor shape: an instantiation missing a connection, where
// the offer has to read the *instantiated* module's declaration to
// know there is anything to offer at all.
let tree = Tree::new("resolve_inst");
let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", text);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), text.to_string());
let offset = text.find("sub u_sub").expect("the instantiation") as u32;
let lazy = offered(&ws, &uri, offset);
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
assert_eq!(menu(&lazy)[0].0, "lucisv: connect 1 missing port");
assert!(only(&lazy).edit.is_none());
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
assert_eq!(
edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text,
", .rst(rst)"
);
}
#[test]
fn the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count() {
// The pin `an_unsaved_buffer_contributes_the_instantiation_the_index
// _has_not_seen` moved to the lazy path. The offer counts instances
// from the index, which has not seen the unsaved one, so the title
// says three; the *edit* is computed over the fan-out plus every open
// buffer, so it disconnects all four. Exactness lives in the edit,
// which is what the user actually applies.
let tree = Tree::new("lazy_unsaved");
let mut ws = crowded(&tree, 20);
let extra = tree.path.join("noise0.sv");
let extra_uri = path_to_uri(&extra).expect("uri");
let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n";
ws.set_document(extra_uri.clone(), typed.to_string());
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let lazy = offered(&ws, &sub_uri, offset);
assert_eq!(
menu(&lazy)[0].0,
"lucisv: remove port `rst` (updates 3 instantiations)",
"the index has not seen the fourth"
);
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
assert_eq!(
resolved.title, "lucisv: remove port `rst` (updates 4 instantiations)",
"and the resolve says so"
);
let edit = resolved.edit.as_ref().expect("an edit");
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
assert_eq!(resolved.edit, only(&code_actions(&ws, &sub_uri, offset)).edit);
}
#[test]
fn a_resolve_of_an_action_the_buffer_no_longer_carries_is_refused() {
let tree = Tree::new("lazy_stale");
let mut ws = crowded(&tree, 10);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
// The user kept typing: the port the lightbulb was about is gone.
ws.set_document(sub_uri.clone(), "module sub (\n input logic clk\n);\nendmodule\n".into());
let message = resolve(&ws, offered.clone()).expect_err("nothing to resolve");
assert_eq!(message, GONE);
// And a document that has been closed altogether says the same.
ws.close_document(&sub_uri);
assert_eq!(resolve(&ws, offered).expect_err("no buffer"), GONE);
}
#[test]
fn a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused() {
// `codeAction/resolve`'s params are a `CodeAction`, so the fast path's
// own gate — which reads a `textDocument` out of the params — never
// sees this request. A buffer that grew past the threshold since it
// was offered an action must still not be parsed.
let tree = Tree::new("lazy_large");
let mut ws = crowded(&tree, 5);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
let _ = ws.set_client_settings(crate::settings::ClientSettings {
large_file_threshold: 8,
..Default::default()
});
ws.set_document(sub_uri.clone(), SUB.to_string());
assert!(ws.document(&sub_uri).expect("open").large, "the buffer is on the fast path");
assert_eq!(resolve(&ws, offered).expect_err("not parsed"), GONE);
}
#[test]
fn a_resolve_of_something_this_server_never_offered_says_so() {
let tree = Tree::new("lazy_foreign");
let (ws, uri, _) = opened(&tree);
let bare = CodeAction { title: "someone else's action".to_string(), ..Default::default() };
assert_eq!(resolve(&ws, bare.clone()).expect_err("no data"), NOT_OURS);
// Data that is not ours either — a shape `serde` cannot read as an
// offer. Refused, not guessed at.
let junk = CodeAction { data: Some(serde_json::json!({"nope": 1})), ..bare.clone() };
assert_eq!(resolve(&ws, junk).expect_err("junk data"), NOT_OURS);
// An action that already carries its edit — every quick fix in
// `code_action.rs`, and the port actions a non-resolving client is
// sent — comes straight back, because there is nothing to add to it.
let complete =
CodeAction { edit: Some(WorkspaceEdit::new(HashMap::from([(uri, vec![])]))), ..bare };
assert_eq!(resolve(&ws, complete.clone()).expect("nothing to do"), complete);
}
#[test]
fn a_name_the_workspace_declares_twice_is_not_offered_either() {
// The eager path refuses because both declaring files are in the set
// it reads (`a_module_declared_twice_is_refused_through_the_subset_as
// _well`). The offer reads neither, so it asks the index the same
// question — otherwise it would offer an action resolve then refuses.
let tree = Tree::new("lazy_ambiguous");
let mut ws = crowded(&tree, 10);
tree.write("clone.sv", SUB);
ws.rebuild_index();
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
assert!(offered(&ws, &sub_uri, offset).is_empty());
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "as the eager path does");
}
#[test]
fn a_title_keys_on_everything_but_its_count() {
assert_eq!(
key("lucisv: remove port `rst` (updates 3 instantiations)"),
key("lucisv: remove port `rst` (no instantiation in scope)")
);
assert_eq!(key("lucisv: connect 1 missing port"), "lucisv: connect 1 missing port");
assert_ne!(
key("lucisv: remove port `rst` (updates 1 instantiation)"),
key("lucisv: remove port `clk` (updates 1 instantiation)")
);
}
/// `cargo test --release -p lucisv_server --bin lucisv-server ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn the_offer_is_flat_where_the_eager_answer_grows() {
// `performance_take2.md` §6a measured the eager answer growing with
// the module's fan-out — ~1.4 ms per instantiating file plus a ~13 ms
// floor, 185 ms at 128 files, to offer *zero* actions. The offer reads
// one file (a cursor on a port declaration) or two (a cursor on an
// instantiation), so its column should be flat. Beside the code it
// measures rather than in `perf.rs`, which is what `perf::mean` is
// `pub(crate)` for.
for instantiators in [3usize, 40, 128] {
let tree = Tree::new(&format!("perf_offer_{instantiators}"));
tree.write("sub.sv", SUB);
for n in 0..instantiators {
tree.write(
&format!("top{n:03}.sv"),
&format!(
"module top{n:03};\n logic c, r;\n \
sub u_sub (.clk(c), .rst(r));\nendmodule\n"
),
);
}
for n in 0..200 {
tree.write(
&format!("noise{n:03}.sv"),
&format!(
"module noise{n:03};\n logic a;\n wire b;\n \
assign b = a;\nendmodule\n"
),
);
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
for (what, file, needle, skip) in [
("a port declaration", "sub.sv", "input logic rst", 12u32),
("an instantiation ", "top000.sv", "sub u_sub", 0),
] {
let path = tree.path.join(file);
let text = std::fs::read_to_string(&path).expect("read");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.clone());
let offset = text.find(needle).expect("the cursor") as u32 + skip;
let eager = crate::perf::mean(5, || {
std::hint::black_box(code_actions(&ws, &uri, offset));
});
let offer = crate::perf::mean(20, || {
std::hint::black_box(offered(&ws, &uri, offset));
});
eprintln!(
" fan-out {instantiators:>3}, cursor on {what}: eager {eager:?}, \
offer {offer:?} ({} actions)",
offered(&ws, &uri, offset).len()
);
}
}
}
#[test]
fn an_unknown_command_is_declined() {
let tree = Tree::new("unknown");
@@ -829,8 +1421,144 @@ mod tests {
assert!(message.contains("position"), "{message}");
}
// ------------------------------------------------------------------
// the `.*` expansion (TODO §50)
// ------------------------------------------------------------------
/// A workspace whose `top.sv` instantiates `sub` with a wildcard.
fn wildcard(tree: &Tree) -> (Workspace, Uri, &'static str) {
const TEXT: &str =
"module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TEXT);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TEXT.to_string());
(ws, uri, TEXT)
}
#[test]
fn expand_wildcard_takes_a_position() {
let tree = Tree::new("expand");
let (ws, uri, text) = wildcard(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 2, character: 24 }).expect("position"),
];
let (edit, warnings) = execute(&ws, EXPAND_WILDCARD, &arguments).expect("expands");
assert!(warnings.is_empty(), "{warnings:?}");
let edits = edits_for(&edit, &uri);
assert_eq!(edits.len(), 1, "{edits:#?}");
assert_eq!(edits[0].new_text, ".rst(rst)");
// The range is the `.*` itself, in the client's own coordinates.
assert_eq!(edits[0].range.start.character, 24);
assert_eq!(edits[0].range.end.character, 26);
assert_eq!(&text[text.find(".*").expect("the wildcard")..][..2], ".*");
}
#[test]
fn expand_wildcard_refuses_where_there_is_no_wildcard() {
let tree = Tree::new("expand_none");
let (ws, top_uri, _) = opened(&tree);
let arguments = vec![
serde_json::to_value(&top_uri).expect("uri"),
serde_json::to_value(Position { line: 2, character: 6 }).expect("position"),
];
let message = execute(&ws, EXPAND_WILDCARD, &arguments).expect_err("no wildcard");
assert!(message.contains("writes no `.*` to expand"), "{message}");
}
#[test]
fn the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
let tree = Tree::new("expand_action");
let (ws, uri, text) = wildcard(&tree);
let offset = text.find(".*").expect("the wildcard") as u32;
let lazy = offered(&ws, &uri, offset);
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
// The count is the connections the wildcard becomes, and the index's
// instantiation census must not overwrite it.
assert_eq!(menu(&lazy)[0].0, "lucisv: expand .* (1 connection)");
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
assert_eq!(resolved.title, "lucisv: expand .* (1 connection)");
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, ".rst(rst)");
}
// ------------------------------------------------------------------
// the non-ANSI → ANSI conversion (TODO §51)
// ------------------------------------------------------------------
/// A workspace whose `legacy.sv` writes a Verilog-2001 header.
const LEGACY: &str =
"module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
fn legacy(tree: &Tree) -> (Workspace, Uri) {
let path = tree.write("legacy.sv", LEGACY);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), LEGACY.to_string());
(ws, uri)
}
#[test]
fn convert_to_ansi_takes_a_position() {
let tree = Tree::new("ansi");
let (ws, uri) = legacy(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
// The module's own name — inside the header, and nowhere near a
// port declaration.
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
];
// Two insertions — the ANSI prefixes — and three deletions: `input a;`,
// `output [7:0] b;` and the `reg [7:0] b;` that completed it.
let (edit, warnings) = execute(&ws, CONVERT_TO_ANSI, &arguments).expect("converts");
assert!(warnings.is_empty(), "{warnings:?}");
let edits = edits_for(&edit, &uri);
let written: Vec<&str> = edits.iter().map(|e| e.new_text.as_str()).collect();
assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}");
}
#[test]
fn convert_to_ansi_refuses_an_ansi_header() {
let tree = Tree::new("ansi_none");
let (ws, top_uri, _) = opened(&tree);
let arguments = vec![
serde_json::to_value(&top_uri).expect("uri"),
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
];
let message = execute(&ws, CONVERT_TO_ANSI, &arguments).expect_err("nothing to convert");
assert!(message.contains("declares no ports"), "{message}");
}
#[test]
fn the_ansi_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
let tree = Tree::new("ansi_action");
let (ws, uri) = legacy(&tree);
// The cursor on the module's name: in the header, on no port.
let offset = LEGACY.find("legacy (").expect("the name") as u32;
let lazy = offered(&ws, &uri, offset);
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
assert_eq!(menu(&lazy)[0].0, "lucisv: convert ports to ANSI (2 ports)");
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
assert_eq!(resolved.title, "lucisv: convert ports to ANSI (2 ports)");
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, "input ");
}
#[test]
fn the_command_list_is_what_the_server_advertises() {
assert_eq!(commands(), vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS]);
assert_eq!(
commands(),
vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS, EXPAND_WILDCARD, CONVERT_TO_ANSI]
);
}
}
+324 -12
View File
@@ -17,9 +17,11 @@ use std::path::PathBuf;
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
use vlog_parser::LineIndex;
use vlog_semantic::FileFacts;
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,25 +50,62 @@ 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())?;
// The engine's own first look at the request, over the buffer it is about
// to be handed anyway. It refuses only what `vlog_refactor::rename` is
// certain to refuse in the same words — so this is still one voice
// deciding, just asked before the workspace is materialized for it. A
// cursor on nothing used to read, parse and index all 3 976 files before
// saying so (take 5 review §3 item 6); now it reads none.
//
// Sound because both selectors below hand the engine this very buffer, so
// the out-of-scope refusal that outranks a cursor refusal cannot fire.
//
// A refusal here still writes a trace, because "where did the time go" is
// a question about the fast refusals too — and the answer, nowhere, is
// only believable if the line says `selected=0` and `parses=0` in the same
// fields the slow road fills.
if let Err(refusal) = vlog_refactor::rename_preflight(&doc.semantics, offset, new_name) {
let (selection, engine) =
(SelectionTrace::default(), vlog_refactor::RenameTrace::default());
*trace = Some(format!("{} {} preflight=true", selection.line(), engine.line()));
return Err(refusal);
}
// The name the cursor sits on, read off the buffer, is what the index is
// asked for the fan-out. No refusal is taken here: `vlog_refactor::rename`
// is the one voice that decides, and it decides over the files below. A
// 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 known = Known(ws);
let outcome =
vlog_refactor::rename_traced_with(&sources, &path, offset, new_name, &known, &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 {
@@ -100,6 +139,23 @@ pub fn rename(
Ok((WorkspaceEdit::new(changes), warnings))
}
/// The workspace answering the engine's `KnownFacts` question, and nothing
/// else: one call, to the one query that ties a record to the bytes it was
/// read off ([`Workspace::known_facts`]).
///
/// A newtype rather than an `impl` on `Workspace` so that the promise this
/// makes to `vlog_refactor` is written where a reader of the rename can see
/// it, and so that no other handler can acquire it by accident — the facts a
/// refactoring may reuse are the facts of the very texts it was handed, which
/// is a property of *this* call site.
struct Known<'a>(&'a Workspace);
impl vlog_refactor::KnownFacts for Known<'_> {
fn facts_for(&self, path: &std::path::Path, text: &str) -> Option<FileFacts> {
self.0.known_facts(path, text)
}
}
/// One sentence per file that writes the old name inside a macro invocation,
/// a directive line or an attribute and was **not** among the files the engine
/// was handed.
@@ -116,7 +172,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 +197,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,
@@ -186,6 +253,118 @@ mod tests {
(ws, uri)
}
/// A third file that spells nothing this rename is about, kept open so
/// the open-buffer rung selects it: the "container" class in miniature —
/// a file the engine must index and never analyses.
const BYSTANDER: &str = "module bystander;\n logic unrelated;\nendmodule\n";
/// `sub.sv`, `top.sv` and `quiet.sv`, with the last two open and a
/// persistent index store behind the workspace — so a rename is handed
/// records keyed on the very bytes it reads.
fn three_with_store(tree: &Tree, store: Option<&Tree>) -> (Workspace, Uri) {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let quiet = tree.write("bystander.sv", BYSTANDER);
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_cache_path: store.map(|s| s.path.to_string_lossy().into_owned()),
index_scope: crate::settings::IndexScope::Workspace,
..Default::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.set_document(path_to_uri(&quiet).expect("uri"), BYSTANDER.to_string());
(ws, uri)
}
/// Every edit and every warning one rename produced, with the workspace's
/// own scratch path taken out — the fingerprint the parity proof compares.
fn print(result: &(WorkspaceEdit, Vec<String>), root: &Path) -> String {
let (edit, warnings) = result;
let mut lines: Vec<String> = Vec::new();
for (uri, edits) in edit.changes.iter().flatten() {
for one in edits {
lines.push(format!(
"{} {:?}..{:?} -> {}",
uri.as_str(),
one.range.start,
one.range.end,
one.new_text
));
}
}
lines.sort();
lines.extend(warnings.iter().map(|w| format!("warn {w}")));
lines.join("\n").replace(root.to_str().expect("utf-8"), "")
}
/// **§R3b's server-side proof.** The same rename over the same files, once
/// with a warm index store behind it — where the engine is handed every
/// file's record and stops parsing the ones nothing analyses — and once
/// with no store at all, where it parses them all: byte-identical edits,
/// byte-identical warnings.
///
/// The reuse is asserted to have happened *and* to have removed a parse,
/// so a store that silently stopped answering would fail this rather than
/// pass it for the wrong reason.
#[test]
fn a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says() {
let tree = Tree::new("reuse_store");
let store = Tree::new("reuse_store_cache");
let (warm, uri) = three_with_store(&tree, Some(&store));
let mut line = None;
let with_store = rename_traced(&warm, &uri, at(TOP, "clk"), "clk_x", &mut line)
.expect("the rename succeeds");
let trace = line.expect("a trace is always written");
assert!(trace.contains("selected=3"), "all three files are selected: {trace}");
assert!(trace.contains("reused_files=3"), "and every record came from the store: {trace}");
assert!(trace.contains("other_files=1"), "bystander.sv is the unread one: {trace}");
assert!(trace.contains("parses{index=2"), "so only the two analysed files: {trace}");
let bare = Tree::new("reuse_none");
let (plain, plain_uri) = three_with_store(&bare, None);
let mut plain_line = None;
let no_store = rename_traced(&plain, &plain_uri, at(TOP, "clk"), "clk_x", &mut plain_line)
.expect("the rename succeeds");
let plain_trace = plain_line.expect("a trace is always written");
assert!(plain_trace.contains("reused_files=0"), "premise: no store, no reuse");
assert!(plain_trace.contains("parses{index=3"), "premise: all three parsed");
assert_eq!(
print(&with_store, &tree.path),
print(&no_store, &bare.path),
"the reuse changed an edit or a warning"
);
}
/// **Unsaved-buffer precedence, for free.** A buffer whose text disagrees
/// with the file on disk is not the bytes any record was written from, so
/// the store answers nothing for it and it is parsed — and the rename acts
/// on the buffer's text, which is the precedence it always had.
///
/// Nothing in the reuse arranges this: the key is the content, so unsaved
/// text misses the same way changed text does.
#[test]
fn an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text() {
let tree = Tree::new("reuse_unsaved");
let store = Tree::new("reuse_unsaved_cache");
let (mut ws, uri) = three_with_store(&tree, Some(&store));
// A signal that exists only in the buffer. Its record cannot be in a
// store keyed on what is on disk.
let edited = "module top;\n logic only_here;\n sub u_sub (.clk(only_here));\nendmodule\n";
ws.set_document(uri.clone(), edited.to_string());
let mut line = None;
let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line)
.expect("the buffer's own declaration renames");
let trace = line.expect("a trace is always written");
assert!(trace.contains("reused_files=1"), "only the untouched buffer's record: {trace}");
assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}");
let edits = edit.changes.as_ref().expect("changes").values().flatten().count();
assert_eq!(edits, 2, "the declaration and its one use, both in the buffer");
}
#[test]
fn prepare_offers_the_identifier_and_its_placeholder() {
let tree = Tree::new("prepare");
@@ -281,7 +460,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 +480,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 {
@@ -795,11 +974,16 @@ mod tests {
/// workspace was never consulted), so the file should not even be pulled
/// in — and if it were, the rename must still succeed, since no capture is
/// possible against a symbol nothing outside that file can see.
///
/// The symbol is a **function's** local, not a module's net: since
/// 2026-09-05 a net is a declaration on the module's hierarchical surface
/// and joins the fan-out by that rung (the test below), which would answer
/// this one for the wrong reason. A name inside a subprogram body is on
/// neither surface, which is what this attack needs.
#[test]
fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const LOCAL_ONLY: &str =
"module unrelated;\n wire taken_local;\n assign taken_local = 1'b0;\nendmodule\n";
const LOCAL_ONLY: &str = "module unrelated;\n function automatic int f();\n int taken_local = 0;\n return taken_local;\n endfunction\nendmodule\n";
let tree = Tree::new("fanout_local_only");
let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
@@ -816,6 +1000,32 @@ mod tests {
assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty());
}
/// The rung the hierarchical surface added: a module's internal **net**
/// spelled like the new name *is* a declaration the fan-out has to hold,
/// because `assign w = u_unrelated.taken_net;` in a fourth file resolves
/// to it now. So the file is pulled in — and the rename still succeeds
/// and still writes nothing there, because a package name and a net
/// inside a module capture nothing of each other.
#[test]
fn a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const NET_ONLY: &str =
"module unrelated;\n wire taken_net;\n assign taken_net = 1'b0;\nendmodule\n";
let tree = Tree::new("fanout_hierarchical_net");
let files = [("pkg.sv", PKG), ("net.sv", NET_ONLY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
let at = at(PKG, "cfg_pkg;");
let fan = fan_out(&ws, &path, at, "taken_net");
assert!(
fan.contains(&tree.path.join("net.sv")),
"a net is a hierarchical declaration of its name: {fan:?}"
);
let edit = same_answer(&ws, &path, at, "taken_net").expect("renames, no capture possible");
assert!(edit.edits_for(&tree.path.join("net.sv")).is_empty());
}
/// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two
/// packages, `p_pkg` and `q_pkg`, both export a member spelled the same
/// (`shared_name`); a third file imports both, `p_pkg` first, so
@@ -924,7 +1134,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:?}"
@@ -958,7 +1168,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"
@@ -972,4 +1182,106 @@ mod tests {
"and it is the engine's sentence, not the census's: {warning}"
);
}
// ------------------------------------------------------------------
// The engine-owned preflight (take 5 review §3 item 6, TODO §61.1)
// ------------------------------------------------------------------
/// A cursor on nothing used to select every in-scope file, parse all of
/// them and index them before the engine's 0.1 ms refusal. The preflight
/// is only worth having if that is now literally no parses at all — not
/// fewer, none — so the gate is asserted, not measured.
#[test]
fn a_rename_on_a_cursor_with_no_symbol_parses_nothing() {
let tree = Tree::new("nosymbolparses");
let (ws, uri) = opened(&tree);
let at_comment = TOP.len() as u32 - 1; // the newline after `endmodule`
let before = vlog_parser::stats::parses();
let mut trace = None;
let refusal =
rename_traced(&ws, &uri, at_comment, "probe", &mut trace).expect_err("no symbol there");
let parses = vlog_parser::stats::parses() - before;
assert_eq!(parses, 0, "the refusal parsed {parses} whole files");
assert_eq!(refusal, "there is no symbol to rename at this position.");
// And the `--verbose` channel says so in its own fields, so the phase
// that measures this row reads the parse count instead of trusting it.
let trace = trace.expect("a refusal traces too");
assert!(trace.contains("selected=0"), "{trace}");
assert!(trace.contains("parses=0"), "{trace}");
assert!(trace.contains("preflight=true"), "{trace}");
}
/// …and it is the same sentence the whole workspace produced, taken from
/// the engine over every in-scope file rather than from this module.
#[test]
fn the_preflights_refusal_is_the_whole_workspaces_refusal() {
let tree = Tree::new("preflightparity");
let (ws, uri) = opened(&tree);
let path = tree.path.join("top.sv");
for (case, offset) in [
("past the last item", TOP.len() as u32 - 1),
("on the `module` keyword", at(TOP, "module")),
("on a literal", at(TOP, "1'b0")),
] {
let fast = rename(&ws, &uri, offset, "probe").expect_err(case);
let slow = vlog_refactor::rename(&ws.sources(), &path, offset, "probe")
.expect_err("the whole workspace refuses too");
assert_eq!(fast, slow, "{case}");
}
}
/// Precedence, in the two places the preflight could have disturbed it: an
/// unusable buffer is refused by this module before the engine is asked
/// anything, and an invalid new name outranks whatever the cursor is on.
#[test]
fn the_preflight_does_not_disturb_the_refusal_order() {
let tree = Tree::new("preflightorder");
let (ws, uri) = opened(&tree);
let untitled = Uri::from_str("untitled:Untitled-1").expect("uri");
let mut with_untitled = Workspace::default();
with_untitled.set_document(untitled.clone(), TOP.to_string());
assert_eq!(
rename(&with_untitled, &untitled, at(TOP, "u_sub"), "probe").expect_err("unsaved"),
UNSAVED,
"an untitled buffer is refused before the engine sees the cursor"
);
// A cursor on nothing *and* a keyword for a new name: the name's
// sentence, which is the one `renaming` reaches first.
let refusal = rename(&ws, &uri, TOP.len() as u32 - 1, "module").expect_err("a keyword");
assert_eq!(refusal, "`module` is a Verilog keyword.");
}
/// The one buffer the preflight must never judge: on the large-file fast
/// path every field but the text is the analysis of the *empty* file, so a
/// preflight over it would refuse every cursor as symbolless. The
/// large-buffer gate refuses the whole request first, and this pins that
/// it still does.
#[test]
fn a_large_buffer_is_refused_before_the_preflight_could_see_it() {
let tree = Tree::new("preflightlarge");
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
large_file_threshold: 1,
..Default::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());
let doc = ws.document(&uri).expect("open");
assert!(doc.large, "premise: the buffer took the fast path");
assert!(
vlog_refactor::rename_preflight(&doc.semantics, at(TOP, "u_sub"), "probe").is_err(),
"premise: the empty analysis would refuse a real cursor, which is why \
`server/large_file.rs` must answer this method before we are reached"
);
}
}
+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);
}
}
+585
View File
@@ -0,0 +1,585 @@
//! 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,
// -- discovery, split (TODO §61.3) ----------------------------------
//
// Five disjoint parts of `discovery_ms` and one counter. They are a split
// *of* that stage, not stages beside it, so nothing that adds the scan up
// may add these as well
// (`docs/features/perf5r-first-answer/README.md`).
/// Reading each walk root's `lucisv.toml` for its `exclude` patterns —
/// `Discovery::for_dir`, cached per instance, so a second root under the
/// same config costs a map lookup.
pub config_ms: f64,
/// The directory walks themselves: `read_dir`, `.gitignore` parsing, the
/// cycle guard, and the one `metadata` per entry the walk has always made.
pub walk_ms: f64,
/// How many roots were walked — one per scope directory, so a folder scope
/// over three open buffers' folders is three.
pub walk_dirs: usize,
/// Reading a filelist, when rung 1 is the one in force.
pub filelist_ms: f64,
/// Sorting the walk's output into path order and dropping the paths two
/// overlapping walks both found.
pub sort_ms: f64,
/// Applying `lucisv.index.maxFileSize` to every walked file.
pub cap_ms: f64,
/// `metadata` calls the cap made *itself* — the ones the walk's hand-off
/// did not already answer. Zero for a walked scope since 2026-09-08;
/// a filelist's entries are not walked and still cost one each.
pub stats: usize,
/// Taking every open buffer's text and its finished analysis, and letting
/// it override the disk copy of its own path.
pub buffers_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} config={:.2} walk={:.2} \
filelist={:.2} sort={:.2} cap={:.2} buffers={:.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.config_ms,
self.walk_ms,
self.filelist_ms,
self.sort_ms,
self.cap_ms,
self.buffers_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={} walk_dirs={} stats={} 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.walk_dirs,
self.stats,
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}");
}
}
}
+1
View File
@@ -117,6 +117,7 @@ fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
ItemKind::Class(class) => items(&class.items, offset, out),
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
ItemKind::GenBlock(b) => items(&b.items, offset, out),
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
ItemKind::GenCase(gen_case) => {
+1 -1
View File
@@ -94,7 +94,7 @@ pub(super) fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
/// The request id a `$/cancelRequest` names, or `None` for any other message.
/// Both id forms the protocol allows are read; a cancel whose params do not
/// parse is dropped, because there is no id to act on.
fn cancelled_id(message: &Message) -> Option<RequestId> {
pub(super) fn cancelled_id(message: &Message) -> Option<RequestId> {
let Message::Notification(notification) = message else { return None };
if notification.method != Cancel::METHOD {
return None;
+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
));
}
}
+38 -4
View File
@@ -94,10 +94,44 @@ impl Server {
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` resolved to, and the index's identifier census, which
// is what lets the semantic rules default on here without accusing a
// signal another file reads (`docs/features/semantic-lints-on/`).
diagnostics::all_in(doc, &crate::lint::LintRun::for_document(&self.workspace, doc))
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
// index's identifier census, which is what lets the semantic rules
// default on here without accusing a signal another file reads
// (`docs/features/semantic-lints-on/`).
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
self.report_config_problems(&run);
diagnostics::all_in(doc, &run)
}
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
///
/// Once per (config file, entry), not once per pass: this runs on every
/// keystroke and every index rebuild. The words are the ones `lucisv
/// check` fails the run with, `<file>:<line>: <message>`, so one mistake
/// reads the same in CI and here — but nothing is fatal, the entry is
/// dropped and the buffer is still linted with everything understood
/// (§42.2). Logged, not shown: a typo in a checked-in config is not worth
/// a popup on every editor in the project.
fn report_config_problems(&self, run: &crate::lint::LintRun) {
let problems = run.config_problems();
if problems.is_empty() {
return;
}
// The borrow is released before anything is sent: `notify` takes
// `&self` and could otherwise reach a second borrow one day.
let unsaid = match self.lint_config_problems.try_borrow_mut() {
Ok(mut log) => log.unsaid(problems),
Err(_) => return,
};
for message in unsaid {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {message}; ignored"),
},
);
}
}
/// Publish everything known about a buffer — parse errors and lint
+228 -33
View File
@@ -14,29 +14,29 @@
use lsp_server::{Request, RequestId, Response};
use lsp_types::request::{
CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare,
CodeActionRequest, CodeLensRequest, Completion, DocumentDiagnosticRequest,
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams,
GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest,
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, WillRenameFiles,
WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
CodeActionRequest, CodeActionResolveRequest, CodeLensRequest, Completion,
DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest,
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
PrepareRenameRequest, RangeFormatting, References, Rename, Request as _, SelectionRangeRequest,
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
SignatureHelpRequest, TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes,
WillRenameFiles, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
};
use lsp_types::{
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
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,11 +44,30 @@ 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, 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, lint_trace, nav,
pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
};
/// The requests whose empty answer may mean "this scan has not reached the
/// file yet" rather than "there is nowhere to go".
///
/// All three answer with a **list of places** and with an empty list when they
/// find none, so `[]` is exactly the shape that carries no information. Every
/// other request is left alone: a hover's `null`, a completion's empty list and
/// a code-action menu with no offers all mean what they say whatever the scan
/// has reached, and deferring one would be withholding an answer rather than
/// waiting for a better one. `textDocument/implementation` would belong here;
/// this server does not answer it, so it is not written down as if it did.
const NAVIGATION: [&str; 3] =
[GotoDefinition::METHOD, GotoTypeDefinition::METHOD, References::METHOD];
/// Whether a response says **nowhere**: an answer, not a failure, and an empty
/// list of places. See [`NAVIGATION`].
pub(super) fn names_nowhere(response: &Response) -> bool {
matches!(&response.response_result, Ok(Value::Array(found)) if found.is_empty())
}
impl Server {
/// Answer one request, timing it when `--verbose` asked.
///
@@ -61,18 +80,92 @@ impl Server {
pub(super) fn request(&mut self, request: Request) -> Response {
let Some(started) = self.timer() else { return self.answer_request(request) };
let method = request.method.clone();
// One trace per request, armed here so the flush this request triggers
// is inside it: the diagnostics pass that publishes during the flush is
// the *other* consumer of a lint result, and the two are only readable
// against each other when one line carries both (review round §R1b).
lint_trace::arm();
let response = self.answer_request(request);
self.timing(format!("{method} answered in {}", ms(started)));
// Silent for every request that never linted anything, which is all of
// them but the code actions and the flushes that publish diagnostics.
if let Some(trace) = lint_trace::disarm().filter(|trace| !trace.is_empty()) {
self.timing(format!(
"codeaction method={method} total={} {}",
ms(started),
trace.line()
));
}
response
}
/// A copy of `request` to ask again at the scan's next publish, when an
/// empty answer to it right now would mean "not scanned yet" rather than
/// "nowhere".
///
/// **The lead's ruling from §61.3, as a rule in the drain.** A held
/// startup request is answered the moment the user's own folder is
/// published, and a definition whose target lives in another folder was
/// answered `[]` there — coherent, and wrong by the time the scan ended.
/// Rather than teach the drain to work out whether the published prefix
/// resolves *this* request's target, the answer is computed through the
/// ordinary handler and, when it names nowhere and the index is still
/// growing, put back ([`Server::deferred`]).
///
/// **Only while a scan is running**, so a settled server answers empty
/// exactly as it always did — including the last try, after the scan ends.
/// **Only the three navigation methods that answer with a list of places**
/// ([`NAVIGATION`]): a hover, a completion, a code action or a rename is
/// unaffected, and so is every request whose empty answer means something
/// else. `textDocument/implementation` is not on the list because this
/// server does not answer it.
pub(super) fn ask_again_if_empty(&self, request: &Request) -> Option<Request> {
if !self.scanning || !NAVIGATION.contains(&request.method.as_str()) {
return None;
}
Some(Request::new(request.id.clone(), request.method.clone(), request.params.clone()))
}
/// `--verbose`: that a navigation answer was set aside for the next
/// publish rather than sent, and how many are waiting with it.
pub(super) fn say_deferred(&self, request: &Request) {
if !self.verbose {
return;
}
self.timing(format!(
"{} DEFERRED to the next publish (empty mid-scan, already deferred={})",
request.method,
self.deferred.len()
));
}
/// [`Server::flush_dirty`], with the dirty-buffer stage measured apart
/// from the handler that follows it.
///
/// The review's item 4: *if the dirty-buffer stage dominates the 136 ms, a
/// lint cache alone cannot fix it*. The flush rebuilds each dirty
/// `Document` (parse and analysis, counted as whole-file parses) and then
/// publishes its diagnostics, which lints; the handler lints again. One
/// line carrying both is what makes the two comparable.
fn flush_dirty_traced(&mut self) {
if !lint_trace::armed() {
return self.flush_dirty();
}
let buffers = self.dirty.len();
let before = vlog_parser::stats::parses();
let started = std::time::Instant::now();
self.flush_dirty();
let parses = vlog_parser::stats::parses().saturating_sub(before);
lint_trace::close_flush(started.elapsed(), buffers, parses);
}
fn answer_request(&mut self, request: Request) -> Response {
// A request answers from a buffer's analysis, so any change the client
// has already sent is in effect before it is answered — the order
// contract the loop has always promised. Here is also where a typing
// burst is coalesced: the changes before this request all become one
// `set_document` in `flush_dirty`.
self.flush_dirty();
self.flush_dirty_traced();
let id = request.id.clone();
let method = request.method.clone();
// The large-file fast path answers first, and for most methods it
@@ -246,22 +339,90 @@ 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 mut actions =
code_action::code_actions(&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 — read by the run itself, off
// the `FileConfig` it discovers anyway, so this path no longer
// walks for a config file twice (review round §R1a).
let run = lint::LintRun::for_document(&self.workspace, doc);
actions.extend(code_action::code_actions(
&run,
&uri,
doc,
p.range,
only.as_deref(),
));
}
// 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))
{
let offset = doc.positions().offset(p.range.start);
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
// A client that can resolve is offered the actions without
// their edits, which is what keeps a cursor resting on an
// instantiation off the module's fan-out; one that cannot
// gets the whole edit, exactly as before.
actions.extend(match self.abilities.code_action_resolve {
true => ports::offers(&self.workspace, &uri, p.range.start, offset),
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| {
// 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)),
}
}),
// Custom method, so it is matched by name rather than through a
// `lsp_types::request` type. Nothing advertises it: a client that
// does not know it never asks.
@@ -299,7 +460,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)
@@ -326,6 +496,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);
+170 -22
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,9 +219,31 @@ 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;
self.answer_what_was_deferred();
warnings
}
/// Answer whatever the empty-answer rule set aside, now that the index has
/// stopped growing.
///
/// **The other half of that rule, and the reason it can never strand a
/// request.** A navigation answer was deferred because `[]` might have
/// meant "not scanned yet"; here it cannot mean that any more, so an empty
/// answer is the honest one and goes out. The scan is over, so
/// [`Server::ask_again_if_empty`] defers nothing this time round — and a
/// request the order contract still holds, one behind something already
/// `held`, is put back by `process_batch`'s own rule exactly as any other
/// message would be.
pub(super) fn answer_what_was_deferred(&mut self) {
let deferred = std::mem::take(&mut self.deferred);
if deferred.is_empty() || self.stopped {
return;
}
self.stopped = !matches!(self.process_batch(deferred), Ok(false));
}
/// One whole scan: the bar up, every file indexed with the client's
/// messages answered between two of them, the bar down.
///
@@ -224,25 +257,48 @@ 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 interleave = scan.total() > INTERLEAVE_ABOVE;
let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_scan(watch, verbose));
// A scan that has walked the user's own folders and owes itself the
// rest of the workspace **always** interleaves, whatever its work list
// says today: the whole point of leading with that neighbourhood is
// that the request waiting for it is answered the moment it is in
// (`docs/features/perf5r-first-answer/README.md`).
let interleave = scan.total() > INTERLEAVE_ABOVE || scan.discovery_pending();
let total = scan.total();
if started.is_some() {
// Whether it interleaves is said here because it is decided here,
// and because it is the answer to "why did my hover wait?" — a
// scan that does not interleave answers nothing until it is done.
let interleaving = if interleave { ", interleaved" } else { "" };
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
let staged = if scan.discovery_pending() { " (the folder first)" } else { "" };
self.timing(format!(
"scan started: {total} file{}{staged}{interleaving}",
plural(total)
));
}
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
{
loop {
// **No bar while the denominator can still grow.** The work list
// is the neighbourhood so far, and a percentage against it would
// fall to a twentieth of itself the moment the rest of the
// workspace lands. The per-file log still runs — it names files,
// not fractions — and the first percentage the client sees is the
// first measured one (`docs/features/indexing-ux/README.md`).
let showing = if scan.discovery_pending() { None } else { bar.as_ref() };
let stepped =
self.watching(showing, |workspace, watch| workspace.scan_step(&mut scan, watch));
if !stepped {
break;
}
if interleave && self.answer_what_is_waiting(&mut scan) {
// Nothing after this may speak to a client that has gone, the
// timing line included.
return Vec::new();
}
}
let total = scan.total();
let (skipped, cached) = (scan.skipped(), scan.cached());
let warnings = self.workspace.finish_scan(scan);
self.end_indexing(bar, skipped, cached);
@@ -252,9 +308,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.
///
@@ -280,36 +354,110 @@ impl Server {
/// **This is the round's whole point, and its whole cost.** Polling costs
/// one `try_recv` per file and finds nothing in a scan nobody is waiting
/// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting
/// on pays one merge per burst to make the records it has taken since the
/// last one answerable ([`Workspace::publish_scan`]). The messages then go
/// on pays a merge to make the records it has taken since the last one
/// answerable ([`Workspace::publish_scan`]). The messages then go
/// through the same `process_batch` the loop uses, so a `didChange` queued
/// ahead of a hover is applied before that hover is answered and a cancel
/// beside its request still answers it `RequestCancelled` — the order
/// contract is the loop's, unchanged, because it is the loop's code.
///
/// **A merge per burst was the cost; a merge per 512 files is what it is
/// now.** [`Scan::publish_is_due`] is the cadence, and the one drain
/// exempt from it is the one with something *waiting* — the startup's held
/// requests, drained the moment the neighbourhood is in, which is the
/// session's first useful answer and must not be a file later than it was
/// (`docs/features/perf5r-first-answer/README.md`). Everything else reads
/// a coherent prefix that is at most a cadence older, which is the trade
/// `docs/features/perf5r-publication/README.md` measures.
///
/// An error here is a client that has gone: there is nobody to report it
/// 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();
let owed = !batch.is_empty();
let mut arrived = Vec::new();
while let Ok(message) = self.queue.try_recv() {
batch.push(message);
arrived.push(message);
}
// A quiet scan pays nothing at all, and that is a promise: the cadence
// is asked only when there is something for a publish to be *for*.
if !owed && arrived.is_empty() && self.deferred.is_empty() {
return false;
}
if owed || scan.publish_is_due() {
self.workspace.publish_scan(scan);
// A navigation answer this scan could not give yet is asked again
// off the prefix that has just grown — behind whatever was already
// waiting, ahead of everything newer ([`Server::deferred`]).
batch.append(&mut self.deferred);
}
batch.append(&mut arrived);
if batch.is_empty() {
return false;
}
let opened = opened_in(&batch);
self.workspace.publish_scan(scan);
// 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.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.watching(None, |workspace, watch| workspace.open_next(scan, watch));
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);
+142 -137
View File
@@ -44,10 +44,10 @@ 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_id, cancelled_in, cancelled_response};
use dispatch::names_nowhere;
mod batch;
mod client;
@@ -59,6 +59,7 @@ mod large_file;
mod notification;
mod progress;
mod semantic_tokens;
mod startup;
#[cfg(test)]
mod tests;
@@ -104,6 +105,20 @@ pub struct ClientAbilities {
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
/// a notification whenever the installed workspace index changes.
pub hierarchy_view: bool,
/// Whether the client can fetch a code action's `edit` through
/// `codeAction/resolve` — `textDocument.codeAction.resolveSupport`
/// listing `"edit"`. Only then are the port refactorings *offered* without
/// their edits; a client that said nothing gets the whole edit up front,
/// 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.
@@ -114,6 +129,19 @@ pub struct Server {
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<Uri>,
/// Which `[lint]` entries of which `lucisv.toml` have already been
/// reported (§42.2). Interior-mutable because a lint pass runs behind
/// `&self` — the pull models compute diagnostics inside a `map` over the
/// open buffers — and the memo is the one thing a pass has to write.
/// Nothing is called while it is borrowed.
lint_config_problems: std::cell::RefCell<crate::lint::ProblemLog>,
/// The unknown-rule-name lines already logged for the **editor's**
/// `lucisv.lint.select`/`ignore` (§45.1), exactly as the last settings
/// value produced them. A client that re-pushes the same section — VS Code
/// does, whenever anything in it changes — says nothing again; a list the
/// user edited re-arms every name that is new to it. The project file's
/// twin memo is `lint_config_problems` above.
said_lint_names: Vec<String>,
abilities: ClientAbilities,
/// The id of the file-watcher registration in force, if any. Kept so a
/// changed `lucisv.filelist` can replace it: the watched filelist path is
@@ -165,6 +193,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,
@@ -182,11 +228,33 @@ pub struct Server {
/// [`Server::must_wait`] — this is the order contract, not a queue of its
/// own.
held: Vec<Message>,
/// Navigation requests a scan answered **empty** while it was still
/// growing the index, to be asked again at its next publish.
///
/// **Not a second `held`, and deliberately not part of
/// [`Server::must_wait`].** A held request is one the order contract says
/// nothing newer may overtake; this is one whose answer was computed,
/// found to name nowhere, and set aside because the reason it named
/// nowhere may be that the file it wants has not been scanned yet
/// (`docs/features/perf5r-publication/README.md`). Nothing else is owed
/// anything by it — a hover, a completion or a code action behind one is
/// answered exactly as before — and it is asked again at most once per
/// publish, so the re-computation is bounded by the cadence and not by the
/// scan's file count. A scan ending runs whatever is left through the
/// dispatch one last time, with itself already over — so nothing is
/// deferred that time round and an empty answer, which is now the honest
/// one, goes out ([`Server::answer_what_was_deferred`]).
deferred: Vec<Message>,
/// `--verbose`: whether every operation says how long it took, in the
/// client's log channel. Off is the shipped state and the whole of what it
/// 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
@@ -225,8 +293,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
@@ -237,134 +306,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(),
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
@@ -470,7 +411,20 @@ impl Server {
let response = if cancelled.remove(&request.id) {
cancelled_response(request.id)
} else {
self.request(request)
// A navigation request whose answer would be `[]` only
// because the scan has not reached its target yet is
// asked again at the next publish rather than answered
// with nowhere ([`Server::deferred`]).
let again = self.ask_again_if_empty(&request);
let response = self.request(request);
match again.filter(|_| names_nowhere(&response)) {
Some(request) => {
self.say_deferred(&request);
self.deferred.push(Message::Request(request));
continue;
}
None => response,
}
};
self.connection.sender.send(Message::Response(response))?;
}
@@ -479,7 +433,14 @@ impl Server {
// already been done above. Kept only so that a request behind
// one that has to wait takes its cancel with it.
Message::Notification(notification) if notification.method == Cancel::METHOD => {
consumed_cancels.push(Message::Notification(notification));
let cancel = Message::Notification(notification);
// A request the empty-answer rule set aside is not in this
// burst, so `cancelled_in` cannot see it — but it is still
// a request the client is waiting on, and a cancel for it
// is honoured where it lands: answered `RequestCancelled`
// now, and never asked again (QA, perf5r-publication).
self.cancel_deferred(&cancel)?;
consumed_cancels.push(cancel);
}
Message::Notification(notification) => self.notification(notification),
Message::Response(response) => self.response(response),
@@ -488,6 +449,22 @@ impl Server {
Ok(false)
}
/// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]:
/// take it out and answer it cancelled. A cancel naming anything else is
/// left to the batch's own rule.
fn cancel_deferred(&mut self, cancel: &Message) -> Result<(), Box<dyn Error + Sync + Send>> {
let Some(id) = cancelled_id(cancel) else { return Ok(()) };
let found = self
.deferred
.iter()
.position(|message| matches!(message, Message::Request(request) if request.id == id));
if let Some(at) = found {
self.deferred.remove(at);
self.connection.sender.send(Message::Response(cancelled_response(id)))?;
}
Ok(())
}
/// Whether a request reaching the dispatch right now must wait instead of
/// being answered.
///
@@ -499,7 +476,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
@@ -507,7 +484,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
@@ -515,7 +504,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
@@ -12,19 +12,20 @@ use lsp_server::{ExtractError, Notification};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, DidSaveTextDocument, Notification as _,
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _,
};
use lsp_types::{
DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, RenameFilesParams, Uri, WorkspaceFolder,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, LogMessageParams, MessageType,
RenameFilesParams, Uri, WorkspaceFolder,
};
use serde::de::DeserializeOwned;
use super::batch::{widen_of, Widen};
use super::client::ms;
use super::Server;
use crate::{file_ops, settings, sync, watch};
use crate::{file_ops, lint, settings, sync, watch};
impl Server {
/// Handle one notification, timing it when `--verbose` asked. A
@@ -244,14 +245,62 @@ impl Server {
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
let watched = self.workspace.filelist_path();
let linted = self.lint_selection();
// A `lucisv.lint.options` entry the registry refused is dropped, not
// fatal (`settings::rule_options`) — so the log line is the only way
// the user learns their option is doing nothing. Logged, not shown: a
// typo in a settings file is not worth a popup, and a client that
// resends its whole section would raise the same one repeatedly.
for warning in &settings.lint_option_warnings {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
// A name in `lucisv.lint.select`/`ignore` the registry does not know is
// dropped just as silently, and the same typo in a `lucisv.toml`'s
// `[lint] select` has been said since §42. Said here too — but **once**
// per (setting, name): unlike the options warnings above, which cost a
// line each time the setting arrives, a client that re-pushes its whole
// section on every keystroke must not repeat these. A list the user
// edited re-arms whatever is new in it. See §2.9-29.
for warning in unsaid(&settings.lint_name_warnings, &self.said_lint_names) {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
self.said_lint_names.clone_from(&settings.lint_name_warnings);
// And the same for `lucisv.lint.waivers`: a file that is not there, or
// a directive that does not parse, is dropped and said once — here,
// where the setting arrives, rather than on every keystroke from the
// lint pass that reads the files. Only the setting's own files are
// checked; a `lucisv.toml`'s `[lint] waivers` is that file's problem
// and `lucisv check` fails the run over it.
for problem in waiver_problems(&settings, self.workspace.roots()) {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: lucisv.lint.waivers: {problem}; ignored"),
},
);
}
// Only `exclude` and `filelist` change which files exist as far as
// this server is concerned; the other settings are read afresh by the
// next request that wants them and need no invalidation.
if self.workspace.set_client_settings(settings) {
self.reindex();
} else if self.lint_selection() != linted {
// `lucisv.lint.select`/`ignore` change which rules run and nothing
// else: no file's contents moved, so there is nothing to rescan —
// `lucisv.lint.select`/`ignore`, the class switches, the per-rule
// toggles and the per-rule *options* change which rules run and
// what they report, and nothing else: no file's contents moved,
// so there is nothing to rescan —
// but every published squiggle was drawn under the old selection,
// and a client that pulls has cached answers under it too.
self.generation += 1;
@@ -305,3 +354,32 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
fn folder_paths(folders: &[WorkspaceFolder]) -> Vec<std::path::PathBuf> {
folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect()
}
/// What `lucisv.lint.waivers` names that could not be used: a file that is not
/// there, or a directive that does not parse.
///
/// Read here rather than trusted, because a path is not something a settings
/// parser can validate: only opening the file says whether it exists. The
/// files are read again by the lint pass that actually applies them — a few
/// small files beside a parse and an analysis — which keeps one reader for
/// both and no cache to go stale when the user edits a waiver file.
fn waiver_problems(
settings: &settings::ClientSettings,
roots: &[std::path::PathBuf],
) -> Vec<String> {
if settings.lint_waivers.is_empty() {
return Vec::new();
}
let paths = lint::waiver_paths(settings, roots, &lucisv_core::config::FileConfig::default());
lint::external_waivers(&paths).1
}
/// The lines of `warnings` that `said` does not already hold, in order.
///
/// The whole of §45.1's "once": the memo is the previous settings value's own
/// warning list, so re-pushing a section says nothing and editing the list
/// says exactly what is new in it. Both lists are a handful of entries at
/// most — one per typo — so a scan is cheaper than a set.
fn unsaid<'a>(warnings: &'a [String], said: &[String]) -> Vec<&'a String> {
warnings.iter().filter(|w| !said.contains(w)).collect()
}
+366
View File
@@ -0,0 +1,366 @@
//! 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);
/// How long a startup waits, *after* the settings answer, for the editor to
/// say which file it has open.
///
/// **Only when that name changes what the scan does.** A workspace-scoped scan
/// with a buffer open walks that buffer's folder first, indexes it, and
/// answers the request waiting for it in ~115 ms; without the name it walks
/// all 3 976 files first and answers in ~290
/// (`docs/features/perf5r-first-answer/README.md`). The two messages are
/// written by the client at the same moment — the settings answer by whatever
/// handles server-initiated requests, the `didOpen` by the editor — so which
/// arrives first is a coin toss, and losing it costs 175 ms of the thing this
/// round is about. This is that coin toss removed.
///
/// It is spent **only** by a session that is going to walk a whole workspace
/// and has no buffer at all yet: a folder-scoped session has nothing to lead
/// with, and a session whose buffer is already in hand stops waiting the
/// moment it applies one. So the session that pays the full bound is the one
/// with an empty editor, where nothing is waiting on the scan.
pub(super) const OPENING_FILE_WAIT: Duration = Duration::from_millis(25);
/// 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(),
deferred: 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);
// Inside the staging window, because it is the same window: every
// request is still held, and the scan has still not begun.
if !wait.is_zero() && !self.stopped {
self.await_opening_file(OPENING_FILE_WAIT);
}
self.staging = false;
self.rescan_wanted = false;
}
/// Wait a bounded moment for the editor's first `didOpen`, when knowing
/// which folder the user is in is what decides the shape of the scan
/// about to run ([`OPENING_FILE_WAIT`]).
///
/// Silent for every session that would not spend the knowledge: only a
/// workspace-scoped scan leads with a folder, and only one with nothing
/// open has a folder still to learn. The loop stops on the first buffer
/// rather than draining the bound, so the ordinary session pays what the
/// message took to arrive and nothing more.
///
/// **Not a scope decision.** Which files the scan indexes is settled by
/// the settings that have just landed; this decides only which of them it
/// indexes *first*, which `vlog_semantic::IndexBuilder` cannot see
/// (`crate::scan_order`).
fn await_opening_file(&mut self, wait: Duration) {
if !self.workspace.leads_with_a_folder() {
return;
}
let asked = Instant::now();
while self.workspace.open_uris().is_empty() {
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);
self.stopped = !matches!(self.process_batch(batch), Ok(false));
if self.stopped {
return;
}
}
}
/// 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);
}
}
}
@@ -386,3 +386,35 @@ fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
// cancel did not intercept it.
session.answer(server_id, Value::Null);
}
/// A request the empty-answer rule set aside (`Server::deferred`,
/// perf5r-publication) is not in any burst, so the burst's own cancel rule
/// cannot see it. A cancel for it must still be honoured where it lands:
/// answered `RequestCancelled` at once, taken out of the deferred set, and
/// never asked again when the scan ends. Found by QA on §61.4; the request is
/// planted directly because a real deferral lives only inside a running scan.
#[test]
fn a_cancel_for_a_deferred_request_answers_it_cancelled_and_forgets_it() {
let (_tree, mut session, uri) = cancelling_session("cancel-deferred", ONE_MODULE);
let parked = Request::new(
RequestId::from(41),
GotoDefinition::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 0, "character": 7 }
}),
);
session.server.deferred.push(Message::Request(parked));
session.server.process_batch(vec![cancel(serde_json::json!(41))]).expect("a burst");
assert_eq!(outcomes(&session), vec![(RequestId::from(41), Some(CANCELLED))]);
assert!(session.server.deferred.is_empty(), "the cancelled request is not asked again");
// And the scan's end finds nothing left to answer: exactly one response.
session.server.answer_what_was_deferred();
assert!(outcomes(&session).is_empty(), "a cancelled request is answered once");
// A cancel naming a request that is *not* deferred changes nothing.
session.server.process_batch(vec![cancel(serde_json::json!(42))]).expect("a burst");
assert!(outcomes(&session).is_empty());
}
@@ -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");
}
}
@@ -0,0 +1,370 @@
//! One test per row of the lint snapshot's invalidation table.
//!
//! Take 5 **review** round §R1a
//! (`docs/features/perf5r-lint-snapshot/README.md`). A `Document` keeps the
//! findings of one `lint_with` pass so that the diagnostics publish and
//! quick-fix discovery do not run the same 21 ms twice on one revision. What
//! makes that legitimate is that **every input which can change the answer
//! either builds a new `Document`, or is in the key, or clears the slot** —
//! and the README's table has one row per input.
//!
//! This file walks that table through the real doors: a `didChange`, a
//! `didChangeConfiguration`, a `lucisv.toml` rewritten on disk, a waiver file
//! rewritten in place, a watched file in **another** buffer, a close and
//! reopen, a UTF-16 range, a large buffer — and one attack, a fix offered for
//! a span the buffer no longer has.
//!
//! Reuse is observed by pointer, not by a stopwatch: two passes that share a
//! snapshot answer with the same `Arc`, and one that recomputed cannot. A
//! timing assertion on a lint pass would be a flake; `Arc::ptr_eq` is not.
use std::sync::Arc;
use vlog_linter::Violation;
use super::*;
use crate::lint::{fixable, violations_in, LintRun};
/// A module with one tab in it: one `no-tabs` finding, carrying a Safe fix
/// whose text is the indent width. Line 1 is the tab.
const TABBED: &str = "module m;\n\twire a;\nendmodule\n";
/// A session over `tree` with `m.sv` open, its diagnostics already published.
fn opened(tree: &Tree, text: &str) -> (Session, Uri) {
let mut session = Session::wide(vec![tree.path.clone()], true);
let uri = session.open(&tree.path.join("m.sv"), text);
let _ = session.drain();
(session, uri)
}
/// The findings quick-fix discovery would offer for `uri` right now, taken
/// through the same two calls the dispatcher makes.
fn offered(session: &Session, uri: &Uri) -> Arc<[Violation]> {
let doc = session.server.workspace.document(uri).expect("an open buffer");
let run = LintRun::for_document(&session.server.workspace, doc);
fixable(&run, doc)
}
/// The rules that fired, by name, in the order they fired.
fn rules(found: &[Violation]) -> Vec<&'static str> {
found.iter().map(|violation| violation.rule).collect()
}
/// The replacement text of the first fix, for the rows about fix bytes.
fn fix_text(found: &[Violation]) -> String {
let fix = found.first().and_then(|v| v.fix.as_ref()).expect("a fix");
fix.edits.first().map(|(_, text)| text.clone()).expect("an edit")
}
/// Push one `lucisv.lint.*` section and let the republish it triggers settle.
fn push_lint_settings(session: &mut Session, lint: Value) {
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
);
let _ = session.drain();
}
// ------------------------------------------------------------------
// the headline: one pass, two consumers
// ------------------------------------------------------------------
/// The whole point of the round. A `didOpen` publishes diagnostics, which
/// lints; the code action that follows reads **that** answer rather than
/// running the rules again, and the two are the same object.
#[test]
fn the_diagnostics_publish_and_the_quick_fix_pass_share_one_lint() {
let tree = Tree::new("lsshare");
let (session, uri) = opened(&tree, TABBED);
let doc = session.server.workspace.document(&uri).expect("open");
assert!(
!doc.lint.is_empty(),
"the publish that answered the didOpen left its findings on the document"
);
let run = LintRun::for_document(&session.server.workspace, doc);
let published = violations_in(doc, &run);
let fixes = fixable(&run, doc);
assert!(Arc::ptr_eq(&published, &fixes), "one pass answers both doors");
assert_eq!(rules(&published), vec!["no-tabs"]);
// ... and asking twice more does not compute twice more.
assert!(Arc::ptr_eq(&fixes, &fixable(&run, doc)));
}
// ------------------------------------------------------------------
// row 1 — the buffer's own text
// ------------------------------------------------------------------
#[test]
fn an_edited_buffer_is_relinted() {
let tree = Tree::new("lsedit");
let (mut session, uri) = opened(&tree, TABBED);
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
change(
&mut session,
&uri,
2,
serde_json::json!([{ "text": "module m;\n wire a;\nendmodule\n" }]),
);
assert!(
offered(&session, &uri).is_empty(),
"the tab is gone, so the finding and its fix are gone"
);
change(&mut session, &uri, 3, serde_json::json!([{ "text": TABBED }]));
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and back again");
}
// ------------------------------------------------------------------
// row 2 — the large-file fast path
// ------------------------------------------------------------------
#[test]
fn a_large_buffer_lints_nothing_and_stores_nothing() {
let tree = Tree::new("lslarge");
let mut session = Session::wide(vec![tree.path.clone()], true);
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 16 } } } }),
);
let uri = session.open(&tree.path.join("m.sv"), TABBED);
let _ = session.drain();
let doc = session.server.workspace.document(&uri).expect("open");
assert!(doc.large, "premise: over the threshold");
assert!(doc.lint.is_empty(), "a large buffer's publish lints nothing to keep");
let menu = session.result(
CodeActionRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"range": { "start": { "line": 1, "character": 1 },
"end": { "line": 1, "character": 1 } },
"context": { "diagnostics": [] },
}),
);
assert_eq!(menu, serde_json::json!([]), "and offers nothing");
let doc = session.server.workspace.document(&uri).expect("open");
assert!(doc.lint.is_empty(), "the request left no snapshot behind either");
}
// ------------------------------------------------------------------
// rows 3 and 11 — the rule selection, pushed by the editor
// ------------------------------------------------------------------
#[test]
fn a_pushed_rule_selection_is_relinted() {
let tree = Tree::new("lsselect");
let (mut session, uri) = opened(&tree, TABBED);
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
push_lint_settings(&mut session, serde_json::json!({ "ignore": ["no-tabs"] }));
assert!(offered(&session, &uri).is_empty(), "the setting silenced the rule and its fix");
push_lint_settings(&mut session, serde_json::json!({ "ignore": [] }));
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and un-silenced it");
}
// ------------------------------------------------------------------
// rows 4, 5, 8 and 12 — the `lucisv.toml`, rewritten under a running server
// with no watcher event of any kind
// ------------------------------------------------------------------
#[test]
fn a_rewritten_toml_is_relinted() {
let tree = Tree::new("lstoml");
tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n");
let (session, uri) = opened(&tree, TABBED);
assert!(offered(&session, &uri).is_empty(), "premise: the project ignores the rule");
// Rewritten behind the server's back. `watch::SOURCE_GLOB` covers
// `**/*.{v,vh,sv,svh}` and the filelist, so **no event is sent** — the
// only thing that can notice is the per-request read and the key.
tree.write("lucisv.toml", "[lint]\nignore = [\"posix-eof\"]\n");
assert_eq!(
rules(&offered(&session, &uri)),
vec!["no-tabs"],
"the next request read the new file"
);
}
// ------------------------------------------------------------------
// row 6 — the indent width, which is a fix's bytes
// ------------------------------------------------------------------
#[test]
fn a_tab_width_change_rewrites_the_fix() {
let tree = Tree::new("lsindent");
let (session, uri) = opened(&tree, TABBED);
assert_eq!(fix_text(&offered(&session, &uri)), " ", "premise: the default indent");
tree.write("lucisv.toml", "indent = 4\n");
assert_eq!(
fix_text(&offered(&session, &uri)),
" ",
"the same finding, a different fix — and the snapshot must not hand back the old one"
);
}
// ------------------------------------------------------------------
// row 7 — an external waiver file, rewritten in place
// ------------------------------------------------------------------
#[test]
fn a_rewritten_waiver_file_is_relinted() {
let tree = Tree::new("lswaiver");
tree.write("lucisv.toml", "[lint]\nwaivers = [\"team.waiver\"]\n");
tree.write("team.waiver", "waive --rule=no-tabs\n");
let (session, uri) = opened(&tree, TABBED);
assert!(offered(&session, &uri).is_empty(), "premise: the waiver silences it");
// Rewritten to name a different rule. The two texts are different
// lengths, so this row alone would pass on a length check too — the
// same-length case is `lint_snapshot::tests`'
// `a_waiver_rewritten_in_place_is_a_different_key`.
tree.write("team.waiver", "waive --rule=posix-eof\n");
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "the waiver moved");
tree.write("team.waiver", "waive --rule=no-tabs\n");
assert!(offered(&session, &uri).is_empty(), "and moved back");
}
// ------------------------------------------------------------------
// rows 9 and 10 — the workspace index the census oracle reads
// ------------------------------------------------------------------
/// A change in **another** file, which is the row a document-revision key
/// could not have covered: this buffer's bytes never move, and what the
/// semantic rules say about it does.
#[test]
fn a_change_in_another_file_relints_this_one() {
let tree = Tree::new("lsoracle");
let dut = "module dut;\n logic dbg_probe;\nendmodule\n";
tree.write("dut.sv", dut);
tree.write(
"tb.sv",
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
);
let mut session = Session::wide(vec![tree.path.clone()], true);
let uri = session.open(&tree.path.join("dut.sv"), dut);
let _ = session.drain();
assert!(
offered(&session, &uri).is_empty(),
"premise: another file reads the signal, so it is not unused"
);
// The other file stops mentioning it, and the watcher says so.
tree.write("tb.sv", "module tb;\n dut d ();\nendmodule\n");
session.watched(&[tree.path.join("tb.sv")]);
let _ = session.drain();
assert_eq!(
rules(&offered(&session, &uri)),
vec!["unused-signal"],
"the index moved, so the snapshot had to go"
);
tree.write(
"tb.sv",
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
);
session.watched(&[tree.path.join("tb.sv")]);
let _ = session.drain();
assert!(offered(&session, &uri).is_empty(), "and back");
}
// ------------------------------------------------------------------
// row 13 — close and reopen
// ------------------------------------------------------------------
#[test]
fn a_closed_and_reopened_buffer_is_relinted() {
let tree = Tree::new("lsreopen");
let (mut session, uri) = opened(&tree, TABBED);
assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise");
session.notify(
DidCloseTextDocument::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
let _ = session.drain();
assert!(session.server.workspace.document(&uri).is_none(), "the snapshot went with it");
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
let _ = session.drain();
assert!(offered(&session, &uri).is_empty(), "reopened with different text, relinted");
}
// ------------------------------------------------------------------
// row 14 — a fix's range, in UTF-16 units, off a reused snapshot
// ------------------------------------------------------------------
/// The snapshot holds byte spans; the range on the wire is built per request
/// from the buffer's text. A reused snapshot must therefore still produce
/// UTF-16 columns, which is the one place a cached *position* would have gone
/// wrong.
#[test]
fn a_snapshot_fix_keeps_its_utf16_range() {
let tree = Tree::new("lsutf16");
// The `é` is two bytes and one UTF-16 unit; `🎉` is four bytes and two.
let text = "module m;\n // é 🎉\twire a;\nendmodule\n";
let (mut session, uri) = opened(&tree, text);
let ask = serde_json::json!({
"textDocument": { "uri": uri },
"range": { "start": { "line": 1, "character": 9 },
"end": { "line": 1, "character": 9 } },
"context": { "diagnostics": [] },
});
// Twice: the first request may compute, the second is the reuse — and
// both must name the same UTF-16 column.
let first = session.result(CodeActionRequest::METHOD, ask.clone());
let again = session.result(CodeActionRequest::METHOD, ask);
assert_eq!(first, again, "the reused answer is the computed one");
let edit = &first[0]["edit"]["changes"][uri.as_str()][0];
assert_eq!(edit["range"]["start"]["character"], 9, "in UTF-16 units, not bytes");
assert_eq!(edit["range"]["start"]["line"], 1);
}
// ------------------------------------------------------------------
// the attack
// ------------------------------------------------------------------
/// The failure the previous lane deferred this memo over: a **stale fix
/// offer**. The buffer is edited so the bytes a previously offered fix named
/// no longer exist; the next menu must not offer that fix, and must not offer
/// an edit whose range runs past the end of the buffer.
#[test]
fn a_fix_is_never_offered_for_a_span_the_buffer_no_longer_has() {
let tree = Tree::new("lsattack");
// Two tabs, far apart, so the second fix's span is deep into the buffer.
let long = format!("module m;\n\twire a;\n{}\twire z;\nendmodule\n", " // pad\n".repeat(40));
let (mut session, uri) = opened(&tree, &long);
let before = offered(&session, &uri);
assert_eq!(before.len(), 2, "two tabs, two fixes: {:?}", rules(&before));
let deepest = before.iter().map(|v| v.span.end).max().expect("a span");
assert!(deepest as usize > 40, "premise: the fix is deep in the buffer");
// Now the buffer becomes three lines long. Every byte the second fix
// named is gone.
let after_text = "module m;\n wire a;\nendmodule\n";
change(&mut session, &uri, 2, serde_json::json!([{ "text": after_text }]));
let after = offered(&session, &uri);
assert!(after.is_empty(), "no fix survives the text that justified it: {:?}", rules(&after));
// ... and through the wire, where a stale span would be a range past the
// end of a three-line document.
let menu = session.result(
CodeActionRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"range": { "start": { "line": 0, "character": 0 },
"end": { "line": 2, "character": 9 } },
// The fix families alone: an extraction is offered for any whole
// selection and is not what this row is about.
"context": { "diagnostics": [], "only": ["quickfix", "source.fixAll.lucisv"] },
}),
);
assert_eq!(menu, serde_json::json!([]), "and nothing is offered: {menu:#?}");
assert_eq!(
session.server.workspace.document(&uri).expect("open").text,
after_text,
"the buffer the answer describes is the buffer the client has"
);
}
+96 -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,29 @@ 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 lint_snapshot;
mod progress;
mod pull_diagnostics;
mod requests;
mod scan;
mod scan_trace;
mod settings;
mod startup;
mod sync;
mod tokens;
mod watchers;
@@ -85,7 +93,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 +169,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 +210,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,324 @@
//! 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);
}
#[test]
fn the_discovery_split_is_a_split_of_discovery_and_not_stages_beside_it() {
// §61.3. `config`, `walk`, `filelist`, `sort`, `cap` and `buffers` are
// disjoint parts of `discovery`, so they may never add up to more than it
// — and anything that sums the scan (`the_stages_add_up_to_the_scan_they
// _describe`) must not sum these as well, which is why they are absent
// from that test's list. The slack is `collect_sources`'s own bookkeeping:
// the `spoken_for` set, the `Vec` pushes, the `Scope` moves.
let tree = trace_tree("tracediscovery", 30);
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let lines = scan_lines(&session);
let stages = line_of(&lines, "stages");
let discovery = number(&stages, "discovery");
let parts: f64 = ["config", "walk", "filelist", "sort", "cap", "buffers"]
.iter()
.map(|key| number(&stages, key))
.sum();
assert!(discovery > 0.0, "a walk of 30 files takes measurable time: {stages}");
assert!(parts <= discovery * 1.02, "the parts cannot exceed the whole: {parts} of {discovery}");
assert!(parts > 0.0, "and at least one of them was timed: {stages}");
// Not asserted: that the parts account for *most* of discovery. On a
// fixture this small the whole is well under a millisecond and the
// bookkeeping slack — the `spoken_for` set, the `Vec` pushes — rivals the
// walk, so a ratio bound is a stopwatch under the workspace suite's
// parallel load (it tripped once at 50 % in the lead's gate run and
// passed alone three times). On opentitan the walk is 95 % of discovery
// (`docs/features/perf5r-first-answer/README.md`); that ratio is the
// README's measurement, not this test's claim.
assert_eq!(number(&stages, "filelist"), 0.0, "no filelist is in force: {stages}");
// Nothing was walked twice: one root, and the cap read the walk's own
// lengths rather than asking the filesystem again.
let counts = line_of(&lines, "counts");
assert_eq!(field(&counts, "walk_dirs"), "1", "one root, walked once: {counts}");
assert_eq!(field(&counts, "stats"), "0", "the cap stats nothing the walk already read");
}
@@ -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:#?}"
);
}
@@ -408,3 +416,95 @@ fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
session.answer(RequestId::from("never-sent".to_string()), serde_json::json!([{ "indent": 2 }]));
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
}
// ------------------------------------------------------------------
// the editor's unknown rule name (TODO §45.1, docs/topo.md §2.9-29)
// ------------------------------------------------------------------
/// A `didChangeConfiguration` push with the given `lucisv.lint` section.
fn push_lint(session: &mut Session, lint: Value) {
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
);
}
/// The unknown-rule lines the server logged since the last drain.
fn unknown_rule_lines(session: &Session) -> Vec<String> {
session
.logged()
.into_iter()
.map(|(_, message)| message)
.filter(|message| message.contains("unknown rule"))
.collect()
}
#[test]
fn an_unknown_rule_name_in_the_editors_select_is_logged_once() {
let tree = Tree::new("unknownrule");
tree.write("m.sv", "module m;\nendmodule\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
assert_eq!(
unknown_rule_lines(&session),
["lucisv: lucisv.lint.select: unknown rule: no-tab"],
"said once, naming the list and the name"
);
// Four diagnostics passes later it has not been said again: the pass runs
// on every keystroke and the log is not a place to shout from.
for _ in 0..4 {
session.server.publish(&uri);
}
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by a diagnostics pass");
// Nor by the same section arriving again, which is what VS Code sends
// whenever anything at all in it changes.
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by an identical push");
}
#[test]
fn a_changed_list_re_arms_the_log() {
let tree = Tree::new("unknownrulearm");
let mut session = Session::new(vec![tree.path.clone()], false);
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
assert_eq!(unknown_rule_lines(&session).len(), 1);
// A second typo added to the list is new, and is said; the first is not.
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
assert_eq!(
unknown_rule_lines(&session),
["lucisv: lucisv.lint.select: unknown rule: nope"],
"only what is new in the list"
);
// Cleared and re-typed: the memo is the previous value, so it is armed
// again.
push_lint(&mut session, serde_json::json!({ "select": [] }));
assert!(unknown_rule_lines(&session).is_empty(), "an empty list has nothing to say");
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
assert_eq!(unknown_rule_lines(&session).len(), 1, "re-armed by the change");
}
#[test]
fn a_select_emptied_by_the_dropping_falls_through_the_ladder_unchanged() {
// §42's ladder: a `select` that named nothing the registry knows is an
// empty `select`, which is no opinion at all — the project's list, then
// the base set. The log line is the whole of what §45.1 changed.
let tree = Tree::new("unknownruleladder");
let mut session = Session::new(vec![tree.path.clone()], false);
let base = settings::lint_selection(session.server.workspace.client_settings());
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
assert_eq!(unknown_rule_lines(&session).len(), 2, "both names said");
let now = session.server.workspace.client_settings();
assert!(now.lint_select.is_empty(), "the dropping left an empty select");
assert_eq!(settings::lint_selection(now), base, "and the rule set is untouched");
}
File diff suppressed because it is too large. Load diff
+281 -13
View File
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use serde_json::Value;
use vlog_linter::Severity;
use vlog_linter::{OptionValue, RuleOptions, Severity};
/// Accepted `line-length`, and accepted `indent`.
///
@@ -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`.
@@ -190,6 +196,39 @@ pub struct ClientSettings {
/// toggle nobody touched would silently override `select` and the class
/// switches.
pub lint_rules: BTreeMap<String, bool>,
/// `lucisv.lint.options`: `{"<rule>": {"<key>": value}}`, validated
/// against the rule registry.
///
/// Refused entries are **dropped**, not fatal — this module's standing
/// rule, and the reason it matters here more than anywhere else: one
/// typo in an options object must not be able to switch the linter off
/// for a whole session. What was refused is kept in
/// [`ClientSettings::lint_option_warnings`] so the user is told.
pub lint_options: RuleOptions,
/// One line per refused `lucisv.lint.options` entry, ready for a
/// `window/logMessage`. Empty for a settings push that was all valid.
pub lint_option_warnings: Vec<String>,
/// One line per name in `lucisv.lint.select` / `lucisv.lint.ignore` that
/// the registry does not know, in the shape
/// `lucisv.lint.select: unknown rule: <name>`.
///
/// Separate from [`ClientSettings::lint_option_warnings`] because the two
/// are said differently: an options warning is raised every time the
/// setting arrives, while an unknown name is said **once** per (setting,
/// name) and re-armed only when the list changes — a client that re-pushes
/// its whole section on every keystroke must not repeat it
/// (`docs/features/small-items-4/README.md`).
pub lint_name_warnings: Vec<String>,
/// `lucisv.lint.waivers`: external waiver files, each absolute or relative
/// to the first workspace root — the editor's spelling of
/// `lucisv check --waiver-file` and of `waivers` under `[lint]` in a
/// `lucisv.toml`. They **add** to whatever that table names.
///
/// The paths are taken as written and nothing is read here: whether a file
/// exists and whether its directives parse is answered where the files are
/// read (`lint::external_waivers`), and reported once through the log when
/// this value arrives.
pub lint_waivers: Vec<String>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -204,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,
@@ -218,6 +258,10 @@ impl Default for ClientSettings {
lint_ignore: Vec::new(),
lint_severity: every_class_on(),
lint_rules: BTreeMap::new(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::new(),
lint_name_warnings: Vec::new(),
lint_waivers: Vec::new(),
}
}
}
@@ -232,16 +276,31 @@ fn every_class_on() -> BTreeMap<Severity, bool> {
///
/// Its only use is equality — the server compares it across a settings change
/// to decide whether every open file must be published again.
pub type LintSelection =
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>);
pub type LintSelection = (
Vec<String>,
Vec<String>,
BTreeMap<Severity, bool>,
BTreeMap<String, bool>,
RuleOptions,
Vec<String>,
);
/// The four lint settings of `settings`, as one comparable value.
/// The lint settings of `settings`, as one comparable value.
///
/// The options are in here with the four that choose rules, because a changed
/// option changes what a rule *reports* — a `line-length` of 120 unpublishes
/// every finding drawn at 100 — and every open file must be published again
/// for exactly the same reason a changed selection does.
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
(
settings.lint_select.clone(),
settings.lint_ignore.clone(),
settings.lint_severity.clone(),
settings.lint_rules.clone(),
settings.lint_options.clone(),
// A waiver file added or dropped changes which findings survive, so it
// republishes for exactly the reason a changed option does.
settings.lint_waivers.clone(),
)
}
@@ -272,11 +331,18 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
let large_file = lucisv.get("largeFile");
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
let lint = lucisv.get("lint");
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
// The names the registry did not know, collected as the two lists are
// filtered so the user hears about a typo instead of losing a rule to it.
let mut names = Vec::new();
let lint_select = rules(lint.and_then(|l| l.get("select")), "select", &mut names);
let lint_ignore = rules(lint.and_then(|l| l.get("ignore")), "ignore", &mut names);
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
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
@@ -313,23 +379,44 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// prevent.
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
lint_select: rules(lint.and_then(|l| l.get("select"))),
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
lint_select,
lint_ignore,
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
// one level deeper again, for the same reason `index.*` does.
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
lint_options: options,
lint_option_warnings: warnings,
lint_name_warnings: names,
// Paths, not rule names: nothing to validate against the registry, and
// a path that names nothing is reported when the file is read.
lint_waivers: strings(lint.and_then(|l| l.get("waivers"))),
}
}
/// The rule names in a settings array, dropping every one that names neither a
/// rule nor a severity class.
/// rule nor a severity class and describing each drop in `warnings`.
///
/// Silence rather than an error, on this module's standing rule: a push is
/// JSON on a socket, and a typo in one name must not cost the user every
/// diagnostic in the file. A dropped name leaves the rule where it was.
fn rules(value: Option<&Value>) -> Vec<String> {
strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect()
/// The drop itself is this module's standing rule: a push is JSON on a socket,
/// and a typo in one name must not cost the user every diagnostic in the file,
/// so a name the registry does not know leaves the rule where it was. Silence
/// about it was not the rule, only the state of things — `[lint] select` in a
/// `lucisv.toml` has said the same mistake out loud since §42, and this is the
/// editor's half of that (`docs/topo.md` §2.9-29).
///
/// `setting` is `select` or `ignore`, so the line names the list the user
/// typed in.
fn rules(value: Option<&Value>, setting: &str, warnings: &mut Vec<String>) -> Vec<String> {
strings(value)
.into_iter()
.filter(|name| {
let known = vlog_linter::rules_named(name).is_some();
if !known {
warnings.push(format!("lucisv.lint.{setting}: unknown rule: {name}"));
}
known
})
.collect()
}
/// The three class master switches, each `true` unless a client turned it off.
@@ -364,6 +451,63 @@ fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
.collect()
}
/// The `lucisv.lint.options` object, validated against the rule registry.
///
/// The shape is `{"<rule>": {"<key>": value}}` — the nesting VS Code's
/// settings model produces for an object setting, and the one a hand-written
/// Neovim config writes. Every entry goes through the **same** validator a
/// `[lint.<rule>]` table in a `lucisv.toml` goes through
/// (`RuleOptions::set`), so an option means one thing in both front ends.
///
/// A refused entry is dropped and described, rather than failing the push:
/// the CLI can fail a run over a typo because a user typed it and is watching,
/// while a settings push arrives on a socket and failing it would leave an
/// editor with no diagnostics and no way to see why. The descriptions are
/// returned for the caller to log.
fn rule_options(value: Option<&Value>) -> (RuleOptions, Vec<String>) {
let mut options = RuleOptions::new();
let mut warnings = Vec::new();
let Some(Value::Object(rules)) = value else { return (options, warnings) };
for (rule, keys) in rules {
let Some(Value::Object(keys)) = Some(keys) else {
warnings.push(format!("lucisv.lint.options.{rule} is not an object; ignored"));
continue;
};
for (key, raw) in keys {
let Some(value) = option_value(raw) else {
warnings.push(format!(
"lucisv.lint.options.{rule}.{key}: {raw} is not a boolean, number, \
string or list of strings; ignored"
));
continue;
};
if let Err(problem) = options.set(rule, key, value) {
warnings.push(format!("lucisv.lint.options.{rule}.{key}: {problem}; ignored"));
}
}
}
(options, warnings)
}
/// One JSON value as an option value, or nothing for a shape no option takes.
///
/// Structural only — whether the *kind* is the one the option declares is
/// `RuleOptions::set`'s answer, so the error a user reads names the option
/// and its kind rather than JSON's.
fn option_value(raw: &Value) -> Option<OptionValue> {
match raw {
Value::Bool(b) => Some(OptionValue::Bool(*b)),
Value::Number(n) => n.as_i64().map(OptionValue::Int),
Value::String(s) => Some(OptionValue::Str(s.clone())),
Value::Array(items) => items
.iter()
.map(|item| item.as_str().map(str::to_string))
.collect::<Option<Vec<String>>>()
.map(OptionValue::List),
_ => None,
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
/// case and all — because the enum in `package.json` is what a settings UI
/// offers, and forgiving `"Workspace"` here would make a typo mean something
@@ -798,6 +942,39 @@ mod tests {
}}}));
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
assert_eq!(found.lint_ignore, vec!["warning"]);
// And the one name that is neither is described, not just dropped.
assert_eq!(found.lint_name_warnings, vec!["lucisv.lint.select: unknown rule: nope"]);
}
/// TODO §45.1: a name the registry does not know is still dropped — the
/// rule stays where it was — and now says so, once per name, naming the
/// list the user typed it in.
#[test]
fn an_unknown_rule_name_is_described_for_each_list_it_appears_in() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["no-tabs", "nope", "also-nope"],
"ignore": ["nope"],
}}}));
assert_eq!(found.lint_select, vec!["no-tabs"]);
assert!(found.lint_ignore.is_empty());
assert_eq!(
found.lint_name_warnings,
vec![
"lucisv.lint.select: unknown rule: nope",
"lucisv.lint.select: unknown rule: also-nope",
"lucisv.lint.ignore: unknown rule: nope",
]
);
}
#[test]
fn two_lists_of_known_names_describe_nothing() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["no-tabs", "error"],
"ignore": ["unused-signal"],
}}}));
assert!(found.lint_name_warnings.is_empty(), "{:?}", found.lint_name_warnings);
assert!(settings(json!({"lucisv": {}})).lint_name_warnings.is_empty());
}
/// What the server compares two settings pushes by, to decide whether the
@@ -813,7 +990,9 @@ mod tests {
selected.lint_select = vec!["error".to_string()];
let mut ignored = base.clone();
ignored.lint_ignore = vec!["no-tabs".to_string()];
for changed in [severity, toggled, selected, ignored] {
let mut configured = base.clone();
configured.lint_options.set_raw("line-length", "length", "120").expect("accepted");
for changed in [severity, toggled, selected, ignored, configured] {
assert_ne!(lint_selection(&base), lint_selection(&changed));
}
// A setting that does not change which rules run does not republish.
@@ -822,6 +1001,95 @@ mod tests {
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
}
/// §34.0(c): the object is read, validated against the registry, and a
/// bad entry is dropped **with a warning** rather than failing the push.
#[test]
fn the_lint_options_object_is_read_and_validated() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 120},
"generate-label-prefix": {"prefix": ["blk_"]},
"typedef-structs-unions": {"allow_anonymous_nested": true},
"signal-name-style": {"style_regex": "[a-z_0-9]+"},
}}}}));
assert_eq!(found.lint_options.int("line-length", "length"), 120);
assert_eq!(
found.lint_options.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()]
);
assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested"));
assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings);
}
#[test]
fn a_refused_option_is_dropped_and_described_rather_than_fatal() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 10, "len": 120},
"no-such-rule": {"x": 1},
"no-tabs": {"width": 4},
"signal-name-style": {"style_regex": "[a-"},
"interface-name-style": {"style_regex": "\\bword\\b"},
"macro-name-style": {"style_regex": 4},
"package-filename": "not-an-object",
"port-name-suffix": {"suffixes": [1, 2]},
}}}}));
// Nothing was accepted, and every refusal says which entry and why.
assert!(found.lint_options.is_empty(), "{:?}", found.lint_options);
let warnings = found.lint_option_warnings.join("\n");
for wanted in [
"line-length.length",
"must be between",
"has no option `len`",
"unknown rule `no-such-rule`",
"takes no options",
"not a valid pattern",
"unsupported escape `\\b`",
"expects a pattern, found an integer",
"package-filename is not an object",
"port-name-suffix.suffixes",
] {
assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}");
}
// ... and the rest of the settings survived the bad object.
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
}
/// `lucisv.lint.waivers` is a list of paths, taken as written: this module
/// has no filesystem to check them against, and whether a file exists or
/// parses is answered where it is read. TODO §39.
#[test]
fn the_waivers_setting_is_a_list_of_paths_taken_as_written() {
let found = settings(json!({"lucisv": {"lint": {
"waivers": ["project.waiver", "/abs/other.waiver", 7, null]
}}}));
assert_eq!(found.lint_waivers, vec!["project.waiver", "/abs/other.waiver"]);
assert!(settings(json!({"lucisv": {"lint": {}}})).lint_waivers.is_empty());
// Wrong-typed altogether: the whole list is "no opinion", never a
// guess, exactly as `select` and `exclude` are.
for bad in [json!("project.waiver"), json!(3), json!(null), json!({"a": 1})] {
assert!(
settings(json!({"lucisv": {"lint": {"waivers": bad}}})).lint_waivers.is_empty(),
"waivers {bad} must be ignored"
);
}
// A changed list republishes, for the reason a changed option does.
let one = settings(json!({"lucisv": {"lint": {"waivers": ["a.waiver"]}}}));
let two = settings(json!({"lucisv": {"lint": {"waivers": ["b.waiver"]}}}));
assert_ne!(lint_selection(&one), lint_selection(&two));
}
/// A settings payload with no options object is exactly today's
/// behaviour: every rule reads its own default.
#[test]
fn no_options_object_means_every_default() {
for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] {
let found = settings(payload);
assert!(found.lint_options.is_empty());
assert!(found.lint_option_warnings.is_empty());
assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default");
}
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
+614
View File
@@ -0,0 +1,614 @@
//! Which files a scan will index, how they were found, and what the finding
//! cost.
//!
//! The scope ladder ([`Workspace::source_files`]) and the overlay that lets an
//! open buffer beat the disk ([`Workspace::collect_sources`]), lifted out of
//! `state/mod.rs` on 2026-09-08 (TODO §61.3) when discovery grew a stage split
//! and a second entry point. It answers one question — *which files exist as
//! far as this server is concerned, and how big are they* — and every rung of
//! the ladder is in this file.
//!
//! **The size a walked file reports is the walk's own.** `lucisv_core`'s walk
//! calls `metadata` on every directory entry to answer "directory?", so the
//! length is a field it already holds; asking the filesystem again, once per
//! file, was 6.9 ms of a 165 ms discovery over 3 976 files — measured, not
//! assumed, and smaller than it looks because the walk has just warmed every
//! one of those inodes (`docs/features/perf5r-first-answer/README.md`). A path
//! the walk did not stat — a filelist entry, an input named rather than walked
//! — carries no length and is stat'd here, exactly as every path used to be.
//!
//! **And the walk is split in two when it pays to be.** A workspace-scoped
//! session with a buffer open walks that buffer's own folders first, so the
//! scan can index and publish them before it discovers the other 3 850 files
//! ([`Workspace::first_scope`]). One scan, one work list, every file once.
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use lucisv_core::config::Discovery;
use lucisv_core::walk::{collect_files_below, collect_files_with, EXTENSIONS};
use crate::scan_trace::ScanTrace;
use super::scan::{Analyzed, HeldAnalyses, IndexEvent, PendingDiscovery, Sources};
use super::Workspace;
/// One in-scope file, and the length whoever found it already knew.
///
/// `len` is `None` for a path nothing stat'd on the way here — a filelist
/// entry, or an input named rather than walked. It is not "unknown size": it
/// is "nobody has looked yet", and [`oversize`] is what looks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Found {
pub(super) path: PathBuf,
pub(super) len: Option<u64>,
}
impl Found {
/// A path nothing has stat'd.
fn unmeasured(path: PathBuf) -> Found {
Found { path, len: None }
}
/// One path on its own, for a caller asking the cap about a single file
/// rather than about a walk ([`Workspace::current_text`]).
pub(super) fn of(path: &Path) -> Found {
Found::unmeasured(path.to_path_buf())
}
}
/// What the scope ladder decided: the files to index, the directories an
/// `` `include`` in them is looked for in, and what to tell the user.
#[derive(Default)]
pub(super) struct Scope {
pub(super) files: Vec<Found>,
/// The filelist's `+incdir+`s, in filelist order. Empty for every rung
/// but the filelist — nothing else names an include path.
pub(super) incdirs: Vec<PathBuf>,
pub(super) warnings: Vec<String>,
}
/// The size of `found` when it is over `cap`, else `None` — the whole of the
/// `lucisv.index.maxFileSize` test.
///
/// Metadata only: the point of the cap is that a 200 MB netlist is never read
/// into memory, so knowing how big it is has to come first. A `cap` of 0 is
/// the client asking for no cap, and a file whose metadata cannot be read is
/// not skipped here — it simply fails the read later, as it always did.
///
/// `stats` counts the `metadata` calls this one really made, so a session can
/// prove the walk's hand-off removed them rather than assert it.
pub(super) fn oversize(found: &Found, cap: u64, stats: &mut usize) -> Option<u64> {
if cap == 0 {
return None;
}
let size = match found.len {
Some(size) => size,
None => {
*stats += 1;
fs::metadata(&found.path).ok()?.len()
}
};
(size > cap).then_some(size)
}
impl Workspace {
/// Resolve the scope: which files are in it, with open buffers overriding
/// disk, and those buffers' own text.
///
/// **Metadata only, plus what is already in memory.** Nothing on disk is
/// read here — a file's text is read by whoever indexes or rewrites it,
/// one file at a time ([`Workspace::scan_step`], [`Workspace::sources`]).
///
/// This is where `lucisv.index.maxFileSize` applies, and it applies to the
/// **walked** files only: an open buffer is folded in below whatever its
/// size, because the user opened it deliberately and an editor that
/// refused to understand the file on screen would be absurd. The check is
/// the size the walk read, so an oversized file is still never read at all
/// — which is the whole saving, and it is still counted and reported here
/// so that a scan's skip count is known before its first step.
///
/// A refactoring reads this same list through `sources()`, so a file the
/// cap keeps out of the index is also a file a workspace rename will not
/// rewrite. That is the consistent answer: the cap says which files exist
/// as far as this server is concerned.
pub(super) fn collect_sources(
&self,
watch: &mut dyn FnMut(IndexEvent),
analyses: HeldAnalyses,
trace: &mut ScanTrace,
) -> Sources {
let scope = self.source_files(trace);
self.overlay_buffers(scope, watch, analyses, trace)
}
/// [`Workspace::collect_sources`] over one already-resolved scope — the
/// cap, then the open buffers over the top.
///
/// Split out because the two-phase startup resolves the scope twice (the
/// user's own folders, then the rest of the workspace) and both halves owe
/// the buffers the same precedence.
pub(super) fn overlay_buffers(
&self,
scope: Scope,
watch: &mut dyn FnMut(IndexEvent),
analyses: HeldAnalyses,
trace: &mut ScanTrace,
) -> Sources {
let cap = self.client.max_file_size;
// Every path an open buffer speaks for. Reading such a file from disk
// is work thrown away — the buffer's text replaces it below, whatever
// the disk says — so the read is skipped rather than undone. The cap is
// still consulted first, so an oversized file still reports itself
// skipped exactly as it did before the buffer put its own text back.
let spoken_for: HashSet<&Path> =
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
let capping = trace.now();
let mut stats = 0usize;
let mut files: Vec<PathBuf> = Vec::new();
for found in scope.files {
if let Some(size) = oversize(&found, cap, &mut stats) {
watch(IndexEvent::Skipped { path: &found.path, size, cap });
continue;
}
if spoken_for.contains(found.path.as_path()) {
continue;
}
files.push(found.path);
}
ScanTrace::add(&mut trace.cap_ms, capping);
trace.stats += stats;
// Open buffers override what is on disk, and contribute themselves
// when they are not on disk at all.
//
// Except a buffer on the large-file fast path, which overrides disk
// with *nothing*: indexing it means parsing the hundred megabytes the
// fast path exists not to parse. Removing the path rather than leaving
// the disk copy in is the honest half of that — the alternative would
// be an index describing a file the user is looking at by bytes it no
// longer has. See `docs/features/large-file-mode/README.md` for the
// interaction with `lucisv.index.maxFileSize`, whose "an open buffer is
// never capped" rule this is the one exception to.
let buffering = trace.now();
let mut analyzed = Analyzed::default();
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
for doc in self.docs.values() {
let Some(path) = doc.path.clone() else { continue };
files.retain(|p| p != &path);
if !doc.large {
if analyses == HeldAnalyses::Wanted {
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
analyzed.words.insert(path.clone(), doc.words());
}
buffered.insert(path.clone(), doc.text.clone());
files.push(path);
}
}
ScanTrace::add(&mut trace.buffers_ms, buffering);
Sources { files, buffered, analyzed, incdirs: scope.incdirs, warnings: scope.warnings }
}
/// The files the index covers, and what the user should be told about how
/// they were chosen. The scope ladder, highest first:
///
/// 1. **A filelist** — `lucisv.filelist`, else a `filelist` key in the
/// config governing a workspace root. It names *exactly* the files to
/// index; the project said so, and guessing past it would defeat the
/// point of having one. This is the "project file", and it is the one
/// rung that is whole-project by definition.
/// 2. **The workspace-folder walk**, on `lucisv.index.scope:
/// "workspace"` — what every session did before 2026-08-27, now opt-in.
/// 3. **The folder scope**, the default: each opened buffer's own
/// directory raised `lucisv.index.scopeDepth` levels, walked. See
/// `docs/features/index-scope/README.md` for what that costs, which is
/// that a definition in another folder does not resolve until the
/// scope reaches that folder.
///
/// A configured filelist that cannot be read falls back to rung 2 (or 3)
/// with a warning. An editor that shows no symbols because of a typo in a
/// path is worse than one that quietly indexes what it can and says so.
///
/// Only rung 1 can carry `+incdir+` directories: a walked workspace names
/// none, so an `` `include`` there resolves against the including file's
/// own directory alone (`docs/features/include-nav/README.md`).
pub(super) fn source_files(&self, trace: &mut ScanTrace) -> Scope {
// The walk's own warnings join the scope's, so an unreadable directory
// reaches the output channel by the road a filelist's problems already
// travel — said once per scan and never per keystroke.
let mut warnings: Vec<String> = Vec::new();
let Some(path) = self.filelist_path() else {
let files = self.default_files(&mut |w| warnings.push(w), trace);
return Scope { files, warnings, ..Default::default() };
};
let reading = trace.now();
let read = lucisv_core::filelist::read(&path);
ScanTrace::add(&mut trace.filelist_ms, reading);
match read {
Ok(list) => Scope {
files: list.files.into_iter().map(Found::unmeasured).collect(),
incdirs: list.incdirs,
warnings: list.warnings,
},
Err(problem) => {
let files = self.default_files(&mut |w| warnings.push(w), trace);
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
Scope { files, incdirs: Vec::new(), warnings }
}
}
}
/// The filelist governing this workspace, if any: the client's setting
/// first (absolute, or relative to the first root), else the `filelist`
/// key of the config governing a root, in root order.
///
/// Public because the file watchers must name it: a `.f` edited outside
/// the editor changes the index's scope, and nothing else on disk would
/// tell us (`docs/features/file-watching/README.md`).
pub fn filelist_path(&self) -> Option<PathBuf> {
if let Some(setting) = &self.client.filelist {
let path = Path::new(setting);
return Some(match self.roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
});
}
let mut discovery = Discovery::new(true);
// A broken `lucisv.toml` names no filelist, exactly as it contributes no
// excludes below: the user hears about it when they format.
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
}
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
/// asked for it, else the folder scope.
fn default_files(&self, warn: &mut dyn FnMut(String), trace: &mut ScanTrace) -> Vec<Found> {
if self.walks_the_workspace() {
return self.walked_files(&self.roots, warn, trace);
}
self.folder_files(warn, trace)
}
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
/// filter the workspace walk applies.
///
/// One exception, kept exactly as it was from before this rung became the
/// default: **a rootless session at depth 0 reads its directories flat**,
/// one level, no `.gitignore`. That is the "a file opened on its own"
/// case, where descending a tree the user never named would be a surprise
/// — and the moment the user raises `scopeDepth` they have named one, so
/// the walk is what they asked for.
fn folder_files(&self, warn: &mut dyn FnMut(String), trace: &mut ScanTrace) -> Vec<Found> {
let dirs = self.scope_dirs();
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
return sibling_files(&dirs, trace);
}
self.walked_files(&dirs, warn, trace)
}
/// Every source file under `dirs`, found by the CLI's own walk: the same
/// extensions, the same `.gitignore` handling, and the `exclude` patterns
/// of the config governing each directory. What `lucisv` skips, the index
/// skips.
///
/// `dirs` is the workspace roots for rung 2 and the scope directories for
/// rung 3. The one honest difference between the two: `.gitignore` files
/// are read from the walk's own starting directory downwards, so a rule
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
/// starts below it. The `exclude` patterns are matched against whole
/// paths and so behave identically either way.
pub(super) fn walked_files(
&self,
dirs: &[PathBuf],
warn: &mut dyn FnMut(String),
trace: &mut ScanTrace,
) -> Vec<Found> {
let mut discovery = Discovery::new(true);
let mut out: Vec<Found> = Vec::new();
for root in dirs {
// The walk names its inputs as strings; every directory here came
// from a `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
let configuring = trace.now();
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `lucisv.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
ScanTrace::add(&mut trace.config_ms, configuring);
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
// is skipped and said — the warning rides out on the scope's own
// warnings, which `server/notification.rs` logs once per scan.
let walking = trace.now();
let _ = collect_files_with(
input,
&exclude,
true,
&mut |path, len| out.push(Found { path, len }),
&mut |w| warn(w.to_string()),
);
ScanTrace::add(&mut trace.walk_ms, walking);
trace.walk_dirs += 1;
}
let sorting = trace.now();
sort_found(&mut out);
ScanTrace::add(&mut trace.sort_ms, sorting);
out
}
/// The files the directories a widen added bring into scope, by the same
/// rules [`Workspace::folder_files`] applies to the whole scope — including
/// the rootless-at-depth-0 flat read.
pub(super) fn widened_files(
&self,
added: &[PathBuf],
warn: &mut dyn FnMut(String),
trace: &mut ScanTrace,
) -> Vec<Found> {
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
return sibling_files(added, trace);
}
self.walked_files(added, warn, trace)
}
}
/// The largest neighbourhood a startup will index before it finds out how big
/// the workspace is.
///
/// The split's whole premise is that the user's own folder is a small part of
/// the workspace, so stepping it first costs the rest of the scan nothing a
/// user notices. Beyond this many files that premise is not proven — the
/// count that would prove it is the walk this order exists to postpone — so
/// the walk is finished first and the scan is ordered exactly as it was
/// before, `scan_order::worth_waiting` and all.
///
/// 512 is a measured bound and not a round number: a warm step costs about
/// 0.2 ms a file (124 files in 25 ms, `docs/features/perf5-p4/README.md`
/// §P4b3), so a head of this size is ~100 ms of stepping and the whole first
/// answer still fits inside the round's 200 ms gate.
pub(crate) const HEAD_WALK_MAX: usize = 512;
impl Workspace {
/// Whether this scan may walk the user's own folders first and the rest of
/// the workspace afterwards.
///
/// Three conditions, and each of them names a case the split would
/// otherwise make *worse*:
///
/// * **the workspace walk is the rung in force.** It is the only rung
/// whose discovery is a walk of everything: a filelist names its files
/// and reads in one go, and the folder rung's own scope *is* the
/// neighbourhood, so splitting it would put the whole scan in the head.
/// * **a buffer is open, in a folder below a workspace root.** With no
/// buffer there is no neighbourhood to lead with; with one opened from
/// the root itself, the folder it raises to *is* the workspace, which is
/// the case `scan_order::worth_waiting` exists for and the case this
/// returns `false` for so that rule still decides it.
/// * **the walk finds a small enough neighbourhood** — checked by the
/// caller once the folders are walked, against [`HEAD_WALK_MAX`].
/// * **it is the session's first scan** — checked by the caller, which is
/// the only one that knows the scan number.
pub(super) fn splits_discovery(&self) -> bool {
if !self.leads_with_a_folder() {
return false;
}
let dirs = self.raised_dirs();
!dirs.is_empty() && dirs.iter().all(|dir| self.below_a_root(dir))
}
/// Whether a scan of this workspace would lead with the user's own folder
/// if it knew one — the rung half of [`Workspace::splits_discovery`],
/// asked on its own by the startup that waits a bounded moment to be told
/// which folder that is (`server/startup.rs`).
pub fn leads_with_a_folder(&self) -> bool {
self.walks_the_workspace()
}
/// Whether `dir` is a **strict** descendant of some workspace root.
///
/// A directory that *is* a root is the whole of that root's walk, so
/// leading with it is leading with everything.
fn below_a_root(&self, dir: &Path) -> bool {
self.roots.iter().any(|root| dir.starts_with(root) && dir != root)
}
/// What a whole scan starts from: its scope, and whatever of that scope is
/// still to be walked.
///
/// `None` for the second half means what it has always meant — the scope
/// was resolved entire before the first file was indexed, and the work
/// list the caller gets is the whole of it. `Some` means the caller is
/// holding the user's own folders and owes itself the rest of the
/// workspace once it has published them ([`PendingDiscovery`]).
pub(super) fn first_scope(
&self,
watch: &mut dyn FnMut(IndexEvent),
trace: &mut ScanTrace,
) -> (Sources, Option<PendingDiscovery>) {
// **The session's first scan only.** Every later whole rescan is one a
// message asked for, and `must_wait`'s `answering_a_rescan` holds every
// request for the whole of it — so leading with a folder buys no answer
// any sooner and costs the neighbourhood one extra directory
// traversal. The startup scan is the one nothing is queued ahead of,
// and it is the one this order is for
// (`docs/features/perf5r-first-answer/README.md`).
if trace.number > 1 || !self.splits_discovery() {
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
}
let mut warnings: Vec<String> = Vec::new();
let head = self.neighbourhood_files(&mut |w| warnings.push(w), trace);
// Every path the neighbourhood walk named, before the cap has had a
// say: what the remaining walk must not decide about a second time.
let mut seen: HashSet<PathBuf> = head.iter().map(|found| found.path.clone()).collect();
seen.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
if head.len() > HEAD_WALK_MAX {
// Too big to lead with unproven. Finish the walk now and hand back
// the whole scope, ordered the way every scan before this one was.
let (mut files, rest_warnings, _) = self.walked_rest(&seen, trace);
warnings.extend(rest_warnings);
files.extend(head);
sort_found(&mut files);
let scope = Scope { files, incdirs: Vec::new(), warnings };
return (self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace), None);
}
let scope = Scope { files: head, incdirs: Vec::new(), warnings };
let sources = self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace);
(sources, Some(PendingDiscovery { roots: self.roots.clone(), seen }))
}
/// The user's own neighbourhood, walked: every source file under the
/// folders the open buffers raise to, **as the walk of the workspace root
/// would have found them**.
///
/// `collect_files_below` rather than `collect_files_with` is the whole of
/// that "as": a walk starting at `hw/ip/aes` reads no `.gitignore` above
/// itself, and the rung in force here is the *root's*, so the folder half
/// of one scope must obey the same rules the other half does. Without it
/// the head would index files the rest of the scan excludes, and the two
/// halves of one scan would disagree about which files exist.
fn neighbourhood_files(
&self,
warn: &mut dyn FnMut(String),
trace: &mut ScanTrace,
) -> Vec<Found> {
let mut discovery = Discovery::new(true);
let mut out: Vec<Found> = Vec::new();
for dir in self.raised_dirs() {
// The root this folder was raised inside: the deepest one that
// contains it, which is the one `Workspace::raised` clamped to.
let Some(root) = self.deepest_root(&dir) else { continue };
let configuring = trace.now();
let mut exclude =
discovery.for_dir(&root).unwrap_or_default().exclude.unwrap_or_default();
exclude.extend(self.client.exclude.iter().cloned());
ScanTrace::add(&mut trace.config_ms, configuring);
let walking = trace.now();
let _ = collect_files_below(
&root,
&dir,
&exclude,
true,
&mut |path, len| out.push(Found { path, len }),
&mut |w| warn(w.to_string()),
);
ScanTrace::add(&mut trace.walk_ms, walking);
trace.walk_dirs += 1;
}
let sorting = trace.now();
sort_found(&mut out);
ScanTrace::add(&mut trace.sort_ms, sorting);
out
}
/// The deepest workspace root containing `dir` — the one
/// [`Workspace::raised`] clamped the raise to, and so the one whose walk
/// this folder is part of.
fn deepest_root(&self, dir: &Path) -> Option<PathBuf> {
self.roots
.iter()
.filter(|root| dir.starts_with(root))
.max_by_key(|root| root.components().count())
.cloned()
}
/// The roots walked, less what `seen` already names — the walk half of
/// [`Workspace::rest_of_scope`], with no cap and no reporting.
fn walked_rest(
&self,
seen: &HashSet<PathBuf>,
trace: &mut ScanTrace,
) -> (Vec<Found>, Vec<String>, usize) {
let mut warnings: Vec<String> = Vec::new();
let walked = self.walked_files(&self.roots, &mut |w| warnings.push(w), trace);
let kept: Vec<Found> =
walked.into_iter().filter(|found| !seen.contains(&found.path)).collect();
let count = kept.len();
(kept, warnings, count)
}
/// The rest of the workspace: everything the roots hold that `seen` does
/// not already name, capped and reported exactly as the neighbourhood was.
///
/// Returns the files to index, what the walk wants said, and how many the
/// cap kept out. Open buffers are **not** folded in again — they were
/// folded into the head, and a buffer's path is in `seen`.
pub(super) fn rest_of_scope(
&self,
roots: &[PathBuf],
seen: &HashSet<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
trace: &mut ScanTrace,
) -> (Vec<PathBuf>, Vec<String>, usize) {
let mut warnings: Vec<String> = Vec::new();
let walked = self.walked_files(roots, &mut |w| warnings.push(w), trace);
let cap = self.client.max_file_size;
let capping = trace.now();
let mut stats = 0usize;
let mut skipped = 0usize;
let mut files: Vec<PathBuf> = Vec::new();
for found in walked {
// Already decided about by the neighbourhood: indexed, capped out,
// or spoken for by an open buffer. Deciding again would step a
// file twice or report one skip as two.
if seen.contains(&found.path) {
continue;
}
if let Some(size) = oversize(&found, cap, &mut stats) {
watch(IndexEvent::Skipped { path: &found.path, size, cap });
skipped += 1;
continue;
}
files.push(found.path);
}
ScanTrace::add(&mut trace.cap_ms, capping);
trace.stats += stats;
(files, warnings, skipped)
}
}
/// Path order, one entry per path — what the walk's callers have always done
/// with the paths of several overlapping directory walks.
///
/// The first entry for a path wins, which matters only for the length beside
/// it, and two walks that found the same file read the same `metadata` for it.
pub(super) fn sort_found(found: &mut Vec<Found>) {
found.sort_by(|a, b| a.path.cmp(&b.path));
found.dedup_by(|a, b| a.path == b.path);
}
/// The source files sitting in each of `dirs`, one directory deep. No walk, no
/// `.gitignore`: this is the rootless default, where descending a tree the
/// user never named would be a surprise.
fn sibling_files(dirs: &[PathBuf], trace: &mut ScanTrace) -> Vec<Found> {
let walking = trace.now();
let mut out: Vec<Found> = Vec::new();
for dir in dirs {
let Ok(entries) = fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
if !EXTENSIONS.contains(&extension) {
continue;
}
// One `metadata` — the same call `is_file()` was, with the length
// it always had kept rather than thrown away. It follows symlinks,
// exactly as `is_file()` did.
let Ok(meta) = fs::metadata(&path) else { continue };
if meta.is_file() {
out.push(Found { path, len: Some(meta.len()) });
}
}
}
ScanTrace::add(&mut trace.walk_ms, walking);
trace.walk_dirs += dirs.len();
let sorting = trace.now();
sort_found(&mut out);
ScanTrace::add(&mut trace.sort_ms, sorting);
out
}
File diff suppressed because it is too large. Load diff
+401
View File
@@ -0,0 +1,401 @@
//! 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, HashSet};
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 rest of the workspace, still to be discovered — see
/// [`PendingDiscovery`]. `None` for every scan that resolved its whole
/// scope before it started, which is every scan but a workspace-scoped
/// startup with a buffer already open.
pub(super) pending: Option<PendingDiscovery>,
/// 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,
}
/// The half of a scan's scope that has not been walked yet.
///
/// **One scan, discovered in two goes.** A workspace-scoped session with a
/// buffer already open walks that buffer's own folders first, indexes them,
/// publishes them and answers the request that has been waiting — and only
/// then walks the remaining 3 800 directories, whose 155 ms used to sit in
/// front of every one of those steps (`docs/features/perf5r-first-answer`).
/// It is emphatically **not** two scans: one work list, one index, one
/// `finish_scan`, one `gone` computed against the whole of it, and every file
/// stepped exactly once — which is what `seen` is for.
pub(super) struct PendingDiscovery {
/// The directories still to walk: the workspace roots.
pub(super) roots: Vec<PathBuf>,
/// Every path the neighbourhood walk yielded — the ones it indexed, the
/// ones the size cap kept out, and every open buffer's own path. The
/// remaining walk covers the roots, so it finds all of these again; each
/// one it names here has already been decided about, and deciding twice
/// would step a file twice or report one skip as two.
pub(super) seen: HashSet<PathBuf>,
}
/// How many records may be staged before another mid-scan publish is worth the
/// whole-index merge it costs — see [`Scan::publish_is_due`].
///
/// **512 is a work bound, and it is deliberately the same number
/// `HEAD_WALK_MAX` is.** Both answer "how much of this workspace may a user
/// wait for before an answer stops being worth waiting for": 512 warm steps is
/// ~100 ms of scanning on the corpus the round measured
/// (`docs/features/perf5r-first-answer/README.md`), so a request landing
/// between two publishes reads an index at most that far behind and the whole
/// scan pays at most one merge per 512 files instead of one per burst.
pub(crate) const PUBLISH_EVERY: usize = 512;
/// 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
}
/// Whether enough has been staged since the last publish for another one
/// to be worth the merge it costs — the **publication cadence**.
///
/// **A publish is a pass over the whole index, and it used to be one per
/// burst of requests.** `answer_what_is_waiting` published whenever
/// anything at all was waiting, so a client asking ten times a second
/// bought ten merges a second over a table that grows all the way to the
/// end of the scan. Measured on opentitan under a definition every 100 ms
/// (`docs/features/perf5r-publication/README.md`): 13 to 18 publishes in
/// one warm scan, and `absorb` + `candidates` alone were 46 % of it.
///
/// The rule this asks is **how much new the next answer would see**, not
/// how long ago the last publish was: a merge's cost is the index's size
/// and its value is the records it makes answerable, so files staged is
/// the currency both are in — and it is a count, so what a scan does is
/// the same on a fast machine and a slow one, and a test may assert it.
///
/// It bounds staleness, never correctness: a request answered between two
/// publishes reads a prefix at most [`PUBLISH_EVERY`] files older than the
/// one it could have had, and every table in it still agrees with every
/// other ([`Workspace::publish_scan`](super::Workspace::publish_scan)).
/// The **first** publish of a scan is never deferred by it — that one is
/// the session's first useful answer, and `server/index.rs` asks for it by
/// a different door.
pub fn publish_is_due(&self) -> bool {
self.staged.len() >= PUBLISH_EVERY
}
/// Whether this scan still owes itself the rest of its own scope — see
/// [`PendingDiscovery`].
///
/// Two callers, and they want it for the same reason: `scan_once` must
/// interleave a scan whose work list is short *so far*, and must not paint
/// a percentage against a denominator that is going to grow
/// (`docs/features/indexing-ux/README.md`).
pub fn discovery_pending(&self) -> bool {
self.pending.is_some()
}
/// Take the remaining discovery, so the workspace can run it.
pub(super) fn take_pending(&mut self) -> Option<PendingDiscovery> {
self.pending.take()
}
/// Fold the rest of the scope into this scan: its files onto the end of
/// the work list, its paths into the set the include graph learns from,
/// its warnings and its skips onto the scan's own.
///
/// Appended rather than re-ordered: the neighbourhood at the front has
/// already been stepped, and `vlog_semantic::IndexBuilder` sorts by path
/// inside `finish`, so what arrives here decides latency and nothing else
/// ([`Scan::reorder`] makes the same argument).
pub(super) fn land_discovery(
&mut self,
files: Vec<PathBuf>,
warnings: Vec<String>,
skipped: usize,
) {
self.paths.extend(files.iter().cloned());
self.paths.sort();
self.paths.dedup();
self.work.extend(files);
self.warnings.extend(warnings);
self.skipped += skipped;
}
/// 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 },
}
+6 -2
View File
@@ -4,7 +4,7 @@
use lsp_types::{Location, SymbolInformation, SymbolKind as LspKind};
use vlog_semantic::{Symbol, SymbolKind};
use crate::locate::location;
use crate::locate::definition_location;
use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT};
/// How a declaration reads in hover text.
@@ -129,7 +129,11 @@ pub fn workspace_symbols(ws: &Workspace, query: &str) -> Vec<SymbolInformation>
.take(WORKSPACE_SYMBOL_LIMIT)
.filter_map(|hit| {
let path = index.path(hit.def.file)?;
let location: Location = location(ws, path, hit.def.name_span)?;
// A unit's range is in the index; a member's is not, and falls
// back to the file read. `workspace/symbol` answers up to
// `WORKSPACE_SYMBOL_LIMIT` hits at once, so this is the request
// the index-carried positions matter most to.
let location: Location = definition_location(ws, path, hit.def)?;
// `deprecated` is a deprecated protocol field that is still a
// named field of the struct.
#[allow(deprecated)]
+11
View File
@@ -456,6 +456,17 @@ mod tests {
}
}
/// The premise [`every_untouched_expansion_parses`] rests on: the probe
/// can still fail. Header recovery (TODO §32) widened what a tolerant
/// parse reads, and a probe that answered "clean" for everything would
/// pass that test while proving nothing.
#[test]
fn the_expansion_probe_still_reports_text_that_does_not_parse() {
let probe = "module p;\n always_comb begin\n case (sel\n end\nendmodule\n";
let (_, diagnostics) = vlog_parser::parse_source_tolerant(probe);
assert!(!diagnostics.is_empty(), "recovery must not make a broken expansion look clean");
}
#[test]
fn every_hole_is_a_tabstop_the_snippet_grammar_reads() {
// The editor-snippets lesson, restated for generated text: VS Code
+10 -7
View File
@@ -41,7 +41,7 @@
use lsp_types::{Location, Uri};
use vlog_parser::ast::{
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
ListElem, Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
TypedefKind,
};
use vlog_parser::TextRange;
@@ -180,6 +180,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
site_at(items, offset)
}
ItemKind::GenBlock(b) => gen_block_site(b, offset),
ItemKind::GenIf(g) => gen_if_site(g, offset),
ItemKind::GenFor(g) => gen_block_site(&g.body, offset),
ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)),
@@ -250,18 +251,20 @@ fn module_site(m: &Module, offset: u32) -> Option<Site<'_>> {
.or_else(|| site_at(&m.items, offset))
}
fn ansi_port_site(ports: &[AnsiPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
// The three header lists below skip their error elements: text a tolerant
// parse could not read names no type, so there is no definition to go to.
fn ansi_port_site(ports: &[ListElem<AnsiPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn param_port_site(ports: &[ParamPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
fn param_port_site(ports: &[ListElem<ParamPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn tf_arg_site(args: &[TfArg], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().find(|a| a.span.contains(offset))?;
fn tf_arg_site(args: &[ListElem<TfArg>], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().filter_map(ListElem::ok).find(|a| a.span.contains(offset))?;
site(&arg.ty.name, TextRange::new(arg.span.start, arg.name_span.start))
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -245,6 +245,7 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
ItemKind::GenCase(g) => {
+10 -2
View File
@@ -38,7 +38,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &c.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &c.param_directives);
let broken = !c.param_directives.is_empty();
@@ -52,7 +56,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &ext.param_directives);
let broken = !ext.param_directives.is_empty();
+35 -7
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};
@@ -296,22 +297,49 @@ impl<'a> Fmt<'a> {
pub(super) fn data_decl(&self, d: &DataDecl) -> Doc {
let mut docs = Vec::new();
if let Some(net) = &d.net {
docs.push(text(format!("{net} ")));
}
if let Some(delay) = &d.delay {
docs.push(text("#"));
docs.push(self.expr(delay));
docs.push(text(" "));
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);
if let Some(t) = self.data_type(&d.ty) {
docs.push(t);
docs.push(text(" "));
self.net_delay(d, true, &mut docs);
}
// Neither arm needs an `else`: a delay before the type is only read
// after a net keyword, and one after the type only when a type was
// actually written, so an implicit type has none to print.
docs.push(self.declarators(&d.declarators));
concat(docs)
}
/// The separator that follows the word just emitted, and then `#5` when
/// the declaration's net delay was written on the side of the data type
/// `after_type` names. IEEE 1800 §6.7 allows either side and lucisv
/// prints it where the source put it; moving it across the type would
/// reorder tokens, which `verify.rs` refuses.
///
/// The separator is the delay's `before_hash` comments when it has any
/// (`wire /* c */ #5 w;`) and a plain space otherwise — so a declaration
/// with no comment there is laid out exactly as it was before the slot
/// existed, delay or no delay.
fn net_delay(&self, d: &DataDecl, after_type: bool, docs: &mut Vec<Doc>) {
let delay = d.delay.as_ref().filter(|n| n.after_type == after_type);
match delay.map(|n| &n.before_hash).filter(|c| !c.is_empty()) {
Some(comments) => self.inline_comments_spaced(comments, docs),
None => docs.push(text(" ")),
}
let Some(delay) = delay else { return };
docs.push(text("#"));
self.slot_comments(&delay.after_hash, docs);
docs.push(self.expr(&delay.expr));
docs.push(text(" "));
}
pub(super) fn port_decl(&self, d: &PortDecl) -> Doc {
let mut docs = vec![text(format!("{} ", d.dir))];
if let Some(net) = &d.net {
+33 -4
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),
@@ -305,8 +320,22 @@ impl<'a> Fmt<'a> {
// region never begins its own line, so a dedent-by-column would
// drift instead of reaching a fixed point.
ExprKind::Verbatim(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
// Unreachable from `format_source`, as `ItemKind::Error` is: only
// a tolerant parse builds this leaf, and the formatter parses
// strictly. Printed verbatim so nothing is lost if that ever
// changes — see `ListItem::from_raw`.
ExprKind::Error(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max, comments } => {
let mut docs = vec![self.expr(min)];
self.slot_comments(&comments.before_typ, &mut docs);
docs.push(text(":"));
self.slot_comments(&comments.after_typ, &mut docs);
docs.push(self.expr(typ));
self.slot_comments(&comments.before_max, &mut docs);
docs.push(text(":"));
self.slot_comments(&comments.after_max, &mut docs);
docs.push(self.expr(max));
concat(docs)
}
}
}
+125 -27
View File
@@ -28,7 +28,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &inst.params {
let items: Vec<ListItem> = params
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
.map(|c| {
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma)
})
})
.collect();
let items = self.list_entries(items, &inst.param_directives);
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
@@ -109,19 +113,23 @@ impl<'a> Fmt<'a> {
list.iter()
.zip(&aligns)
.map(|(c, a)| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
})
})
.collect()
}
Connections::Ordered(list) => list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
self.list_elem(c, |c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
})
})
.collect(),
};
@@ -132,18 +140,20 @@ impl<'a> Fmt<'a> {
/// The alignment plan for an instance's named connection list.
fn connection_aligns(
&self,
conns: &[Connection],
conns: &[ListElem<Connection>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = conns
.iter()
.map(|c| {
// An error element has no cells to align, so it has no row.
let c = c.ok()?;
let paren = self.open_paren_offset(c.name_span.end)?;
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
})
.collect();
let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives);
let breaks = Self::list_breaks(conns.iter().map(|c| c.ok().map(|c| &c.meta)), directives);
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
}
@@ -330,32 +340,85 @@ 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
// a comment in it, exactly as a net delay's `before_hash` is.
match g.before_hash.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&g.before_hash, &mut docs),
}
docs.push(text("#"));
self.slot_comments(&g.after_hash, &mut docs);
}
if let [delay] = g.delay.as_slice() {
// One value prints itself, brackets and all (`#5`, `#(5)`).
docs.push(text(" #"));
docs.push(self.expr(delay));
docs.push(self.expr(&delay.expr));
} else if !g.delay.is_empty() {
// `#(rise, fall[, turn-off])` — the parens are the list's own.
docs.push(text(" #("));
// `#(rise, fall[, turn-off])` — the parens and the commas are the
// list's own, so the comments written around them are too.
docs.push(text("("));
for (i, d) in g.delay.iter().enumerate() {
if i > 0 {
docs.push(text(", "));
docs.push(text(","));
match d.leading.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&d.leading, &mut docs),
}
} else {
self.slot_comments(&d.leading, &mut docs);
}
docs.push(self.expr(d));
docs.push(self.expr(&d.expr));
self.slot_comments(&d.trailing, &mut docs);
}
docs.push(text(")"));
}
let last = g.instances.len().saturating_sub(1);
// True once a trailing comment has ended the previous instance's line:
// the next instance then starts on a fresh, indented line, and the
// space that normally separates it from the `,` is not written.
let mut broke = false;
for (i, inst) in g.instances.iter().enumerate() {
docs.push(if i > 0 { text(", ") } else { text(" ") });
// What stands between the delay (or the previous instance's `,`)
// and this instance's name — a space when nothing does.
match (broke, inst.meta.leading.is_empty()) {
(true, true) => {}
(false, true) => docs.push(text(" ")),
(_, false) => self.inline_comments_spaced(&inst.meta.leading, &mut docs),
}
broke = false;
if let Some(name) = &inst.name {
docs.push(name_doc(name));
docs.push(text(" "));
match inst.before_args.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&inst.before_args, &mut docs),
}
}
docs.push(self.expr_list("(", &inst.args, ")"));
if i == last {
continue;
}
// Comments written between the instance and its `,` print on the
// instance's side of it, as every list element's do.
if self.inline_comments(&inst.meta.before_sep, &mut docs) {
docs.push(Doc::HardLine);
}
docs.push(text(","));
if let Some(tr) = &inst.meta.trailing {
docs.push(text(" "));
docs.push(self.comment(tr));
// A line comment ends the line (a `// p` would otherwise
// swallow the next instance on re-lex — §45's QA); the next
// instance continues one level in. A block comment stays
// inline, as the case table for this slot expects.
if is_line_comment(&tr.text) {
docs.push(indent(vec![Doc::HardLine]));
broke = true;
}
}
}
docs.push(text(";"));
docs.push(self.semi(&g.before_semi));
concat(docs)
}
}
@@ -369,17 +432,52 @@ impl<'a> Fmt<'a> {
/// be measured as one short line and flattened around a value that is
/// twenty lines tall. It is exactly the reason a list holding a
/// [`ListDirective`] is broken, for exactly the same construct.
fn holds_verbatim_value(list: &[Connection]) -> bool {
list.iter().any(|c| match &c.expr {
fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
list.iter().filter_map(ListElem::ok).any(|c| match &c.expr {
Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'),
_ => false,
})
}
/// `(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)
}
+97 -27
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;`, `;;`.
@@ -274,6 +315,21 @@ impl<'a> Fmt<'a> {
body.extend(self.dangling(dangling));
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
}
// A bare `begin … end` standing where an item belongs. Never
// reached from `format_source`: the parser records a diagnostic
// beside it and a file with a diagnostic is emitted unchanged.
// The arm exists so a range or tolerant printer has nothing to
// invent — the block prints the way a generate block's does,
// without the separator `gen_block` puts in front of the keyword
// for the header it usually hangs off.
ItemKind::GenBlock(b) => {
let mut docs = Vec::new();
if self.inline_comments(&b.before_kw, &mut docs) {
docs.push(Doc::HardLine);
}
self.begin_block(&mut docs, b, depth);
concat(docs)
}
ItemKind::GenIf(g) => self.gen_if(g, depth),
ItemKind::GenFor(g) => self.gen_for(g, depth),
ItemKind::GenCase(g) => self.gen_case(g, depth),
@@ -337,18 +393,24 @@ 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);
docs.push(self.expr(delay));
docs.push(text(" "));
match a.after_delay.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&a.after_delay, &mut docs),
}
}
let items: Vec<ListItem> = a
.assigns
@@ -464,26 +526,7 @@ impl<'a> Fmt<'a> {
} else {
self.inline_comments_spaced(&b.before_kw, docs);
}
docs.push(text("begin"));
if let Some(l) = &b.label {
self.slot_comments(&b.before_colon, docs);
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
if b.after_colon.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&b.after_colon, docs);
}
docs.push(text(named(l)));
}
let mut body = Vec::new();
if !b.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&b.items, depth + 1));
}
body.extend(self.dangling(&b.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
self.begin_block(docs, b, depth);
true
} else {
let item = &b.items[0];
@@ -492,6 +535,33 @@ impl<'a> Fmt<'a> {
}
}
/// A generate block's `begin … end` and everything between, from the
/// keyword on — the separator in front of it is the caller's, because a
/// block hanging off an `if (…)` header needs one and a block standing on
/// its own as an item ([`ItemKind::GenBlock`]) does not.
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
docs.push(text("begin"));
if let Some(l) = &b.label {
self.slot_comments(&b.before_colon, docs);
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
if b.after_colon.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&b.after_colon, docs);
}
docs.push(text(named(l)));
}
let mut body = Vec::new();
if !b.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&b.items, depth + 1));
}
body.extend(self.dangling(&b.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
}
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
let mut header = Vec::new();
self.for_open(&g.comments, &mut header);
+40 -2
View File
@@ -38,6 +38,27 @@ pub(super) struct ListItem {
}
impl ListItem {
/// The entry an error element of a header list prints as: the text a
/// tolerant parse skipped, verbatim, carrying no comments of its own —
/// they are bytes of that text.
///
/// **Unreachable from `format_source`**, exactly as `ItemKind::Error` is:
/// the formatter parses strictly, and only [`vlog_parser::parse_tolerant`]
/// builds a [`ListElem::Error`]. Printing the bytes rather than nothing
/// means that if some future entry point ever did hand one over,
/// `verify.rs`'s token-equivalence check would see the tokens instead of
/// silently losing them.
pub(super) fn from_raw(doc: Doc) -> Self {
ListItem {
leading: Vec::new(),
doc,
before_sep: Vec::new(),
trailing: None,
comma: None,
directive: false,
}
}
pub(super) fn from_meta(meta: &Meta, doc: Doc) -> Self {
ListItem {
leading: meta.leading.clone(),
@@ -58,6 +79,20 @@ impl ListItem {
}
impl<'a> Fmt<'a> {
/// One entry of a **header** list: the element as `entry` prints it, or —
/// for an error element — its bytes; see [`ListItem::from_raw`] for why
/// the second case cannot be reached from `format_source`.
pub(super) fn list_elem<T>(
&self,
elem: &ListElem<T>,
entry: impl FnOnce(&T) -> ListItem,
) -> ListItem {
match elem {
ListElem::Ok(v) => entry(v),
ListElem::Error(raw) => ListItem::from_raw(self.raw_text(raw)),
}
}
/// A bracketed expression list (concatenation, call arguments, `inside`
/// set). Comments on an element ride along and break the list open.
pub(super) fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
@@ -316,15 +351,18 @@ impl<'a> Fmt<'a> {
/// with a comment or an attribute of their own — both print on their own
/// line — and those a compiler directive was written in front of.
///
/// A `None` meta is an error element, which has none; it always starts a
/// group, being raw bytes of a width no other row shares.
///
/// A blank line is deliberately *not* a boundary here: `delimited` drops
/// blank lines between list elements, so a boundary drawn at one would
/// vanish from the output and the next pass would group differently.
pub(super) fn list_breaks<'m>(
metas: impl Iterator<Item = &'m Meta>,
metas: impl Iterator<Item = Option<&'m Meta>>,
directives: &[ListDirective],
) -> Vec<bool> {
let mut breaks: Vec<bool> =
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
metas.map(|m| m.is_none_or(|m| !m.leading.is_empty() || !m.attrs.is_empty())).collect();
for d in directives {
if let Some(b) = breaks.get_mut(d.before) {
*b = true;
+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 }
}
}
+102 -31
View File
@@ -67,7 +67,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &m.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &m.param_directives);
let broken = !m.param_directives.is_empty();
@@ -94,15 +98,19 @@ impl<'a> Fmt<'a> {
.iter()
.zip(&aligns)
.map(|(p, a)| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
})
.collect()
}
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
})
})
.collect(),
_ => Vec::new(),
@@ -223,13 +231,15 @@ impl<'a> Fmt<'a> {
/// The alignment plan for a module header's ANSI port list.
fn ansi_port_aligns(
&self,
ports: &[AnsiPort],
ports: &[ListElem<AnsiPort>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = ports
.iter()
.map(|p| {
// An error element has no cells to align, so it has no row.
let p = p.ok()?;
Self::row_of(
&self.ansi_port_cells(p),
vec![p.name_span.start],
@@ -237,7 +247,7 @@ impl<'a> Fmt<'a> {
)
})
.collect();
let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives);
let breaks = Self::list_breaks(ports.iter().map(|p| p.ok().map(|p| &p.meta)), directives);
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
}
@@ -306,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));
@@ -343,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(", "));
@@ -376,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("}")])
}
}
+21 -8
View File
@@ -27,7 +27,7 @@ pub(super) struct TfHeader<'h> {
name: &'h str,
has_parens: bool,
before_args: &'h [Comment],
args: &'h [TfArg],
args: &'h [ListElem<TfArg>],
args_dangling: &'h [Comment],
}
@@ -119,9 +119,11 @@ impl<'a> Fmt<'a> {
}
}
pub(super) fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> =
args.iter().map(|a| ListItem::from_meta(&a.meta, self.tf_arg(a))).collect();
pub(super) fn tf_args(&self, args: &[ListElem<TfArg>], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> = args
.iter()
.map(|a| self.list_elem(a, |a| ListItem::from_meta(&a.meta, self.tf_arg(a))))
.collect();
self.delimited_dangling("(", items, dangling, ")", false)
}
@@ -243,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;
+18 -3
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)])
}
@@ -482,7 +497,7 @@ impl<'a> Fmt<'a> {
},
StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]),
StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]),
StmtKind::Disable(name) => {
StmtKind::Disable { name, .. } => {
concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)])
}
StmtKind::WaitFork => concat(vec![text("wait fork"), 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,101 @@
# TODO §45.4 — the comment slots inside a delay list. `parse_delay_values`
# serves `#(1:2:3)` on nets and continuous assignments and `#(rise, fall)` on
# gates; the gaps around the `(`, the two `:` and the `,` had no owner, so a
# comment written in one moved and `verify.rs` refused the file.
#
# The `min:typ:max` colons: `MinTypMaxComments`, four slots, one grammar
# shared with the parenthesized `(a:b:c)` expression.
module m;
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
endmodule
----
module m;
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
endmodule
====
# The parentheses of a one-value delay are its own `ExprKind::Paren`, which
# has had the two slots all along — and a comment inside a bracket pair forces
# that pair open, as it does everywhere else in the formatter.
module m;
wire #( /* a */ 1:2:3 /* f */ ) w;
endmodule
----
module m;
wire #(
/* a */
1:2:3 /* f */
) w;
endmodule
====
# A continuous assignment's delay: the gap after its `#` and the gap between
# the delay and the first left-hand side. Without the second slot the comment
# joins the first pair's leading comments, which print in front of the delay.
module m;
assign # /* g */ (1:2:3) /* h */ z = a;
endmodule
----
module m;
assign # /* g */ (1:2:3) /* h */ z = a;
endmodule
====
# A gate's multi-value list writes its own parentheses and commas, so it owns
# the comments around them: `DelayValue::{leading, trailing}`. With them the
# gate's `before_hash`, `after_hash`, the instance's `before_args` and the
# item's `before_semi`.
module m;
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
endmodule
----
module m;
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
endmodule
====
# A line comment runs to end of line, so what follows it starts a new one —
# the same rule every other slot in the formatter obeys.
module m;
wire #(1 // why
:2:3) w;
endmodule
----
module m;
wire #(
1 // why
:2:3
) w;
endmodule
====
# Nothing written in any of the slots costs a byte: the comment-free spellings
# are laid out exactly as they were before the slots existed.
module m;
wire #(1:2:3) a;
assign #(1:2:3) z = a;
and #(1, 2, 3) g1 (o, a, b);
not #(1:2:3, 4:5:6) n0 (o, a);
buf #(5) b1 (o, a);
buf #5 b2 (o, a);
buf b3 (o, a);
nand (weak0, weak1) #2 n1 (o, a, b);
and #(2, 3) g0 (y, a), g2 (z, b);
endmodule
----
module m;
wire #(1:2:3) a;
assign #(1:2:3) z = a;
and #(1, 2, 3) g1 (o, a, b);
not #(1:2:3, 4:5:6) n0 (o, a);
buf #(5) b1 (o, a);
buf #5 b2 (o, a);
buf b3 (o, a);
nand (weak0, weak1) #2 n1 (o, a, b);
and #(2, 3) g0 (y, a), g2 (z, b);
endmodule
====
# A comment between two gate instances, and one written before the `,` that
# separates them: the element's own `leading` and `before_sep`.
module m;
and #(2, 3) g0 (y, a) /* before */ , /* after */ g1 (z, b);
endmodule
----
module m;
and #(2, 3) g0 (y, a) /* before */, /* after */ g1 (z, b);
endmodule
@@ -224,3 +224,42 @@ module tb;
sub #() u1 (.a(x));
sub #(.W(8)) u2 (.a(x));
endmodule
====
# TODO §45.3 — an inline aggregate as a parameter-override argument. It is a
# type where a type is legal (IEEE 1800 §6.19, §7.2), the override a
# `parameter type` defaulting to one takes, and it prints through the existing
# type printer: a struct or union body opens, an enum body stays inline.
module m;
sub #(.T(struct packed { logic a; })) u0 ();
sub #(.T(union packed { logic [7:0] a; })) u1 ();
sub #(.T(enum logic [1:0] {A, B})) u2 ();
sub #(.T(struct packed { /* why */ logic a; })) u3 ();
sub #(.T(logic [7:0])) u4 ();
endmodule
----
module m;
sub #(
.T(
struct packed {
logic a;
}
)
) u0 ();
sub #(
.T(
union packed {
logic [7:0] a;
}
)
) u1 ();
sub #(.T(enum logic [1:0] {A, B})) u2 ();
sub #(
.T(
struct packed {
/* why */
logic a;
}
)
) u3 ();
sub #(.T(logic [7:0])) u4 ();
endmodule
@@ -0,0 +1,121 @@
# TODO §38.2 — a net delay is printed on the side of the data type it was
# written on. IEEE 1800 §6.7 puts `delay3` after the type; the rest of the
# corpus puts it before. Neither spelling is normalised into the other.
# docs/features/parser-skips/README.md
module m;
wire #5 before_the_type;
wire [31:0] #0.1 after_the_type = y;
endmodule
----
module m;
wire #5 before_the_type;
wire [31:0] #0.1 after_the_type = y;
endmodule
====
# after a packed dimension, after a plain `logic`-typed net, and after a
# signing keyword — with the min:typ:max spelling of the delay itself
module m;
wire [7:0] #1 a;
wire logic #2 b;
wire signed [7:0] #(1:2:3) c;
wire #(1:2:3) signed [7:0] d;
endmodule
----
module m;
wire [7:0] #1 a;
wire logic #2 b;
wire signed [7:0] #(1:2:3) c;
wire #(1:2:3) signed [7:0] d;
endmodule
====
# the real lines: hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv:38-41
# (opentitan, read-only there), the §11 skip this item closes
module SimDTM (
input clk,
output [31:0] exit
);
bit r_reset;
wire #0.1 __debug_req_ready = debug_req_ready;
wire #0.1 __debug_resp_valid = debug_resp_valid;
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
endmodule
----
module SimDTM (input clk, output [31:0] exit);
bit r_reset;
wire #0.1 __debug_req_ready = debug_req_ready;
wire #0.1 __debug_resp_valid = debug_resp_valid;
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
endmodule
====
# a comment written directly in front of the `#` is the delay's own —
# `NetDelay::before_hash`, TODO §43.2. It was the `#SKIP` §38 recorded and
# `verify.rs` refused the file for; the slot prints it back where it was
# written, on either side of the data type.
module m;
wire /* c */ #5 x;
wire [7:0] /* d */ #1 z;
wire [3:0] /* one */ /* two */ #3 w;
endmodule
----
module m;
wire /* c */ #5 x;
wire [7:0] /* d */ #1 z;
wire [3:0] /* one */ /* two */ #3 w;
endmodule
====
# the delay's other gap, between the `#` and the value: `after_hash`. Both
# slots at once on one declaration, since the fuzzer asks for both
module m;
wire # /* why */ 5 x;
wire [7:0] /* a */ # /* b */ 1 z = q;
endmodule
----
module m;
wire # /* why */ 5 x;
wire [7:0] /* a */ # /* b */ 1 z = q;
endmodule
====
# a line comment in the same slot runs to end of line, so the `#` cannot
# follow it: it starts the next one, the way the `wire #5 /* after */` case
# below breaks before its declarator
module m;
wire // why the delay
#2 y;
endmodule
----
module m;
wire // why the delay
#2 y;
endmodule
====
# the other three gaps around a delay do have slots and round-trip
module m;
(* keep *) wire [3:0] #2 k = j;
wire #5 /* after */ x;
endmodule
----
module m;
(* keep *)
wire [3:0] #2 k = j;
wire #5 /* after */
x;
endmodule
====
# a line comment after a gate instance's comma ends the line: the next
# instance continues one level in (§45's QA; the module-instantiation
# printer already did this)
module m;
and #(2, 3) g0 (y, a), // p
g1 (z, b);
endmodule
----
module m;
and #(2, 3) g0 (y, a), // p
g1 (z, b);
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,386 @@
# TODO §38.1 — two rival, bracket-balanced unit headers written across the
# arms of one `ifdef region. The whole unit is one verbatim item, so it comes
# back byte for byte apart from the block's own re-indent.
# docs/features/parser-skips/README.md
`ifdef A
interface i ();
`else
interface i ();
`endif
wire tck;
endinterface
parameter int AFTER = 1;
----
`ifdef A
interface i ();
`else
interface i ();
`endif
wire tck;
endinterface
parameter int AFTER = 1;
====
# a module spelling with a real port list and a closing label
`ifdef SYNTHESIS
module m (input a, output b);
`else
module m (input a, output b);
`endif
wire x;
endmodule : m
----
`ifdef SYNTHESIS
module m (input a, output b);
`else
module m (input a, output b);
`endif
wire x;
endmodule : m
====
# the block's *relative* layout is what survives: the whole unit is dedented
# to the item's own indent, exactly as every other verbatim block is
`ifdef A
interface i #(parameter int P = 1) ();
`else
interface i #(parameter int P = 2) ();
`endif
wire tck;
endinterface
----
`ifdef A
interface i #(parameter int P = 1) ();
`else
interface i #(parameter int P = 2) ();
`endif
wire tck;
endinterface
====
# the real file: hw/dv/sv/jtag_agent/jtag_if.sv (opentitan), the §11
# skip this item closes. Read-only there; copied here verbatim.
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
`ifdef GATE_LEVEL
// jtag interface with default 24MHz tck for GLS
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
`else
// jtag interface with default 50MHz tck for faster DV simulations
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
`endif
// interface pins
wire tck;
wire trst_n;
wire tms;
wire tdi;
wire tdo;
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
// observing some signals from the wider simulation?
//
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
// customise is_active will see the interface be driven actively, but allows a testbench that
// *does* want to customise the signal to pull it low.
wire is_active;
assign (weak0, weak1) is_active = 1'b1;
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
// is_active.
bit tck_en;
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
// "previous device in the scan chain".
bit tms_oe = 1'b1;
bit tdi_oe = 1'b1;
bit tdo_oe = 1'b0;
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
modport host_mp(clocking host_cb, output trst_n);
clocking device_cb @(posedge tck);
input tms;
input tdi;
output tdo = _tdo_internal;
endclocking
modport device_mp(clocking device_cb, input trst_n);
clocking mon_cb @(posedge tck);
input tms;
input tdi;
input tdo;
endclocking
modport mon_mp (clocking mon_cb, input trst_n);
// Signals for local tck
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
int unsigned _clk_hi_ps, _clk_lo_ps;
assign _clk_hi_ps = _tck_period_ps / 2;
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
// Sets the TCK frequency.
function automatic void set_tck_period_ps(int unsigned value);
_tck_period_ps = value;
endfunction
function automatic int unsigned get_tck_period_ps();
return _tck_period_ps;
endfunction
// Wait for one TCK cycle
//
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
// bounds the wait by _tck_period_ps (in case the clock has stopped).
//
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
task automatic wait_one_tck();
fork : isolation_fork begin
fork
begin
wait(!tck);
wait(tck);
end
#(_tck_period_ps * 1ps);
join_any
disable fork;
end join
endtask
// Wait for the given number of cycles of TCK
task automatic wait_tck(int cycles);
repeat (cycles) wait_one_tck();
endtask
// Start asserting a test reset through trst_n (no effect if the interface is not active)
function automatic void assert_test_reset();
_trst_n_internal <= 1'b0;
endfunction
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
function automatic void clear_test_reset();
_trst_n_internal <= 1'b1;
endfunction
// Assert a test reset through trst_n (no effect if the interface is not active)
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
assert_test_reset();
wait_tck(cycles);
clear_test_reset();
endtask
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
// gets used to drive the tck signal.
task automatic _drive_active();
forever begin
wait(tck_en);
fork : isolation_fork begin
fork
wait(!tck_en);
forever begin
_tck_internal = 1'b1;
#(_clk_hi_ps * 1ps);
_tck_internal = 1'b0;
#(_clk_lo_ps * 1ps);
end
join_any
disable fork;
end join
end
endtask
initial begin
_tck_internal = 1'b1;
forever begin
wait(is_active === 1'b1);
fork : isolation_fork begin
fork
wait(is_active !== 1'b1);
_drive_active();
join_any
disable fork;
end join
end
end
endinterface
----
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
`ifdef GATE_LEVEL
// jtag interface with default 24MHz tck for GLS
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
`else
// jtag interface with default 50MHz tck for faster DV simulations
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
`endif
// interface pins
wire tck;
wire trst_n;
wire tms;
wire tdi;
wire tdo;
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
// observing some signals from the wider simulation?
//
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
// customise is_active will see the interface be driven actively, but allows a testbench that
// *does* want to customise the signal to pull it low.
wire is_active;
assign (weak0, weak1) is_active = 1'b1;
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
// is_active.
bit tck_en;
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
// "previous device in the scan chain".
bit tms_oe = 1'b1;
bit tdi_oe = 1'b1;
bit tdo_oe = 1'b0;
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
modport host_mp(clocking host_cb, output trst_n);
clocking device_cb @(posedge tck);
input tms;
input tdi;
output tdo = _tdo_internal;
endclocking
modport device_mp(clocking device_cb, input trst_n);
clocking mon_cb @(posedge tck);
input tms;
input tdi;
input tdo;
endclocking
modport mon_mp (clocking mon_cb, input trst_n);
// Signals for local tck
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
int unsigned _clk_hi_ps, _clk_lo_ps;
assign _clk_hi_ps = _tck_period_ps / 2;
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
// Sets the TCK frequency.
function automatic void set_tck_period_ps(int unsigned value);
_tck_period_ps = value;
endfunction
function automatic int unsigned get_tck_period_ps();
return _tck_period_ps;
endfunction
// Wait for one TCK cycle
//
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
// bounds the wait by _tck_period_ps (in case the clock has stopped).
//
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
task automatic wait_one_tck();
fork : isolation_fork begin
fork
begin
wait(!tck);
wait(tck);
end
#(_tck_period_ps * 1ps);
join_any
disable fork;
end join
endtask
// Wait for the given number of cycles of TCK
task automatic wait_tck(int cycles);
repeat (cycles) wait_one_tck();
endtask
// Start asserting a test reset through trst_n (no effect if the interface is not active)
function automatic void assert_test_reset();
_trst_n_internal <= 1'b0;
endfunction
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
function automatic void clear_test_reset();
_trst_n_internal <= 1'b1;
endfunction
// Assert a test reset through trst_n (no effect if the interface is not active)
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
assert_test_reset();
wait_tck(cycles);
clear_test_reset();
endtask
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
// gets used to drive the tck signal.
task automatic _drive_active();
forever begin
wait(tck_en);
fork : isolation_fork begin
fork
wait(!tck_en);
forever begin
_tck_internal = 1'b1;
#(_clk_hi_ps * 1ps);
_tck_internal = 1'b0;
#(_clk_lo_ps * 1ps);
end
join_any
disable fork;
end join
end
endtask
initial begin
_tck_internal = 1'b1;
forever begin
wait(is_active === 1'b1);
fork : isolation_fork begin
fork
wait(is_active !== 1'b1);
_drive_active();
join_any
disable fork;
end join
end
end
endinterface
@@ -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);
}
+268 -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)
@@ -2350,6 +2480,22 @@ const RTL_FIXTURES: &[&str] = &[
"package p;\n typedef struct packed {\n logic [3:0] hi;\n logic [3:0] lo;\n } word_t;\n typedef enum logic [1:0] {A = 2'd0, B, C} st_e;\nendpackage\n",
"module m;\n sub #(.W(8)) u0 (.clk(clk), .d(d[3:0]), .q());\nendmodule\n",
"module m;\n assign y = cond ? a[3:0] : pkg::f(b).c;\nendmodule\n",
// A net delay on either side of the data type: the gap in front of the
// `#` is `NetDelay::before_hash` (TODO §43.2), and the fuzzer is what
// says the other gaps around it kept their owners.
"module m;\n wire #5 a;\n wire [7:0] #1 b = c;\nendmodule\n",
// A delay *list*: the `min:typ:max` spelling a net and a continuous
// assignment take, and the `(rise, fall)` spelling only a gate takes
// (TODO §45.4). The gaps around the `(`, the two `:` and the `,` had no
// 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]
@@ -2357,8 +2503,24 @@ fn a_comment_in_every_rtl_gap_still_formats() {
assert_no_failing_gaps("RTL", RTL_FIXTURES, EXPECTED_RTL_GAPS);
}
/// Inter-token gaps across [`RTL_FIXTURES`].
const EXPECTED_RTL_GAPS: usize = 352;
/// Inter-token gaps across [`RTL_FIXTURES`]. 374 before TODO §45.4 added the
/// 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`
@@ -2888,3 +3050,106 @@ fn a_structured_assertion_may_be_relaid_out() {
assert!(out.contains("lbl: assert property (@(posedge clk) disable iff (rst)"), "{out}");
assert_eq!(format_source(&out, &Config::default()).expect("and is a fixed point"), out);
}
// ----------------------------------------------------------------------
// The delay list's new comment slots — `docs/features/small-items-4/README.md`
//
// `verify.rs` was not touched and no normalization was widened; these are the
// standing attack pairs CLAUDE.md invariant 4 asks for anyway, one per token
// a slot added by TODO §45.4 is defined *between*. Each moves the comment
// across exactly that token, and each must be refused.
// ----------------------------------------------------------------------
#[test]
fn a_delay_comment_moved_across_a_min_typ_max_colon_is_rejected() {
expect_divergence(
"module m;\n wire #(1 /*c*/ : 2 : 3) w;\nendmodule\n",
"module m;\n wire #(1 : /*c*/ 2 : 3) w;\nendmodule\n",
);
expect_divergence(
"module m;\n wire #(1 : 2 /*c*/ : 3) w;\nendmodule\n",
"module m;\n wire #(1 : 2 : /*c*/ 3) w;\nendmodule\n",
);
}
#[test]
fn a_delay_comment_moved_across_the_lists_brackets_is_rejected() {
// The `(` of a one-value delay, whose slots are its `ExprKind::Paren`'s.
expect_divergence(
"module m;\n wire # /*c*/ (1:2:3) w;\nendmodule\n",
"module m;\n wire #( /*c*/ 1:2:3) w;\nendmodule\n",
);
// And the `)`.
expect_divergence(
"module m;\n wire #(1:2:3 /*c*/ ) w;\nendmodule\n",
"module m;\n wire #(1:2:3) /*c*/ w;\nendmodule\n",
);
}
#[test]
fn a_gate_delay_comment_moved_across_the_hash_or_a_comma_is_rejected() {
expect_divergence(
"module m;\n and /*c*/ #(2, 3) g (y, a);\nendmodule\n",
"module m;\n and # /*c*/ (2, 3) g (y, a);\nendmodule\n",
);
expect_divergence(
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
"module m;\n and #(2, /*c*/ 3) g (y, a);\nendmodule\n",
);
// The gate instance's own two new slots: before its `(` and before the `;`.
expect_divergence(
"module m;\n and #(2, 3) g /*c*/ (y, a);\nendmodule\n",
"module m;\n and #(2, 3) g ( /*c*/ y, a);\nendmodule\n",
);
expect_divergence(
"module m;\n and #(2, 3) g (y, a) /*c*/ ;\nendmodule\n",
"module m;\n and #(2, 3) g (y, a); /*c*/\nendmodule\n",
);
}
#[test]
fn a_continuous_assignments_delay_comment_moved_across_it_is_rejected() {
expect_divergence(
"module m;\n assign # /*c*/ (5) y = a;\nendmodule\n",
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
);
expect_divergence(
"module m;\n assign #(5) /*c*/ y = a;\nendmodule\n",
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
);
}
#[test]
fn a_dropped_delay_list_comment_is_rejected() {
expect_divergence(
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
"module m;\n and #(2, 3) g (y, a);\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// The inline aggregate as a parameter-override argument — TODO §45.3
//
// A construct the parser refused until this round is a construct the safety
// net had never been asked about. These say it is asked now.
// ----------------------------------------------------------------------
#[test]
fn a_dropped_member_of_an_inline_aggregate_override_is_rejected() {
expect_divergence(
"module m;\n sub #(.T(struct packed {logic a; logic b;})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
);
expect_divergence(
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
"module m;\n sub #(.T(enum logic [1:0] {A})) u ();\nendmodule\n",
);
}
#[test]
fn a_dropped_packed_keyword_in_an_override_argument_is_rejected() {
expect_divergence(
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct {logic a;})) u ();\nendmodule\n",
);
}
+6
View File
@@ -12,6 +12,12 @@ vlog_parser = { path = "../vlog_parser" }
# workspace crate that answers that, and it depends on `vlog_parser` alone, so
# this adds no external code — see docs/features/semantic-lints/README.md.
vlog_semantic = { path = "../vlog_semantic" }
# A waiver file's `--location` is matched exactly the way an `--exclude`
# pattern is, and that matcher is `lucisv_core::walk::is_excluded`. Depending
# on it rather than copying it is the only way the two can be *the same*
# semantics; `lucisv_core` itself has no dependencies at all, so this adds no
# external code and closes no loop — see docs/features/waiver-files/README.md.
lucisv_core = { path = "../lucisv_core" }
[dev-dependencies]
# Tests only: the .lint case harness asserts that a lint fix never produces
+115 -1
View File
@@ -7,14 +7,22 @@ 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;
/// The default tab stop used when a fix expands a tab, matching lucisv's
/// default indent. `LintContext::with_tab_width` follows `--indent`.
const DEFAULT_TAB_WIDTH: usize = 2;
/// The width `line-length` holds a file to when nothing says otherwise —
/// `vlog_formatter::Config`'s own default, because the two are the same
/// number: a formatted file that the linter then calls too wide would be
/// lucisv disagreeing with itself. `LintContext::with_line_length` follows
/// `--line-length` and `lucisv.toml`.
const DEFAULT_LINE_LENGTH: usize = 100;
/// One text, parsed once: the products a lint run reads.
///
/// This is the owned half of "one parse, two tools" (TODO §4): a caller with
@@ -150,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.
@@ -201,6 +237,10 @@ pub struct LintContext<'a> {
backing: Backing<'a>,
path: Option<PathBuf>,
tab_width: usize,
line_length: usize,
/// What the run configured about each rule, or `None` for a run that
/// configured nothing — which reads exactly as the specs' own defaults.
options: Option<&'a RuleOptions>,
/// Byte ranges of string literals, ascending — the one place text rules
/// must not rewrite, because there whitespace is data.
strings: Vec<TextRange>,
@@ -254,6 +294,8 @@ impl<'a> LintContext<'a> {
backing,
path,
tab_width: DEFAULT_TAB_WIDTH,
line_length: DEFAULT_LINE_LENGTH,
options: None,
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
@@ -271,6 +313,68 @@ impl<'a> LintContext<'a> {
self
}
/// Sets the width the run's formatter would wrap to, which is what
/// `line-length` holds the file to unless that rule's own `length` option
/// says otherwise.
pub fn with_line_length(mut self, line_length: usize) -> LintContext<'a> {
self.line_length = line_length.max(1);
self
}
/// Lends the per-rule options the run resolved. A context without them
/// reads every option at its declared default, which is the shipped
/// behaviour.
pub fn with_options(mut self, options: &'a RuleOptions) -> LintContext<'a> {
self.options = Some(options);
self
}
/// The width the run's formatter wraps to. See
/// [`with_line_length`](LintContext::with_line_length).
pub fn line_length(&self) -> usize {
self.line_length
}
/// What the run configured, or the empty set.
pub fn options(&self) -> &RuleOptions {
match self.options {
Some(options) => options,
None => RuleOptions::none(),
}
}
/// One boolean option of `rule`, or its declared default.
pub fn option_bool(&self, rule: &str, key: &str) -> bool {
self.options().bool(rule, key)
}
/// One integer option of `rule`, or its declared default.
pub fn option_int(&self, rule: &str, key: &str) -> i64 {
self.options().int(rule, key)
}
/// One string (or pattern) option of `rule`, or its declared default.
pub fn option_str(&self, rule: &str, key: &str) -> &str {
self.options().str(rule, key)
}
/// One list option of `rule`, or its declared default.
pub fn option_list(&self, rule: &str, key: &str) -> Vec<String> {
self.options().list(rule, key)
}
/// Whether the run said anything about this option at all — the question
/// a rule asks when its fallback is not its spec's default.
pub fn option_is_set(&self, rule: &str, key: &str) -> bool {
self.options().is_set(rule, key)
}
/// One pattern option of `rule`, compiled, or `None` if it does not
/// compile — which cannot happen for a value this run accepted.
pub(crate) fn option_pattern(&self, rule: &str, key: &str) -> Option<crate::regex::Regex> {
crate::options::pattern(self.options(), rule, key)
}
/// Lends the symbol table the caller already built for this exact text —
/// "one parse, two tools" extended to the analysis (the language server
/// analyzes every buffer anyway, so its lint pass must not analyze twice).
@@ -308,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()
+110 -8
View File
@@ -9,9 +9,10 @@
//! becoming "everything a rule might want to walk".
use vlog_parser::ast::{
DataType, Dim, EnumType, FunctionDecl, ItemKind, SourceFile, StmtKind, StructType, TaskDecl,
TfArg, TypeExtra, TypedefKind,
DataType, Dim, EnumType, FunctionDecl, ItemKind, ListElem, SourceFile, StmtKind, StructType,
TaskDecl, TfArg, TypeExtra, TypedefKind,
};
use vlog_parser::span::TextRange;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
@@ -34,7 +35,7 @@ pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
for port in ports.iter().filter_map(ListElem::ok) {
visit(&port.ty);
}
}
@@ -77,7 +78,7 @@ fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
for port in ports.iter().filter_map(ListElem::ok) {
unpacked(&port.unpacked);
}
}
@@ -105,8 +106,8 @@ fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut
}
}
fn arg_dims(args: &[TfArg], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args {
fn arg_dims(args: &[ListElem<TfArg>], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args.iter().filter_map(ListElem::ok) {
unpacked(&arg.unpacked);
}
}
@@ -124,13 +125,13 @@ fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
if let Some(ret) = &decl.ret {
visit(ret);
}
for arg in &decl.args {
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
for arg in &decl.args {
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
@@ -147,6 +148,107 @@ fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
}
}
/// A type written in a declaration, with the name that declaration gives.
///
/// What the two `typedef-*` rules need and `walk_data_types` cannot say: a
/// `DataType` carries no span of its own, so a rule that judges the *type* of
/// a declaration reports at the name — and needs to know whether that
/// declaration is nested inside another aggregate's body.
pub(crate) struct DeclaredType<'a> {
/// The type as written.
pub(crate) ty: &'a DataType,
/// The name declared with it.
pub(crate) name: &'a str,
/// Byte range of that name — where a finding points.
pub(crate) span: TextRange,
/// True when this declaration is a member of another `struct`/`union`.
pub(crate) nested: bool,
}
/// Calls `f` on every type written in a **declaration** — a data or port
/// declaration, an ANSI port, a variable declaration in a statement — and on
/// every member of an aggregate written inside one.
///
/// A `typedef`'s own base type is deliberately not visited: a named type is
/// exactly what the `typedef-*` rules ask for, so passing it to them would be
/// asking them to flag the shape they exist to encourage. Its members are
/// visited, as nested declarations.
pub(crate) fn walk_declared_types(file: &SourceFile, f: &mut dyn FnMut(&DeclaredType)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports.iter().filter_map(ListElem::ok) {
declared(&port.ty, &port.name, port.name_span, false, f);
}
}
}
ItemKind::DataDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
ItemKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
// Only the members: the typedef itself is the named type these rules
// want, and the naming rules judge its name.
ItemKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
}
/// One declaration, and whatever aggregate its type carries.
fn declared(
ty: &DataType,
name: &str,
span: TextRange,
nested: bool,
f: &mut dyn FnMut(&DeclaredType),
) {
f(&DeclaredType { ty, name, span, nested });
members_of(ty, f);
}
/// One declaration's type, once per name it declares.
fn declarator_types(
ty: &DataType,
declarators: &[vlog_parser::ast::Declarator],
f: &mut dyn FnMut(&DeclaredType),
) {
for declarator in declarators {
declared(ty, &declarator.name, declarator.name_span, false, f);
}
}
/// The members of an anonymous aggregate, and of the aggregates inside it.
fn members_of(ty: &DataType, f: &mut dyn FnMut(&DeclaredType)) {
if let Some(TypeExtra::Struct(structure)) = ty.inline() {
struct_members(structure, f);
}
}
/// The members of a `struct`/`union` body, each as a nested declaration.
fn struct_members(structure: &StructType, f: &mut dyn FnMut(&DeclaredType)) {
for member in &structure.members {
for declarator in &member.declarators {
f(&DeclaredType {
ty: &member.ty,
name: &declarator.name,
span: declarator.name_span,
nested: true,
});
}
members_of(&member.ty, f);
}
}
/// A typedef's members — everything inside its body, but not the body itself.
fn typedef_members(kind: &TypedefKind, f: &mut dyn FnMut(&DeclaredType)) {
if let TypedefKind::Struct(structure) = kind {
struct_members(structure, f);
}
}
/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an
/// anonymous `struct`'s members are types written inside this one.
fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) {
+315
View File
@@ -0,0 +1,315 @@
//! Every expression written in a file.
//!
//! `visit` walks the item and statement spines and `decls` the types and
//! dimensions; neither reaches *into* an expression, and a rule that judges
//! the shape of one (`suggest-parentheses`) needs every node of every tree,
//! wherever it was written. Collecting them lives here so each of the three
//! files stays one sentence long.
use vlog_parser::ast::{
Connections, Expr, ExprKind, ForStep, Instantiation, ItemKind, ListElem, SourceFile, StmtKind,
TimingControl,
};
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
/// Calls `f` on every expression of the file, sub-expressions included.
///
/// The **roots** are the places an expression is written: a continuous or
/// procedural assignment, a declaration's initialiser, a condition, a call
/// argument, an instantiation's connections, a generate header, an expression
/// statement. Sub-expressions are then reached through every composite
/// [`ExprKind`], so a node buried in a concatenation inside a call argument is
/// visited like any other.
pub(crate) fn walk_exprs(file: &SourceFile, f: &mut dyn FnMut(&Expr)) {
let mut root = |expr: &Expr| descend(expr, f);
walk_param_ports(file, &mut |port| {
if let Some(default) = &port.default {
root(default);
}
});
walk_items(file, &mut |item| match &item.kind {
ItemKind::ContAssign(assign) => {
if let Some(delay) = &assign.delay {
root(delay);
}
for pair in &assign.assigns {
root(&pair.lhs);
root(&pair.rhs);
}
}
ItemKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root),
ItemKind::DataDecl(decl) => initialisers(&decl.declarators, &mut root),
ItemKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root),
ItemKind::ElabTask(expr) => root(expr),
ItemKind::Instantiation(inst) => connections(inst, &mut root),
ItemKind::Bind(bind) => connections(&bind.inst, &mut root),
ItemKind::GenIf(gen_if) => root(&gen_if.cond),
ItemKind::GenFor(gen_for) => {
root(&gen_for.init.lhs);
root(&gen_for.init.rhs);
root(&gen_for.cond);
match &gen_for.step {
ForStep::Assign(assign) => {
root(&assign.lhs);
root(&assign.rhs);
}
ForStep::Expr(expr) => root(expr),
}
}
ItemKind::GenCase(gen_case) => {
root(&gen_case.expr);
for case_item in &gen_case.items {
for label in &case_item.labels {
root(&label.expr);
}
}
}
ItemKind::Defparam(pairs) => {
for (target, value) in pairs {
root(target);
root(value);
}
}
ItemKind::Alias(terms) => {
for term in terms {
root(term);
}
}
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::Assign { lhs, rhs, timing, .. } => {
root(lhs);
root(rhs);
if let Some(TimingControl::Delay { expr, .. }) = timing {
root(expr);
}
}
StmtKind::ExprStmt(expr) => root(expr),
StmtKind::EventTrigger(t) => root(&t.expr),
StmtKind::If { cond, .. } => root(cond),
StmtKind::Case { expr, items, .. } => {
root(expr);
for case_item in items {
for label in &case_item.labels {
root(&label.expr);
}
}
}
StmtKind::RandCase { items, .. } => {
for case_item in items {
for label in &case_item.labels {
root(&label.expr);
}
}
}
StmtKind::For { init, cond, step, .. } => {
for one in init {
root(&one.assign.lhs);
root(&one.assign.rhs);
}
if let Some(cond) = cond {
root(cond);
}
for one in step {
match one {
ForStep::Assign(assign) => {
root(&assign.lhs);
root(&assign.rhs);
}
ForStep::Expr(expr) => root(expr),
}
}
}
StmtKind::While { cond, .. } | StmtKind::DoWhile { cond, .. } => root(cond),
StmtKind::Repeat { count, .. } => root(count),
StmtKind::Foreach { target, .. } => root(target),
StmtKind::Wait { cond, .. } => root(cond),
// A sensitivity list holds edge terms, not values; only the `#delay`
// spelling carries an expression a rule would judge.
StmtKind::Timing { control: TimingControl::Delay { expr, .. }, .. } => root(expr),
StmtKind::ForceRelease { lhs, rhs, .. } => {
root(lhs);
if let Some(rhs) = rhs {
root(rhs);
}
}
StmtKind::Return { expr: Some(expr), .. } => root(expr),
StmtKind::VarDecl(decl) => initialisers(&decl.declarators, &mut root),
StmtKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root),
StmtKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root),
_ => {}
});
}
fn initialisers(declarators: &[vlog_parser::ast::Declarator], root: &mut dyn FnMut(&Expr)) {
for declarator in declarators {
if let Some(init) = &declarator.init {
root(init);
}
}
}
fn connections(inst: &Instantiation, root: &mut dyn FnMut(&Expr)) {
if let Some(params) = &inst.params {
for conn in params.iter().filter_map(ListElem::ok) {
if let Some(expr) = &conn.expr {
root(expr);
}
}
}
for instance in &inst.instances {
match &instance.conns {
Connections::Named(conns) => {
for conn in conns.iter().filter_map(ListElem::ok) {
if let Some(expr) = &conn.expr {
root(expr);
}
}
}
Connections::Ordered(conns) => {
for conn in conns.iter().filter_map(ListElem::ok) {
if let Some(expr) = &conn.expr {
root(expr);
}
}
}
}
}
}
/// One expression and everything inside it.
fn descend(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
f(expr);
match &expr.kind {
ExprKind::Unary { expr: inner, .. }
| ExprKind::Postfix { expr: inner, .. }
| ExprKind::New(inner)
| ExprKind::Paren { inner, .. } => descend(inner, f),
ExprKind::Binary { lhs, rhs, .. } => {
descend(lhs, f);
descend(rhs, f);
}
ExprKind::Ternary { cond, then, els, .. } => {
descend(cond, f);
descend(then, f);
descend(els, f);
}
ExprKind::Call { callee, args, .. } => {
descend(callee, f);
for arg in args {
descend(&arg.expr, f);
}
}
ExprKind::Index { base, index, .. } => {
descend(base, f);
descend(index, f);
}
ExprKind::Range { base, msb, lsb, .. } => {
descend(base, f);
descend(msb, f);
descend(lsb, f);
}
ExprKind::Member { base, .. }
| ExprKind::Scope { base, .. }
| ExprKind::Parameterized { base, .. } => descend(base, f),
ExprKind::Concat(items) => {
for item in items {
descend(&item.expr, f);
}
}
ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => {
descend(count, f);
for item in inner {
descend(&item.expr, f);
}
}
ExprKind::Stream { slice, inner, .. } => {
if let Some(slice) = slice {
descend(slice, f);
}
for item in inner {
descend(&item.expr, f);
}
}
ExprKind::Cast { ty, expr: inner, .. } => {
descend(ty, f);
descend(inner, f);
}
ExprKind::Inside { lhs, ranges, .. } => {
descend(lhs, f);
for item in ranges {
descend(&item.expr, f);
}
}
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) => {
for item in items {
if let Some(key) = &item.key {
descend(key, f);
}
descend(&item.value, f);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn ternaries(src: &str) -> usize {
let (file, _) = parse_source_tolerant(src);
let mut n = 0;
walk_exprs(&file, &mut |expr| {
if matches!(expr.kind, ExprKind::Ternary { .. }) {
n += 1;
}
});
n
}
#[test]
fn reaches_an_expression_written_anywhere() {
let src = "module m #(parameter int P = a ? 1 : 2) (\n\
input logic i\n\
);\n\
logic v = b ? 1 : 2;\n\
assign w = c ? 1 : 2;\n\
sub u (.p(d ? 1 : 2));\n\
if (e ? 1 : 2) begin : g\n wire x;\n end\n\
initial begin\n\
if (f ? 1 : 2) y = g_ ? 1 : 2;\n\
z = {h ? 1 : 2, call(i ? 1 : 2)};\n\
end\n\
endmodule\n";
assert_eq!(ternaries(src), 9);
}
#[test]
fn a_nested_expression_is_reached_through_every_composite() {
assert_eq!(ternaries("module m;\n assign x = ~(a ? 1 : 2);\nendmodule\n"), 1);
assert_eq!(ternaries("module m;\n assign x = y[a ? 1 : 2];\nendmodule\n"), 1);
assert_eq!(ternaries("module m;\n assign x = int'(a ? 1 : 2);\nendmodule\n"), 1);
assert_eq!(ternaries("module m;\n assign x = {2{a ? 1 : 2}};\nendmodule\n"), 1);
}
#[test]
fn a_file_with_no_expressions_visits_nothing() {
assert_eq!(ternaries("module m;\nendmodule\n"), 0);
}
}
+313 -5
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 vlog_parser::ast::{ItemKind, Module, ParamPort, PortList, SourceFile};
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.
@@ -49,8 +160,12 @@ fn interface_of(module: &Module) -> Option<ModuleInterface> {
/// to it by name.
fn ports_of(module: &Module) -> Vec<String> {
match &module.ports {
PortList::Ansi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::NonAnsi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::Ansi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::NonAnsi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::None | PortList::Empty => Vec::new(),
}
}
@@ -67,7 +182,7 @@ fn ports_of(module: &Module) -> Vec<String> {
fn parameters_of(module: &Module) -> Vec<String> {
let mut out = Vec::new();
let mut overridable = true;
for port in module.param_ports.iter().flatten() {
for port in module.param_ports.iter().flatten().filter_map(ListElem::ok) {
overridable = is_parameter(port, overridable);
if overridable {
out.push(port.name.clone());
@@ -176,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()]))]);
}
}
+60 -6
View File
@@ -22,9 +22,14 @@
mod context;
mod decls;
mod exprs;
mod interfaces;
mod literal;
mod module_decls;
mod naming;
mod options;
mod preproc;
mod regex;
mod registry;
mod rule_docs;
mod rules;
@@ -34,11 +39,13 @@ mod violation;
mod visit;
mod vscode;
mod waiver;
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,
};
@@ -50,8 +57,12 @@ 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};
use waiver::Waivers;
@@ -68,14 +79,32 @@ pub fn run(source: &str, path: Option<PathBuf>, enabled: &[&'static dyn Rule]) -
/// The result is sorted by position, then by rule name, so two runs over the
/// same file print in the same order whatever order the registry has.
pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation> {
lint_with(ctx, enabled, &ExternalWaivers::default()).0
}
/// [`lint`] with the run's external waiver files applied too, reporting which
/// of their directives fired.
///
/// **Precedence is union**: a violation is dropped when an inline waiver *or*
/// an external one covers it, and one both cover marks both used, so neither
/// is then reported as dead. The usage half is the caller's to keep — only a
/// whole run knows whether a `--location` matched some file somewhere, which
/// is why `lucisv check` reports unused external waivers and the server does
/// not. See `docs/features/waiver-files/README.md`.
pub fn lint_with(
ctx: &LintContext,
enabled: &[&'static dyn Rule],
external: &ExternalWaivers,
) -> (Vec<Violation>, WaiverUse) {
let names: Vec<&'static str> = enabled.iter().map(|rule| rule.name()).collect();
let mut waivers = Waivers::collect(ctx);
let mut used = WaiverUse::default();
let mut found = Vec::new();
for rule in enabled {
found.extend(rule.check(ctx));
}
let mut kept = waivers.filter(ctx, found);
let mut kept = waive(ctx, &mut waivers, external, &mut used, found);
if names.contains(&UNUSED_WAIVER) {
// `unused-waiver` findings are themselves waivable, which is circular:
@@ -86,7 +115,7 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
loop {
let before = waivers.used_count();
let unused = waivers.unused(&names);
let surviving = waivers.filter(ctx, unused);
let surviving = waive(ctx, &mut waivers, external, &mut used, unused);
if waivers.used_count() == before {
kept.extend(surviving);
break;
@@ -98,7 +127,31 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
});
stamp_severities(&mut kept);
kept
(kept, used)
}
/// The violations neither an inline waiver nor an external one covers.
///
/// Both are always asked — never `||` short-circuited — because a violation
/// two waivers cover has to mark both of them used.
fn waive(
ctx: &LintContext,
inline: &mut Waivers,
external: &ExternalWaivers,
used: &mut WaiverUse,
violations: Vec<Violation>,
) -> Vec<Violation> {
let path = ctx.path();
violations
.into_iter()
.filter(|violation| {
let (line, _) = ctx.line_index().line_col(violation.span.start);
let inline_waived = inline.covers(violation.rule, line);
let external_waived =
!external.is_empty() && external.covers(path, violation.rule, line, used);
!(inline_waived || external_waived)
})
.collect()
}
/// Gives every finding the class its rule declares.
@@ -197,11 +250,12 @@ mod tests {
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
// has not implemented are that codebase's, not typos, so they are
// neither honored nor reported.
let src = "module m;\n // verilog_lint: waive macro-name-style\n wire a;\nendmodule\n";
let src = "module m;\n // verilog_lint: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
assert!(lint_all(src).is_empty());
// lucisv's own spelling gets no such benefit of the doubt.
let src = "module m;\n // lucisv: waive macro-name-style\n wire a;\nendmodule\n";
let src =
"module m;\n // lucisv: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
}
+234
View File
@@ -0,0 +1,234 @@
//! The nets, variables and ports a module declares — what the two signal
//! naming rules judge.
//!
//! A module's own declarations are a different population from "every
//! declared name in the file": a class property, a loop variable and a
//! function local are not signals, and a rule that judged them would be
//! reporting on things the style guide says nothing about. Collecting them
//! lives here rather than in `visit` (the item and statement spines) or
//! `decls` (types and dimensions), so each of the three files stays one
//! sentence long.
use vlog_parser::ast::{
AnsiPort, GenBlock, GenElse, Item, ItemKind, ListElem, PortList, SourceFile,
};
use vlog_parser::span::TextRange;
/// One net, variable or port a module declares.
pub(crate) struct SignalDecl {
/// The declared name, as written.
pub(crate) name: String,
/// Byte range of that name.
pub(crate) span: TextRange,
/// The word a diagnostic calls it: `port` or `signal`.
pub(crate) what: &'static str,
/// The direction of a port, as written (`input`, `output`, `inout`), or
/// `None` for a signal.
pub(crate) dir: Option<String>,
}
/// Every net, variable and port declared inside a module, interface or
/// program of `file`, header and body alike, generate blocks included.
///
/// A `class` body is deliberately not descended into: its properties are not
/// signals. A function or task body is not either — a local is scoped to the
/// subroutine and named for it.
pub(crate) fn module_signals(file: &SourceFile) -> Vec<SignalDecl> {
let mut out = Vec::new();
for item in &file.items {
collect_item(item, &mut out);
}
out
}
fn collect_item(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::Module(module) => {
header_ports(&module.ports, out);
for inner in &module.items {
collect_body(inner, out);
}
}
// A module may be written inside a package; nothing else at file
// level holds one.
ItemKind::Package { items, .. } => {
for inner in items {
collect_item(inner, out);
}
}
_ => {}
}
}
/// One item of a module body.
fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::DataDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "signal",
dir: None,
});
}
}
ItemKind::PortDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "port",
dir: Some(decl.dir.clone()),
});
}
}
// A nested module is a module of its own.
ItemKind::Module(_) => collect_item(item, out),
ItemKind::GenerateRegion { items, .. } => {
for inner in items {
collect_body(inner, out);
}
}
ItemKind::GenBlock(b) => block(b, out),
ItemKind::GenIf(gen_if) => {
block(&gen_if.then, out);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
block(&nested.then, out);
els = nested.els.as_deref();
}
GenElse::Block(inner) => {
block(inner, out);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => block(&gen_for.body, out),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
block(&case_item.body, out);
}
}
_ => {}
}
}
fn block(block: &GenBlock, out: &mut Vec<SignalDecl>) {
for item in &block.items {
collect_body(item, out);
}
}
/// The ports of a module header, in either style.
fn header_ports(ports: &PortList, out: &mut Vec<SignalDecl>) {
match ports {
PortList::Ansi(ports) => {
// A port with no direction keyword continues the previous one, as
// the language says; a first port with none is `inout` by default.
let mut carried: Option<String> = None;
for port in ports.iter().filter_map(ListElem::ok) {
carried = direction(port).or(carried);
out.push(SignalDecl {
name: port.name.clone(),
span: port.name_span,
what: "port",
dir: carried.clone(),
});
}
}
// A non-ANSI header *names* its ports; the body declares them
// (`input clk;`), and that declaration is the one collected — so a
// rule reports each port once, where its direction is written.
PortList::NonAnsi(_) | PortList::None | PortList::Empty => {}
}
}
fn direction(port: &AnsiPort) -> Option<String> {
port.dir.clone()
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn signals(src: &str) -> Vec<(String, &'static str, Option<String>)> {
let (file, _) = parse_source_tolerant(src);
module_signals(&file).into_iter().map(|decl| (decl.name, decl.what, decl.dir)).collect()
}
#[test]
fn collects_header_ports_body_ports_and_signals() {
let src = "module m (input logic clk, output data);\n\
\x20 wire a;\n\
\x20 logic [7:0] b, c;\n\
endmodule\n";
assert_eq!(
signals(src),
vec![
("clk".to_string(), "port", Some("input".to_string())),
("data".to_string(), "port", Some("output".to_string())),
("a".to_string(), "signal", None),
("b".to_string(), "signal", None),
("c".to_string(), "signal", None),
]
);
}
#[test]
fn a_port_with_no_direction_continues_the_previous_one() {
let src = "module m (input logic a, b, output c);\nendmodule\n";
let dirs: Vec<Option<String>> = signals(src).into_iter().map(|s| s.2).collect();
assert_eq!(
dirs,
vec![Some("input".to_string()), Some("input".to_string()), Some("output".to_string())]
);
}
/// A non-ANSI port is declared once, in the body: the header only lists
/// the names, and collecting those too would report every such port
/// twice.
#[test]
fn a_non_ansi_port_is_collected_where_the_body_declares_it() {
let src = "module m (a, b);\n input a;\n output b;\nendmodule\n";
assert_eq!(
signals(src),
vec![
("a".to_string(), "port", Some("input".to_string())),
("b".to_string(), "port", Some("output".to_string())),
]
);
}
#[test]
fn generate_blocks_are_descended_into_and_class_bodies_are_not() {
let src = "module m;\n\
\x20 generate\n\
\x20 if (A) begin : g\n wire in_gen;\n end\n\
\x20 endgenerate\n\
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire looped;\n end\n\
endmodule\n\
class c;\n logic property_of_a_class;\nendclass\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["in_gen".to_string(), "looped".to_string()]);
}
#[test]
fn an_interface_and_a_module_in_a_package_are_covered() {
let src = "interface i (input clk);\n wire w;\nendinterface\n\
package p;\n module inner;\n wire deep;\n endmodule\nendpackage\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["clk".to_string(), "w".to_string(), "deep".to_string()]);
}
#[test]
fn a_function_local_is_not_a_signal() {
let src = "module m;\n function void f();\n logic local_var;\n endfunction\n\
endmodule\n";
assert!(signals(src).is_empty());
}
}
+106 -21
View File
@@ -1,13 +1,12 @@
//! The naming-style presets the naming rules check against.
//!
//! Verible spells its naming conventions as RE2 regular expressions. lucisv
//! spells the same conventions as character-class predicates instead, on
//! purpose: every preset anyone actually uses is "these character classes, in
//! this order", which is four small functions — and a regex engine is a
//! dependency this crate (today: `vlog_parser` + std) does not otherwise need.
//! The cost is that user-supplied patterns are not expressible; that waits on
//! the `lint` key in `lucisv.toml` and is recorded as such in
//! `docs/features/lint-rules-2/README.md`.
//! Verible spells its naming conventions as RE2 regular expressions, and
//! since §34 so does lucisv: `crate::regex` reads the subset a style guide is
//! written in, and each naming rule takes the pattern as an option whose
//! default is the preset it shipped with. What survives here are the two
//! `CamelCase`/`ALL_CAPS` predicates — Verible spells those as *words* in
//! `parameter_style`, not as patterns — and the three small helpers every
//! naming rule shares.
//!
//! An **escaped identifier** (`\my$name `) is exempt from every style: its
//! whole point is to carry characters no convention allows.
@@ -17,13 +16,6 @@ pub(crate) fn is_escaped(name: &str) -> bool {
name.starts_with('\\')
}
/// `lower_snake_case`: starts with a lowercase letter, then lowercase
/// letters, digits and underscores.
pub(crate) fn is_lower_snake_case(name: &str) -> bool {
starts_with(name, char::is_ascii_lowercase)
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// `UPPER_SNAKE_CASE`: starts with an uppercase letter, then uppercase
/// letters, digits and underscores. Verible calls this preset `ALL_CAPS`.
pub(crate) fn is_upper_snake_case(name: &str) -> bool {
@@ -37,6 +29,80 @@ pub(crate) fn is_camel_case(name: &str) -> bool {
starts_with(name, char::is_ascii_uppercase) && name.chars().all(|c| c.is_ascii_alphanumeric())
}
/// The vocabulary Verible's `*_style` options are written in, and the one
/// [`matches_style_words`] reads.
pub(crate) const STYLE_WORDS: [&str; 2] = ["CamelCase", "ALL_CAPS"];
/// Whether `name` fits any of the `|`-separated preset words of a `*_style`
/// option (`CamelCase|ALL_CAPS`). A word outside the vocabulary cannot reach
/// here — the option refuses it — so an unknown one simply matches nothing.
pub(crate) fn matches_style_words(name: &str, spelling: &str) -> bool {
spelling.split('|').map(str::trim).any(|word| match word {
"CamelCase" => is_camel_case(name),
"ALL_CAPS" => is_upper_snake_case(name),
_ => false,
})
}
/// Whether `name` is one this rule accepts, given a `*_style_regex` override
/// the run may have set and the `*_style` words otherwise.
///
/// The two-key shape is Verible's: the words are what a style guide says, and
/// the pattern is the escape hatch for a project whose convention is neither.
/// An override that does not compile cannot be set (the option is validated
/// when it is read), so a `None` pattern here means "nobody set one".
pub(crate) fn fits_style(
ctx: &crate::context::LintContext,
rule: &str,
style_key: &str,
regex_key: &str,
name: &str,
) -> bool {
if ctx.option_is_set(rule, regex_key) {
return match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
None => true,
};
}
matches_style_words(name, ctx.option_str(rule, style_key))
}
/// Whether `name` matches this rule's single pattern option — the shape the
/// three type-and-module naming rules take.
pub(crate) fn fits_pattern(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
name: &str,
) -> bool {
match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
// Unreachable for a validated option; being quiet is the safe
// direction for a rule that cannot tell what it was asked.
None => true,
}
}
/// What a naming rule says about a name it rejected.
///
/// A run that configured nothing reads the preset's own words — the sentence
/// the rule has always printed, so a default run's diagnostics are the ones
/// CI already has — and a run that set a pattern is told **which** pattern it
/// failed, because "is not lower_snake_case" would be a lie there.
pub(crate) fn style_message(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
subject: &str,
preset: &str,
) -> String {
if ctx.option_is_set(rule, regex_key) {
format!("{subject} does not match `{}`", ctx.option_str(rule, regex_key))
} else {
format!("{subject} {preset}")
}
}
/// True when `name` is non-empty and its first character passes `first`.
fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
name.chars().next().is_some_and(|c| first(&c))
@@ -46,13 +112,32 @@ fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
mod tests {
use super::*;
/// The `lower_snake_case` preset the three type-and-module naming rules
/// used before §34 gave them `style_regex` is now spelled as the pattern
/// `[a-z][a-z_0-9]*`, and the two accept exactly the same names — which
/// is what keeps those rules' findings byte-identical.
#[test]
fn lower_snake_case_accepts_what_rtl_writes() {
for name in ["a", "clk", "data_i", "fifo2_wr_en", "a1_b2"] {
assert!(is_lower_snake_case(name), "{name}");
}
for name in ["", "Clk", "_clk", "clkA", "clk-en", "CLK", "1clk"] {
assert!(!is_lower_snake_case(name), "{name}");
fn the_lower_snake_case_pattern_is_the_preset_it_replaced() {
let pattern = crate::regex::Regex::compile("[a-z][a-z_0-9]*").expect("compiles");
let preset = |name: &str| {
name.chars().next().is_some_and(|c| c.is_ascii_lowercase())
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
};
for name in [
"a",
"clk",
"data_i",
"fifo2_wr_en",
"a1_b2",
"",
"Clk",
"_clk",
"clkA",
"clk-en",
"CLK",
"1clk",
] {
assert_eq!(pattern.is_match(name), preset(name), "{name}");
}
}
Loaded 100 of 459 files, more files were not shown because too many files have changed in this diff. Show more