Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95f930cf20 | ||
|
|
311551f232 | ||
|
|
ff67281995 | ||
|
|
7ca2508ec7 | ||
|
|
91b7c2fd67 | ||
|
|
ce2f858e5e | ||
|
|
14fbdab717 | ||
|
|
f8401a0024 | ||
|
|
307a56e921 | ||
|
|
1e30ea0fb5 | ||
|
|
3f912e7fce | ||
|
|
f3b5a9d189 | ||
|
|
02b4204536 | ||
|
|
03a4958294 | ||
|
|
f27fa1c045 | ||
|
|
cadb4319e4 | ||
|
|
1cfbab4a56 | ||
|
|
a1fa402fd8 | ||
|
|
bc533c6cb1 | ||
|
|
5ad0772475 | ||
|
|
af3280c651 | ||
|
|
24b0dd9912 | ||
|
|
852d05d9ad | ||
|
|
98675c630a | ||
|
|
7f65a2449a | ||
|
|
3f300fa9e9 | ||
|
|
7881cc869c | ||
|
|
89186a8eaa | ||
|
|
27a652ee3d | ||
|
|
d3deacf0f6 | ||
|
|
17633d2214 | ||
|
|
e2c954ba77 | ||
|
|
e565dc0812 | ||
|
|
34b766cbef | ||
|
|
8cdc1b3375 | ||
|
|
651e58bfb3 | ||
|
|
37560cad5e | ||
|
|
e4407984cb | ||
|
|
40094c4c4e | ||
|
|
829302d0bf | ||
|
|
ee1efe3fb1 | ||
|
|
1029d2f199 | ||
|
|
36caf1dd19 | ||
|
|
61f345aca7 | ||
|
|
ad27ed23dc | ||
|
|
bf9170a850 | ||
|
|
b7a934080a | ||
|
|
172a034c67 | ||
|
|
20567e1a7f |
No files matched your search
@@ -5,3 +5,5 @@
|
||||
/.lucisv_cache
|
||||
/.score-results.tsv
|
||||
.DS_Store
|
||||
/.zcode
|
||||
/.claude
|
||||
+391
@@ -4,6 +4,397 @@ 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.24.0 — 2026-09-01
|
||||
|
||||
Interface semantics — interfaces, modports and clocking blocks become
|
||||
symbols, and `vif.sig` crosses files.
|
||||
|
||||
An interface was indexed as a `Module` (its hover card said "module"),
|
||||
modports and clocking blocks declared nothing, the signal names inside
|
||||
them were not references, and one export line kept an interface's
|
||||
signals out of the workspace's member table — so `virtual my_if vif;
|
||||
vif.sig` resolved only when the interface was in the same file. Now:
|
||||
`SymbolKind::{Interface, Modport, Clocking}`; an interface exports its
|
||||
signals (they are its surface — a module still exports ports and
|
||||
parameters only); every name inside a modport or clocking block is a
|
||||
reference to the interface's signal, method or block; the modport half
|
||||
of `bus_if.mp` in a port type or a `virtual bus_if.mp` handle resolves
|
||||
to the modport; a clocking block carries its enclosing interface as its
|
||||
type, so `vif.cb.data` reaches `data`'s declaration through the member
|
||||
chase unchanged. `FACTS_FORMAT` 7 → 8 (older stores rebuild once).
|
||||
Interfaces stay in the completion/ghost module table, the design
|
||||
hierarchy and the port refactorings — pinned unchanged — while hover,
|
||||
outline and completion kinds become honest.
|
||||
|
||||
Unresolved names on the 860-file corpus fell 1 256 → 1 203, the first
|
||||
movement in three rounds — the `@(cb)` and `cb.data` names that had
|
||||
nothing to bind. Store +1.2 %. Renaming a modport from its
|
||||
type-position use now rewrites its declaration and every use. QA: 17
|
||||
live opentitan probes, zero wrong answers, every hover sub-millisecond.
|
||||
|
||||
## 0.23.0 — 2026-09-01
|
||||
|
||||
Member chains and instance heads — DV class-semantics round 2.
|
||||
|
||||
`cfg.vif.clk`, `item.hdr.addr`, `u_sub.port`, `tb.dut.u_core.done_o`:
|
||||
the tail of a chain now resolves link by link through each link's
|
||||
declared type. In one file the resolver hops declared type → declared
|
||||
type; across files a chain becomes one composed path (`item_t::hdr::addr`)
|
||||
the workspace's member table walks, so hover, find-references and rename
|
||||
agree by construction. `Def::type_name` rides every indexed declaration
|
||||
(`FACTS_FORMAT` 6 → 7; older stores rebuild once), and `this.x`/`super.x`
|
||||
uses now post to the index, so references from a base class's
|
||||
declaration list its subclasses' uses in other files.
|
||||
|
||||
Instance heads: an instance's type is its module, and modules export
|
||||
their ports and parameters — so `u_sub.port` resolves cross-file;
|
||||
internal nets and vars resolve in the declaring file only, by ruling:
|
||||
exporting them cost +24 % store and made `.port(w)` connections resolve
|
||||
to internals. Typedef'd class aliases (`typedef c1 my_t; my_t h; h.x`)
|
||||
are chased, visited-guarded. A chain link whose type is declared twice
|
||||
in the workspace with different kinds is refused — round 1's lesson,
|
||||
one hop out. No link ever guesses.
|
||||
|
||||
Rename's truth moved with it: renaming `sub`'s `wire sig` now rewrites
|
||||
`u_sub.sig` too, which a compiler needs; an unresolvable tail is left
|
||||
alone (and, a known gap filed as topo §2.9-20, no longer warned about).
|
||||
|
||||
Corpus: unresolved unchanged at 1 256; store +15.4 % (opentitan
|
||||
30.8 → 35.4 MB), most of it the inherited-member postings. Zero wrong
|
||||
answers in QA's 15 live opentitan probes. Formatter output unchanged.
|
||||
|
||||
## 0.22.0 — 2026-09-01
|
||||
|
||||
Class member access — the first DV class-semantics round.
|
||||
|
||||
`task class2::update(c1 in_item); address = in_item.user_id; …` —
|
||||
hovering `user_id` used to show nothing. Now the tail of `handle.member`
|
||||
resolves through the handle's declared type: a new `Symbol::type_name`
|
||||
records the type as written; the member is found in that class's scope,
|
||||
else up its `extends` chain in the file, else through the workspace's
|
||||
member table, which chases `WorkspaceIndex::base_of` — a subclass→base
|
||||
map built from the inheritance census the index already keeps —
|
||||
cycle-guarded on both sides. Hover shows `rand bit user_id;` with its
|
||||
file and line; go-to-definition, find-references (from either end) and
|
||||
rename follow. `this.x`/`super.x` misses resolve to inherited members
|
||||
through the same chase (the open handshake since the classes wave), and
|
||||
an out-of-class method body sees its class's members. `FACTS_FORMAT`
|
||||
5 → 6 (the reference census grew; older stores are discarded).
|
||||
|
||||
Honest by construction: a head whose type is declared in the file as
|
||||
anything without a member scope — a struct typedef, an alias, an enum —
|
||||
records nothing rather than reaching the workspace, after QA caught the
|
||||
first cut answering `bus_t s; s.field` from an unrelated class named
|
||||
`bus_t` elsewhere. Module-instance heads, chains `a.b.c`, struct fields
|
||||
and typedef'd class aliases are round 2.
|
||||
|
||||
Cost: hover 7–143 µs; on opentitan a `tl_seq_item` member resolves in
|
||||
0.12 ms cold / 0.01 ms warm; store +2.85 %. Formatter output unchanged.
|
||||
|
||||
## 0.21.0 — 2026-09-01
|
||||
|
||||
Null items: `endgenerate;` parses — and everywhere else a stray `;` may
|
||||
legally stand.
|
||||
|
||||
The report was "for loop inside generate fails"; the diagnosis was that
|
||||
every generate-for spelling — and three published examples — already
|
||||
parsed, and the failing token was the lone `;` after `endgenerate`.
|
||||
IEEE 1800-2017 A.1.4 makes that a *null item*, legal in module,
|
||||
generate, package, interface, program and class scope and at file
|
||||
scope; lucisv rejected it in all of them with `expected item`. Now
|
||||
`ItemKind::Empty`, accepted by one parser branch, laid out where it
|
||||
was written (glued to the previous line for `endgenerate;` / `end;` /
|
||||
`endmodule;` / `;;`, or on its own line), token-preserving and
|
||||
idempotent both ways. `verify.rs` untouched; eight masked-corruption
|
||||
attack pairs (a dropped `;`, one moved across a comment, into a
|
||||
procedural block, between `` `ifdef `` arms) all rejected.
|
||||
|
||||
New lint **`empty-item`** (slang's `-Wempty-member`): warns on a null
|
||||
item; its safe fix deletes the `;` — and the line, when nothing else
|
||||
stood on it — with a deletion range that structurally cannot swallow a
|
||||
comment. In the editor, a file that used to show a parse error now
|
||||
shows a warning with a quick fix and *fix all*.
|
||||
|
||||
Formatter output changes only for files that contain a null item;
|
||||
the 820-file corpus is byte-identical (813/820) and the opentitan
|
||||
sweep is unchanged file-for-file. Version bumped per the format-cache
|
||||
rule.
|
||||
|
||||
## 0.20.0 — 2026-08-30
|
||||
|
||||
Fuzzy completion: `clkenq` reaches `clk_osc_en_q`.
|
||||
|
||||
Identifier completion now matches by **subsequence** — the typed
|
||||
letters present in the name, in order — at three or more typed
|
||||
characters, and by prefix below that: VS Code's own rule, ruled by the
|
||||
owner. The scope-visible, project-declaration and project-word tiers
|
||||
go fuzzy; modules (substring), keywords, templates and `` `define ``
|
||||
names keep their own semantics, and the instantiation ghost's
|
||||
exact-match trigger deliberately stays exact.
|
||||
|
||||
Ranking is prefix-first, then a boundary-aware score: letters landing
|
||||
at the starts of name parts (`c`·`l`·`k` at `clk_…`'s components)
|
||||
outrank accidental scatter, contiguous runs outrank gaps, and the
|
||||
order is deterministic. The scan is affordable because every table
|
||||
entry carries a 32-bit character mask — a `clkenq` keystroke rejects
|
||||
99.6 % of opentitan's 100 022-word table with one AND each and costs
|
||||
+0.05 ms; the expensive class is three very common letters (`aes`,
|
||||
`ena`), measured at 1–4 ms server-side and accepted as imperceptible
|
||||
in a popup. 1–2-character responses are always `isIncomplete`, so the
|
||||
third keystroke — the one that turns fuzzy on — always reaches the
|
||||
server.
|
||||
|
||||
Formatter output unchanged; the bump is the completion behavior.
|
||||
|
||||
## 0.19.0 — 2026-08-30
|
||||
|
||||
Inline instantiation, round 2 — two rulings from first live use.
|
||||
|
||||
**The space is the commitment.** The ghost now appears only after
|
||||
`name<space>`: `aes` alone may still be growing into `aes_dft`, so the
|
||||
typed space is what says the name is finished. An exactly-typed name
|
||||
with the cursor at its end offers nothing; one space arms it; two
|
||||
spaces or a tab do not. The popup flow is accept the name, type the
|
||||
space you were going to type anyway, Tab the ghost.
|
||||
|
||||
**Every indexed module answers.** A module declared in more than one
|
||||
file used to get no ghost (`ast_dft` and `io_osc` are each declared
|
||||
under both `top_earlgrey` and `top_darjeeling` in opentitan — two
|
||||
whole IP blocks silenced). The server now picks the declaration
|
||||
nearest the file being edited: most shared leading path components,
|
||||
then the shallower copy, then the smallest path — deterministic, and
|
||||
the popup's detail names the file that will be read. The refusal
|
||||
residue is a named enum, and the QA sweep proves the ruling: **all
|
||||
1,131 opentitan module names ghost, zero declines** (199 of them
|
||||
multiply declared, one of them 61 ways), at 0.05–0.08 ms per
|
||||
non-matching keystroke and ~0.5 ms per ghost.
|
||||
|
||||
Formatter output unchanged; the bump is the trigger and chooser
|
||||
behavior.
|
||||
|
||||
## 0.18.0 — 2026-08-30
|
||||
|
||||
Inline instantiation: the popup names the module, the ghost writes the
|
||||
rest. Two levels, sized for a 4,000-file SoC.
|
||||
|
||||
### The two-level split
|
||||
|
||||
**Level 1 — the completion popup offers module names.** Tier 0 used to
|
||||
plan a full instantiation skeleton for up to 64 candidate modules on
|
||||
every keystroke — each one a definition-file read and a header parse.
|
||||
It is now a scan of the in-memory module table and nothing else: the
|
||||
item inserts the name, `Module` icon and declaring file beside it.
|
||||
|
||||
**Level 2 — the exact name grows a ghost.** The moment the identifier
|
||||
at the cursor exactly (case-sensitively) matches an indexed module, at
|
||||
a position where an instantiation is legal, with nothing after the
|
||||
cursor, `textDocument/inlineCompletion` offers the rest of the
|
||||
instantiation in grey: every parameter override, every port
|
||||
connection, each a snippet tabstop, ports matching an in-scope signal
|
||||
auto-connected. Tab writes it; the editor's own tab settings indent
|
||||
it. Works the same whether the name was typed by hand or accepted
|
||||
from the popup. Exactly one module is ever planned, through the
|
||||
guarded header-slice path and the file-view cache.
|
||||
|
||||
The per-keystroke probe is `Candidates::has_module` — a case-sensitive
|
||||
binary search whose sorted-table premise is pinned by test. Measured
|
||||
on opentitan (3,976 files): a keystroke that is not a module name
|
||||
costs 0.10–0.17 ms; the ghost for `aes` (14 parameters, 16 ports)
|
||||
0.6–1.1 ms; the 112-parameter `top_earlgrey` 2.5 ms cold.
|
||||
|
||||
New setting: `lucisv.inlineInstantiation` (default on), independent of
|
||||
`lucisv.inlineTemplates`.
|
||||
|
||||
Honest losses, written down: the popup's per-module documentation
|
||||
panel is gone (it cost a plan per item); a client without
|
||||
`inlineCompletion` support (Neovim's built-in LSP today) gets names
|
||||
but no skeleton — filed as `docs/topo.md` §2.9-19 for an
|
||||
execute-command spelling. A module declared in two files now appears
|
||||
in the popup by name (it used to vanish entirely); its ghost declines
|
||||
rather than guess which file.
|
||||
|
||||
Formatter output is unchanged; the bump is the two-level completion
|
||||
behavior itself. Also checked in: `docs/performance_take2.md`
|
||||
(referenced since 0.15.0, never staged — `performance.md`,
|
||||
`performance_take2.md`).
|
||||
|
||||
## 0.17.0 — 2026-08-29
|
||||
|
||||
The wave's second half: from 100 sweep failures to **11** on the
|
||||
3,943-file opentitan checkout — 99.7 % of the tree parses, formats and
|
||||
round-trips clean, and what remains is macro `` `include `` fragments
|
||||
(a preprocessing decision), vendor files that are not SystemVerilog
|
||||
(exclude patterns recommended in the analysis), and three written-up
|
||||
skips.
|
||||
|
||||
### The mop-up: nine small buckets
|
||||
|
||||
Block-scoped `typedef` statements, system-function casting types
|
||||
(`$bits(x)'(…)`), enum member ranges, casts over assignment patterns,
|
||||
gate delay lists, `virtual iface.modport` declarations, `rand` on
|
||||
struct members, `foreach` skipped dimensions, hierarchical `bind`
|
||||
instance paths — 45 files, seven of the nine buckets needing no new
|
||||
AST surface at all.
|
||||
|
||||
### The clocking wave: eight more, one round
|
||||
|
||||
Clocking signal bindings, `default disable iff` (half of what the
|
||||
analysis had called "clocking"), `iff` on event-control terms, indexed
|
||||
event names, gate drive strengths, `program` blocks, and macros as a
|
||||
concurrent assertion's action — where QA caught a real regression in
|
||||
four UVM-idiom shapes and the rework decides by the token after the
|
||||
macro, with the failure direction proven trunk-identical rather than
|
||||
assumed. The expression-chain limit rises 256 → 1024 on measured need
|
||||
(a generated pinmux file chains 567 links) with the parse stack
|
||||
resized to keep its safety margin, sabotage-proven.
|
||||
|
||||
**Formatter output moved in exactly one file-class** (code previously
|
||||
swallowed into an assertion's opaque bytes is now parsed and laid
|
||||
out), so this release bumps the version and warm format caches
|
||||
re-verify.
|
||||
|
||||
## 0.16.0 — 2026-08-29
|
||||
|
||||
The testbench-syntax release: the coverage gap named by
|
||||
`syntax_coverage.md` (a full sweep of a 3,943-file opentitan checkout),
|
||||
closed bucket by bucket. Sweep failures 151 → 100 across three
|
||||
lead-reviewed rounds.
|
||||
|
||||
### Out-of-class constraints parse
|
||||
|
||||
`constraint ClassName::name { ... }` at file or package scope — the
|
||||
single biggest bucket, 45 files — was a one-line grammar fix reusing
|
||||
the out-of-body method-name path. The real win is tolerant-mode: the
|
||||
cascade of bogus diagnostics these files produced in the editor
|
||||
(300+ per file, 1,349 across the bucket) collapses to at most one
|
||||
honest report.
|
||||
|
||||
### Directives may open inside a statement
|
||||
|
||||
An `` `ifdef `` splitting the right-hand side of an assign, an
|
||||
expression, or an instantiation head — the mirror image of every
|
||||
previous directive feature, which all recovered at a *closing*
|
||||
directive — is captured verbatim, with a head classifier that refuses
|
||||
what it cannot prove rather than guessing. Fixes chip_if.sv in both
|
||||
opentitan tops, both flagship tb.sv testbenches, and friends. Crafted
|
||||
corrupted-capture pairs are asserted rejected by the safety net.
|
||||
|
||||
### Three formatter comment bugs, fixed where they lived
|
||||
|
||||
A line comment trailing `end` no longer swallows a cuddled `else`; a
|
||||
comment inside an `if`/`while`/`repeat`/`wait`/`case` header's parens
|
||||
stays inside them; `default;` no longer grows an invented `:`. Eleven
|
||||
of the twelve files the safety net had (correctly) refused now format
|
||||
and round-trip; the twelfth needed a parser-side pending-comment fix
|
||||
(`take_gap`) delivered by the directive round — all twelve close on
|
||||
the merged tree. `verify.rs`'s forgiveness was not widened; the
|
||||
attack-test template was applied anyway.
|
||||
|
||||
**Formatter output changed for the comment shapes above, so this
|
||||
release bumps the version and warm format caches re-verify** (the
|
||||
format-cache rule).
|
||||
|
||||
## 0.15.0 — 2026-08-29
|
||||
|
||||
The interactive-latency release, benchmarked twice against a real
|
||||
3 976-file opentitan checkout (`performance.md`, `performance_take2.md`
|
||||
at the repo root), plus a design-hierarchy sidebar contributed by
|
||||
codex.
|
||||
|
||||
### Every hot path measured, then fixed
|
||||
|
||||
- **codeAction** (fires per cursor move): 3.1–4.6 s → **7 ms** — the
|
||||
port-refactor engine reads the cursor module's indexed fan-out, not
|
||||
the workspace; equality with the whole-workspace computation is
|
||||
pinned, ambiguity refusals intact.
|
||||
- **prepareRename** (pressing F2): 2.5–3.0 s → **microseconds**, flat
|
||||
in project size — answered from the open buffer and the index, with
|
||||
a refusal-by-refusal parity table; refusals are deferred to the
|
||||
rename, never lost.
|
||||
- **rename**: 3.6–8.7 s → **~105 ms** over the reference-postings
|
||||
fan-out, including a sixth rung over unresolved spellings so the
|
||||
dangling-import capture refusal fires exactly as the whole-workspace
|
||||
walk's did. willRenameFiles rides the include graph: 250 → 14 ms.
|
||||
- **completion**: 34–66 ms per keystroke → **3–15 ms** — module
|
||||
headers are sliced, not whole-file-parsed, with whole-file re-plans
|
||||
wherever the slice cannot be proven identical; items byte-identical.
|
||||
- **documentHighlight**: fixed — it answered nothing for any name the
|
||||
file uses but does not declare (a module instance, a connected
|
||||
port), which is most of what a tb hovers.
|
||||
- A widen that subsumes the old scope indexes only its new files, and
|
||||
the word table merges per batch instead of per word (935 → 555 ms
|
||||
for the first jump into a 1 685-file root, warm).
|
||||
|
||||
### The scope default finds your block
|
||||
|
||||
**Behavior change:** `lucisv.index.scopeDepth` defaults to **2** (was
|
||||
0). Opening `hw/ip/aes/dv/tb/tb.sv` now indexes the aes block and
|
||||
cross-file answers work immediately, where before exactly one file was
|
||||
indexed and every cross-file answer was empty until a jump widened the
|
||||
scope. An explicit `0` restores the old behavior exactly.
|
||||
|
||||
### `--verbose`, when you want receipts
|
||||
|
||||
`lucisv-server --verbose` (or the `lucisv.verbose` setting, which
|
||||
restarts the server through a race-proof one-chain restarter) prints a
|
||||
`timing:` line for every operation into the output channel. Off by
|
||||
default and free when off. `--stdio` is accepted as the statement of
|
||||
fact it is.
|
||||
|
||||
### The design-hierarchy sidebar (contributed by codex)
|
||||
|
||||
An instance-oriented hierarchy in the Activity Bar: every module, its
|
||||
instances, search over the whole design, bookmarks, click-to-jump.
|
||||
Snapshots read no files at all — the index now carries client
|
||||
positions — so the handler answers in ~17 ms on opentitan and a save
|
||||
with the sidebar open costs ~141 ms total. Search runs over a resident
|
||||
model in single-digit milliseconds at 120 000 entries, collapsed by
|
||||
default, expansion preserved across refreshes.
|
||||
|
||||
### One-time index rebuild
|
||||
|
||||
The persisted facts format moved to 5 (declaration spans, instance
|
||||
occurrences, client positions; ~+2 % store). The first scan after
|
||||
upgrading rebuilds the store once.
|
||||
|
||||
## 0.14.0 — 2026-08-28
|
||||
|
||||
The first-hover release: the owner's "hover is really slow on first
|
||||
try," traced to three costs and each one removed. Hover's steady state
|
||||
was already microseconds; now the firsts are too — or as close as
|
||||
physics allows.
|
||||
|
||||
### The index carries every declaration's line
|
||||
|
||||
Each indexed declaration — modules, and ports/parameters through the
|
||||
same member entries — now records its line number(s), computed at index
|
||||
time for a `u32` per name (+68 KB over the 860-file corpus). A hover
|
||||
heading into a closed file costs zero I/O: it survives the file being
|
||||
deleted. The persisted facts format moved to 4; an older cache is
|
||||
discarded whole and rebuilt once (~175 ms on the corpus).
|
||||
|
||||
### Closed files are read once, not per hover
|
||||
|
||||
The snippet's one remaining read is served from a small bounded view
|
||||
cache (4 files / 8 MiB, newest kept, invalidated on every path that can
|
||||
change a file's text): a repeat hover into a 12 MB closed file goes
|
||||
5.8 ms → ~1 µs, and mean cross-file hover 40/157 µs → 4.7/12.9 µs.
|
||||
A stale view can only ever omit a snippet — the wrong-line guard is
|
||||
unchanged.
|
||||
|
||||
### The startup scan answers requests as it goes
|
||||
|
||||
A request sent right after `initialized` used to wait out the whole
|
||||
scan: 780 ms cold / 287 ms warm over 200 files. The scan now feeds the
|
||||
live index incrementally and drains the message queue between files —
|
||||
the first hover of a session answers in ~15 ms against the index so
|
||||
far, with the open file indexed first. One merge per drain (per-file
|
||||
merging measured quadratic: 11.7 s over 800 files), scans under 64
|
||||
files stay one-shot, only the startup scan answers mid-way so the
|
||||
request-order contract holds, and the finished index fingerprints
|
||||
byte-identical to the old all-at-once scan. Scan totals unchanged
|
||||
within noise.
|
||||
|
||||
## 0.13.1 — 2026-08-28
|
||||
|
||||
The F12-latency release: the two costs behind a slow jump out of a big
|
||||
|
||||
@@ -86,3 +86,38 @@ Rules:
|
||||
(`cargo test -p vlog_formatter`).
|
||||
- Update `TODO.md`: check items your feature completes (leave the item
|
||||
text intact).
|
||||
|
||||
## Parallel lanes (the 2-agent loop)
|
||||
|
||||
Up to **two dev/QA lanes may run concurrently** when — and only when —
|
||||
their features do not collide in `docs/topo.md`: no shared edge between them
|
||||
(no `──▶`, no `◀──▶`, and neither touching the same open handshake in
|
||||
§2.9), and disjoint file sets. `docs/topo.md` is the authority; if the
|
||||
collision question is not answerable from it, the features are not
|
||||
proven independent and run serially. Rules for a parallel wave:
|
||||
|
||||
- **The lead plans the lanes** before anything is dispatched: one brief
|
||||
per lane with an explicit file-ownership list. That list is the merge
|
||||
contract — a lane touches nothing outside it. A needed change to a
|
||||
file the other lane owns (or to any unlisted file) is a Handshake
|
||||
request in the lane's README plus a flag in its report, never a
|
||||
silent edit; the lead rules on it at merge.
|
||||
- **Each lane works in its own git worktree** branched from the same
|
||||
trunk commit. Never two agents in one tree. Trunk stays untouched
|
||||
while lanes are in flight; the lead merges each lane back only after
|
||||
that lane's QA verdict and lead review, and re-runs the full gates on
|
||||
the merged tree before pushing.
|
||||
- **Roles per lane are unchanged**: one dev (Opus), then one QA
|
||||
(Sonnet) in the same worktree, then the lead's review — so at most
|
||||
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
|
||||
its own dev is done. A QA rework loops inside its lane without
|
||||
blocking the other lane.
|
||||
- **Tracking lives in `TODO.md`**: the lead writes the wave's section
|
||||
(one subsection per lane, each item naming its files) on trunk before
|
||||
branching; each lane ticks only its own lines. Shared-by-nature files
|
||||
(`TODO.md`, `docs/perf/README.md`) may be appended to by both lanes
|
||||
in their own sections — the lead resolves the trivially-parallel
|
||||
merge; anything worse than trivially-parallel means the lanes were
|
||||
not actually independent, which is a planning failure to record.
|
||||
- After merging, the lead updates `docs/topo.md` for any edge a lane added
|
||||
or amended, so the next wave plans against reality.
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.13.1"
|
||||
version = "0.24.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -678,7 +678,11 @@ to the folder walk, so the index is never silently empty.
|
||||
<path-to-binary>` spawns it exactly as the extension does and drives a whole
|
||||
`initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if
|
||||
the handshake and the advertised capabilities are intact — which tells you
|
||||
whether a failure is the server or your editor config.
|
||||
whether a failure is the server or your editor config. Its neighbour
|
||||
`node editors/vscode/restart_test.js` needs no binary at all: it drives the
|
||||
extension's server-restart chain (the one `lucisv.verbose` uses) against a
|
||||
scripted fake client, so a toggle can never be lost to a restart that was
|
||||
already in flight.
|
||||
|
||||
**Formatting through an editor reads `lucisv.toml` too**, discovered from the
|
||||
buffer's own path by the CLI's rule, so format-on-save agrees with what
|
||||
|
||||
@@ -585,6 +585,32 @@ later:
|
||||
salsa question is ever reopened, that is the number it has to beat —
|
||||
incremental *lexing and parsing*, not incremental queries over a whole-file
|
||||
parse, and it lands squarely on `CLAUDE.md`'s hard invariants 1 and 2.
|
||||
**A fourth piece answered without salsa, 2026-08-28**
|
||||
(`docs/features/hover-line-index/README.md`): a derived fact a query used to
|
||||
recompute — the *line* a declaration is written on, which cost a whole file
|
||||
read and a whole `LineIndex` per request — is now computed once when the
|
||||
file is indexed and stored beside the span (`Def::lines`, `FACTS_FORMAT`
|
||||
3 → 4), and the one thing still needing that file's text is served from a
|
||||
small bounded cache of closed files. A repeat hover into a 12 MB closed file
|
||||
goes 5.75 ms → 0.95 µs; a whole scan is unchanged and the store grows 2.9 %.
|
||||
Still no query graph: what is cached is a value, invalidated at four named
|
||||
points, not a node in a dependency graph. **The larger number the same round
|
||||
measured is not an incrementality problem at all**: the first request of a
|
||||
session waits out the startup scan (780 ms cold, 287 ms warm), because
|
||||
`Server::new` scans before the message loop starts. Filed there, not fixed.
|
||||
→ **Fixed 2026-08-28** (`docs/features/scan-interleave/README.md`): the scan
|
||||
is now per-file steps with the message queue drained between them, so a
|
||||
startup scan of more than 64 files answers requests while it runs — 780 ms →
|
||||
**15.5 ms** cold, 287 ms → **12.8 ms** warm, with the scan's own total moving
|
||||
under a percent (860-file corpus: 351 → 353 ms cold, 187 → 189 ms warm). The
|
||||
merge cost was measured first and ruled per-file feeding out: a merge is a
|
||||
pass over the whole index, so one per file would have cost 631 ms of merging
|
||||
on 200 files against 464 ms of parsing. Records are staged per file and folded
|
||||
in with one `WorkspaceIndex::absorb` per *drain*, and a drain only happens
|
||||
when a message is waiting — so a scan nobody is waiting on pays nothing.
|
||||
Answers given mid-scan read the index as of that moment, and only the startup
|
||||
scan gives them: a request queued behind a message that asked for a rescan
|
||||
waits for that rescan, which is the order contract the loop always kept.
|
||||
- [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version
|
||||
bumped to 0.2.0 across the workspace and the extension, `tools/release.sh`
|
||||
(release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and
|
||||
@@ -625,12 +651,25 @@ section only tracks the milestones.
|
||||
**Since 2026-08-28 a rescan no longer re-parses the buffers it already
|
||||
analyzed** — an open buffer's index facts and completion words come from the
|
||||
analysis it holds — so a scope-widening `didOpen` with a 1.4 MB buffer open
|
||||
costs ~23 ms rather than ~228 ms.
|
||||
costs ~23 ms rather than ~228 ms. **And since 2026-08-28 a widen indexes only
|
||||
the folders it added** rather than rescanning every folder reached so far, so
|
||||
the wait a jump puts in front of the next request stops growing with the
|
||||
session: over opentitan's 3 979 files, 120/132/137/169 ms per jump became
|
||||
22/18/12/44 ms.
|
||||
- [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
|
||||
`prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves,
|
||||
cross-file, whole-edit-or-nothing verified by re-parse.
|
||||
- [x] **M3 `refactor-ports`** — add/remove/propagate module ports across
|
||||
the declaration and every instantiation (named/ordered/`.*`).
|
||||
**Amended 2026-08-28** (`docs/features/refactor-ports/README.md`): a
|
||||
`textDocument/codeAction` no longer reads the in-scope file set from
|
||||
disk per cursor move. The engine is handed the cursor's module's own
|
||||
fan-out through the index — definers, instantiation edges, reference
|
||||
postings, open buffers — by one builder both the code action and the
|
||||
three commands use, and the answer is asserted equal to the
|
||||
whole-workspace one. Over opentitan a code action went 4.56 s → 7.1 ms
|
||||
(2.93 s → 83 ms for a module instantiated in 36 files); it was the
|
||||
request every queued definition and hover had been waiting behind.
|
||||
- [x] **M4 `refactor-instantiate`** — module hinting: instantiation
|
||||
skeleton completion from the definition, auto-connect, signature help.
|
||||
- [x] **M5 `completion-core`** — keyword + project-wide identifier
|
||||
@@ -1089,3 +1128,779 @@ Notebook sync, moniker (LSIF), inline value (debugger), document
|
||||
color, goto implementation, goto declaration (Verilog has no
|
||||
declaration/definition split lucisv models). Recorded here so the
|
||||
audit doesn't repeat.
|
||||
|
||||
## 10. Performance wave (2026-08-28) — docs/performance.md findings
|
||||
|
||||
Source: `docs/performance.md` (benchmark of every LSP action against
|
||||
opentitan, 3 976 files). Tracking for the two-worktree parallel round;
|
||||
each lane's dev ticks only its own lines. Lane file ownership is the
|
||||
merge contract — a lane touches no file outside its list.
|
||||
|
||||
### Done before the wave (trunk)
|
||||
|
||||
- [x] `textDocument/codeAction` 3.1–4.6 s per cursor move →
|
||||
7.1 ms (83 ms at a 36-file fan-out): `Workspace::module_sources`
|
||||
subset instead of `ws.sources()` — refactor-ports README,
|
||||
2026-08-28 work log + Review.
|
||||
|
||||
### Lane A — rename family (worktree A; files: crates/vlog_refactor/*,
|
||||
crates/lucisv_server/src/{rename.rs,file_ops.rs,state.rs,perf.rs},
|
||||
docs/features/{refactor-rename,file-operations}/README.md,
|
||||
docs/perf/README.md)
|
||||
|
||||
- [x] `prepareRename` 2.5–3.0 s (F2 blocks everything) → buffer+index
|
||||
answer, < 1 ms; refusal-by-refusal parity table in the README.
|
||||
**1.663 s → 139 ns on OpenTitan**; parity table and six
|
||||
byte-by-byte parity suites in refactor-rename's README, plus 564
|
||||
offsets of a real `tb.sv` swept identical, zero deferrals.
|
||||
- [x] `rename` 3.6–8.7 s → reference-postings fan-out subset with a
|
||||
written sufficiency argument; verifier integrity proven.
|
||||
**3.467 s → 105.5 ms on OpenTitan**, edits byte-identical at every
|
||||
cursor checked (7 files at `aes`, 114 files at `clk_rst_if`), the
|
||||
capture refusal still firing on a real workspace. QA found one
|
||||
lost refusal (a dangling use of the *new* name); closed by a sixth
|
||||
rung, `WorkspaceIndex::files_spelling` — 852 µs worst case on
|
||||
OpenTitan. One accepted residue remains —
|
||||
macro-**invocation**-argument warnings in files outside the
|
||||
fan-out, costing no edit and no refusal.
|
||||
- [x] `willRenameFiles` same `ws.sources()` shape (file_ops.rs:120) →
|
||||
include-graph/index-bounded subset. **249 ms of `sources()` → a
|
||||
14.1 ms whole answer on OpenTitan** (331 includers of 3 976).
|
||||
|
||||
### Lane B — hot path + UX (worktree B; files:
|
||||
crates/lucisv_server/src/{completion.rs,candidates.rs,nav.rs,
|
||||
settings.rs,perf.rs}, crates/lucisv_server/tests/e2e.rs,
|
||||
editors/vscode/package.json, docs/features/{completion-core,
|
||||
references-nav,index-scope}/README.md, docs/perf/README.md)
|
||||
|
||||
- [x] `completion` 34–66 ms per keystroke (worst at 0–4 chars) →
|
||||
profile, then < 5 ms with item-identical answers pinned.
|
||||
Profiled: the whole cost was tier 0, the module skeletons — every
|
||||
other tier is 0.19 ms at every prefix. Tier 0 now parses the
|
||||
declaring file's *header* instead of all of it, and reads the
|
||||
module names off a table built with the index instead of sorting
|
||||
the workspace's whole symbol table per keystroke. **3.17 ms** at
|
||||
the empty prefix on a 4 000-file generated corpus (was 53.2 ms);
|
||||
**13–15 ms** worst case on opentitan (was 34–66), and typing
|
||||
`aes_reg_top` 201 ms → 64.5 ms. Items pinned identical by a
|
||||
fifteen-shape plan-equality test and a module-table equality test.
|
||||
- [x] `documentHighlight` answered 0 results at every opentitan
|
||||
position while references answered — root-cause and fix (or
|
||||
prove the benchmark request wrong and correct docs/performance.md).
|
||||
**A real bug, not a benchmark mistake**: the handler asked only
|
||||
single-file `Semantics`, so a name this file uses but does not
|
||||
declare — an instantiated module, a `.port` connection — had no
|
||||
symbol to find, while `references` read the workspace overlay.
|
||||
Fixed in `nav::external_occurrences`, with a unit regression test
|
||||
and the two opentitan positions pinned over the wire.
|
||||
- [x] Default `lucisv.index.scopeDepth` 0 → 2 (folder scope indexed
|
||||
exactly one file in opentitan's dv/tb layout; every cross-file
|
||||
answer empty until a jump widens) — behavior change, CHANGELOG
|
||||
callout at release. Also removed the *rootless* climb, which had
|
||||
no root to clamp against and would have walked an unnamed tree at
|
||||
the new default. Cost measured rung by rung: 1 / 1 / 21 / 252
|
||||
files at depths 0 / 1 / 2 / 3.
|
||||
|
||||
### Take 2 follow-up (2026-08-29) — the first RTL open at the default scope
|
||||
|
||||
Measured in `performance_take2.md` §5b: opening `hw/ip/aes/rtl/aes.sv`
|
||||
at `scopeDepth: 2` raises the scope to `hw/ip` and costs 1.4–1.7 s.
|
||||
Files: `crates/lucisv_server/src/{candidates.rs,state.rs,server.rs,perf.rs}`,
|
||||
`docs/features/index-scope/README.md`, `docs/perf/README.md`.
|
||||
|
||||
- [x] Diagnosis corrected against the running binary: the widen already
|
||||
takes the cheap path for a subsuming scope and already diffs by
|
||||
**file against the index** (the bar reads 1 685, not 1 807, when
|
||||
the old block's 124 files are inside the new root), so nothing was
|
||||
re-indexed. The chooser's `Whole` arm is still unreachable. Pinned
|
||||
by `state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`
|
||||
and a `widen_of` table row.
|
||||
- [x] The real cost found and fixed: folding a widen's words into the
|
||||
completion table inserted each new word into a sorted `Vec` on its
|
||||
own, which is quadratic in the batch — **403 ms of the 935 ms** on
|
||||
opentitan's `hw/ip`. Counted per batch and merged once: 43 ms.
|
||||
Warm **935 / 881 → 555 / 564 ms**, cold **1 529 → 1 175 ms**.
|
||||
- [ ] **Still slow, filed:** what is left of that jump is real work over
|
||||
1 683 genuinely new files — 325 ms re-lexing them for the
|
||||
completion word table (the persistent store holds a file's facts
|
||||
but not its words), ~100 ms walking and reading them, ~80 ms
|
||||
hashing and decoding records. Storing the word list beside the
|
||||
facts is the next lever and is `index-persistence`'s call: it is a
|
||||
`FACTS_FORMAT` change.
|
||||
- [ ] **Not done, deliberately:** a widen still does not interleave, so
|
||||
this is a bar the user watches once per session per big widen. The
|
||||
coalescing rule is unchanged.
|
||||
|
||||
### Deferred, filed
|
||||
|
||||
- [ ] `codeAction` costs 185–201 ms at a 128-file fan-out and offers
|
||||
**zero** actions there (`performance_take2.md` §6a): ~1.4 ms per
|
||||
instantiating file plus a ~13 ms floor, paid before anything knows
|
||||
there is nothing to offer. Wants either the lazy resolve below or
|
||||
a cheap zero-detector that answers before the fan-out is walked.
|
||||
- [ ] `inlayHint` returns **0 hints at the default scope** where the
|
||||
workspace scope returns 4 (`performance_take2.md` §8): investigate
|
||||
before assuming it is scope-relative-answers working as intended —
|
||||
the hinted instantiation's module may be in scope and still unhinted.
|
||||
- [ ] codeAction lazy resolution (`codeAction/resolve`): make the offer
|
||||
index-only (~0 ms regardless of fan-out), edits computed on
|
||||
lightbulb click — kills the 83 ms worst case. Owner-approved
|
||||
direction, after the wave.
|
||||
- [x] Rename over an index-stale workspace: Lane A must state the
|
||||
staleness premise; if the verifier cannot catch a hidden
|
||||
reference, the honesty gate is the lead's review call. Stated
|
||||
verbatim under "The staleness premise, stated exactly" in
|
||||
refactor-rename's README, with what it costs (a file whose disk
|
||||
copy moved unseen is neither rewritten nor refused over) and the
|
||||
one exemption (open buffers, always in the set). Both residues
|
||||
ruled on: the dangling-use lost refusal was rejected and fixed
|
||||
(rung 6, `files_spelling`); the macro-invocation warning loss is
|
||||
accepted as documented, with the `FileFacts` macro census filed
|
||||
as the real fix.
|
||||
|
||||
## VS Code design-hierarchy sidebar (2026-08-29)
|
||||
|
||||
Feature by codex; this section is that round plus the lead's QA finding
|
||||
and three owner items. See
|
||||
`docs/features/vscode-hierarchy-sidebar/README.md`.
|
||||
|
||||
- [x] `lucisv/moduleHierarchy` + `lucisv/moduleHierarchyChanged`, gated
|
||||
on `initializationOptions.hierarchyView`; Activity Bar container,
|
||||
webview view, navigation, context menu, bookmark.
|
||||
- [x] `FACTS_FORMAT` 4 → 5: `Def::decl_span`, per-instance
|
||||
`InstanceOccurrence`s on the statement edge, and client positions
|
||||
on file-scope declarations and instance occurrences. Call
|
||||
hierarchy and code-lens counts unchanged.
|
||||
- [x] **Lead's HIGH finding — the snapshot read every module-declaring
|
||||
file per request.** Fixed by index-carried positions (zero file
|
||||
I/O), `WorkspaceIndex::units_of`, and a schema-2 wire (file
|
||||
table, four-number ranges, no ids, no per-instance definition
|
||||
copies). On opentitan, server-side handler **145–167 ms → 17–20 ms**
|
||||
warm, response **11.6 MB → 2.3 MB**, a definition pipelined behind
|
||||
a snapshot **263 ms → 41 ms**. Store cost of the positions: +1.7 %
|
||||
on the corpus, +1.9 % on opentitan.
|
||||
- [x] `complete` tightened to `!scanning && !must_wait()` and the
|
||||
window it has to be honest about written down and tested.
|
||||
- [x] Owner: the five-line hover source preview removed — the feature's
|
||||
last consumer of file text.
|
||||
- [x] Owner: every tree level collapsed by default; expansion state
|
||||
survives a refresh on stable row ids.
|
||||
- [x] Owner: search freeze fixed. The model is flat and resident, tree
|
||||
levels are built lazily, and a query is one pass over a prebuilt
|
||||
lowercased index with a character-mask pre-filter and a counting
|
||||
top-K — 3–8 ms per query over a generated 120 000-entry
|
||||
hierarchy, asserted in the node suite.
|
||||
- [ ] Filed, not done: rewire `locate::location` onto `DeclPositions`
|
||||
so `textDocument/definition`, references, the lens and both
|
||||
hierarchies stop reading a file to convert an indexed span. Every
|
||||
unit's range is now in the index for free.
|
||||
- [ ] Manual extension-host acceptance (themes, keyboard-only, zoom,
|
||||
screen readers, an old server binary, both VSIX shapes).
|
||||
|
||||
## 11. Testbench-syntax wave (2026-08-29) — syntax_coverage.md findings
|
||||
|
||||
Source: `syntax_coverage.md` (opentitan sweep, 96.2% → the gap). The top
|
||||
two buckets both edit `vlog_parser/src/parser.rs`, so per CLAUDE.md's
|
||||
parallel-lane rule they run serially; the wave's first two lanes pair
|
||||
the constraints round with the TOPO-independent formatter bugs instead.
|
||||
|
||||
### Lane A — out-of-class constraints (worktree; files:
|
||||
crates/vlog_parser/src/parser.rs, crates/vlog_parser/tests/*,
|
||||
crates/vlog_semantic if an arm is needed, docs/features/
|
||||
out-of-class-constraints/README.md, TODO.md §11 Lane A lines)
|
||||
|
||||
- [x] `constraint C::name { ... }` at file/package/class-external scope
|
||||
— 45 files blocked, and the tolerant-mode cascade (300+ bogus
|
||||
diagnostics per file) is the real LSP damage. Expected shape: the
|
||||
classes feature's verbatim capture reused (justify if not).
|
||||
Done: `parse_constraint` reuses `parse_method_name`, no new AST
|
||||
variant. OpenTitan 151 → 107 failures; 44 of the 45 clean, the
|
||||
45th advances to bucket 10. Tolerant diagnostics over the 45:
|
||||
1 349 → 1. `docs/features/out-of-class-constraints/README.md`.
|
||||
|
||||
### Lane B — formatter round-trip bugs (worktree; files:
|
||||
crates/vlog_formatter/src/* EXCEPT verify.rs forgiveness,
|
||||
crates/vlog_formatter/tests/*, docs/features/formatter-bug-fixes/
|
||||
README.md, TODO.md §11 Lane B lines)
|
||||
|
||||
- [x] The 12 files the safety net refused (comment / `else if` merging
|
||||
shapes in syntax_coverage.md §bucket 2): fix the formatter so its
|
||||
output verifies; verify.rs forgiveness may NOT be widened (any
|
||||
widening needs masked-corruption attack tests per invariant 4 —
|
||||
prefer no widening at all). **11 of 12 fixed; `verify.rs`
|
||||
untouched.** The 12th (`keymgr_scoreboard.sv`) had its bucket-2
|
||||
bug fixed and a second, distinct, *parser*-side bug behind it —
|
||||
`Parser::take_before_open` (parser.rs:757) drains the whole
|
||||
pending-comment queue, so a comment written after `if (` is
|
||||
swallowed by the condition's first call. Out of Lane B's file set;
|
||||
filed as a handshake in `docs/features/formatter-bug-fixes/
|
||||
README.md`.
|
||||
- [ ] Owner/lead: the one-line parser fix above (Lane A's file), which
|
||||
closes the last of the 12.
|
||||
|
||||
### Serial, after Lane A merges (parser.rs frees up)
|
||||
|
||||
- [x] Directive-split for expressions/statements: `` `ifdef `` splitting
|
||||
an assign RHS / instantiation head (chip_if.sv:1192 anchor; blocks
|
||||
both top_* tb.sv testbenches). 5-file floor, high leverage.
|
||||
Done: the mirror of `directive-split` — the failure lands on the
|
||||
`` `ifdef `` that *opens* a region inside a construct, not on the
|
||||
`` `else `` that closes one around it. Verbatim capture, at item and
|
||||
at statement level; no new AST variant or field, so no printer arm.
|
||||
Plus one guard in `take_list_directives` so an outer region's seam
|
||||
is not harvested as a list element, which is all the two tb.sv files
|
||||
needed. OpenTitan 107 → 100 failures: all 5 bucket-7 files, both
|
||||
`top_{earlgrey,darjeeling}/dv/tb/tb.sv`, zero regressions, corpus
|
||||
gate byte-identical at 813/820.
|
||||
`docs/features/directive-in-statements/README.md`.
|
||||
Also delivered there: the `Parser::take_before_open` handshake Lane B
|
||||
filed (`docs/features/formatter-bug-fixes/README.md`), which unblocks
|
||||
the 12th bucket-2 file, `keymgr_scoreboard.sv`.
|
||||
- [x] Mop-up bundle (~26 files): enum member ranges, cast-base drive
|
||||
strengths, local typedef statement, gate delays, virtual+modport,
|
||||
rand-on-struct, foreach-skip-dim, hierarchical bind instance list.
|
||||
Done: nine shapes, **47** files (the estimate was low, and two of
|
||||
`syntax_coverage.md`'s bucket labels were mis-diagnoses — bucket 6 is
|
||||
a *system function call* as the casting type, `$bits(x)'(y)`, not a
|
||||
drive strength; bucket 12 has six files, not five). Real grammar
|
||||
throughout, no verbatim capture, `verify.rs` untouched. One new
|
||||
`StmtKind` variant (the block-scoped `typedef`, which is the item form
|
||||
exactly) and four new fields; seven of the nine buckets needed no AST
|
||||
surface at all. OpenTitan 88 → 43 failures: 45 files clean, 2 advance
|
||||
to the `iff`-in-event-control gap, **zero** newly failing, and zero
|
||||
output change on any of the 3,896 previously-passing files. Corpus
|
||||
gate byte-identical at 813/820. Tolerant diagnostics over the failing
|
||||
set 1 644 → 1 290, none worse anywhere.
|
||||
`docs/features/testbench-mopup/README.md`.
|
||||
- [x] Skipped there, one file: a gate's drive strength
|
||||
(`pullup (weak1) u (...)`, spi_host/dv/tb.sv:101) — a different
|
||||
production from the cast bases bucket 6 named, costing two AST changes
|
||||
for one file. See that README's Status for the exact shape.
|
||||
Done in Round 2 below, at the amortized cost that round predicted.
|
||||
|
||||
### Round 2 (clocking wave) — every remaining grammar bucket, one round
|
||||
|
||||
Serial in the main tree (`docs/features/clocking-wave/README.md`). Baseline
|
||||
43 failures over 3,943 files at `5ad0772`; **43 → 11**, and the eleven left
|
||||
are the two OUT rows — macro fragments that need a preprocessor, and vendor
|
||||
files that are not SystemVerilog. Zero newly failing; one previously-passing
|
||||
file's output moves, and it moves because 55 lines that used to be swallowed
|
||||
into an opaque blob are now parsed (see below). Corpus byte-identical at
|
||||
813/820 over all 860 files; `verify.rs` untouched.
|
||||
|
||||
- [x] **Clocking signal bindings** — `output tms = _tms_internal;`, IEEE 1800
|
||||
§14.4's `clocking_decl_assign`. **7 files.** Deviation from the brief:
|
||||
clocking is already a modelled node with a printer, spans and a linter
|
||||
guard, so the fix is the one missing field, not a verbatim capture that
|
||||
would have thrown that model away. The *opacity* the brief wanted is
|
||||
where it already lived — `analyze` keeps the block a leaf and the linter
|
||||
takes the whole item span, binding included, out through `opaque_spans`
|
||||
— and is now pinned by a lint case.
|
||||
Files: `crates/vlog_parser/src/{ast,parser}.rs`,
|
||||
`crates/vlog_formatter/src/format.rs`.
|
||||
- [x] **`default disable iff expr;`** (IEEE 1800 §16.12) — **7 files**, and not
|
||||
a clocking construct at all: the bucket label came from the error text,
|
||||
and reading all 14 sites is what split it 7 + 7. Verbatim capture, the
|
||||
round's only one, with six masked-corruption attack pairs.
|
||||
- [x] **A macro as a concurrent assertion's action statement** — not in the
|
||||
brief; the next blocker on 6 of the above once they parsed.
|
||||
`assert property (p) else \`ASSERT_ERROR(A)` has no `;` to scan to, so
|
||||
`skip_action_stmt` used to run through whatever followed. **This is the
|
||||
one change with a whole-tree output effect**: `prim_sync_reqack.sv` had
|
||||
~55 lines of generate-block code absorbed into an assertion's opaque
|
||||
bytes; they are now parsed and laid out.
|
||||
- [x] **`iff` on an event-control term** (§9.4.2) — **5 files**. LRM scope
|
||||
checked: `iff` gates one event-expression term, so `@( … )` is the only
|
||||
position; the paren-less form and `wait` have no `iff` alternative.
|
||||
- [x] **Bare event control over an indexed hierarchical path** —
|
||||
`@cfg.agents["k"].vif.cb`, **3 files** (the rstmgr shape). Also closed a
|
||||
pre-existing hole: that loop boxed a layer per `.name` without charging
|
||||
the chain budget.
|
||||
- [x] **`program … endprogram`** (§24.3) — **3 files**, one dispatch arm
|
||||
reusing `parse_module`.
|
||||
- [x] **Chain limit 256 → 1024, `PARSE_STACK_SIZE` 16 → 32 MiB** — **7 files**,
|
||||
an engineering measurement, not a grammar change. Real generated register
|
||||
files need up to **567** links (`pinmux_reg_top.sv`); 9.20 KiB of debug
|
||||
stack per postfix link; the new worst case is **9 894 KiB** (a maximal
|
||||
chain inside nesting), so 32 MiB keeps the 2.7×-or-better margin. This
|
||||
round retires the feature's own "chains do not move the worst case" —
|
||||
true at 256, false at 1024 — while re-verifying the phase argument that
|
||||
keeps the two budgets additive.
|
||||
`docs/features/recursion-limit/README.md` round 4.
|
||||
- [ ] **Skipped, `jtag_if.sv`**: its clocking blocker is fixed; a
|
||||
**pre-existing** one sits behind it. Two rival, bracket-*balanced*
|
||||
interface headers in an `` `ifdef ``/`` `else `` region, which
|
||||
`at_split_conditional` does not fire on (it requires an open bracket), so
|
||||
the parser nests them. Handshake request to a future `directive-split`
|
||||
round; reproduced on trunk grammar alone.
|
||||
- [ ] **Skipped, `SimDTM.sv`**: a net delay written *after* the type
|
||||
(`wire [31:0] #0.1 x = y;`), which is where the LRM puts it — lucisv
|
||||
parses it only before. One `DataDecl` field has one print position, so
|
||||
accepting both spellings needs a positional field or the safety net
|
||||
rightly refuses the reordered tokens. One vendor file in `tb/unused/`.
|
||||
- [ ] **Skipped, `kmac_reduced_tb.sv`**: a trailing comma in a *named*
|
||||
parameter override list. Not legal SystemVerilog; rejecting it is
|
||||
correct.
|
||||
- [ ] **Recommended instead of grammar work**, for the sweep's non-SystemVerilog
|
||||
files: exclude patterns `**/*.tpl.sv`,
|
||||
`**/vendor/google_riscv-dv/**`, `**/pulp_riscv_dbg/tb/unused/**`.
|
||||
|
||||
## 12. Inline instantiation wave (2026-08-30) — owner request
|
||||
|
||||
Two-level module-instantiation snippet expansion, sized for opentitan
|
||||
(~4 000 files, ~43k declarations). Single lane (one dev, one QA), no
|
||||
concurrency. Files: crates/lucisv_server/src/{inline.rs, completion.rs,
|
||||
candidates.rs, settings.rs}, crates/lucisv_server/tests/e2e.rs,
|
||||
editors/vscode/{package.json, smoke.js},
|
||||
docs/features/inline-instantiation/README.md (new), handshake
|
||||
amendments in docs/features/{completion-core, refactor-instantiate,
|
||||
inline-templates, completion-templates}/README.md, TODO.md §12 lines.
|
||||
|
||||
- [x] **Level 1 — popup names only.** `completion.rs::module_tier`
|
||||
stops planning skeletons per keystroke (up to 64 file reads +
|
||||
header parses today): module items insert just the module name.
|
||||
Owner ruling 2026-08-30 supersedes the M4 completion-skeleton
|
||||
byte-for-byte pins; flip them to name-only. Signature help and
|
||||
inlay hints keep consuming `instantiation_plan` unchanged.
|
||||
- [x] **Level 2 — exact-match ghost.** New trigger in `inline.rs`:
|
||||
cursor at the end of an `Ident` whose text exactly
|
||||
(case-sensitively) matches an indexed module name, at a position
|
||||
where an instantiation is legal, rest of line blank → ghost the
|
||||
full instantiation (parameters + all ports, tabstopped snippet)
|
||||
planned for exactly one module through the existing
|
||||
`module_definition` → `module_header` slice → `instantiation_plan`
|
||||
path and the `FileView` cache. Relative `\t` indentation per the
|
||||
inline indentation contract.
|
||||
- [x] **Exact-match probe.** `Candidates` exposes an O(log n) exact
|
||||
lookup over its sorted module table; the non-matching keystroke
|
||||
does no file I/O and no planning.
|
||||
- [x] **Setting.** `lucisv.inlineInstantiation` (unset = on), following
|
||||
the `lucisv.inlineTemplates` pattern; package.json entry.
|
||||
- [x] **Pins.** e2e: accept the name-only popup item, then
|
||||
`inlineCompletion` at the landing cursor ghosts the skeleton
|
||||
("before or after autocomplete"); negatives (partial name,
|
||||
expression position, text after cursor, setting off, no-lex
|
||||
buffer); accepted ghost parses.
|
||||
- [x] **QA on opentitan** (read-only: `--check`/`--stdout` only, git
|
||||
status after): timing via `--verbose` — non-matching keystroke
|
||||
well under 1 ms, matching ghost sub-ms warm / few ms cold, popup
|
||||
module tier no longer reads files.
|
||||
|
||||
### §12 round 2 (2026-08-30, owner rulings after live use)
|
||||
|
||||
Files: same lane list as round 1 (inline.rs, completion.rs, candidates.rs
|
||||
if needed, state.rs ONLY if a selector is needed there, e2e.rs,
|
||||
package.json description, smoke.js, the feature README + amendments,
|
||||
TODO.md §12).
|
||||
|
||||
- [x] **Space-armed trigger.** The ghost offers only after
|
||||
`name<space>`: the identifier must end exactly one space before
|
||||
the cursor (`aes ` ghosts; `aes` alone never does — `aes_dft`
|
||||
may still be coming). Ghost text loses its leading space
|
||||
accordingly. Popup round trip becomes accept-name, type space,
|
||||
ghost.
|
||||
- [x] **Every indexed module expands.** A module declared in more than
|
||||
one file no longer declines: pick the definition whose path
|
||||
shares the longest common prefix with the requesting document's
|
||||
path (the same top's copy in opentitan), tie-broken by
|
||||
lexicographic path; deterministic and pinned. `ast_dft` and
|
||||
`io_osc` (duplicated across top_earlgrey/top_darjeeling) are the
|
||||
motivating cases.
|
||||
- [x] **QA sweep on opentitan**: request a ghost for every module name
|
||||
in the index at a synthetic legal site; every non-ghosting name
|
||||
needs a written reason (escaped identifiers, unparseable
|
||||
definition file); `ast_dft`, `io_osc`, `aes` verified by hand.
|
||||
1 131/1 131 ghosted, 0 declined; 199 names duplicated across 2-61
|
||||
files, all resolved. One non-blocking finding (nearest-definition
|
||||
tie-break on a nested-subdirectory sibling) — see the feature
|
||||
README's round-2 QA log.
|
||||
|
||||
## 13. Fuzzy completion wave (2026-08-30) — owner request
|
||||
|
||||
Subsequence ("fuzzy") matching for identifier completion, VS Code
|
||||
policy: prefix matching below 3 typed characters, fuzzy from 3 up
|
||||
(`clkenq` reaches `clk_osc_en_q`). Sized by the lead's benchmark on
|
||||
the real opentitan word list (139,800 words): char-bitmask prefilter
|
||||
+ two-pointer scan = 0.07-0.32 ms/keystroke; naive scan 3.4 ms;
|
||||
1-2-char queries stay prefix so the degenerate single-letter case
|
||||
never runs fuzzy. Single lane. Files:
|
||||
crates/lucisv_server/src/{candidates.rs, completion.rs},
|
||||
crates/lucisv_server/tests/e2e.rs,
|
||||
docs/features/fuzzy-completion/README.md (new), amendment in
|
||||
docs/features/completion-core/README.md, TODO.md §13.
|
||||
|
||||
- [x] **Mask table in `Candidates`.** Per-word 32-bit character mask
|
||||
for the words and units tables, built with the index and
|
||||
maintained by every mutation path (build, update_words, absorb,
|
||||
remove_file); query mask subset-check prunes before the
|
||||
subsequence scan.
|
||||
- [x] **Fuzzy tiers at ≥3 chars.** Words, index (project
|
||||
declarations) and scope-visible tiers match by case-insensitive
|
||||
subsequence when the typed word is 3+ chars; below 3, today's
|
||||
prefix behavior byte-for-byte. Module tier unchanged
|
||||
(substring, its own semantics). Dedup across tiers preserved.
|
||||
- [x] **Ranking.** Prefix hits outrank fuzzy hits within a tier;
|
||||
fuzzy hits scored (word-boundary bonus at `_`/case/digit
|
||||
boundaries, contiguity, gap penalty), deterministic, stable
|
||||
tie-break by name; top-K under the existing LIMIT.
|
||||
- [x] **isIncomplete correctness.** The 2-char prefix response must
|
||||
be marked incomplete or VS Code filters locally and the 3rd
|
||||
keystroke never reaches the server (the prefix→fuzzy transition
|
||||
is the trap); truncated fuzzy responses incomplete too.
|
||||
- [x] **Pins.** clkenq→clk_osc_en_q end to end; boundary-scored
|
||||
ranking; 1-2 char = prefix only; textEdit still replaces the
|
||||
typed word; no fuzzy hit whose letters are out of order; e2e
|
||||
over the wire incl. the 2→3 char transition.
|
||||
- [x] **QA on opentitan** (read-only, --check/--stdout only, git
|
||||
status after): fuzzy keystroke adds ≤0.5 ms warm vs today's
|
||||
2.6-3.2 ms popup; <3-char path unchanged; index build/absorb
|
||||
not measurably slower from mask maintenance; clkenq finds
|
||||
clk_osc_en_q in a real ast buffer.
|
||||
**Dev note (2026-08-30): the ≤0.5 ms bar does not hold on the
|
||||
widest three-letter queries.** Measured on the real checkout:
|
||||
`clkenq` +0.05 ms, `clk` +0.52 ms, `prim_` +0.77 ms, `aes`
|
||||
+0.80 ms; 1-2-char requests unchanged. Numbers, the reason
|
||||
(three common letters leave 39 362 of 100 022 names past the
|
||||
mask and half of them really match) and the two untaken levers
|
||||
are in docs/features/fuzzy-completion/README.md, *Performance*
|
||||
— for the lead to rule on.
|
||||
**QA verdict (2026-08-30): SHIP.** Gates clean (fmt, clippy,
|
||||
`cargo test --workspace` 2691/0/36 exact match, debug+release
|
||||
builds, smoke.js). git status on opentitan confirmed unchanged
|
||||
(only the three pre-existing owner edits) before and after every
|
||||
session. `clkenq` confirmed live over the wire against the real
|
||||
`clk_osc_en_q` in `hw/top_earlgrey/ip/ast/rtl/gfr_clk_mux2.sv`
|
||||
(ast.sv itself doesn't declare it; grepped for the closest real
|
||||
name as instructed), both from another buffer and from inside
|
||||
that file's own buffer. Ten adversarial attack tests written
|
||||
against the matcher (mixed case, `$`/digit/`_` queries, a
|
||||
non-ASCII byte in a table entry, ranking determinism, absorb
|
||||
overwriting a path, remove-then-readd) — all ten passed, no
|
||||
corruption found; reverted after running (nothing to fix).
|
||||
Server "answered in" timings (fairer than wall-clock; still pays
|
||||
JSON marshalling the dev's isolated number does not): `aes`
|
||||
1.7-2.2 ms, `clkenq` 0.4-0.5 ms, 1-2-char queries 0.9-2.0 ms
|
||||
(matches the unchanged-path claim in shape). **New finding**:
|
||||
`ena` (a common real RTL fragment) measured 2.95-4.05 ms,
|
||||
worse than `aes` — the *Performance* section's "aes is the
|
||||
worst case" is not shown to be a proven upper bound, just the
|
||||
case the dev tried. Informational, not blocking: same
|
||||
architecture, same order of magnitude, still within the ~1.1 ms
|
||||
absolute framing the lead already accepted. See the feature
|
||||
README's QA log for the full latency table and repro.
|
||||
|
||||
## 14. Null items wave (2026-09-01) — owner report "for loop inside generate"
|
||||
|
||||
Lead diagnosis: the generate-for itself parses in every spelling
|
||||
(genvar in the header, declared outside, region-less; the three
|
||||
systemverilog.io examples all round-trip). What fails is the stray
|
||||
`;` the owner wrote after `endgenerate` — a **null item**, legal SV
|
||||
(IEEE 1800-2017 A.1.4 `package_or_generate_item_declaration ::= … | ;`
|
||||
and `class_item ::= … | ;`; slang warns `-Wempty-member`, "an
|
||||
unnecessary semicolon in a non-procedural scope"). Rejected today at
|
||||
module scope, inside `generate…endgenerate`, after a generate block's
|
||||
`end`, in package/interface/class bodies and at file scope; the
|
||||
procedural null *statement* already works; `endfunction;`/`endtask;`
|
||||
already survive via `end_semi`. Single lane. Files:
|
||||
crates/vlog_parser/src/{ast.rs,parser.rs}, crates/vlog_parser/tests/
|
||||
spans.rs, crates/vlog_formatter/src/format.rs (+align.rs only if a
|
||||
group rule needs it), crates/vlog_formatter/tests/cases/
|
||||
null_items.cases (new), crates/vlog_formatter/tests/verification.rs,
|
||||
crates/vlog_semantic/src/bind.rs (arm), crates/vlog_linter/src/
|
||||
rules/empty_item.rs (new) + registry + a .lint case + rule docs,
|
||||
compile-fix arms elsewhere as the compiler demands (listed in
|
||||
Handshakes), docs/features/null-items/README.md (new), TODO.md §14.
|
||||
|
||||
- [x] **`ItemKind::Empty`** — a first-class null item wherever an
|
||||
item may appear (module, generate region, generate-block body,
|
||||
package, interface, program, class body, file scope), span =
|
||||
the `;` token, comments attached through the ordinary `Meta`.
|
||||
No cascade: tolerant mode emits no diagnostic for it.
|
||||
- [x] **Formatter layout, token-preserving**: a null item on the same
|
||||
line as the previous item's last token prints glued
|
||||
(`endgenerate;`, `end;`, `;;`); one on its own line prints `;`
|
||||
at the current indent. Idempotent both ways; alignment groups
|
||||
are not joined across it. Corpus byte-identical (813/820).
|
||||
- [x] **Blast radius arms**: `format.rs`, `bind.rs`, `tests/spans.rs`
|
||||
(+ any other exhaustive match the compiler names).
|
||||
- [x] **Safety-net template**: `verify.rs` untouched; rejection pairs
|
||||
added anyway (dropped `;`, `;` moved across a comment, `;`
|
||||
moved into a procedural block).
|
||||
- [x] **Lint `empty-item`** (slang's `-Wempty-member`): warn on a null
|
||||
item, safe auto-fix removes it; default on; `.lint` case with
|
||||
the fix output verified by the harness.
|
||||
- [x] **Online-example pins**: the three systemverilog.io generate
|
||||
examples (16-input mux, arbiter assertions, nested memory case)
|
||||
as formatter cases, plus the owner's `endgenerate;` shape and
|
||||
slang's two warning examples.
|
||||
- [x] **QA**: adversarial null-item placements (before/after
|
||||
directives, between `` `ifdef `` arms, after attributes, with
|
||||
trailing/leading comments, CRLF), idempotency, opentitan sweep
|
||||
unchanged at 11 failures (read-only), LSP diagnostics show the
|
||||
lint (not a parse error) with the quick fix.
|
||||
|
||||
## 15. DV class semantics wave (2026-09-01) — owner request
|
||||
|
||||
Round 1: **class-member-access**. `handle.member` through a class-typed
|
||||
variable resolves (hover / definition / references), inherited members
|
||||
chased through `extends` in-file and cross-file, `this.x`/`super.x`
|
||||
chased the same way (delivers topo §2.9-9), and an out-of-class method
|
||||
body (`task c2::update(...)`) sees its class's members. Design by the
|
||||
lead from the Explore map: today `a.b` records a reference for the head
|
||||
only (bind.rs `ExprKind::Member` arm, vlog-semantic rule 8), `Symbol`
|
||||
carries no declared type, `resolve_external` never chases
|
||||
`InheritedCandidate::base`, and the index has no base-class-of lookup.
|
||||
Single lane. Files: crates/vlog_semantic/src/{model.rs, bind.rs,
|
||||
resolve.rs, workspace.rs, facts.rs}, crates/vlog_semantic/tests/*
|
||||
(+ new member_access.rs), crates/lucisv_server/src/{hover.rs, nav.rs}
|
||||
only if a rendering detail needs it, crates/lucisv_server/tests/e2e.rs,
|
||||
docs/features/class-member-access/README.md (new), amendments in
|
||||
docs/features/{class-semantics, overlay-promotion, vlog-semantic}/
|
||||
README.md, TODO.md §15.
|
||||
|
||||
- [x] **`Symbol::type_name`** — the declared type as written (`c1`,
|
||||
`pkg::c1`), captured where declarators bind (Var, TfArg, Port,
|
||||
class properties); additive field, `None` for everything else.
|
||||
- [x] **Tail reference for `head.member`** when the head is a plain
|
||||
identifier: new `Target::MemberOf`, tail span via `member_tail`;
|
||||
resolves the head lexically → its `type_name` → the class
|
||||
(in-file scope, else `ExternalCandidate { paths: ["C::member"] }`)
|
||||
→ the member in the class scope, else chase `Scope::extends`
|
||||
in-file, else `InheritedCandidate { base, paths }`.
|
||||
- [x] **Index-side inheritance chase**: `WorkspaceIndex::base_of(class)`
|
||||
as a reverse map built from the existing inheritance-edge census
|
||||
(no new facts field); `resolve_external` follows
|
||||
`InheritedCandidate::base` upward with a visited set until a
|
||||
member hit or an unknown base. Also serves `this.x`/`super.x`
|
||||
misses (§2.9-9 delivered).
|
||||
- [x] **Out-of-class method bodies** (`task C::m(...)`): names inside
|
||||
resolve in class `C` first (in-file scope chain; cross-file via
|
||||
`InheritedCandidate { base: C }`), so `address = in_item.user_id`
|
||||
resolves both sides in the owner's example.
|
||||
- [x] **`FACTS_FORMAT` 5 → 6** — the reference census grows (new tail
|
||||
postings), so stores written by older builds must be discarded;
|
||||
`fingerprint`/`absorb`/`update_one` equalities re-pinned.
|
||||
- [x] **Hover renders the member's declaration** (`rand bit user_id;`
|
||||
with file:line for cross-file) through the existing external
|
||||
path; definition/references follow for free and are pinned.
|
||||
- [x] **Pins**: the owner's three-file example (base/c1/class2) in-file
|
||||
and split across files; inherited member two hops up; cycle in
|
||||
`extends` terminates; unknown base → graceful `None`; module
|
||||
instance heads unchanged (`a_hierarchical_name_resolves_only_its_head`
|
||||
stays green); rename of `user_id` renames the tail use.
|
||||
- [x] **QA on opentitan DV** (read-only; 2026-09-01): `item.a_addr`
|
||||
(`tl_seq_item`, cross-file) resolves correctly, 0.12 ms cold /
|
||||
0.01 ms warm; `cfg.clk_rst_vif` (type-parameterized `cfg`)
|
||||
correctly answers nothing; no `uvm_pkg.sv` in the tree, so every
|
||||
UVM-base chase ends at an unknown base by construction; cold
|
||||
full-workspace scan 2956 ms / warm 1521 ms (3976 files), matching
|
||||
`docs/performance_take2.md`'s baseline; diagnostics unchanged on
|
||||
3 sampled DV files; store size +9.56% on the whole opentitan tree
|
||||
(28 200 598 → 30 895 566 bytes). **First-pass QA verdict: REWORK**
|
||||
— finding 1: a typedef-typed (struct, enum or plain alias) local
|
||||
variable's member access is documented to record no reference at
|
||||
all but instead became an `ExternalCandidate`, which a same-named
|
||||
unit elsewhere in the workspace could wrongly answer (hover/
|
||||
definition landing on an unrelated declaration). Confirmed live in
|
||||
real opentitan DV code (`cip_base_scoreboard.sv`'s
|
||||
`expected_alert_t`/`exp_alert`, harmless there for lack of a naming
|
||||
collision) and by three isolated repros.
|
||||
**Fixed by the dev (rework round, same day)**: `resolve.rs`'s
|
||||
`member_of` now routes through a three-way `TypeHere::{Scope,
|
||||
NotAUnit, Absent}` — only `Absent` (nothing in this file declares
|
||||
the type name at all) reaches the workspace; a type declared here
|
||||
as a typedef (`NotAUnit`) records no reference, full stop. Four new
|
||||
permanent pins in `member_access.rs`. **Re-verified 2026-09-01: all
|
||||
three original repros now pass; the live collision scenario
|
||||
(`bus_t` struct in A vs. unrelated `class bus_t` in B) answers
|
||||
`null`/`[]` over the release server, never B's member; the
|
||||
corrected live opentitan occurrence
|
||||
(`cip_base_scoreboard.sv:469`, `exp_alert.is_fatal`/`.max_delay`)
|
||||
now answers nothing; `item.a_addr` still resolves at the same
|
||||
timing; honest positives (owner's example, both file layouts,
|
||||
inherited `base_field`, out-of-body `address`, rename) unchanged
|
||||
byte-for-byte; corpus references 97 892 → 97 454 (−438 bogus
|
||||
postings removed), unresolved unchanged at 1 256. Gates:
|
||||
`cargo test -p vlog_semantic` 176/0/1, `-p lucisv_server`
|
||||
1431/0/36, `--workspace` 2736/0/37, fmt/clippy clean.
|
||||
**Final QA verdict: SHIP.**
|
||||
- Round 2 (filed, not this round): chains `a.b.c` needing
|
||||
`Def::type_name` in the index; instance heads `u.port` via the
|
||||
module member table; struct-typed variables (`s.field`, needs
|
||||
§2.9-13 first); and a `base` field on `ReferenceFact` (another
|
||||
`FACTS_FORMAT` bump) so a use whose *only* handle on its declaration
|
||||
is the recorded base — `this.x`, `super.x`, a bare miss inside an
|
||||
extending class — gets an index posting too, and cross-file
|
||||
find-references lists it. Every use carrying a path, which is every
|
||||
`handle.member` tail, already posts.
|
||||
|
||||
### §15 round 2 — member chains and instance heads (2026-09-01)
|
||||
|
||||
Rides on round 1's shape (`Symbol::type_name`, `Target::MemberOf`,
|
||||
`TypeHere`, `base_of`/`member_chain`). Same feature README, new
|
||||
round-2 section. Files: crates/vlog_semantic/src/{model.rs, bind.rs,
|
||||
resolve.rs, workspace.rs, facts.rs}, crates/vlog_semantic/tests/
|
||||
member_access.rs (+ others as needed), crates/lucisv_server/tests/
|
||||
e2e.rs, docs/features/class-member-access/README.md, amendments in
|
||||
docs/features/vlog-semantic/README.md (rule 8), TODO.md §15 round 2.
|
||||
|
||||
- [x] **`Def::type_name`** on indexed declarations (members and
|
||||
units' ports), same capture rule as `Symbol::type_name` (none on
|
||||
unpacked declarators); **`FACTS_FORMAT` 6 → 7**.
|
||||
- [x] **Chains `a.b.c`**: the tail carries the head's spelling plus the
|
||||
links before it (`Target::MemberOf { head, mids }`) rather than the
|
||||
inner tail's reference — the in-file walk hops declared type to
|
||||
declared type, and a chain that leaves the file arrives as **one
|
||||
composed path** (`item_t::hdr::addr`) in the existing path
|
||||
contract, which `follow_one` walks member by member. No new
|
||||
`Resolution` variant, and the index's own postings come free, so
|
||||
hover, cross-file references and rename cannot disagree. Any link
|
||||
that cannot be resolved honestly stops the chain.
|
||||
`item.hdr.addr`, `tb.dut_i.u_core.sig`.
|
||||
- [x] **Instance heads `u.port` / `u.internal`**: an instance symbol's
|
||||
type is its module (not for an instance array), and `type_here`
|
||||
already accepted a `Module` scope, so `u.port`, `u.internal_sig`
|
||||
and hierarchical tb paths resolve; `.*`/positional connections are
|
||||
unchanged. `a_hierarchical_name_resolves_only_its_head` flipped,
|
||||
old assertion kept for an untyped head.
|
||||
**Ruling against the plan: modules go on exporting ports and
|
||||
parameters only.** Exporting nets and vars costs +24 % of the
|
||||
corpus store (3 112 102 → 3 871 557 bytes) *and* makes a `.port`
|
||||
connection resolve to the module's internal net — a wrong answer
|
||||
(`an_internal_net_of_another_module_is_not_reachable` fails).
|
||||
Separating the two lookups is a workspace-index decision; left for
|
||||
the lead with the numbers. `u.internal_sig` resolves in-file.
|
||||
- [x] **Typedef alias chase**: `typedef c1 my_t; my_t h; h.x` follows
|
||||
the typedef's own `type_name` (in-file and, via `Def::type_name`,
|
||||
cross-file), visited-guarded; a typedef of a non-unit still
|
||||
records nothing (round-1 pins stay). Cross-file only for a
|
||||
file-scope typedef; one inside a package is filed.
|
||||
- [x] **`this.x`/`super.x` index postings**: a `base` on
|
||||
`ReferenceFact` so cross-file references from the declaration
|
||||
side list inherited-member uses (round-1 residue). `rename`'s
|
||||
`files_spelling` fan-out is deliberately unchanged; the rung-6
|
||||
question it raises is filed in the feature README's Handshakes.
|
||||
- [x] **Pins**: two- and three-link chains in-file and across three
|
||||
files (both index orders); a chain broken by a struct link records
|
||||
nothing past the break, including against a same-named class
|
||||
elsewhere; a chain through an inherited member; instance port,
|
||||
parameter and internal signal through a module in another file;
|
||||
hierarchical tb path in one file and across two; alias one and two
|
||||
hops; alias cycle; ambiguous hop; record round-trip and every
|
||||
index mutation; e2e hover/definition/references/rename on a
|
||||
chain's third link and hover on an instance port.
|
||||
- [x] **Filed, fixed by the lead**: `crates/vlog_refactor/tests/
|
||||
rename.rs:818` `a_hierarchical_tail_is_left_alone_and_named_as_such`
|
||||
pinned round 1's truth — a rename of `sig` leaves `u_sub.sig` alone and
|
||||
warns. Round 2 resolves that tail, so the rename correctly edits it;
|
||||
the pin was stale. The lead split it into
|
||||
`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`
|
||||
(resolves, is edited) and
|
||||
`a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such`
|
||||
(unknown module: left alone, correctly, but the old `stray_reason`
|
||||
warning no longer fires — the tail now carries an `ExternalCandidate`
|
||||
the workspace cannot answer, which is neither an edit nor a warning
|
||||
today). The rename engine needed no other change. The lost warning is
|
||||
filed as `docs/topo.md` §2.9-20, not a REWORK item — the edit behavior
|
||||
itself is correct in both directions.
|
||||
- [x] **QA on opentitan DV/RTL** (read-only, 2026-09-01): real chains
|
||||
in `hw/ip/aon_timer/dv/env/aon_timer_scoreboard.sv:496`
|
||||
(`cfg.m_tl_agent_cfg.vif.h2d.a_valid`, a class-parameterized `cfg`
|
||||
— head resolves, every link past it correctly answers nothing per
|
||||
the no-elaboration assumption) and
|
||||
`hw/ip/uart/dv/env/uart_scoreboard.sv:195` (`ral.ctrl.tx`, `ral`
|
||||
typed `RAL_T` — same shape, same correct "nothing"); a hierarchical
|
||||
tb path `hw/ip/uart/dv/tb/tb.sv:84` (`dut.uart_core.rx_sync` — `dut`
|
||||
resolves, `uart_core` is an instance of `uart` in another file and
|
||||
answers nothing cross-file since a module exports ports/parameters
|
||||
only, `rx_sync` (an internal signal two hops deep) likewise); the
|
||||
round-1 positive case re-verified (`item.a_addr` →
|
||||
`tl_seq_item.sv:45`, cross-file, ~35-42 ms including RPC/parse) and
|
||||
the round-1 negative case re-verified (`exp_alert.is_fatal` /
|
||||
`.max_delay` against the real non-macro line,
|
||||
`cip_base_scoreboard.sv:469` — both still answer nothing; no
|
||||
coincidentally-named external unit). **15 probes, zero wrong
|
||||
answers.** Store: `FileFacts::of` + `encode()` over all 3979
|
||||
`.sv`/`.v`/`.svh` files, trunk (v0.22.0, `91b7c2f`, detached
|
||||
worktree) vs this tree: 30 821 130 → 35 440 798 bytes (**+4 619 668,
|
||||
+15.0%**), matching the internal 860-file corpus's own +15.4%
|
||||
closely; read time ~1.8 s both trees (noise-dominated, no
|
||||
regression). `git -C opentitan status --short`: only the three
|
||||
pre-existing owner files, untouched by this QA pass. Diagnostics:
|
||||
not independently re-measured this round — `vlog_parser` and
|
||||
`vlog_linter` are outside this round's diff (confirmed by `git diff
|
||||
--stat`), and diagnostics are produced from parse/lint alone, so
|
||||
they structurally cannot move; round 1's own before/after
|
||||
measurement already stands for the shared code paths.
|
||||
|
||||
## 16. Interface semantics wave (2026-09-01) — coverage_gaps C2/H2
|
||||
|
||||
Interfaces are `SymbolKind::Module` (hover labels them "module");
|
||||
modports and clocking blocks declare no symbol and the signal names
|
||||
inside them are not references; `is_exported(Module, ·)` passes ports
|
||||
and params only, so `vif.sig` through a `virtual my_if vif` handle
|
||||
resolves in-file but never across files (H2). `virtual my_if.mp vif`
|
||||
already records `type_name = my_if` (the modport half is dropped);
|
||||
`b_if.mp` in a connection resolves nothing (the C2 "wrong answer" was
|
||||
the head's "module" label, re-probed against HEAD). Delivers topo
|
||||
§2.9-7. Single lane. Files: crates/vlog_semantic/src/{model.rs,
|
||||
bind.rs, resolve.rs, workspace.rs, facts.rs}, crates/vlog_semantic/
|
||||
tests/* (+ new interfaces.rs), mechanical kind arms in
|
||||
crates/lucisv_server/src/{symbols.rs, hover.rs, tokens.rs,
|
||||
completion.rs, candidates.rs, type_def.rs, design_hierarchy.rs,
|
||||
hierarchy.rs} and crates/vlog_refactor/src/{ports.rs, instantiate.rs}
|
||||
(Module-only filters widened to Module|Interface so behavior is
|
||||
unchanged), crates/lucisv_server/tests/e2e.rs,
|
||||
docs/features/interface-semantics/README.md (new), amendments in
|
||||
docs/features/{interfaces, ansi-first-port, type-definition,
|
||||
class-member-access}/README.md, TODO.md §16.
|
||||
|
||||
- [x] **`SymbolKind::Interface`** for `interface … endinterface`
|
||||
(`program` stays `Module` this round, documented). Every
|
||||
Module-exact match gains the arm (resolve.rs `Target::Module`/
|
||||
`Target::Port`/`container_scope`/`member_scope`, workspace
|
||||
`is_unit`/`counts`, facts `kind_name`/`kind_of`, server labels
|
||||
and LSP kinds — hover says "interface", `SymbolKind::INTERFACE`
|
||||
/ `CompletionItemKind::INTERFACE`); interfaces stay in the
|
||||
module table, the design hierarchy and code lens (an interface
|
||||
instance is an instantiation edge) — pinned unchanged.
|
||||
- [x] **Export rule for interfaces**: `Net | Var | Port | Param |
|
||||
Typedef | Function | Task | Modport | Clocking` — an interface's
|
||||
signals ARE its surface, so the module ruling (ports/params
|
||||
only) does not apply. `vif.sig` and `vif.cb.sig` resolve
|
||||
cross-file.
|
||||
- [x] **Modport symbols**: `SymbolKind::Modport` declared in the
|
||||
interface scope from `ModportDecl.name_span`; each modport port
|
||||
name / `import`/`export` name / `clocking cb` name becomes a
|
||||
reference to the interface's signal, method or clocking block;
|
||||
`b_if.mp` (connection) and the `.mp` half of an interface-typed
|
||||
port or `virtual my_if.mp` type resolve to the modport (bound as
|
||||
a member of the type in `bind_data_type`, where ansi-first-port
|
||||
said "the tail is where to bind them"). Hover shows
|
||||
`modport mp (…)`.
|
||||
- [x] **Clocking block symbols**: `SymbolKind::Clocking` for named
|
||||
blocks, with `type_name` = the enclosing interface's name so
|
||||
`vif.cb.data` hops cb → interface → `data` through round 2's
|
||||
machinery unchanged (the clocking signal aliases the interface
|
||||
signal; answering the signal's declaration is honest); each
|
||||
`ClockingSignal.name` is a reference to the interface signal
|
||||
(and `= expr` values bind as expressions).
|
||||
- [x] **`FACTS_FORMAT` 7 → 8** (new kinds; older stores discarded).
|
||||
- [x] **Pins**: kind flips in tests/workspace.rs (`an interface is a
|
||||
Module symbol` → Interface); modport/clocking symbols and
|
||||
references in-file and cross-file; `vif.sig`, `vif.cb.sig`,
|
||||
`virtual my_if.mp vif; vif.sig`, `b_if.mp` hover/definition;
|
||||
rename of an interface signal rewrites its modport list, clocking
|
||||
block and `vif.sig` uses (e2e); the refactor test
|
||||
`renaming_the_modport_half_of_a_port_type_is_refused` is
|
||||
re-examined by the lead at merge (a modport is a symbol now —
|
||||
renaming it should rename its type-position uses).
|
||||
- [x] **QA on opentitan DV** (read-only) — 2026-09-01, verdict SHIP.
|
||||
17 probes over the real server (cfg.vif.* class-parameter chains,
|
||||
`vif.cb.scl_i` genuine cross-file resolution in `i2c_monitor.sv`,
|
||||
modport/clocking hovers in `uart_if.sv`/`tl_if.sv`, interface
|
||||
instance hovers in `tb.sv`): zero wrong answers, sub-ms hover
|
||||
(cold and warm). Store: index-cache +0.81% (31 949 117 →
|
||||
32 208 241 bytes); cold scan 3 976 files unchanged at ~3.0s;
|
||||
diagnostics 0→0 on 5 DV files with interfaces. Full table in
|
||||
`docs/features/interface-semantics/README.md`'s QA log.
|
||||
File diff suppressed because it is too large.
Load diff
+1229
-208
File diff suppressed because it is too large.
Load diff
@@ -24,15 +24,13 @@ impl<'a> Positions<'a> {
|
||||
|
||||
/// The LSP position of a byte offset. An offset inside a multi-byte
|
||||
/// character is floored to that character's start.
|
||||
///
|
||||
/// The conversion itself lives on [`LineIndex`], so that the semantic
|
||||
/// index — which records the same positions for a declaration while its
|
||||
/// file is scanned — cannot answer differently from the wire.
|
||||
pub fn position(&self, offset: u32) -> Position {
|
||||
let offset = self.floor_boundary(offset);
|
||||
let (line, _) = self.index.line_col(offset);
|
||||
let start = self.index.line_range(line).map_or(0, |r| r.start) as usize;
|
||||
let slice = self.text.get(start..offset as usize).unwrap_or("");
|
||||
// LSP line content excludes the whole `\r\n`; `LineIndex` keeps the
|
||||
// `\r` as an ordinary byte of its line, so drop it here.
|
||||
let slice = slice.strip_suffix('\r').unwrap_or(slice);
|
||||
Position { line: line - 1, character: utf16_len(slice) }
|
||||
let (line, character) = self.index.utf16_position(self.text, offset);
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
/// A cursor for converting many byte offsets in one non-decreasing sweep,
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
//! The VS Code instance-oriented design hierarchy.
|
||||
//!
|
||||
//! LSP call hierarchy deliberately groups a module's calls by target module
|
||||
//! type. The sidebar needs the other view of the same facts: every individual
|
||||
//! instance name, its source range, and every declaration its module type may
|
||||
//! name. The response stays flat; the client chooses roots and expands paths,
|
||||
//! which keeps recursion out of the protocol and lets one snapshot serve
|
||||
//! search as well as rendering.
|
||||
//!
|
||||
//! **Two things this answer must not be, and the shape follows from both.** It
|
||||
//! must not read files — every line and character below was converted once,
|
||||
//! when the declaring file was scanned, and rides the index
|
||||
//! (`vlog_semantic::DeclPositions`, `InstanceOccurrence::positions`). And it
|
||||
//! must not be enormous: a whole design re-sent on every save is a message the
|
||||
//! request queue is blocked writing. So a URI is written **once**, in `files`,
|
||||
//! and every location names it by index; a range is four numbers rather than
|
||||
//! four nested objects; a row carries no id, because the client can compose the
|
||||
//! one it used to be sent; and an instance carries no copy of the declarations
|
||||
//! its module name resolves to, because the client already has every module.
|
||||
//! Those four together are 11.6 MB → 1.9 MB on opentitan, and the client
|
||||
//! rebuilds the richer shape in `hierarchyModel.js`'s `validateSnapshot` — see
|
||||
//! `docs/features/vscode-hierarchy-sidebar/README.md`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::Serialize;
|
||||
use vlog_semantic::{FileId, Utf16Range, WorkspaceIndex};
|
||||
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
pub const METHOD: &str = "lucisv/moduleHierarchy";
|
||||
pub const CHANGED_METHOD: &str = "lucisv/moduleHierarchyChanged";
|
||||
|
||||
/// The wire version. Bumped on any change to the shape below; the client
|
||||
/// refuses a snapshot it does not recognise rather than half-reading one.
|
||||
const SCHEMA_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Snapshot {
|
||||
schema_version: u32,
|
||||
revision: u64,
|
||||
complete: bool,
|
||||
/// Every file a location below names, once. Locations index into this.
|
||||
files: Vec<String>,
|
||||
modules: Vec<Module>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Module {
|
||||
module_name: String,
|
||||
definition: Location,
|
||||
instances: Vec<Instance>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Instance {
|
||||
instance_name: String,
|
||||
module_name: String,
|
||||
site: Location,
|
||||
}
|
||||
|
||||
/// A place in the workspace: which file, the whole construct, and the name
|
||||
/// inside it. Each range is `[startLine, startCharacter, endLine,
|
||||
/// endCharacter]`, 0-based lines and UTF-16 characters — an LSP `Range` with
|
||||
/// its four field names left off.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Location {
|
||||
file: u32,
|
||||
range: [u32; 4],
|
||||
selection_range: [u32; 4],
|
||||
}
|
||||
|
||||
/// A complete snapshot of the index currently installed in `workspace`.
|
||||
///
|
||||
/// **It reads no files.** The first shape of this function read every
|
||||
/// module-declaring file and built a `LineIndex` over each — 5.0 s cold and
|
||||
/// ~300 ms warm on opentitan, on *every* request, which is the per-request
|
||||
/// whole-workspace read the release before it existed to kill.
|
||||
///
|
||||
/// `complete` is false only when the request arrived between two files of the
|
||||
/// startup scan. The server sends `CHANGED_METHOD` when that scan lands, so a
|
||||
/// client can render the partial answer as loading and replace it once.
|
||||
pub fn snapshot(workspace: &Workspace, revision: u64, complete: bool) -> Snapshot {
|
||||
let index = workspace.index();
|
||||
let mut files = FileTable::default();
|
||||
|
||||
let mut modules = Vec::new();
|
||||
let mut module_at = HashMap::new();
|
||||
// An interface instance is an instantiation edge exactly as a module
|
||||
// instance is, so both kinds are roots here — the wire shape is unchanged.
|
||||
for (name, def) in index.instantiable_units() {
|
||||
// Every file-scope declaration carries its positions; one without them
|
||||
// would be a declaration the index built by some other route, and
|
||||
// dropping it beats inventing a range for it.
|
||||
let Some(positions) = def.lines.positions else { continue };
|
||||
let Some(file) = files.of(index, def.file) else { continue };
|
||||
module_at.insert((def.file, def.name_span.start, def.name_span.end), modules.len());
|
||||
modules.push(Module {
|
||||
module_name: name.to_string(),
|
||||
definition: location(file, positions.name, positions.decl),
|
||||
instances: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
for (target_name, edges) in index.instantiations() {
|
||||
for edge in edges {
|
||||
let owner = (edge.file, edge.owner.name_span.start, edge.owner.name_span.end);
|
||||
let Some(&owner_at) = module_at.get(&owner) else { continue };
|
||||
let Some(file) = files.of(index, edge.file) else { continue };
|
||||
for occurrence in &edge.instances {
|
||||
modules[owner_at].instances.push(Instance {
|
||||
instance_name: occurrence.name.clone(),
|
||||
module_name: target_name.to_string(),
|
||||
site: location(file, occurrence.name_positions, occurrence.positions),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `sort_by_cached_key`, not `sort_by`: both keys lowercase a name, and
|
||||
// paying for that once per element rather than twice per comparison is the
|
||||
// difference between a few and a few hundred thousand allocations on a
|
||||
// workspace with 14 000 instances in it.
|
||||
for module in &mut modules {
|
||||
module.instances.sort_by_cached_key(|instance| instance_key(&files, instance));
|
||||
}
|
||||
modules.sort_by_cached_key(|module| module_key(&files, module));
|
||||
|
||||
Snapshot { schema_version: SCHEMA_VERSION, revision, complete, files: files.uris, modules }
|
||||
}
|
||||
|
||||
/// The snapshot's file table: one URI per file, given an index the first time
|
||||
/// a location needs it.
|
||||
#[derive(Default)]
|
||||
struct FileTable {
|
||||
uris: Vec<String>,
|
||||
at: HashMap<FileId, Option<u32>>,
|
||||
}
|
||||
|
||||
impl FileTable {
|
||||
/// This file's index, adding it if it is new. `None` for a path that is
|
||||
/// not a URI — the same answer every other feature gives for such a path,
|
||||
/// and it drops that file's rows rather than the whole snapshot.
|
||||
fn of(&mut self, index: &WorkspaceIndex, file: FileId) -> Option<u32> {
|
||||
if let Some(&known) = self.at.get(&file) {
|
||||
return known;
|
||||
}
|
||||
let found = index.path(file).and_then(path_to_uri).map(|uri| {
|
||||
self.uris.push(uri.as_str().to_string());
|
||||
self.uris.len() as u32 - 1
|
||||
});
|
||||
self.at.insert(file, found);
|
||||
found
|
||||
}
|
||||
|
||||
fn uri(&self, file: u32) -> &str {
|
||||
self.uris.get(file as usize).map_or("", |uri| uri.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// One location, built from ranges the index already holds.
|
||||
fn location(file: u32, selection: Utf16Range, whole: Utf16Range) -> Location {
|
||||
Location { file, range: range(whole), selection_range: range(selection) }
|
||||
}
|
||||
|
||||
fn range(range: Utf16Range) -> [u32; 4] {
|
||||
[range.start.line, range.start.character, range.end.line, range.end.character]
|
||||
}
|
||||
|
||||
fn module_key(files: &FileTable, module: &Module) -> (String, String, u32, u32) {
|
||||
(
|
||||
module.module_name.to_ascii_lowercase(),
|
||||
files.uri(module.definition.file).to_string(),
|
||||
module.definition.selection_range[0],
|
||||
module.definition.selection_range[1],
|
||||
)
|
||||
}
|
||||
|
||||
fn instance_key(files: &FileTable, instance: &Instance) -> (String, String, String, u32, u32) {
|
||||
(
|
||||
instance.instance_name.to_ascii_lowercase(),
|
||||
instance.module_name.to_ascii_lowercase(),
|
||||
files.uri(instance.site.file).to_string(),
|
||||
instance.site.selection_range[0],
|
||||
instance.site.selection_range[1],
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{json, Value};
|
||||
use std::path::PathBuf;
|
||||
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_design_hierarchy_{}_{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree(path)
|
||||
}
|
||||
|
||||
fn write(&self, name: &str, text: &str) {
|
||||
std::fs::write(self.0.join(name), text).expect("write fixture");
|
||||
}
|
||||
|
||||
fn workspace(&self) -> Workspace {
|
||||
let mut workspace = Workspace::default();
|
||||
workspace.open_whole_workspace(vec![self.0.clone()]);
|
||||
workspace
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn taken(workspace: &Workspace) -> Value {
|
||||
serde_json::to_value(snapshot(workspace, 7, true)).expect("serializes")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_is_flat_sorted_and_keeps_every_individual_instance() {
|
||||
let tree = Tree::new("flat");
|
||||
tree.write("leaf.sv", "module leaf; endmodule\n");
|
||||
tree.write("top.sv", "module top;\n leaf zed (), alpha ();\nendmodule\n");
|
||||
tree.write("tb.sv", "module TB; top dut (); missing u_missing (); endmodule\n");
|
||||
|
||||
let value = taken(&tree.workspace());
|
||||
assert_eq!(value["schemaVersion"], 2);
|
||||
assert_eq!(value["revision"], 7);
|
||||
assert_eq!(value["complete"], true);
|
||||
let modules = value["modules"].as_array().expect("modules");
|
||||
let names: Vec<&str> =
|
||||
modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect();
|
||||
assert_eq!(names, ["leaf", "TB", "top"], "case-insensitive alphabetical order");
|
||||
|
||||
let top = module(modules, "top");
|
||||
// `[startLine, startCharacter, endLine, endCharacter]`: the whole
|
||||
// module for `range`, its name alone for `selectionRange`.
|
||||
assert_eq!(top["definition"]["range"], json!([0, 0, 2, 9]));
|
||||
assert_eq!(top["definition"]["selectionRange"], json!([0, 7, 0, 10]));
|
||||
let instances = top["instances"].as_array().expect("instances");
|
||||
let names: Vec<&str> = instances
|
||||
.iter()
|
||||
.map(|instance| instance["instanceName"].as_str().expect("name"))
|
||||
.collect();
|
||||
assert_eq!(names, ["alpha", "zed"], "one statement became two sorted children");
|
||||
|
||||
let tb = module(modules, "TB");
|
||||
let missing = tb["instances"]
|
||||
.as_array()
|
||||
.expect("instances")
|
||||
.iter()
|
||||
.find(|instance| instance["instanceName"] == "u_missing")
|
||||
.expect("unresolved instance is still a row");
|
||||
// Nothing on the wire says "unresolved": the client asks its own module
|
||||
// table for `missing`, finds none, and that is the same answer.
|
||||
assert_eq!(missing["moduleName"], "missing");
|
||||
assert_eq!(missing["site"]["selectionRange"][0], 0);
|
||||
}
|
||||
|
||||
/// An interface is an instantiable unit, so it is a row of the sidebar
|
||||
/// and an interface instance is an ordinary child — exactly as both were
|
||||
/// when an interface was indexed as a `SymbolKind::Module`
|
||||
/// (`docs/features/interface-semantics/README.md`). The wire shape is
|
||||
/// unchanged: schema 2, the same fields, one more module row.
|
||||
#[test]
|
||||
fn an_interface_is_a_row_and_its_instance_a_child_like_any_other() {
|
||||
let tree = Tree::new("iface");
|
||||
tree.write("bus_if.sv", "interface bus_if;\nendinterface\n");
|
||||
tree.write("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n");
|
||||
|
||||
let value = taken(&tree.workspace());
|
||||
assert_eq!(value["schemaVersion"], 2);
|
||||
let modules = value["modules"].as_array().expect("modules");
|
||||
let names: Vec<&str> =
|
||||
modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect();
|
||||
assert_eq!(names, ["bus_if", "top"]);
|
||||
let instances = module(modules, "top")["instances"].as_array().expect("instances");
|
||||
assert_eq!(instances.len(), 1);
|
||||
assert_eq!(instances[0]["instanceName"], "u_bus");
|
||||
assert_eq!(instances[0]["moduleName"], "bus_if");
|
||||
}
|
||||
|
||||
/// The round's central claim, pinned the way `hover-line-index` pinned its
|
||||
/// own: delete every source file after indexing, and the answer is
|
||||
/// byte-identical, because no part of it comes from a file.
|
||||
#[test]
|
||||
fn a_snapshot_reads_no_files_at_all() {
|
||||
let tree = Tree::new("noreads");
|
||||
tree.write("leaf.sv", "module leaf; endmodule\n");
|
||||
tree.write("top.sv", "module top;\n leaf u_leaf ();\nendmodule\n");
|
||||
let workspace = tree.workspace();
|
||||
let before = taken(&workspace);
|
||||
assert_eq!(
|
||||
before["modules"].as_array().expect("modules").len(),
|
||||
2,
|
||||
"premise: both indexed"
|
||||
);
|
||||
|
||||
for name in ["leaf.sv", "top.sv"] {
|
||||
std::fs::remove_file(tree.0.join(name)).expect("delete");
|
||||
}
|
||||
assert_eq!(taken(&workspace), before, "the snapshot came from the index, not the disk");
|
||||
}
|
||||
|
||||
/// A URI appears once however many rows name it, and a range is four
|
||||
/// numbers — the two decisions that took the opentitan answer from 11.6 MB
|
||||
/// to under 2 MB.
|
||||
#[test]
|
||||
fn every_file_is_named_once_and_a_range_is_four_numbers() {
|
||||
let tree = Tree::new("filetable");
|
||||
tree.write("leaf.sv", "module leaf; endmodule\n");
|
||||
tree.write("top.sv", "module top;\n leaf a (), b (), c ();\nendmodule\n");
|
||||
|
||||
let value = taken(&tree.workspace());
|
||||
let files = value["files"].as_array().expect("files");
|
||||
assert_eq!(files.len(), 2, "one entry per file, not one per row: {files:#?}");
|
||||
let text = serde_json::to_string(&value).expect("serializes");
|
||||
for uri in files {
|
||||
let uri = uri.as_str().expect("a uri string");
|
||||
assert_eq!(text.matches(uri).count(), 1, "{uri} is written more than once");
|
||||
}
|
||||
let top = module(value["modules"].as_array().expect("modules"), "top");
|
||||
for instance in top["instances"].as_array().expect("instances") {
|
||||
assert!(instance["site"]["file"].is_number(), "a file index, not a URI");
|
||||
assert_eq!(instance["site"]["range"].as_array().expect("range").len(), 4);
|
||||
}
|
||||
}
|
||||
|
||||
/// Positions are the client's, not the index's: 0-based lines and UTF-16
|
||||
/// code units, so a two-byte character before a name still counts one.
|
||||
#[test]
|
||||
fn positions_are_zero_based_utf16_even_through_multibyte_text() {
|
||||
let tree = Tree::new("utf16");
|
||||
// `🎉` is four UTF-8 bytes and two UTF-16 units, so every column after
|
||||
// it on that line differs from the byte column the index records.
|
||||
tree.write("m.sv", "module top;\n /*\u{1F389}*/ sub u_x ();\nendmodule\n");
|
||||
|
||||
let value = taken(&tree.workspace());
|
||||
let top = module(value["modules"].as_array().expect("modules"), "top");
|
||||
assert_eq!(
|
||||
top["definition"]["selectionRange"],
|
||||
json!([0, 7, 0, 10]),
|
||||
"line 0 counting from 0, `top` at character 7"
|
||||
);
|
||||
let instance = &top["instances"].as_array().expect("instances")[0];
|
||||
assert_eq!(instance["instanceName"], "u_x");
|
||||
assert_eq!(instance["site"]["selectionRange"], json!([1, 13, 1, 16]));
|
||||
assert_eq!(instance["site"]["range"], json!([1, 13, 1, 19]));
|
||||
}
|
||||
|
||||
/// **The one property the whole zero-I/O trick rests on**: a position the
|
||||
/// index recorded while a file was scanned is the position `convert` would
|
||||
/// have produced from that file's text on the wire. The two answers come
|
||||
/// from one function on `LineIndex`, and this is what says so out loud —
|
||||
/// over the shapes that break naive conversions.
|
||||
#[test]
|
||||
fn an_indexed_position_is_the_position_the_wire_converter_would_have_given() {
|
||||
let sources = [
|
||||
"module plain;\n sub u ();\nendmodule\n",
|
||||
// A CRLF file: `\r` is a byte of its line but not of its content.
|
||||
"module crlf;\r\n sub u_crlf ();\r\nendmodule\r\n",
|
||||
// Two, three and four byte characters ahead of the names.
|
||||
"// \u{e9}\u{2713}\u{1F389}\nmodule wide;\n /*\u{1F389}*/ sub u_wide ();\nendmodule\n",
|
||||
// A name on the last line, with no trailing newline at all.
|
||||
"module tail;\n sub u_tail ();\nendmodule",
|
||||
// Two instances in one statement, and an attribute before `module`.
|
||||
"(* keep *) module many;\n sub a (), b ();\nendmodule\n",
|
||||
// CRLF and bare LF mixed in one file: the `\r`-stripping rule must
|
||||
// apply per line, not once for the whole file.
|
||||
"module mixed;\r\n sub u_a ();\n sub u_b ();\r\nendmodule\n",
|
||||
// The instance on the very same line as the module header, so the
|
||||
// name and the instance share a line's worth of UTF-16 columns.
|
||||
"module oneline; sub u_same ();\nendmodule\n",
|
||||
];
|
||||
let tree = Tree::new("agreement");
|
||||
let mut texts = Vec::new();
|
||||
for (at, source) in sources.iter().enumerate() {
|
||||
tree.write(&format!("f{at}.sv"), source);
|
||||
texts.push((tree.0.join(format!("f{at}.sv")), *source));
|
||||
}
|
||||
let workspace = tree.workspace();
|
||||
let index = workspace.index();
|
||||
|
||||
let mut checked = 0usize;
|
||||
for (path, text) in &texts {
|
||||
let lines = vlog_parser::LineIndex::new(text);
|
||||
let positions = crate::convert::Positions::new(text, &lines);
|
||||
let file = index.file_id(path).expect("the file is indexed");
|
||||
for (_, def) in index.instantiable_units() {
|
||||
if def.file != file {
|
||||
continue;
|
||||
}
|
||||
let recorded = def.lines.positions.expect("a unit carries positions");
|
||||
assert_eq!(range(recorded.name), as_four(positions.range(def.name_span)));
|
||||
assert_eq!(range(recorded.decl), as_four(positions.range(def.decl_span)));
|
||||
checked += 1;
|
||||
}
|
||||
for (_, edges) in index.instantiations() {
|
||||
for edge in edges.iter().filter(|edge| edge.file == file) {
|
||||
for occurrence in &edge.instances {
|
||||
assert_eq!(
|
||||
range(occurrence.name_positions),
|
||||
as_four(positions.range(occurrence.name_span))
|
||||
);
|
||||
assert_eq!(
|
||||
range(occurrence.positions),
|
||||
as_four(positions.range(occurrence.span))
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked >= 16, "premise: every fixture contributed rows, got {checked}");
|
||||
}
|
||||
|
||||
/// QA (2026-08-29): two files declaring the same module name must each
|
||||
/// keep their own row, their own instances, and never merge — the wire's
|
||||
/// only handle on a module is `(file, definition range)`, exactly as an
|
||||
/// ambiguous type is meant to look on the client.
|
||||
#[test]
|
||||
fn duplicate_module_names_across_files_stay_two_distinct_rows() {
|
||||
let tree = Tree::new("duplicate");
|
||||
tree.write("a.sv", "module dup;\n sub u_in_a ();\nendmodule\n");
|
||||
tree.write("b.sv", "module dup;\n sub u_in_b ();\nendmodule\n");
|
||||
tree.write("sub.sv", "module sub; endmodule\n");
|
||||
|
||||
let value = taken(&tree.workspace());
|
||||
let modules = value["modules"].as_array().expect("modules");
|
||||
let dups: Vec<&Value> =
|
||||
modules.iter().filter(|module| module["moduleName"] == "dup").collect();
|
||||
assert_eq!(dups.len(), 2, "one row per declaration, not one merged row: {dups:#?}");
|
||||
assert_ne!(
|
||||
dups[0]["definition"]["file"], dups[1]["definition"]["file"],
|
||||
"the only thing distinguishing them is which file",
|
||||
);
|
||||
let mut instance_names: Vec<&str> = dups
|
||||
.iter()
|
||||
.flat_map(|module| module["instances"].as_array().expect("instances"))
|
||||
.map(|instance| instance["instanceName"].as_str().expect("name"))
|
||||
.collect();
|
||||
instance_names.sort_unstable();
|
||||
assert_eq!(
|
||||
instance_names,
|
||||
["u_in_a", "u_in_b"],
|
||||
"each declaration keeps only the instances its own body writes",
|
||||
);
|
||||
}
|
||||
|
||||
/// QA (2026-08-29): an escaped Verilog identifier (`\foo$bar `, terminated
|
||||
/// by whitespace, the space itself not part of the name) is as ordinary a
|
||||
/// module or instance name as any other — the wire and the position
|
||||
/// conversion must not choke on the backslash or the trailing space.
|
||||
#[test]
|
||||
fn an_escaped_identifier_names_a_module_and_an_instance() {
|
||||
let tree = Tree::new("escaped");
|
||||
tree.write(
|
||||
"m.sv",
|
||||
"module \\weird$leaf ;\nendmodule\n\
|
||||
module top;\n \\weird$leaf \\u$inst ();\nendmodule\n",
|
||||
);
|
||||
|
||||
let value = taken(&tree.workspace());
|
||||
let modules = value["modules"].as_array().expect("modules");
|
||||
let leaf = module(modules, "\\weird$leaf");
|
||||
assert_eq!(leaf["instances"].as_array().expect("instances").len(), 0);
|
||||
let top = module(modules, "top");
|
||||
let instances = top["instances"].as_array().expect("instances");
|
||||
assert_eq!(instances.len(), 1);
|
||||
assert_eq!(instances[0]["instanceName"], "\\u$inst");
|
||||
assert_eq!(instances[0]["moduleName"], "\\weird$leaf");
|
||||
}
|
||||
|
||||
/// QA (2026-08-29): a module instantiated 100 times in one statement list
|
||||
/// produces 100 individual, individually sorted instance rows — the
|
||||
/// flattening the sidebar exists for, at a scale one instance would not
|
||||
/// exercise.
|
||||
#[test]
|
||||
fn one_hundred_instances_of_one_module_are_one_hundred_sorted_rows() {
|
||||
let tree = Tree::new("manyinstances");
|
||||
tree.write("leaf.sv", "module leaf; endmodule\n");
|
||||
let instances: Vec<String> = (0..100).map(|n| format!("u_{n:03} ()", n = n)).collect();
|
||||
tree.write(
|
||||
"top.sv",
|
||||
&format!("module top;\n leaf {};\nendmodule\n", instances.join(", ")),
|
||||
);
|
||||
|
||||
let value = taken(&tree.workspace());
|
||||
let top = module(value["modules"].as_array().expect("modules"), "top");
|
||||
let instances = top["instances"].as_array().expect("instances");
|
||||
assert_eq!(instances.len(), 100, "every one of the 100 instances is its own row");
|
||||
let names: Vec<&str> = instances
|
||||
.iter()
|
||||
.map(|instance| instance["instanceName"].as_str().expect("name"))
|
||||
.collect();
|
||||
let mut sorted = names.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(names, sorted, "sorted by instance name, as every module's instances are");
|
||||
assert!(instances.iter().all(|instance| instance["moduleName"] == "leaf"));
|
||||
}
|
||||
|
||||
fn as_four(range: lsp_types::Range) -> [u32; 4] {
|
||||
[range.start.line, range.start.character, range.end.line, range.end.character]
|
||||
}
|
||||
|
||||
fn module<'a>(modules: &'a [Value], name: &str) -> &'a Value {
|
||||
modules
|
||||
.iter()
|
||||
.find(|module| module["moduleName"] == name)
|
||||
.unwrap_or_else(|| panic!("no module {name}: {modules:#?}"))
|
||||
}
|
||||
}
|
||||
@@ -105,10 +105,15 @@ pub struct Rewrite {
|
||||
/// Rewrite every `` `include`` in the workspace that resolves to a file the
|
||||
/// client is about to rename.
|
||||
///
|
||||
/// The sweep reads the in-scope files (`Workspace::sources`, so an unopened
|
||||
/// file is read off disk and an open buffer contributes its unsaved text), and
|
||||
/// asks the include graph — never the filename — which of them point at
|
||||
/// something that moves.
|
||||
/// The sweep reads the files the include graph recorded an `` `include`` in
|
||||
/// (`Workspace::include_sources`, so an unopened one is read off disk and an
|
||||
/// open buffer contributes its unsaved text), and asks the include graph —
|
||||
/// never the filename — which of them point at something that moves.
|
||||
///
|
||||
/// It used to read *every* in-scope file, which on a 3 976-file workspace is
|
||||
/// 3 900-odd reads to answer "this file has no `` `include``". The graph
|
||||
/// already holds that answer; the argument that the smaller set gives the
|
||||
/// identical `Rewrite` is in `docs/features/file-operations/README.md`.
|
||||
pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
|
||||
let moves = Moves::announced(files);
|
||||
if moves.0.is_empty() {
|
||||
@@ -117,7 +122,7 @@ pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
|
||||
let graph = ws.includes();
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
let mut warnings = Vec::new();
|
||||
for (path, text) in ws.sources() {
|
||||
for (path, text) in ws.include_sources() {
|
||||
// The overwhelming majority of files include nothing; one substring
|
||||
// test each is what keeps this off the resolver for all of them.
|
||||
if !text.contains("`include") {
|
||||
@@ -542,6 +547,35 @@ mod tests {
|
||||
path_to_uri(path).expect("uri").as_str().to_string()
|
||||
}
|
||||
|
||||
/// The sufficiency property [`will_rename`]'s narrowed sweep rests on,
|
||||
/// asserted directly over whatever tree the caller built: every in-scope
|
||||
/// file the sweep no longer reads writes no `` `include`` this workspace
|
||||
/// can resolve, so its turn in the loop could only ever have `continue`d.
|
||||
///
|
||||
/// Checked as the complement rather than as an equality because it is the
|
||||
/// complement that could hide a lost edit: an extra file in the set costs
|
||||
/// a read, a missing one costs an `` `include`` left pointing at nothing.
|
||||
fn nothing_skipped_has_an_include_to_rewrite(ws: &Workspace) {
|
||||
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
|
||||
let graph = ws.includes();
|
||||
let mut skipped = 0usize;
|
||||
for (path, text) in ws.sources() {
|
||||
if read.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
skipped += 1;
|
||||
for include in scan(&text) {
|
||||
assert!(
|
||||
graph.resolve(Some(&path), &include).is_none(),
|
||||
"{} was skipped but its `include \"{}\"` resolves",
|
||||
path.display(),
|
||||
include.target
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(skipped > 0, "the tree must actually exercise the narrowing");
|
||||
}
|
||||
|
||||
/// The one file the rewrite touches, as (uri, the new path spellings).
|
||||
fn only_file(rewrite: &Rewrite) -> (String, Vec<String>) {
|
||||
let edit = rewrite.edit.as_ref().expect("an edit");
|
||||
@@ -579,6 +613,120 @@ mod tests {
|
||||
out
|
||||
}
|
||||
|
||||
/// A wide workspace where almost nothing includes anything — the shape a
|
||||
/// real one has, and the reason the sweep no longer reads all of it. The
|
||||
/// answer must be the one the whole-workspace sweep gave, and the property
|
||||
/// above must hold over the same tree.
|
||||
#[test]
|
||||
fn the_narrowed_sweep_reads_the_includers_and_answers_the_same() {
|
||||
let tree = Tree::new("narrowed");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
|
||||
let mut list = String::from("rtl/top.sv\nrtl/defs.svh\n");
|
||||
// Twenty files with no `include at all, plus two whose includes name
|
||||
// nothing on disk — both kinds are files the sweep may skip.
|
||||
for n in 0..20 {
|
||||
let rel = format!("rtl/quiet{n}.sv");
|
||||
tree.write(&rel, &format!("module quiet{n};\n wire w;\nendmodule\n"));
|
||||
list.push_str(&format!("{rel}\n"));
|
||||
}
|
||||
for n in 0..2 {
|
||||
let rel = format!("rtl/dangling{n}.sv");
|
||||
tree.write(&rel, &format!("`include \"no_such_{n}.svh\"\nmodule d{n};\nendmodule\n"));
|
||||
list.push_str(&format!("{rel}\n"));
|
||||
}
|
||||
tree.write("files.f", &list);
|
||||
let ws = tree.workspace();
|
||||
|
||||
assert_eq!(ws.sources().len(), 24, "the whole scope");
|
||||
assert_eq!(ws.include_sources().len(), 1, "only `top.sv` includes anything that lands");
|
||||
nothing_skipped_has_an_include_to_rewrite(&ws);
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
|
||||
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
|
||||
}
|
||||
|
||||
/// An `` `include`` typed into a buffer and not yet saved is in no edge the
|
||||
/// graph holds — the graph is rebuilt on save. The buffer is in the sweep
|
||||
/// whatever the graph says, which is what keeps that include rewritten.
|
||||
#[test]
|
||||
fn an_unsaved_include_is_still_rewritten() {
|
||||
let tree = Tree::new("unsaved_include");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
let top = tree.write("rtl/top.sv", "module t;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
|
||||
let mut ws = tree.workspace();
|
||||
assert_eq!(ws.include_sources().len(), 0, "premise: the graph knows of no include");
|
||||
|
||||
let buffered = "`include \"defs.svh\"\nmodule t;\nendmodule\n";
|
||||
ws.set_document(path_to_uri(&top).expect("uri"), buffered.to_string());
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
|
||||
assert_eq!(
|
||||
applied(buffered, &rewrite, &uri_of(&top)),
|
||||
"`include \"widths.svh\"\nmodule t;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// QA, 2026-08-28 attack: a chain `a.svh -> b.svh`. Renaming `b.svh` must
|
||||
/// narrow to `a.svh` (its *direct* includer, via `includers()`), and must
|
||||
/// **not** narrow away a file that includes `a.svh` but never spells
|
||||
/// `b.svh` at all — `will_rename` only ever rewrites a *direct* include of
|
||||
/// the file that moves, so a third-order includer has nothing to rewrite
|
||||
/// either way, but it must still not be mistaken for a candidate (which
|
||||
/// would cost a read, not a corruption, but is worth pinning).
|
||||
#[test]
|
||||
fn an_include_chain_narrows_to_the_direct_includer_of_the_moved_file() {
|
||||
let tree = Tree::new("chain");
|
||||
tree.write("rtl/b.svh", "`define W 8\n");
|
||||
let a = tree.write("rtl/a.svh", "`include \"b.svh\"\n");
|
||||
let c = tree.write("rtl/c.sv", "`include \"a.svh\"\nmodule c;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/a.svh\nrtl/b.svh\nrtl/c.sv\n");
|
||||
let ws = tree.workspace();
|
||||
|
||||
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
|
||||
assert!(read.contains(&a), "a.svh includes b.svh directly: {read:?}");
|
||||
assert!(read.contains(&c), "c.sv includes a.svh directly: {read:?}");
|
||||
nothing_skipped_has_an_include_to_rewrite(&ws);
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/b.svh", "rtl/renamed_b.svh")]);
|
||||
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
|
||||
// Only a.svh's own `include \"b.svh\"` line changes; c.sv's
|
||||
// `include \"a.svh\"` is untouched because a.svh itself did not move.
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&a), vec!["renamed_b.svh".to_string()]));
|
||||
}
|
||||
|
||||
/// QA, 2026-08-28 attack: an include spelled with different letter case
|
||||
/// than the file actually has on disk (`` `include "DEFS.svh"`` against a
|
||||
/// real `defs.svh`) — legal and silently resolved on the common
|
||||
/// case-insensitive filesystems (confirmed case-insensitive in this test
|
||||
/// environment). `IncludeGraph::found`/`found_as_if` resolve through the
|
||||
/// filesystem's own `Path::is_file`, so the includer still lands in `raw`
|
||||
/// (keyed by the *includer's* path, not the target's spelling) and
|
||||
/// therefore in `includers()`/`include_sources()` — the narrowing must not
|
||||
/// accidentally depend on the include's target spelling matching the
|
||||
/// disk's.
|
||||
#[test]
|
||||
fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() {
|
||||
let tree = Tree::new("case_mismatch");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
|
||||
let ws = tree.workspace();
|
||||
|
||||
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
|
||||
assert!(
|
||||
read.contains(&top),
|
||||
"top.sv's case-mismatched include still resolves and must narrow in: {read:?}"
|
||||
);
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
|
||||
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_directory_rename_keeps_the_bare_form() {
|
||||
let tree = Tree::new("samedir");
|
||||
|
||||
@@ -22,7 +22,6 @@ use lsp_types::{
|
||||
};
|
||||
use vlog_parser::ast::Item;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
|
||||
use vlog_semantic::SymbolKind as SemanticKind;
|
||||
|
||||
use vlog_semantic::instantiations::{self, Decl};
|
||||
use vlog_semantic::{DeclSite, InstantiationEdge};
|
||||
@@ -231,7 +230,7 @@ fn declarations_of(ws: &Workspace, name: &str) -> Vec<CallHierarchyItem> {
|
||||
ws.index()
|
||||
.units(name)
|
||||
.iter()
|
||||
.filter(|def| def.kind == SemanticKind::Module)
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.filter_map(|def| {
|
||||
let path = ws.index().path(def.file)?;
|
||||
item_in_file(ws, path, name, Some(def.name_span))
|
||||
@@ -407,6 +406,19 @@ endmodule
|
||||
assert_eq!(items[0].range.end.line, 1, "through `endmodule`");
|
||||
}
|
||||
|
||||
/// An interface is instantiated exactly as a module is, so the call
|
||||
/// hierarchy still finds its declaration from an instantiation site
|
||||
/// (`docs/features/interface-semantics/README.md`).
|
||||
#[test]
|
||||
fn the_cursor_on_an_interface_instantiation_prepares_the_interface() {
|
||||
const IFACE: &str = "interface bus_if;\nendinterface\n";
|
||||
const USER: &str = "module top;\n bus_if u_bus ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("ifaceprepare", &[("top.sv", USER), ("bus_if.sv", IFACE)]);
|
||||
let items = prepare(&ws, &uri, at(USER, "bus_if")).expect("the interface");
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(shape(&items[0]), ("bus_if".to_string(), "bus_if.sv".to_string(), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_on_an_instantiation_prepares_the_module_it_names() {
|
||||
let (_tree, ws, uri) = three("inst");
|
||||
|
||||
@@ -179,11 +179,6 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
// `declaration_snippet` checks the other file's text against.
|
||||
let name = doc.semantics.reference_at(offset).map(|r| r.name.as_str());
|
||||
let mut parts = Vec::with_capacity(defs.len());
|
||||
// One read per *file*, not per card: a closed file's heading line
|
||||
// and its snippet below both come from this memoized view, and a
|
||||
// hover can name the same file several times (two modules with
|
||||
// one name, a package and its member).
|
||||
let mut disk: Option<(std::path::PathBuf, String, LineIndex)> = None;
|
||||
for def in defs {
|
||||
let label = kind_label(def.kind);
|
||||
let path = ws.index().path(def.file).map(|p| p.to_path_buf());
|
||||
@@ -192,28 +187,34 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
if let Some(path) = path.as_ref() {
|
||||
if ws.document_for_path(path).is_some() {
|
||||
// The live path reads the open buffer — `live_symbol`
|
||||
// resolves the current span, and its guards stay.
|
||||
// resolves the current span, and its guards stay. The
|
||||
// line comes from that buffer's own index rather than
|
||||
// from `def.lines`, because the buffer may hold
|
||||
// unsaved edits the index has not seen.
|
||||
where_ = line_number(ws, path, def.name_span.start)
|
||||
.map(|line| format!("{}:{line}", display_name(path)));
|
||||
snippet = name.and_then(|name| declaration_snippet(ws, def, name));
|
||||
} else if let Some((text, index)) = disk_view(ws, path, &mut disk) {
|
||||
// The disk path: the same read serves the heading and
|
||||
// the snippet, under the same `spells_exactly` guard
|
||||
// `declaration_snippet` applies.
|
||||
where_ = Some(format!(
|
||||
"{}:{}",
|
||||
display_name(path),
|
||||
index.line_col(def.name_span.start).0
|
||||
));
|
||||
snippet = name.and_then(|name| {
|
||||
spells_exactly(text, def.name_span, name)
|
||||
} else {
|
||||
// The heading costs nothing: the line was recorded
|
||||
// when the file was indexed, from the same text the
|
||||
// span came from (`vlog_semantic::DeclLines`). Only
|
||||
// the snippet still wants the file's text, and that
|
||||
// comes from the workspace's shared view — one read
|
||||
// per file per generation, so a card naming one file
|
||||
// twice, and the next hover into it, are both free.
|
||||
where_ = Some(format!("{}:{}", display_name(path), def.lines.name));
|
||||
snippet = name.zip(ws.file_view(path)).and_then(|(name, view)| {
|
||||
spells_exactly(&view.text, def.name_span, name)
|
||||
.then(|| {
|
||||
fenced_sections(text, index, def.name_span, def.detail_span)
|
||||
fenced_sections(
|
||||
&view.text,
|
||||
&view.lines,
|
||||
def.name_span,
|
||||
def.detail_span,
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
});
|
||||
} else {
|
||||
where_ = Some(display_name(path));
|
||||
}
|
||||
}
|
||||
let where_ = where_.unwrap_or_else(|| "the workspace".to_string());
|
||||
@@ -385,11 +386,11 @@ const SNIPPET_CHARS: usize = 400;
|
||||
|
||||
/// The source of a declaration in an **open** buffer, fenced for the card.
|
||||
///
|
||||
/// The index holds only `{file, name_span, kind}` and no text
|
||||
/// (`docs/features/workspace-index/README.md`), so the line is fetched here,
|
||||
/// at hover time, from whichever text the span is actually valid against.
|
||||
/// A closed file is read by the caller's `disk_view` memo instead — one read
|
||||
/// per hover — so this function never touches the disk.
|
||||
/// The index holds spans, kinds and lines but no text
|
||||
/// (`docs/features/workspace-index/README.md`), so the *source* is fetched
|
||||
/// here, at hover time, from whichever text the span is actually valid
|
||||
/// against. A closed file is served by `Workspace::file_view` in the caller
|
||||
/// instead, so this function never touches the disk.
|
||||
///
|
||||
/// `None` — no snippet, today's card unchanged — wherever the two could
|
||||
/// disagree: the span the live buffer does not cover, or a span covering
|
||||
@@ -414,23 +415,6 @@ fn declaration_snippet(ws: &Workspace, def: &Def, name: &str) -> Option<String>
|
||||
)
|
||||
}
|
||||
|
||||
/// One closed file, read once per hover: the memo `symbol_hover` keys the
|
||||
/// heading line and the snippet off, so a card never pays for the same file
|
||||
/// twice. `None` for an unreadable file, which the caller renders as a bare
|
||||
/// heading — exactly the card it always showed.
|
||||
fn disk_view<'a>(
|
||||
ws: &Workspace,
|
||||
path: &std::path::Path,
|
||||
memo: &'a mut Option<(std::path::PathBuf, String, LineIndex)>,
|
||||
) -> Option<(&'a str, &'a LineIndex)> {
|
||||
if !memo.as_ref().is_some_and(|held| held.0 == path) {
|
||||
let text = ws.text_of(path)?;
|
||||
let index = LineIndex::new(&text);
|
||||
*memo = Some((path.to_path_buf(), text, index));
|
||||
}
|
||||
memo.as_ref().map(|(_, text, index)| (text.as_str(), index))
|
||||
}
|
||||
|
||||
/// The live symbol in an open buffer that *is* this indexed declaration.
|
||||
///
|
||||
/// Only the declarations spelling `name` are probed — `indexed_def_for_symbol`
|
||||
@@ -1201,6 +1185,92 @@ endmodule
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read() {
|
||||
// The round's central claim: `file:line` for an indexed declaration is
|
||||
// `Def::lines`, recorded when the file was scanned, so the heading
|
||||
// costs no read at all. Proved by removing the file from under the
|
||||
// index — a heading that still names the line cannot have read it.
|
||||
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
|
||||
let (dir, ws, uri) = included("headingfromindex", &[("sub.sv", PORTS), ("top.sv", top)]);
|
||||
fs::remove_file(dir.join("sub.sv")).expect("remove");
|
||||
|
||||
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
|
||||
assert!(body.contains("**port** — declared in `sub.sv:2`"), "got {body}");
|
||||
// The snippet is the half that really wanted the text, and it is
|
||||
// dropped rather than guessed at — exactly as it always was for a
|
||||
// file that cannot be read.
|
||||
assert!(!body.contains("```systemverilog"), "no snippet without text: got {body}");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_hover_into_one_closed_file_reads_nothing() {
|
||||
// The other half: the snippet's read is shared through
|
||||
// `Workspace::file_view`, so the file is read once and the next hover
|
||||
// into it — the same card, or another name in the same file — is
|
||||
// served from what that read left behind. Observed the only honest
|
||||
// way: rewrite the file behind the server's back and require the
|
||||
// second card to be the first one. Stale text can only ever *omit* a
|
||||
// snippet (the `spells_exactly` guard), never show a wrong line.
|
||||
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
|
||||
let (dir, ws, uri) = included("viewshared", &[("sub.sv", PORTS), ("top.sv", top)]);
|
||||
let first = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
|
||||
assert!(first.contains("input logic [7:0] addr"), "premise: got {first}");
|
||||
|
||||
fs::write(dir.join("sub.sv"), "module sub (\n input logic [15:0] addr\n);\nendmodule\n")
|
||||
.expect("write");
|
||||
let second = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
|
||||
assert_eq!(second, first, "the second hover did not read the file again");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): the staleness window the README's Assumptions section
|
||||
/// claims — "a line is a fact about the same snapshot the span is... where
|
||||
/// the file has changed on disk with nothing telling the server, both are
|
||||
/// stale together" — reproduced rather than taken on faith, and in the
|
||||
/// one shape that could actually disagree: the index was built from the
|
||||
/// *original* `sub.sv`, but `sub.sv` is rewritten on disk — no `didSave`,
|
||||
/// no watcher event, no `update_one`/`rebuild_index` call, so the index is
|
||||
/// never told — **before the view cache ever reads it**, so the first
|
||||
/// hover's disk read sees the *new* bytes under the *old* span and offset.
|
||||
/// The heading must still show the line the index recorded at the last
|
||||
/// scan (stale, not a fresh-read line the index never computed), and the
|
||||
/// snippet, reading the genuinely current text, must find the old span no
|
||||
/// longer spells `addr` there and drop itself via `spells_exactly` rather
|
||||
/// than show whatever now sits at that byte range.
|
||||
#[test]
|
||||
fn an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet() {
|
||||
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
|
||||
let (dir, ws, uri) = included("staleheading", &[("sub.sv", PORTS), ("top.sv", top)]);
|
||||
|
||||
// Edited behind the server's back, before any hover has read this
|
||||
// file at all: four lines inserted above the module, so `addr`'s true
|
||||
// line is now 6 — and the byte offset the index still holds for it
|
||||
// (from the *original* `sub.sv`) now lands inside a comment, not
|
||||
// `addr`. The view cache is empty for this path, so the hover below
|
||||
// is a genuinely fresh disk read of the edited bytes.
|
||||
fs::write(
|
||||
dir.join("sub.sv"),
|
||||
"// one\n// two\n// three\n// four\nmodule sub (\n input logic [7:0] addr,\n\
|
||||
\x20 output logic ready\n);\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let after = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
|
||||
assert!(
|
||||
after.contains("**port** — declared in `sub.sv:2`"),
|
||||
"the heading must show the line the index recorded, not the file's true current \
|
||||
line (6), until something reindexes it: got {after}"
|
||||
);
|
||||
assert!(
|
||||
!after.contains("```systemverilog"),
|
||||
"the snippet must be dropped, not show the comment the stale span now lands on: \
|
||||
got {after}"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_member_shows_its_declaration_line() {
|
||||
let pkg =
|
||||
@@ -1737,15 +1807,18 @@ mod qa_hover_declarations {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Angle 7 (perf smell): a hover resolving into a large *closed* file
|
||||
/// reads the whole file from disk and builds a fresh `LineIndex` over it.
|
||||
/// Before the per-hover `disk_view` memo this happened **twice** — once
|
||||
/// inside `locate::line_number` for the heading and once for the snippet —
|
||||
/// and the memo's whole reason to exist is that it is now once. Not a
|
||||
/// Angle 7 (perf smell): the **first** hover resolving into a large
|
||||
/// *closed* file reads the whole file from disk and builds a fresh
|
||||
/// `LineIndex` over it. It once did that twice — heading and snippet
|
||||
/// independently — then once, through a per-hover memo, and since
|
||||
/// `hover-line-index` (2026-08-28) it does it once *per file per
|
||||
/// generation of that file*: the heading no longer wants any text at all
|
||||
/// (`Def::lines`), and the snippet's read is held in
|
||||
/// `Workspace::file_view` for the next hover. So this number is the first
|
||||
/// touch, which is the one that still costs; the repeat is measured in
|
||||
/// `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`. Not a
|
||||
/// correctness assertion, just the number; run with `cargo test --release
|
||||
/// -p lucisv_server large_closed -- --ignored --nocapture` to see it. The
|
||||
/// same read, measured against the hover it serves, is in
|
||||
/// `perf::hovering_across_files_into_a_closed_file`.
|
||||
/// -p lucisv_server large_closed -- --ignored --nocapture` to see it.
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see QA log"]
|
||||
fn hovering_into_a_large_closed_file_reads_it_once() {
|
||||
@@ -1776,10 +1849,15 @@ mod qa_hover_declarations {
|
||||
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
|
||||
let elapsed = start.elapsed();
|
||||
assert!(body.contains("[7:0] addr"), "got {body}");
|
||||
let start = std::time::Instant::now();
|
||||
let _ = hover(&ws, &uri, at(top, "addr(8")).expect("hover");
|
||||
let again = start.elapsed();
|
||||
eprintln!(
|
||||
"hover into a {:.1} MB closed file took {:?} (one read + one LineIndex, shared by heading and snippet)",
|
||||
"hover into a {:.1} MB closed file took {:?} the first time (one read + one \
|
||||
LineIndex, for the snippet alone) and {:?} the second (nothing read)",
|
||||
sub.len() as f64 / 1_000_000.0,
|
||||
elapsed
|
||||
elapsed,
|
||||
again
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -92,8 +92,21 @@ pub struct IncludeGraph {
|
||||
/// The `+incdir+` directories of the configured filelist, in filelist
|
||||
/// order. Empty when no filelist governs the workspace.
|
||||
incdirs: Vec<PathBuf>,
|
||||
/// Including file → the files it resolves to, in source order.
|
||||
/// Including file → the files it resolves to, in source order, spelled the
|
||||
/// way the index spells them. Derived from `raw` by [`IncludeGraph::respell`]
|
||||
/// and never written to directly.
|
||||
edges: HashMap<PathBuf, Vec<PathBuf>>,
|
||||
/// The same edges as the *filesystem* answered them: normalized, but
|
||||
/// before [`IncludeGraph::as_the_index_spells_it`] re-spells them against
|
||||
/// the in-scope file list.
|
||||
///
|
||||
/// Kept because which file an `` `include`` lands on is a question for the
|
||||
/// disk and which *spelling* that file has is a question for the scope, and
|
||||
/// only the second one moves when the scope grows. Holding the first means
|
||||
/// a scope widen can re-spell every edge it already had without re-reading
|
||||
/// a single file — which is what makes an incrementally widened graph
|
||||
/// byte-identical to a rebuilt one (`docs/features/index-scope/README.md`).
|
||||
raw: HashMap<PathBuf, Vec<PathBuf>>,
|
||||
/// Every in-scope file, exactly as the index spells it.
|
||||
known: HashSet<PathBuf>,
|
||||
/// Lower-cased spelling → the one in-scope file that has it, or `None`
|
||||
@@ -110,14 +123,9 @@ impl IncludeGraph {
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
|
||||
graph.relearn(&paths);
|
||||
for (path, text) in sources {
|
||||
let targets: Vec<PathBuf> = scan(text)
|
||||
.iter()
|
||||
.filter_map(|include| graph.resolve(Some(path), include))
|
||||
.collect();
|
||||
if !targets.is_empty() {
|
||||
graph.edges.insert(path.clone(), targets);
|
||||
}
|
||||
graph.rescan_edges(path, text);
|
||||
}
|
||||
graph.respell();
|
||||
graph
|
||||
}
|
||||
|
||||
@@ -130,25 +138,79 @@ impl IncludeGraph {
|
||||
///
|
||||
/// One honest limit, and the reason the incremental path in `state.rs`
|
||||
/// takes it only for a file that already existed: an edge of a *different*
|
||||
/// file is not re-resolved. So a file appearing or vanishing does not
|
||||
/// change whether some other file's `` `include "x.svh"`` resolves until
|
||||
/// the next whole rebuild. For the case this is used in — one file's text
|
||||
/// changed, the file set did not — there is nothing stale at all.
|
||||
/// file is not re-**resolved** against the disk. So a file appearing or
|
||||
/// vanishing on disk does not change whether some other file's
|
||||
/// `` `include "x.svh"`` finds anything until the next whole rebuild. Every
|
||||
/// held edge *is* re-spelled against the new file list, because that half
|
||||
/// costs no filesystem call — see [`IncludeGraph::respell`]. For the case
|
||||
/// this is used in — one file's text changed, the file set did not — there
|
||||
/// is nothing stale at all.
|
||||
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
|
||||
self.relearn(known);
|
||||
let targets: Vec<PathBuf> =
|
||||
scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect();
|
||||
match targets.is_empty() {
|
||||
true => self.edges.remove(path),
|
||||
false => self.edges.insert(path.to_path_buf(), targets),
|
||||
};
|
||||
self.rescan_edges(path, text);
|
||||
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.
|
||||
///
|
||||
/// `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
|
||||
/// the first publish: which files *exist* is settled the moment the scope
|
||||
/// is resolved, and only the edges are discovered file by file. One
|
||||
/// `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)]) {
|
||||
self.incdirs = incdirs.to_vec();
|
||||
self.relearn(known);
|
||||
for (path, text) in batch {
|
||||
self.rescan_edges(path, text);
|
||||
}
|
||||
self.respell();
|
||||
}
|
||||
|
||||
/// Drop one file from the graph: its own edges, and its place among the
|
||||
/// known files.
|
||||
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
|
||||
self.relearn(known);
|
||||
self.edges.remove(path);
|
||||
self.raw.remove(path);
|
||||
self.respell();
|
||||
}
|
||||
|
||||
/// Read one file's `` `include``s off its text and hold where the disk says
|
||||
/// 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) {
|
||||
let targets: Vec<PathBuf> =
|
||||
scan(text).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),
|
||||
};
|
||||
}
|
||||
|
||||
/// Re-derive every edge's spelling from the file list learned last.
|
||||
///
|
||||
/// The cheap half of resolving an include: which file it lands on was
|
||||
/// settled by the filesystem when the edge was read, and only how the index
|
||||
/// spells that file depends on which files are in scope. So a scope that
|
||||
/// grows re-spells what it already had here, in memory, rather than
|
||||
/// re-reading and re-scanning every file it already knew about.
|
||||
fn respell(&mut self) {
|
||||
// Taken out and put back so the re-spelling may read the tables on
|
||||
// `self` while it walks the edges — the same map, never a copy of it.
|
||||
let raw = std::mem::take(&mut self.raw);
|
||||
self.edges = raw
|
||||
.iter()
|
||||
.map(|(path, targets)| {
|
||||
let spelled =
|
||||
targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect();
|
||||
(path.clone(), spelled)
|
||||
})
|
||||
.collect();
|
||||
self.raw = raw;
|
||||
}
|
||||
|
||||
/// Re-derive the known-file set and the folded-spelling table from the
|
||||
@@ -198,10 +260,29 @@ impl IncludeGraph {
|
||||
from: Option<&Path>,
|
||||
include: &Include,
|
||||
exists: &dyn Fn(&Path) -> bool,
|
||||
) -> Option<PathBuf> {
|
||||
self.found_as_if(from, include, exists).map(|found| self.as_the_index_spells_it(found))
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::resolve`] as far as the *filesystem* answers it: the
|
||||
/// search rungs and `normalize`, without the index's own spelling.
|
||||
///
|
||||
/// The half of an edge that only a disk change can move, which is what the
|
||||
/// graph holds in `raw`.
|
||||
fn found(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
|
||||
self.found_as_if(from, include, &|path| path.is_file())
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::found`] against a filesystem `exists` describes.
|
||||
fn found_as_if(
|
||||
&self,
|
||||
from: Option<&Path>,
|
||||
include: &Include,
|
||||
exists: &dyn Fn(&Path) -> bool,
|
||||
) -> Option<PathBuf> {
|
||||
let target = Path::new(&include.target);
|
||||
if target.is_absolute() {
|
||||
return exists(target).then(|| self.as_the_index_spells_it(normalize(target)));
|
||||
return exists(target).then(|| normalize(target));
|
||||
}
|
||||
let own = match include.system {
|
||||
true => None,
|
||||
@@ -211,7 +292,7 @@ impl IncludeGraph {
|
||||
.chain(self.incdirs.iter().map(PathBuf::as_path))
|
||||
.map(|dir| dir.join(target))
|
||||
.find(|candidate| exists(candidate))
|
||||
.map(|found| self.as_the_index_spells_it(normalize(&found)))
|
||||
.map(|found| normalize(&found))
|
||||
}
|
||||
|
||||
/// A resolved path, re-spelled the way the index spells that file.
|
||||
@@ -244,6 +325,18 @@ impl IncludeGraph {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file that writes at least one `` `include`` the disk answered —
|
||||
/// the keys of the edge table, in no particular order.
|
||||
///
|
||||
/// The complement is the interesting half: a file that is *not* here
|
||||
/// either includes nothing or includes only what nothing resolves, so
|
||||
/// [`IncludeGraph::resolve`] answers `None` for every include it writes.
|
||||
/// `file_ops.rs` reads that as "this file cannot produce an edit or a
|
||||
/// warning" and never reads it (`Workspace::include_sources`).
|
||||
pub fn includers(&self) -> impl Iterator<Item = &PathBuf> {
|
||||
self.raw.keys()
|
||||
}
|
||||
|
||||
/// Every file reachable from `seeds` through include edges, the seeds
|
||||
/// themselves included.
|
||||
///
|
||||
@@ -263,6 +356,33 @@ impl IncludeGraph {
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Everything this graph answers with, as one deterministic string.
|
||||
///
|
||||
/// Test-only, and the witness for "a graph widened one folder at a time is
|
||||
/// the graph a whole rebuild would have produced": the two hash maps are
|
||||
/// rendered in sorted order, so the comparison is of the contents and never
|
||||
/// of the iteration order.
|
||||
#[cfg(test)]
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let mut out = format!("incdirs {:?}\n", self.incdirs);
|
||||
let mut known: Vec<&PathBuf> = self.known.iter().collect();
|
||||
known.sort();
|
||||
out.push_str(&format!("known {known:?}\n"));
|
||||
let mut folded: Vec<(&String, &Option<PathBuf>)> = self.folded.iter().collect();
|
||||
folded.sort();
|
||||
out.push_str(&format!("folded {folded:?}\n"));
|
||||
let mut edges: Vec<(&PathBuf, &Vec<PathBuf>)> = self.edges.iter().collect();
|
||||
edges.sort();
|
||||
out.push_str(&format!("edges {edges:?}\n"));
|
||||
// The unspelled edges too, so a widen that left a stale entry behind
|
||||
// fails here rather than waiting for the scope to grow far enough for
|
||||
// the spelling to notice.
|
||||
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
|
||||
raw.sort();
|
||||
out.push_str(&format!("raw {raw:?}\n"));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
|
||||
|
||||
@@ -569,27 +569,48 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_from_the_previous_facts_format_is_dropped_not_misread() {
|
||||
// Simulates a store written by the released 0.12.1 (FACTS_FORMAT 2,
|
||||
// before detail_span). Same CACHE_FORMAT and VERSION as today — only
|
||||
// FACTS_FORMAT differs — so the only thing that can catch it is the
|
||||
// FACTS_FORMAT field in the header line. QA finding for
|
||||
// docs/features/port-detail-spans/README.md: the format bump 2 → 3
|
||||
// had no regression test of its own; this is that test.
|
||||
let dir = TempDir::new("factsformat2");
|
||||
fn a_store_from_any_previous_facts_format_is_dropped_not_misread() {
|
||||
// Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT`
|
||||
// and `VERSION` — so the header's format field is the only thing that
|
||||
// can catch them. Written as a loop rather than against one number so
|
||||
// it cannot go stale the next time a record grows a field: it was
|
||||
// pinned at 2 for the `detail_span` bump (QA finding,
|
||||
// `docs/features/port-detail-spans/README.md`) and would have gone on
|
||||
// testing 2 forever.
|
||||
let dir = TempDir::new("factsformats");
|
||||
let file = dir.file("m.sv", M);
|
||||
let encoded = facts(&file, M).encode().expect("encodes");
|
||||
let old_format_store = format!(
|
||||
"lucisv-index-cache\t{CACHE_FORMAT}\t2\t{VERSION}\n{}\n",
|
||||
line(content_hash(M.as_bytes()), &encoded)
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), old_format_store).expect("write");
|
||||
for format in 1..FACTS_FORMAT {
|
||||
let old_format_store = format!(
|
||||
"lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n",
|
||||
line(content_hash(M.as_bytes()), &encoded)
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), old_format_store).expect("write");
|
||||
let cache = IndexCache::open(Some(dir.path.clone()));
|
||||
assert!(
|
||||
cache.facts_for(&file, M).is_none(),
|
||||
"a format-{format} record must not be read as a format-{FACTS_FORMAT} one"
|
||||
);
|
||||
}
|
||||
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
// And the belt to that brace: a record really written in an older
|
||||
// *layout* — this one is a format-4 record, which is today's minus
|
||||
// every field `vscode-hierarchy-sidebar` added and minus the declared
|
||||
// type name `class-member-access` round 2 added (format 5 → 6 changed
|
||||
// the census, not the layout; 6 → 7 changed both) — does not decode as
|
||||
// one of today's *even if* something served it past the header.
|
||||
// Field-shifting is what the length prefixes and the end-of-record
|
||||
// check exist to make impossible.
|
||||
let previous = as_a_format_4_record(&encoded);
|
||||
assert_ne!(previous, encoded, "premise: the fixture has fields to strip");
|
||||
assert!(
|
||||
cache.facts_for(&file, M).is_none(),
|
||||
"a format-2 record must not be read as a format-3 one"
|
||||
FileFacts::decode(&previous).is_none(),
|
||||
"a format-4 record decoded as a format-{FACTS_FORMAT} one: {previous}"
|
||||
);
|
||||
|
||||
// Finally, the store is replaced under this build's header rather than
|
||||
// appended to, and reopening reads the fresh record back.
|
||||
let mut cache = IndexCache::open(Some(dir.path.clone()));
|
||||
cache.record(&facts(&file, M), M);
|
||||
let text = dir.store_text();
|
||||
assert!(
|
||||
@@ -602,6 +623,39 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Today's encoded record, minus everything `FACTS_FORMAT` 5 and 7 added
|
||||
/// — i.e. exactly what format 4 wrote for the same file. Four additions
|
||||
/// and all four come out: a declaration's `decl_span`, a file-scope
|
||||
/// declaration's client positions, an instantiation's per-instance
|
||||
/// occurrences (format 5), and a declaration's declared type name
|
||||
/// (format 7).
|
||||
///
|
||||
/// `M` declares exactly one unit, no members, and one instantiation of one
|
||||
/// instance, so every group's field index can be computed rather than
|
||||
/// parsed. Highest index first, so removing one strip does not move the
|
||||
/// others.
|
||||
fn as_a_format_4_record(encoded: &str) -> String {
|
||||
let mut fields: Vec<&str> = encoded.split('\t').collect();
|
||||
let Some(instantiations) = fields.iter().position(|f| *f == "I") else {
|
||||
return encoded.to_string();
|
||||
};
|
||||
// I, count, module, owner (name + two ranges), site range — ten
|
||||
// fields, then the occurrence count and its one thirteen-field
|
||||
// occurrence.
|
||||
fields.drain(instantiations + 10..instantiations + 10 + 1 + 13);
|
||||
let Some(units) = fields.iter().position(|f| *f == "U") else {
|
||||
return encoded.to_string();
|
||||
};
|
||||
// U, count, then name, kind, name_span×2, decl_span×2, detail×2,
|
||||
// lines×2, type_name, and the unit's two client ranges — four numbers
|
||||
// each.
|
||||
let decl_at = units + 2;
|
||||
fields.drain(decl_at + 11..decl_at + 19);
|
||||
fields.drain(decl_at + 10..decl_at + 11);
|
||||
fields.drain(decl_at + 4..decl_at + 6);
|
||||
fields.join("\t")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() {
|
||||
// The one shape `create_new` introduces: a zero-byte store, left by a
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
//! `textDocument/inlineCompletion` — the ghost text that finishes a block as
|
||||
//! you open it.
|
||||
//! you open it, and the instantiation that follows a module's name.
|
||||
//!
|
||||
//! Type `if (` and grey `) begin … end` follows the cursor; type `begin` at the
|
||||
//! end of a line and its `end` does. Accepting one is a snippet insertion, so
|
||||
//! the tabstops land the cursor inside the parens first and on the indented
|
||||
//! body line second.
|
||||
//!
|
||||
//! Type the whole name of a module the workspace declares **and a space**,
|
||||
//! somewhere an instantiation may be written, and the rest of the
|
||||
//! instantiation follows the same way: every parameter, every port, each a
|
||||
//! tabstop. That is the second level of the two the completion popup's module
|
||||
//! tier is the first of — the popup offers *names*, cheaply, and exactly one
|
||||
//! name is ever planned. The space is what says the name is finished: `aes`
|
||||
//! alone may still be growing into `aes_dft` (owner ruling, 2026-08-30). See
|
||||
//! `docs/features/inline-instantiation/README.md`.
|
||||
//!
|
||||
//! Three things here are deliberate. The **triggers are data** — a keyword, the
|
||||
//! punctuation that must follow it, the dialect it belongs to, the check that
|
||||
//! says the construct is still unfinished, and one body per item in
|
||||
@@ -21,7 +30,9 @@
|
||||
use lsp_types::{Position, Range, Uri};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::{Layout, Site};
|
||||
|
||||
use crate::completion;
|
||||
use crate::pairs;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::templates::{self, Dialect};
|
||||
@@ -227,9 +238,6 @@ pub struct InlineItems {
|
||||
/// editor treats both the same, and `null` is the cheaper answer to a request
|
||||
/// that arrives on every keystroke.
|
||||
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
|
||||
if !ws.client_settings().inline_templates.unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let doc = ws.document(uri)?;
|
||||
// No token stream, no answer — the same trade `completion.rs` makes. A
|
||||
// half-typed string or block comment is what breaks the lexer, and those
|
||||
@@ -241,11 +249,59 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
|
||||
if !rest_of_line_is_blank(&doc.text, offset) {
|
||||
return None;
|
||||
}
|
||||
let (trigger, opened) = triggered(doc, offset)?;
|
||||
let at = Range { start: position, end: position };
|
||||
// Two ghosts, told apart by the shape of the text just before the cursor.
|
||||
// An identifier followed by exactly one space may be a module name the
|
||||
// user has committed to; a token ending *at* the cursor may open a
|
||||
// construct. No keystroke reaches both — a space is not a token, so
|
||||
// nothing ends at the cursor when one was just typed — and each carries
|
||||
// its own setting, so a user who turned one off still has the other.
|
||||
if let Some(name) = name_then_space(doc, offset) {
|
||||
return instantiation(ws, doc, name, at);
|
||||
}
|
||||
let last = last_token(doc, offset)?;
|
||||
match doc.tokens.get(last)?.kind {
|
||||
// A name with nothing after it is not an offer (owner ruling,
|
||||
// 2026-08-30): `aes` may still be growing into `aes_dft`, and the
|
||||
// space is the user saying that it is not. No trigger's own last token
|
||||
// is an `Ident` either, so nothing is lost by stopping here.
|
||||
TokenKind::Ident => None,
|
||||
_ => template(ws, doc, last, at),
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier the user has just finished and armed with a space: the token
|
||||
/// ending exactly at `offset - 1`, when that byte is a space and the byte
|
||||
/// before it is not.
|
||||
///
|
||||
/// **One space, and the one just typed.** Two of them is not "you have just
|
||||
/// finished the name" — it is a cursor parked in whitespace — and the crisp
|
||||
/// rule is what keeps the ghost from appearing at every idle position on a
|
||||
/// blank-ish line. A tab is not a space either: only the character a user types
|
||||
/// after a module name arms this.
|
||||
fn name_then_space(doc: &Document, offset: u32) -> Option<usize> {
|
||||
let space = offset.checked_sub(1)?;
|
||||
let bytes = doc.text.as_bytes();
|
||||
if bytes.get(space as usize) != Some(&b' ') {
|
||||
return None;
|
||||
}
|
||||
if space > 0 && bytes.get(space as usize - 1) == Some(&b' ') {
|
||||
return None;
|
||||
}
|
||||
let index = last_token(doc, space)?;
|
||||
(doc.tokens.get(index)?.kind == TokenKind::Ident).then_some(index)
|
||||
}
|
||||
|
||||
/// The block-opening ghost: the trigger table, its gate, and one item per
|
||||
/// body.
|
||||
fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<InlineItems> {
|
||||
if !ws.client_settings().inline_templates.unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let (trigger, opened) = triggered(doc, last)?;
|
||||
if !unfinished(doc, trigger, opened) {
|
||||
return None;
|
||||
}
|
||||
let at = Range { start: position, end: position };
|
||||
Some(InlineItems {
|
||||
items: trigger
|
||||
.bodies
|
||||
@@ -258,6 +314,120 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
|
||||
})
|
||||
}
|
||||
|
||||
/// The instantiation ghost: everything but the name of the module the user has
|
||||
/// just finished spelling, and the space they armed it with.
|
||||
///
|
||||
/// The order of the questions is the feature. A keystroke that is not an exact
|
||||
/// module name — which is nearly every keystroke — costs one binary search in
|
||||
/// a table (`Candidates::has_module`) and stops there: no scope chain is built,
|
||||
/// no file is opened, nothing is parsed. Only an exact match pays for the
|
||||
/// position gate, and only a gated exact match pays for a plan.
|
||||
///
|
||||
/// The gate is asked at the **name's own start**, not at the cursor: the space
|
||||
/// is the arming keystroke, and the instantiation would still be written where
|
||||
/// the name begins.
|
||||
fn instantiation(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<InlineItems> {
|
||||
if !ws.client_settings().inline_instantiation.unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let name = doc.tokens.get(last)?;
|
||||
if !ws.candidates().has_module(&name.text) {
|
||||
return None;
|
||||
}
|
||||
if !completion::at_instantiation_site(doc, name.span.start) {
|
||||
return None;
|
||||
}
|
||||
let value = instantiation_ghost(ws, doc, &name.text, name.span.start).ok()?;
|
||||
Some(InlineItems {
|
||||
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range: at }],
|
||||
})
|
||||
}
|
||||
|
||||
/// Why a module the workspace really declares has no ghost behind it.
|
||||
///
|
||||
/// **The residue, enumerated.** Since round 2 the ghost no longer declines
|
||||
/// because a name is declared twice — `completion::nearest_definition` chooses
|
||||
/// — so what is left is this list and nothing else, and a sweep over a whole
|
||||
/// workspace can bucket its misses by reason instead of shrugging at them.
|
||||
/// `the_only_residue_over_a_workspace_is_the_escaped_identifier` is that sweep
|
||||
/// in miniature.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum NoGhost {
|
||||
/// The index names no module by this name whose declaring file it can
|
||||
/// place — the caller's `has_module` probe and the index disagreeing,
|
||||
/// which only a scope change mid-request can produce.
|
||||
Undeclared,
|
||||
/// The declaring file could not be read.
|
||||
Unreadable,
|
||||
/// Neither the header slice nor the whole file planned: the definition is
|
||||
/// written in syntax this parser does not read as a module header.
|
||||
Unplannable,
|
||||
/// The plan carries an **escaped identifier**, which may legally contain
|
||||
/// `$`, `}` and `\` — the snippet grammar's own punctuation — written by
|
||||
/// the layout where no per-hole escaping can reach it. The popup's answer
|
||||
/// to that was a plain-text item; an inline completion has no plain-text
|
||||
/// spelling to fall back to (there is no `snippetSupport` to negotiate on
|
||||
/// this request), so the honest answer is no ghost at all.
|
||||
EscapedIdentifier,
|
||||
/// The rendered skeleton did not begin with the module's name and exactly
|
||||
/// one space, so there is nothing to cut off its front. Unreachable with
|
||||
/// today's layout and pinned as such
|
||||
/// (`the_rendered_skeleton_really_does_put_one_space_after_the_name`); it
|
||||
/// is here so a change to `vlog_refactor`'s spelling fails loudly in a
|
||||
/// sweep rather than silently truncating a ghost.
|
||||
UnexpectedLayout,
|
||||
}
|
||||
|
||||
/// The instantiation of `module` as it appears behind the cursor: the
|
||||
/// skeleton `completion.rs` plans, laid out **relatively**, with the name the
|
||||
/// user has already typed *and the space after it* cut off the front.
|
||||
fn instantiation_ghost(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
module: &str,
|
||||
at: u32,
|
||||
) -> Result<String, NoGhost> {
|
||||
let path = completion::nearest_definition(ws.index(), module, doc.path.as_deref())
|
||||
.ok_or(NoGhost::Undeclared)?;
|
||||
let site = Site { semantics: &doc.semantics, offset: at };
|
||||
// A closed file goes through the view cache, so holding the cursor on a
|
||||
// name — every keystroke of which re-asks this question — reads the disk
|
||||
// once. An open one has no view by design: its buffer is the authority.
|
||||
let plan = match ws.file_view(path) {
|
||||
Some(view) => completion::plan_for(ws.index(), module, &view.text, site),
|
||||
None => {
|
||||
let text = ws.text_of(path).ok_or(NoGhost::Unreadable)?;
|
||||
completion::plan_for(ws.index(), module, &text, site)
|
||||
}
|
||||
}
|
||||
.map_err(|_| NoGhost::Unplannable)?;
|
||||
if plan.has_escaped_identifier() {
|
||||
return Err(NoGhost::EscapedIdentifier);
|
||||
}
|
||||
let skeleton = plan.render_with(&relative(), &mut completion::snippet_hole);
|
||||
// The user typed the name and the space; the ghost is what follows both.
|
||||
// The same "cut off what is already there" rule every trigger above
|
||||
// follows — the layout writes exactly one space between the module's name
|
||||
// and whatever comes next, whether that is a `#(` or an instance name.
|
||||
skeleton
|
||||
.strip_prefix(module)
|
||||
.and_then(|rest| rest.strip_prefix(' '))
|
||||
.map(str::to_string)
|
||||
.ok_or(NoGhost::UnexpectedLayout)
|
||||
}
|
||||
|
||||
/// The layout an inline completion is written in: no base at all, one `\t` per
|
||||
/// step.
|
||||
///
|
||||
/// The [`render`] contract, in the shape `vlog_refactor` renders a plan
|
||||
/// through. A `base` here would be the site's own indentation baked in, which
|
||||
/// is exactly the double-indentation bug `render`'s doc comment describes; a
|
||||
/// step of anything but `\t` would be this server deciding how wide the user's
|
||||
/// tab stops are, which the editor re-spells anyway.
|
||||
fn relative() -> Layout {
|
||||
Layout { base: String::new(), step: "\t".to_string() }
|
||||
}
|
||||
|
||||
/// The two tokens a gate can ask about: the keyword that opens the construct,
|
||||
/// and the last token the user typed — the `(` whenever the trigger has one.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -266,16 +436,15 @@ struct Opened {
|
||||
last: TextRange,
|
||||
}
|
||||
|
||||
/// The trigger the tokens ending at `offset` spell, and the spans its gate
|
||||
/// needs.
|
||||
/// The token the user has just finished typing: the last one that is not the
|
||||
/// `Eof` sentinel, and only when it ends **exactly** at the cursor.
|
||||
///
|
||||
/// The cursor must sit *exactly* at the last token's end: that is the crisp
|
||||
/// "you just typed this" rule, and it is what keeps the body's first character
|
||||
/// from landing after stray spaces. It is also what makes a comment or a
|
||||
/// string safe without a single check of its own — a comment is lexer trivia
|
||||
/// and never a token, and `"if ("` is one `String` token whose text is not a
|
||||
/// keyword.
|
||||
fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)> {
|
||||
/// That equality is the crisp "you just typed this" rule, and it is what keeps
|
||||
/// a body's first character from landing after stray spaces. It is also what
|
||||
/// makes a comment or a string safe without a single check of its own — a
|
||||
/// comment is lexer trivia and never a token, and `"if ("` is one `String`
|
||||
/// token whose text is not a keyword.
|
||||
fn last_token(doc: &Document, offset: u32) -> Option<usize> {
|
||||
// `Eof` is a zero-width sentinel `tokenize` appends at `text.len()`, so
|
||||
// when the buffer's very last byte is the trigger's own last character —
|
||||
// no trailing newline, nothing typed after it yet — it shares the
|
||||
@@ -288,10 +457,13 @@ fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)>
|
||||
// remaining condition is the `Eof` test alone.
|
||||
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
|
||||
let index = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof)?;
|
||||
(doc.tokens.get(index)?.span.end == offset).then_some(index)
|
||||
}
|
||||
|
||||
/// The trigger the token at `index` and its neighbours spell, and the spans
|
||||
/// its gate needs.
|
||||
fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)> {
|
||||
let last = doc.tokens.get(index)?;
|
||||
if last.span.end != offset {
|
||||
return None;
|
||||
}
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
for trigger in TRIGGERS {
|
||||
if matches!(trigger.dialect, Some(only) if only != dialect) {
|
||||
@@ -1478,4 +1650,569 @@ endmodule
|
||||
let items = inline_completions(&ws, &uri, position).expect("a ghost");
|
||||
assert_eq!(items.items[0].range.start, Position { line: 2, character: 19 });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the instantiation ghost (2026-08-30)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A scratch workspace root, removed on drop. The instantiation ghost is
|
||||
/// the one path here that reads the index, so its tests need real files.
|
||||
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 _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("temp dir");
|
||||
}
|
||||
std::fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The module every ghost below instantiates: parameters *and* ports, one
|
||||
/// of which (`clk`) the buffer declares and so binds itself.
|
||||
const SUB: &str = "\
|
||||
module sub #(
|
||||
parameter int WIDTH = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [WIDTH-1:0] data,
|
||||
output logic ready
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// The ghost `SUB`'s header produces, with the name the user typed *and
|
||||
/// the space that armed it* already cut off the front. Written out once,
|
||||
/// because half the tests below are about whether it appears at all rather
|
||||
/// than about what it says.
|
||||
const SUB_GHOST: &str = "#(\n\t.WIDTH(${1:8})\n) ${2:u_sub} (\n\t.clk(clk),\n\t\
|
||||
.data(${3:data}),\n\t.ready(${4:ready})\n);";
|
||||
|
||||
/// A workspace holding `files` plus an open `top.sv`, with the cursor at
|
||||
/// `needle`'s end.
|
||||
fn workspace(
|
||||
name: &str,
|
||||
files: &[(&str, &str)],
|
||||
top: &str,
|
||||
needle: &str,
|
||||
) -> (Tree, Workspace, Uri, Position) {
|
||||
workspace_at(name, files, "top.sv", top, needle)
|
||||
}
|
||||
|
||||
/// The same, with the open buffer written at `top_rel` — which is what the
|
||||
/// nearest-definition rule reads, so a test about *which* copy is chosen
|
||||
/// has to be able to say where the asking buffer lives.
|
||||
fn workspace_at(
|
||||
name: &str,
|
||||
files: &[(&str, &str)],
|
||||
top_rel: &str,
|
||||
top: &str,
|
||||
needle: &str,
|
||||
) -> (Tree, Workspace, Uri, Position) {
|
||||
let tree = Tree::new(name);
|
||||
for (rel, text) in files {
|
||||
tree.write(rel, text);
|
||||
}
|
||||
let path = tree.write(top_rel, top);
|
||||
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(), top.to_string());
|
||||
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
(tree, ws, uri, position)
|
||||
}
|
||||
|
||||
/// The one ghost offered at `needle`'s end in a workspace declaring `SUB`.
|
||||
///
|
||||
/// `needle` names the text the cursor sits after, and every caller here
|
||||
/// spells the arming space into it: since 2026-08-30 the ghost answers
|
||||
/// `sub ` and never `sub`, because `sub` alone may still be growing into
|
||||
/// `sub_dft`.
|
||||
fn ghosted(name: &str, top: &str, needle: &str) -> Option<String> {
|
||||
ghosted_among(name, &[("sub.sv", SUB)], top, needle)
|
||||
}
|
||||
|
||||
/// The same, over a workspace spelled out by the caller.
|
||||
fn ghosted_among(
|
||||
name: &str,
|
||||
files: &[(&str, &str)],
|
||||
top: &str,
|
||||
needle: &str,
|
||||
) -> Option<String> {
|
||||
ghosted_at(name, files, "top.sv", top, needle)
|
||||
}
|
||||
|
||||
/// The same again, with the asking buffer's own path spelled out.
|
||||
fn ghosted_at(
|
||||
name: &str,
|
||||
files: &[(&str, &str)],
|
||||
top_rel: &str,
|
||||
top: &str,
|
||||
needle: &str,
|
||||
) -> Option<String> {
|
||||
let (_tree, ws, uri, position) = workspace_at(name, files, top_rel, top, needle);
|
||||
let items = inline_completions(&ws, &uri, position)?;
|
||||
assert_eq!(items.items.len(), 1, "an instantiation is one offer, not a menu");
|
||||
Some(items.items[0].insert_text.value.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exactly_spelled_module_name_and_a_space_ghost_the_whole_instantiation() {
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
assert_eq!(ghosted("exact", top, " sub ").as_deref(), Some(SUB_GHOST));
|
||||
}
|
||||
|
||||
/// The owner's ruling of 2026-08-30, both halves in one place: the space is
|
||||
/// what arms the ghost, and without it there is nothing — *even though*
|
||||
/// `sub` is a module the workspace really declares and the cursor really is
|
||||
/// at a legal site. `aes` is not a commitment while `aes_dft` may still be
|
||||
/// coming; `aes ` is.
|
||||
#[test]
|
||||
fn the_name_alone_offers_nothing_and_the_name_and_a_space_offer_everything() {
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
assert_eq!(ghosted("armed_no", top, " sub"), None, "the name alone is not a commitment");
|
||||
assert_eq!(ghosted("armed_yes", top, " sub ").as_deref(), Some(SUB_GHOST));
|
||||
}
|
||||
|
||||
/// One space, and the one just typed. Two of them is a cursor parked in
|
||||
/// whitespace rather than a name just finished, and a tab is not the
|
||||
/// character this rule is about at all.
|
||||
#[test]
|
||||
fn only_a_single_space_arms_the_ghost() {
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
assert_eq!(ghosted("twospaces", top, " sub "), None, "two spaces is not `just typed`");
|
||||
let top = "module top;\n logic clk;\n sub\t\nendmodule\n";
|
||||
assert_eq!(ghosted("tab", top, " sub\t"), None, "a tab does not arm it");
|
||||
// …and the first of the two spaces still does, which is the same rule
|
||||
// read from the other side: the byte before the cursor is a space and
|
||||
// the byte before that is not.
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
assert_eq!(ghosted("firstspace", top, " sub ").as_deref(), Some(SUB_GHOST));
|
||||
}
|
||||
|
||||
/// A name that is not a module, followed by a space, is the overwhelmingly
|
||||
/// common keystroke on this path — it must cost the binary search and stop.
|
||||
#[test]
|
||||
fn a_space_after_a_name_that_is_not_a_module_ghosts_nothing() {
|
||||
let top = "module top;\n logic clk;\n widget \nendmodule\n";
|
||||
assert_eq!(ghosted("notamodule", top, " widget "), None);
|
||||
}
|
||||
|
||||
/// The layout `vlog_refactor` renders really does put exactly one space
|
||||
/// between a module's name and whatever follows it, in both shapes: a
|
||||
/// parameterised header (`sub #(`) and a bare one (`bare u_bare`). The cut
|
||||
/// in `instantiation_ghost` asserts this rather than assuming it — see
|
||||
/// [`NoGhost::UnexpectedLayout`] — and this is what would fail first if the
|
||||
/// spelling ever changed.
|
||||
#[test]
|
||||
fn the_rendered_skeleton_really_does_put_one_space_after_the_name() {
|
||||
for (name, module, files) in [
|
||||
("layout_params", "sub", &[("sub.sv", SUB)][..]),
|
||||
("layout_bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..]),
|
||||
] {
|
||||
let top = format!("module top;\n logic clk;\n {module} \nendmodule\n");
|
||||
let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost");
|
||||
assert!(
|
||||
!ghost.starts_with(char::is_whitespace),
|
||||
"{module}: the arming space is the ghost's, not the user's: {ghost:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The accepted text is what the popup's skeleton used to insert, byte for
|
||||
/// byte — which is the argument that level 2 gives up nothing level 1 gave
|
||||
/// away. The layout the server sends is relative; the editor supplies the
|
||||
/// site's own indentation and the width of a step.
|
||||
#[test]
|
||||
fn the_accepted_ghost_is_the_skeleton_the_popup_used_to_insert() {
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
let ghost = ghosted("accepted", top, " sub ").expect("a ghost");
|
||||
assert_eq!(
|
||||
format!("sub {}", accepted(&ghost, " ", " ")),
|
||||
"\
|
||||
sub #(
|
||||
.WIDTH(${1:8})
|
||||
) ${2:u_sub} (
|
||||
.clk(clk),
|
||||
.data(${3:data}),
|
||||
.ready(${4:ready})
|
||||
);"
|
||||
);
|
||||
// …and it follows the editor's tabs, not `lucisv.indent`, at any depth.
|
||||
assert!(accepted(&ghost, "\t\t", "\t").contains("\n\t\t\t.clk(clk),"), "{ghost}");
|
||||
}
|
||||
|
||||
/// What the user ends up with must parse. The typed name, the accepted
|
||||
/// body, every hole filled in the way the editor preselects it, planted at
|
||||
/// the item position the gate insisted on.
|
||||
#[test]
|
||||
fn the_accepted_ghost_parses_where_it_was_offered() {
|
||||
for (name, module, files, holes) in [
|
||||
("ports", "sub", &[("sub.sv", SUB)][..], 4),
|
||||
("bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..], 1),
|
||||
(
|
||||
"portless",
|
||||
"empty",
|
||||
&[("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n")][..],
|
||||
2,
|
||||
),
|
||||
] {
|
||||
let top = format!("module top;\n logic clk;\n {module} \nendmodule\n");
|
||||
let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost");
|
||||
assert_eq!(
|
||||
ghost.matches("${").count(),
|
||||
holes,
|
||||
"{module}: every fill-in is a tabstop: {ghost}"
|
||||
);
|
||||
// The name, the space that armed the ghost, and the ghost itself —
|
||||
// which is exactly what the buffer holds after Tab.
|
||||
let written = filled(&format!("{module} {}", accepted(&ghost, " ", " ")));
|
||||
let probe = format!("module lucisv_probe;\n logic clk;\n {written}\nendmodule\n");
|
||||
assert!(
|
||||
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
|
||||
"the accepted text must parse:\n{probe}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
|
||||
let top = "module top;\n bare \nendmodule\n";
|
||||
assert_eq!(
|
||||
ghosted_among("bareports", &[("bare.sv", "module bare;\nendmodule\n")], top, " bare ")
|
||||
.as_deref(),
|
||||
Some("${1:u_bare} ();")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_typed_name_ghosts_nothing() {
|
||||
// The popup is what answers here — with the *name*, which is the whole
|
||||
// division of labour between the two levels.
|
||||
let top = "module top;\n logic clk;\n su \nendmodule\n";
|
||||
assert_eq!(ghosted("partial", top, " su "), None);
|
||||
// …and one character past the name is not the name either.
|
||||
let top = "module top;\n logic clk;\n subs \nendmodule\n";
|
||||
assert_eq!(ghosted("past", top, " subs "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_mismatched_name_ghosts_nothing() {
|
||||
// The popup's substring match folds case; this one must not. `SUB` is
|
||||
// not a module any Verilog tool would find.
|
||||
for typed in ["SUB", "Sub", "sUb"] {
|
||||
let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n");
|
||||
assert_eq!(ghosted("case", &top, &format!(" {typed} ")), None, "{typed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_workspace_does_not_declare_as_a_module_ghosts_nothing() {
|
||||
let files =
|
||||
&[("sub.sv", SUB), ("p.sv", "package pkg;\n localparam int W = 1;\nendpackage\n")];
|
||||
for typed in ["pkg", "W", "clk", "nothing_at_all"] {
|
||||
let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n");
|
||||
assert_eq!(
|
||||
ghosted_among("nonmodule", files, &top, &format!(" {typed} ")),
|
||||
None,
|
||||
"{typed} is not a module"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anything_after_the_cursor_on_the_line_ghosts_nothing() {
|
||||
// The rest-of-line rule the templates already live by: a name with a
|
||||
// `;` after it is code the user has finished writing.
|
||||
let top = "module top;\n logic clk;\n sub u_sub ();\nendmodule\n";
|
||||
assert_eq!(ghosted("after", top, " sub "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_not_at_item_position_ghosts_nothing() {
|
||||
// Every one of these spells `sub` exactly and none of them is a place
|
||||
// an instantiation may be written. The gate is `completion.rs`'s own,
|
||||
// so this is the ghost inheriting the popup's answer rather than
|
||||
// inventing a second one.
|
||||
for (name, top, needle) in [
|
||||
("connection", "module top;\n other u (.aes(sub \nendmodule\n", ".aes(sub "),
|
||||
("assign", "module top;\n wire x;\n assign x = sub \nendmodule\n", "= sub "),
|
||||
("declaration", "module top;\n logic sub \nendmodule\n", "logic sub "),
|
||||
(
|
||||
"procedural",
|
||||
"module top;\n initial begin\n sub \n end\nendmodule\n",
|
||||
" sub ",
|
||||
),
|
||||
(
|
||||
"function",
|
||||
"module top;\n function int f();\n sub \n endfunction\nendmodule\n",
|
||||
" sub ",
|
||||
),
|
||||
("file scope", "sub \nmodule top;\nendmodule\n", "sub "),
|
||||
("port list", "module top (sub \n);\nendmodule\n", "top (sub "),
|
||||
] {
|
||||
assert_eq!(ghosted("position", top, needle), None, "{name}: {top}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_block_is_still_item_position_for_the_ghost() {
|
||||
let top = "module top;\n logic clk;\n generate\n sub \n endgenerate\nendmodule\n";
|
||||
assert_eq!(ghosted("gen", top, " sub ").as_deref(), Some(SUB_GHOST));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_name_in_a_comment_or_a_string_ghosts_nothing() {
|
||||
// A token property, not a check of this module's own: a comment is
|
||||
// lexer trivia and never a token, and a string literal is one `String`
|
||||
// token whose kind is not `Ident`.
|
||||
let top = "module top;\n // sub \nendmodule\n";
|
||||
assert_eq!(ghosted("comment", top, "// sub "), None);
|
||||
let top = "module top;\n initial $display(\"sub \nendmodule\n";
|
||||
assert_eq!(ghosted("string", top, "\"sub "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_lex_ghosts_nothing() {
|
||||
let top = "module top;\n /* unterminated\n sub \n";
|
||||
let (_tree, ws, uri, position) = workspace("nolex", &[("sub.sv", SUB)], top, " sub ");
|
||||
assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens");
|
||||
assert!(inline_completions(&ws, &uri, position).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exact_name_at_the_true_end_of_the_file_still_ghosts() {
|
||||
// The `Eof` sentinel shares the last real token's end, so the same
|
||||
// skip the templates needed (QA find, 2026-08-25) is what lets a name
|
||||
// typed as the buffer's very last bytes answer.
|
||||
// True EOF is now the buffer ending with the *space*: the name plus
|
||||
// the keystroke that arms it, with nothing after either.
|
||||
let top = "module top;\n logic clk;\n sub ";
|
||||
assert_eq!(ghosted("eof", top, " sub ").as_deref(), Some(SUB_GHOST));
|
||||
}
|
||||
|
||||
/// opentitan's `ast_dft` and `io_osc` in miniature: one module, one copy
|
||||
/// under each of two tops, with headers that differ so the ghost says which
|
||||
/// copy it read.
|
||||
const TWO_TOPS: &[(&str, &str)] = &[
|
||||
("top_earlgrey/ast_dft.sv", "module ast_dft (input logic clk_earlgrey);\nendmodule\n"),
|
||||
("top_darjeeling/ast_dft.sv", "module ast_dft (input logic clk_darjeeling);\nendmodule\n"),
|
||||
];
|
||||
|
||||
/// What each copy of `ast_dft` ghosts. Neither port is declared in the
|
||||
/// asking buffer, so neither auto-connects and the port name is visible in
|
||||
/// the hole — which is how these tests tell the two copies apart.
|
||||
const EARLGREY_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_earlgrey(${2:clk_earlgrey})\n);";
|
||||
const DARJEELING_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_darjeeling(${2:clk_darjeeling})\n);";
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_ghosts_the_copy_nearest_the_buffer() {
|
||||
// Round 1 gave a twice-declared module no ghost at all:
|
||||
// `module_definition` refuses to guess which file to read, and the
|
||||
// ghost inherited the refusal. In opentitan that silenced `ast_dft`
|
||||
// and `io_osc`, each declared once under `hw/top_earlgrey/ip/ast/rtl`
|
||||
// and once under `hw/top_darjeeling/ip/ast/rtl` — two whole IP blocks.
|
||||
// Owner ruling, 2026-08-30: every indexed module expands, so the
|
||||
// server chooses the copy whose path shares the longest run of leading
|
||||
// path components with the buffer asking.
|
||||
let top = "module top;\n ast_dft \nendmodule\n";
|
||||
assert_eq!(
|
||||
ghosted_at("earlgrey", TWO_TOPS, "top_earlgrey/top.sv", top, " ast_dft ").as_deref(),
|
||||
Some(EARLGREY_GHOST),
|
||||
"a buffer under top_earlgrey gets top_earlgrey's copy"
|
||||
);
|
||||
assert_eq!(
|
||||
ghosted_at("darjeeling", TWO_TOPS, "top_darjeeling/top.sv", top, " ast_dft ")
|
||||
.as_deref(),
|
||||
Some(DARJEELING_GHOST),
|
||||
"…and one under top_darjeeling gets the other"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_near_neither_copy_gets_the_lexicographically_smaller_path() {
|
||||
// No shared prefix to rank by, so the tie-break decides — and it is a
|
||||
// property of the paths rather than of the order the index was built
|
||||
// in, which is what makes it reproducible. `top_darjeeling` sorts
|
||||
// before `top_earlgrey`.
|
||||
let top = "module top;\n ast_dft \nendmodule\n";
|
||||
assert_eq!(
|
||||
ghosted_at("neither", TWO_TOPS, "elsewhere/top.sv", top, " ast_dft ").as_deref(),
|
||||
Some(DARJEELING_GHOST)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_copies_may_have_different_headers_and_the_nearest_one_wins() {
|
||||
// The accepted semantics, written down: the copies are not required to
|
||||
// agree, and the user gets the one their own file is nearest to. Here
|
||||
// one copy has a parameter the other has not, so the two ghosts do not
|
||||
// even have the same shape.
|
||||
let files = &[
|
||||
(
|
||||
"top_a/dup.sv",
|
||||
"module dup #(\n parameter int W = 4\n) (input logic a);\nendmodule\n",
|
||||
),
|
||||
("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"),
|
||||
];
|
||||
let top = "module top;\n dup \nendmodule\n";
|
||||
assert_eq!(
|
||||
ghosted_at("hdr_a", files, "top_a/top.sv", top, " dup ").as_deref(),
|
||||
Some("#(\n\t.W(${1:4})\n) ${2:u_dup} (\n\t.a(${3:a})\n);")
|
||||
);
|
||||
assert_eq!(
|
||||
ghosted_at("hdr_b", files, "top_b/top.sv", top, " dup ").as_deref(),
|
||||
Some("${1:u_dup} (\n\t.b(${2:b})\n);")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_with_an_escaped_identifier_gets_no_ghost() {
|
||||
// An escaped identifier may legally contain `$`, `}` and `\` — the
|
||||
// snippet grammar's own punctuation — and the names are written by the
|
||||
// layout, outside every hole, where no escaping can reach them. The
|
||||
// popup answered this with a plain-text item; an inline completion has
|
||||
// no plain-text spelling, so it answers with nothing.
|
||||
let files =
|
||||
&[("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n")];
|
||||
let top = "module top;\n logic clk;\n odd \nendmodule\n";
|
||||
assert_eq!(ghosted_among("escaped", files, top, " odd "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_may_ghost_itself() {
|
||||
// Cursor inside `top`, typing `top`. The plan is real — `top` is a
|
||||
// module the workspace declares and the instantiation is legal
|
||||
// Verilog — so it is offered. Whether instantiating yourself is a good
|
||||
// idea is the user's business; an elaborator will tell them soon
|
||||
// enough, and refusing would be this server having an opinion about
|
||||
// recursion that it cannot back up (a `generate` guarded by a
|
||||
// parameter is a legitimate recursive structure).
|
||||
let top = "module top (input logic clk);\n top \nendmodule\n";
|
||||
assert_eq!(
|
||||
ghosted("self", top, " top ").as_deref(),
|
||||
Some("${1:u_top} (\n\t.clk(clk)\n);")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setting_turns_the_instantiation_ghost_off_and_leaves_the_templates_on() {
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
let (_tree, mut ws, uri, position) =
|
||||
workspace("setting", &[("sub.sv", SUB)], top, " sub ");
|
||||
assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default");
|
||||
ws.set_client_settings(ClientSettings {
|
||||
inline_instantiation: Some(false),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(inline_completions(&ws, &uri, position).is_none());
|
||||
ws.set_client_settings(ClientSettings {
|
||||
inline_instantiation: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again");
|
||||
|
||||
// The two settings are independent in both directions: the templates
|
||||
// answer with the instantiation off, and the reverse.
|
||||
let (_tree, mut ws, uri, position) =
|
||||
workspace("both", &[("sub.sv", SUB)], "module top;\n always_comb begin\n", "begin");
|
||||
ws.set_client_settings(ClientSettings {
|
||||
inline_instantiation: Some(false),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(
|
||||
inline_completions(&ws, &uri, position).is_some(),
|
||||
"a template is not an offer \
|
||||
the instantiation setting governs"
|
||||
);
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
let (_tree, mut ws, uri, position) =
|
||||
workspace("tmploff", &[("sub.sv", SUB)], top, " sub ");
|
||||
ws.set_client_settings(ClientSettings {
|
||||
inline_templates: Some(false),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(inline_completions(&ws, &uri, position).is_some(), "…and the other way round");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_only_residue_over_a_workspace_is_the_escaped_identifier() {
|
||||
// Round 2, part C: after the space-armed trigger and the
|
||||
// nearest-definition chooser, the reasons an indexed module does *not*
|
||||
// ghost have to be enumerable — so a sweep over every module a
|
||||
// workspace declares can bucket its misses by reason instead of
|
||||
// shrugging at them. This is that sweep in miniature, over a workspace
|
||||
// carrying one of every shape the planner meets: parameters and ports,
|
||||
// neither, parameters only, a non-ANSI port list, a name two files
|
||||
// declare, and the one shape that genuinely cannot be ghosted.
|
||||
let files = &[
|
||||
("sub.sv", SUB),
|
||||
("bare.sv", "module bare;\nendmodule\n"),
|
||||
("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n"),
|
||||
(
|
||||
"nonansi.sv",
|
||||
"module nonansi (a, b);\n input wire a;\n output wire b;\nendmodule\n",
|
||||
),
|
||||
("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n"),
|
||||
("top_a/dup.sv", "module dup (input logic a);\nendmodule\n"),
|
||||
("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"),
|
||||
];
|
||||
let top = "module top;\n logic clk;\n probe \nendmodule\n";
|
||||
let (_tree, ws, uri, _) = workspace("residue", files, top, " probe ");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let at = top.find(" probe").expect("the probe line") as u32 + 2;
|
||||
|
||||
let modules: Vec<String> =
|
||||
ws.candidates().modules("").iter().map(|name| name.to_string()).collect();
|
||||
assert!(modules.len() >= 7, "premise: the sweep really covers the workspace: {modules:?}");
|
||||
let refused: Vec<(&str, NoGhost)> = modules
|
||||
.iter()
|
||||
.filter_map(|module| {
|
||||
instantiation_ghost(&ws, doc, module, at).err().map(|why| (module.as_str(), why))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
refused,
|
||||
vec![("odd", NoGhost::EscapedIdentifier)],
|
||||
"the residue is the escaped identifier and nothing else"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_instantiation_wire_shape_is_one_snippet_item_at_the_cursor() {
|
||||
let top = "module top;\n logic clk;\n sub \nendmodule\n";
|
||||
let (_tree, ws, uri, position) = workspace("wire", &[("sub.sv", SUB)], top, " sub ");
|
||||
let items = inline_completions(&ws, &uri, position).expect("a ghost");
|
||||
assert_eq!(
|
||||
serde_json::to_value(&items).expect("serializes"),
|
||||
serde_json::json!({
|
||||
"items": [{
|
||||
"insertText": { "kind": "snippet", "value": SUB_GHOST },
|
||||
"range": {
|
||||
"start": { "line": 2, "character": 6 },
|
||||
"end": { "line": 2, "character": 6 }
|
||||
}
|
||||
}]
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,15 @@
|
||||
//! The workspace index deliberately keeps no file contents
|
||||
//! (`docs/features/workspace-index/README.md`), so a span in another file has
|
||||
//! to be converted against that file's text, fetched here with the same
|
||||
//! open-buffer-beats-disk precedence the index rebuild uses.
|
||||
//! open-buffer-beats-disk precedence the index rebuild uses — from the
|
||||
//! 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.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Location;
|
||||
use vlog_parser::{LineIndex, TextRange};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
@@ -17,25 +20,28 @@ use crate::uri::path_to_uri;
|
||||
/// The location of a byte span inside a workspace file.
|
||||
pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location> {
|
||||
let uri = path_to_uri(path)?;
|
||||
let text = ws.text_of(path)?;
|
||||
let index = LineIndex::new(&text);
|
||||
let range = Positions::new(&text, &index).range(span);
|
||||
Some(Location { uri, range })
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(Location { uri, range: doc.positions().range(span) });
|
||||
}
|
||||
let view = ws.file_view(path)?;
|
||||
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
|
||||
}
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
/// An open buffer answers from the line index it already carries; a closed
|
||||
/// file is read and indexed here — which is why a hover that names one file
|
||||
/// twice reads it through the per-request memo in `hover::symbol_hover`, not
|
||||
/// through two calls here.
|
||||
/// file answers from the shared view cache. **An indexed declaration should
|
||||
/// not come here at all** — `Def::lines` already holds its line, recorded when
|
||||
/// the file was indexed, and that answer costs nothing
|
||||
/// (`docs/features/hover-line-index/README.md`). What is left for this
|
||||
/// function is the spans the index records no line for, which today is a
|
||||
/// `` `define``'s.
|
||||
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(doc.line_index.line_col(offset).0);
|
||||
}
|
||||
let text = ws.text_of(path)?;
|
||||
Some(LineIndex::new(&text).line_col(offset).0)
|
||||
Some(ws.file_view(path)?.lines.line_col(offset).0)
|
||||
}
|
||||
|
||||
/// How a file is named in hover text: its file name, which is what a Verilog
|
||||
|
||||
@@ -10,6 +10,7 @@ mod candidates;
|
||||
mod code_action;
|
||||
mod completion;
|
||||
mod convert;
|
||||
mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod file_ops;
|
||||
@@ -69,7 +70,34 @@ use vlog_parser::PARSE_STACK_SIZE;
|
||||
use crate::server::{ClientAbilities, Server};
|
||||
use crate::uri::uri_to_path;
|
||||
|
||||
/// The one flag this binary takes: per-operation timing lines in the client's
|
||||
/// log channel. One spelling, no `-v` — see
|
||||
/// `docs/features/verbose-timing/README.md`.
|
||||
const VERBOSE: &str = "--verbose";
|
||||
/// `vscode-languageclient` (and other LSP clients) append `--stdio` to the
|
||||
/// spawn when the transport is stdio — the only transport this server has.
|
||||
/// Accepted as the statement of fact it is; rejecting it turned out to crash
|
||||
/// every real VS Code session the moment strict argument parsing shipped
|
||||
/// (lead hotfix, 2026-08-29 — the smoke and restart harnesses spawn the
|
||||
/// binary directly, so nothing in the loop exercised the library's spawn).
|
||||
const STDIO: &str = "--stdio";
|
||||
|
||||
/// What someone who spelled an argument wrong is told, on stderr. One line:
|
||||
/// this binary is spawned by an editor, not typed at a prompt.
|
||||
const USAGE: &str = "usage: lucisv-server [--verbose] [--stdio]";
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
// Before the transport: an argument we do not understand means the client
|
||||
// asked for something we are not doing, and answering LSP anyway would
|
||||
// hide that for the whole session.
|
||||
let verbose = match verbose_flag(std::env::args().skip(1)) {
|
||||
Ok(verbose) => verbose,
|
||||
Err(unknown) => {
|
||||
eprintln!("error: unknown option: {unknown}");
|
||||
eprintln!("{USAGE}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let (connection, io_threads) = Connection::stdio();
|
||||
|
||||
let (id, params) = connection.initialize_start()?;
|
||||
@@ -81,6 +109,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
// capability at all: `initializationOptions` is whatever the client's
|
||||
// extension put there.
|
||||
let storage = storage_path(¶ms);
|
||||
let hierarchy_view = hierarchy_view_support(¶ms);
|
||||
// A client that sends params we cannot read still gets a server; every
|
||||
// field we want is optional anyway.
|
||||
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
|
||||
@@ -95,6 +124,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -108,13 +138,35 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
std::thread::Builder::new()
|
||||
.name("lucisv-main".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || Server::new(connection, roots, abilities, storage).run())?
|
||||
.spawn(move || Server::new(connection, roots, abilities, storage, verbose).run())?
|
||||
.join()
|
||||
.map_err(|_| "the server thread panicked")??;
|
||||
io_threads.join()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the arguments ask for verbose timing, or the first argument this
|
||||
/// binary does not take.
|
||||
///
|
||||
/// Refused rather than ignored: a client that spawns `lucisv-server --verbos`
|
||||
/// would otherwise get a whole session of silence and no way to tell it from a
|
||||
/// flag that does not work. Repeating the flag is not an error — it says the
|
||||
/// same thing twice — and no argument at all is the spawn every editor has
|
||||
/// always used.
|
||||
fn verbose_flag(args: impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
let mut verbose = false;
|
||||
for arg in args {
|
||||
if arg == STDIO {
|
||||
continue;
|
||||
}
|
||||
if arg != VERBOSE {
|
||||
return Err(arg);
|
||||
}
|
||||
verbose = true;
|
||||
}
|
||||
Ok(verbose)
|
||||
}
|
||||
|
||||
/// What the server tells the client it can do. Nothing is advertised that is
|
||||
/// not implemented: a capability an editor discovers to be a lie is worse than
|
||||
/// one it never had.
|
||||
@@ -412,6 +464,13 @@ fn storage_path(params: &serde_json::Value) -> Option<PathBuf> {
|
||||
(!path.trim().is_empty()).then(|| PathBuf::from(path))
|
||||
}
|
||||
|
||||
/// Whether this client hosts lucisv's custom hierarchy view and therefore
|
||||
/// wants invalidation notifications for it. The snapshot request itself is
|
||||
/// always served; this gate prevents unsolicited traffic to other LSP clients.
|
||||
fn hierarchy_view_support(params: &serde_json::Value) -> bool {
|
||||
params["initializationOptions"]["hierarchyView"] == true
|
||||
}
|
||||
|
||||
/// Whether the client can expand `${1:x}` tabstops in a completion item.
|
||||
///
|
||||
/// A client that did not say so gets the skeleton as plain text: a literal
|
||||
@@ -553,6 +612,68 @@ fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`verbose_flag`] over what a spawn would really hand it.
|
||||
fn args(args: &[&str]) -> Result<bool, String> {
|
||||
verbose_flag(args.iter().map(|arg| (*arg).to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_arguments_is_the_spawn_every_editor_has_always_used() {
|
||||
assert_eq!(args(&[]), Ok(false), "and it must never become verbose by accident");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_one_flag_is_the_one_spelling() {
|
||||
assert_eq!(args(&["--verbose"]), Ok(true));
|
||||
// Twice says the same thing twice.
|
||||
assert_eq!(args(&["--verbose", "--verbose"]), Ok(true));
|
||||
// Every near miss is refused, `-v` included: one spelling, so a client
|
||||
// that guessed is told rather than silently given nothing.
|
||||
for wrong in ["-v", "--Verbose", "--verbos", "verbose", "--verbose=true", "--help"] {
|
||||
assert_eq!(args(&[wrong]), Err(wrong.to_string()), "{wrong} is not the flag");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_is_accepted_as_the_statement_of_fact_it_is() {
|
||||
// `vscode-languageclient` appends `--stdio` for TransportKind.stdio —
|
||||
// the spawn every real VS Code session actually makes. Rejecting it
|
||||
// crashed the extension five times and gave up (lead hotfix,
|
||||
// 2026-08-29); it must parse in every combination and change nothing.
|
||||
assert_eq!(args(&["--stdio"]), Ok(false));
|
||||
assert_eq!(args(&["--stdio", "--verbose"]), Ok(true));
|
||||
assert_eq!(args(&["--verbose", "--stdio"]), Ok(true));
|
||||
assert_eq!(args(&["--stdio", "--stdio"]), Ok(false));
|
||||
// And a near miss of IT is still refused.
|
||||
assert_eq!(args(&["--Stdio"]), Err("--Stdio".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_argument_we_do_not_take_is_the_one_reported() {
|
||||
// Named, so the message can say which word was wrong — the whole
|
||||
// reason this refuses instead of ignoring.
|
||||
assert_eq!(args(&["--verbose", "--colour"]), Err("--colour".to_string()));
|
||||
assert_eq!(args(&["--colour", "--verbose"]), Err("--colour".to_string()));
|
||||
assert_eq!(args(&["/some/file.sv"]), Err("/some/file.sv".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extension_ships_the_flag_off_which_is_what_no_argument_means() {
|
||||
// The two halves of the contract live in different languages: the
|
||||
// manifest's default decides whether `extension.js` puts `--verbose`
|
||||
// in the spawn arguments, and `verbose_flag` decides what the server
|
||||
// does with the arguments it gets. They must agree that the shipped
|
||||
// state is off.
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../editors/vscode/package.json");
|
||||
let text = std::fs::read_to_string(&path).expect("the extension manifest");
|
||||
let manifest: serde_json::Value = serde_json::from_str(&text).expect("valid json");
|
||||
let verbose = &manifest["contributes"]["configuration"]["properties"]["lucisv.verbose"];
|
||||
assert_eq!(verbose["type"], serde_json::json!("boolean"), "{verbose:#?}");
|
||||
assert_eq!(verbose["default"], serde_json::json!(false), "{verbose:#?}");
|
||||
assert_eq!(args(&[]), Ok(false), "which is what the server does with no argument");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_advertised_capability_is_implemented() {
|
||||
let caps = capabilities();
|
||||
@@ -735,6 +856,20 @@ mod tests {
|
||||
assert!(!ranges_formatting_support(&serde_json::Value::Null));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hierarchy_notifications_are_an_explicit_initialization_option() {
|
||||
let saying = serde_json::json!({ "initializationOptions": { "hierarchyView": true } });
|
||||
assert!(hierarchy_view_support(&saying));
|
||||
for silent in [
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({ "initializationOptions": { "hierarchyView": false } }),
|
||||
serde_json::json!({ "initializationOptions": { "hierarchyView": "yes" } }),
|
||||
serde_json::Value::Null,
|
||||
] {
|
||||
assert!(!hierarchy_view_support(&silent), "{silent:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() {
|
||||
// The gate's whole point: every client that shipped before this round
|
||||
|
||||
@@ -363,8 +363,10 @@ fn in_file_references(
|
||||
/// — a use sits on, and LSP is explicit that plain `Text` is a valid answer.
|
||||
/// Building that analysis for a highlight colour is not a trade worth making.
|
||||
pub fn document_highlights(doc: &Document, offset: u32) -> Option<Vec<DocumentHighlight>> {
|
||||
let symbol_id = symbol_at(&doc.semantics, offset)?;
|
||||
let spans = occurrences(&doc.semantics, symbol_id, true);
|
||||
let spans = match symbol_at(&doc.semantics, offset) {
|
||||
Some(symbol_id) => occurrences(&doc.semantics, symbol_id, true),
|
||||
None => external_occurrences(doc, offset),
|
||||
};
|
||||
if spans.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -383,6 +385,49 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option<Vec<DocumentHi
|
||||
)
|
||||
}
|
||||
|
||||
/// Every use in *this* file of the declaration the workspace overlay answered
|
||||
/// for the cursor — the half of the question `Semantics` alone cannot see.
|
||||
///
|
||||
/// A name this file uses but does not declare has no in-file symbol at all:
|
||||
/// `Semantics` records the use as an external candidate and leaves it to the
|
||||
/// workspace layer, so [`symbol_at`] is `None` and the single-file answer is
|
||||
/// empty. That is what `performance.md` §7 caught — `documentHighlight`
|
||||
/// answering nothing on an instantiated module and on a port connection while
|
||||
/// `references` answered at the same positions, because `references` reads
|
||||
/// this overlay and the highlight did not.
|
||||
///
|
||||
/// Two uses name the same declaration when they spell the same name *and* the
|
||||
/// overlay gave them the same answer. Comparing the whole answer rather than
|
||||
/// its first entry keeps two ambiguous uses together only when they are
|
||||
/// ambiguous between the same declarations; an unanswered use — a module the
|
||||
/// index does not hold — is left to the editor's own word highlighting, which
|
||||
/// is the same contract the rest of this function keeps.
|
||||
fn external_occurrences(doc: &Document, offset: u32) -> Vec<TextRange> {
|
||||
let Some(id) = doc.semantics.reference_id_at(offset) else { return Vec::new() };
|
||||
let Some(target) = doc.external.get(id) else { return Vec::new() };
|
||||
if target.defs().is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(name) = doc.semantics.reference(id).map(|r| r.name.as_str()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut spans: Vec<TextRange> = doc
|
||||
.semantics
|
||||
.references()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, reference)| reference.name == name && !reference.name_span.is_empty())
|
||||
.filter(|(at, _)| {
|
||||
doc.external.get(vlog_semantic::ReferenceId(*at as u32)).map(ExternalTarget::defs)
|
||||
== Some(target.defs())
|
||||
})
|
||||
.map(|(_, reference)| reference.name_span)
|
||||
.collect();
|
||||
spans.sort_by_key(|span| (span.start, span.end));
|
||||
spans.dedup();
|
||||
spans
|
||||
}
|
||||
|
||||
/// The symbol at a position. The cursor may sit on a use or on the
|
||||
/// declaration itself; both lead to the same symbol.
|
||||
///
|
||||
@@ -1270,6 +1315,178 @@ mod tests {
|
||||
assert!(document_highlights(doc, 0).is_none(), "the `module` keyword");
|
||||
}
|
||||
|
||||
/// `performance.md` §7, reproduced: `documentHighlight` answered nothing
|
||||
/// at every opentitan position tried — an instantiated module's name, a
|
||||
/// port connection — while `references` at the same positions answered.
|
||||
/// Both names are declared in *another* file, which is the whole of what
|
||||
/// the two handlers used to disagree about.
|
||||
#[test]
|
||||
fn a_cross_file_name_highlights_its_uses_in_this_file() {
|
||||
let dir = temp_dir("highlight_cross");
|
||||
fs::write(
|
||||
dir.join("sub.sv"),
|
||||
"module sub (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "\
|
||||
module top;
|
||||
logic clk, rst;
|
||||
sub u_0 (.clk_i(clk), .rst_ni(rst));
|
||||
sub u_1 (.clk_i(clk), .rst_ni(rst));
|
||||
endmodule
|
||||
";
|
||||
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 doc = ws.document(&uri).expect("open");
|
||||
|
||||
// The module name at an instantiation: both instantiations, and
|
||||
// nothing from the *other* module's file — this is one file's answer.
|
||||
let module = at(top_text, "sub u_0");
|
||||
assert_eq!(references(&ws, &uri, module, true).len(), 3, "premise: references answers");
|
||||
let found = document_highlights(doc, module).expect("the instantiated module");
|
||||
let lines: Vec<u32> = found.iter().map(|h| h.range.start.line).collect();
|
||||
assert_eq!(lines, vec![2, 3], "both instantiations of `sub`");
|
||||
assert!(found.iter().all(|h| h.kind == Some(DocumentHighlightKind::TEXT)));
|
||||
|
||||
// A port connection: the `.clk_i` of both instantiations, and not the
|
||||
// `clk` they are wired to, which is a different symbol.
|
||||
let port = at(top_text, ".clk_i") + 1;
|
||||
assert!(!references(&ws, &uri, port, true).is_empty(), "premise: references answers");
|
||||
let found = document_highlights(doc, port).expect("the connected port");
|
||||
let starts: Vec<(u32, u32)> =
|
||||
found.iter().map(|h| (h.range.start.line, h.range.start.character)).collect();
|
||||
assert_eq!(starts, vec![(2, 12), (3, 12)], "both `.clk_i` connections");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// QA (performance wave Lane B, 2026-08-28): an instantiated module whose
|
||||
/// name two files declare is ambiguous at the workspace layer.
|
||||
/// `references` gives up on an ambiguous external target outright
|
||||
/// (`indexed_target` only ever builds one from `Definition::External([def])`
|
||||
/// — exactly one candidate — so an ambiguous use never reaches
|
||||
/// `indexed_references`, and `in_file_references` needs a *local* symbol,
|
||||
/// which an external use does not have; the net result is an empty
|
||||
/// answer, unchanged by this round). `document_highlights` does not
|
||||
/// inherit that caution: `external_occurrences` groups by the overlay's
|
||||
/// whole answer, ambiguous sets included, so it answers here where
|
||||
/// `references` does not. Recorded rather than asserted as a bug — LSP
|
||||
/// does not require the two to agree, and answering something reasonable
|
||||
/// beats the editor's own word-highlighter falling back to nothing — but
|
||||
/// it is a real divergence the lead should see before calling the two
|
||||
/// "cross-checked".
|
||||
#[test]
|
||||
fn an_ambiguous_instantiation_highlights_where_references_gives_up() {
|
||||
let dir = temp_dir("highlight_ambiguous");
|
||||
let dup = "module dup (input logic clk_i);\nendmodule\n";
|
||||
fs::write(dir.join("a.sv"), dup).expect("write");
|
||||
fs::write(dir.join("b.sv"), dup).expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "\
|
||||
module top;
|
||||
logic clk;
|
||||
dup u_0 (.clk_i(clk));
|
||||
dup u_1 (.clk_i(clk));
|
||||
endmodule
|
||||
";
|
||||
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 doc = ws.document(&uri).expect("open");
|
||||
|
||||
let module = at(top_text, "dup u_0");
|
||||
assert!(leaves_this_file(&ws, doc, module), "dup is a unit the index holds");
|
||||
assert!(
|
||||
references(&ws, &uri, module, true).is_empty(),
|
||||
"references declines an ambiguous external target rather than guessing"
|
||||
);
|
||||
let found = document_highlights(doc, module).expect("highlight groups the ambiguous use");
|
||||
let lines: Vec<u32> = found.iter().map(|h| h.range.start.line).collect();
|
||||
assert_eq!(lines, vec![2, 3], "both instantiations, grouped by the same ambiguous def set");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Two uses of the *same name* that are ambiguous between *different*
|
||||
/// def sets must not be grouped into one highlight — the def-set
|
||||
/// comparison in `external_occurrences`, not the name match alone, is
|
||||
/// what keeps them apart. `dup_a` and `dup_b` are each declared in two
|
||||
/// files (so a connection to either is ambiguous), and both happen to
|
||||
/// export a port with the identical name `same_port` — so the two
|
||||
/// connections below share one `reference.name` but must resolve against
|
||||
/// disjoint ambiguous sets (`dup_a`'s two files vs. `dup_b`'s two files).
|
||||
#[test]
|
||||
fn two_uses_ambiguous_between_different_def_sets_do_not_group() {
|
||||
let dir = temp_dir("highlight_ambiguous_disjoint");
|
||||
let dup_a = "module dup_a (input logic same_port);\nendmodule\n";
|
||||
let dup_b = "module dup_b (input logic same_port);\nendmodule\n";
|
||||
fs::write(dir.join("a1.sv"), dup_a).expect("write");
|
||||
fs::write(dir.join("a2.sv"), dup_a).expect("write");
|
||||
fs::write(dir.join("b1.sv"), dup_b).expect("write");
|
||||
fs::write(dir.join("b2.sv"), dup_b).expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "\
|
||||
module top;
|
||||
logic clk;
|
||||
dup_a u_a (.same_port(clk));
|
||||
dup_b u_b (.same_port(clk));
|
||||
endmodule
|
||||
";
|
||||
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 doc = ws.document(&uri).expect("open");
|
||||
|
||||
let first = at(top_text, "same_port(clk));\n dup_b") + 1;
|
||||
let second = at(top_text, "same_port(clk));\nendmodule") + 1;
|
||||
// Premise: both connections are genuinely ambiguous externals (no
|
||||
// local `same_port`, and the workspace really does hold two
|
||||
// candidates for each), i.e. this exercises the def-set comparison
|
||||
// and not some earlier decline.
|
||||
let first_found =
|
||||
document_highlights(doc, first).expect("dup_a's connection is ambiguous, not empty");
|
||||
let second_found =
|
||||
document_highlights(doc, second).expect("dup_b's connection is ambiguous, not empty");
|
||||
let first_lines: Vec<u32> = first_found.iter().map(|h| h.range.start.line).collect();
|
||||
let second_lines: Vec<u32> = second_found.iter().map(|h| h.range.start.line).collect();
|
||||
assert_eq!(first_lines, vec![2], "dup_a's port only, despite sharing a name with dup_b's");
|
||||
assert_eq!(second_lines, vec![3], "dup_b's port only, despite sharing a name with dup_a's");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A use the overlay never answered — its `defs()` is empty, e.g. a
|
||||
/// package member the index does not hold — must decline like any other
|
||||
/// unanswered position, not fall through to some other file's namesake.
|
||||
#[test]
|
||||
fn an_unanswered_external_use_declines_rather_than_guessing() {
|
||||
let dir = temp_dir("highlight_unanswered");
|
||||
let top_path = dir.join("top.sv");
|
||||
// `missing_pkg` is never declared anywhere in the workspace, so the
|
||||
// import itself is the only thing the index can say nothing about;
|
||||
// `NOPE` is a member reference the overlay tries and fails to place.
|
||||
let top_text = "module top;\n import missing_pkg::*;\n wire [NOPE-1:0] a;\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 doc = ws.document(&uri).expect("open");
|
||||
|
||||
let use_pos = at(top_text, "NOPE") + 1;
|
||||
assert!(document_highlights(doc, use_pos).is_none(), "unresolved, so decline");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_import_resolves_into_the_packages_file() {
|
||||
let dir = temp_dir("pkg");
|
||||
|
||||
@@ -252,10 +252,14 @@ fn hovering_a_local_declaration() {
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn hovering_across_files_into_a_closed_file() {
|
||||
// The disk path: the target file is closed, so the card's heading line and
|
||||
// its snippet both come out of one read (`hover::disk_view`). The second
|
||||
// read that memo removed is measured beside it — it is the whole file
|
||||
// again, plus a whole `LineIndex` again.
|
||||
// The disk path: the target file is closed, so the card's heading line
|
||||
// comes from the index (`Def::lines`, no read at all) and its snippet from
|
||||
// the workspace's shared view of that file — read once, then held. This
|
||||
// is a *mean of twenty*, so nineteen of the runs are the held case: it is
|
||||
// the steady-state hover, not the first touch (which
|
||||
// `hovering_into_a_big_closed_file_first_touch_and_repeat` reports on its
|
||||
// own). Measured beside it is the read the first touch pays and every
|
||||
// later one does not.
|
||||
for lines in SIZES {
|
||||
let sub = generated_module("sub", lines);
|
||||
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
|
||||
@@ -279,12 +283,73 @@ fn hovering_across_files_into_a_closed_file() {
|
||||
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
|
||||
eprintln!(
|
||||
"hover, closed cross-file target: {lines} lines took {took:?} \
|
||||
(one read + LineIndex of that file: {one_read:?}, which is what the memo saves)"
|
||||
(one read + LineIndex of that file: {one_read:?}, which only the first touch pays)"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::hovering_into_a_big -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn hovering_into_a_big_closed_file_first_touch_and_repeat() {
|
||||
// The owner's report, measured: hovering an *instantiation* and hovering
|
||||
// one of its *ports* into a closed file that is big — the netlist-adjacent
|
||||
// shape a real workspace has one of. Two numbers per hover: the first
|
||||
// touch of that file in the session, and the touch after it, which is the
|
||||
// one a text cache can make free.
|
||||
//
|
||||
// "First touch" is cold to *this process* and to nothing else: the file
|
||||
// was written moments ago, so the OS page cache still holds it and the
|
||||
// read below is the cheap kind. A genuinely cold disk is worse than this,
|
||||
// never better.
|
||||
let sub = big_module("sub", 12_000_000);
|
||||
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
|
||||
let dir = scratch("bighover", &[("sub.sv", sub.as_str()), ("top.sv", top)]);
|
||||
let uri = path_to_uri(&dir.join("top.sv")).expect("uri");
|
||||
let instantiation = top.find("sub u").expect("an instantiation") as u32;
|
||||
let port = top.find("data_in(").expect("a port connection") as u32;
|
||||
|
||||
for (what, offset) in [("instantiation", instantiation), ("port", port)] {
|
||||
// A fresh workspace per measurement, so "first touch" really is one.
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
max_file_size: 100_000_000,
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
|
||||
let start = Instant::now();
|
||||
let card = hover(&ws, &uri, black_box(offset)).expect("a cross-file card");
|
||||
let first = start.elapsed();
|
||||
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
|
||||
let repeat = mean(10, || {
|
||||
black_box(hover(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
eprintln!(
|
||||
"hover on a {what} into a {:.1} MB closed file: first touch {first:?}, \
|
||||
repeat {repeat:?}",
|
||||
sub.len() as f64 / 1_000_000.0
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A module of at least `bytes` bytes: a small ANSI header — the declaration a
|
||||
/// hover actually lands on — behind a wall of filler lines, which is the shape
|
||||
/// of the files the owner's report is about.
|
||||
fn big_module(name: &str, bytes: usize) -> String {
|
||||
let mut src = format!("module {name} (\n input logic [31:0] data_in\n);\n");
|
||||
let mut n = 0;
|
||||
while src.len() < bytes {
|
||||
src.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n"));
|
||||
n += 1;
|
||||
}
|
||||
src.push_str("endmodule\n");
|
||||
src
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::reindexing -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
@@ -314,6 +379,102 @@ fn reindexing_one_changed_file() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::what_a_scan -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn what_a_scan_does_before_its_first_file() {
|
||||
// The floor under a mid-scan answer's latency. A scan answers messages
|
||||
// between two *files*, so whatever it does before the first one is a
|
||||
// block no drain can break up: resolving the scope, reading every
|
||||
// in-scope file, and opening the persistent store. Measured because
|
||||
// `docs/features/scan-interleave/README.md` files "read the files lazily"
|
||||
// as a deliberate not-done, and a not-done is only honest with a number.
|
||||
let files: Vec<(String, String)> =
|
||||
(0..200).map(|n| (format!("m{n}.sv"), generated_module(&format!("m{n}"), 1_000))).collect();
|
||||
let refs: Vec<(&str, &str)> =
|
||||
files.iter().map(|(name, text)| (name.as_str(), text.as_str())).collect();
|
||||
let dir = scratch("scanhead", &refs);
|
||||
let mut workspace = Workspace::default();
|
||||
workspace.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
workspace.adopt_roots(vec![dir.clone()]);
|
||||
let started = Instant::now();
|
||||
let mut scan = workspace.begin_scan(&mut |_| {});
|
||||
let head = started.elapsed();
|
||||
let started = Instant::now();
|
||||
workspace.scan_step(&mut scan, &mut |_| {});
|
||||
let one = started.elapsed();
|
||||
let started = Instant::now();
|
||||
while workspace.scan_step(&mut scan, &mut |_| {}) {}
|
||||
let rest = started.elapsed();
|
||||
let started = Instant::now();
|
||||
workspace.finish_scan(scan);
|
||||
let tail = started.elapsed();
|
||||
eprintln!(
|
||||
"scan of {} files of 1k lines: before the first file {head:?}, \
|
||||
one file {one:?}, the other {} {rest:?}, finishing {tail:?}",
|
||||
files.len(),
|
||||
files.len() - 1
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::publishing -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn publishing_a_half_built_index_mid_scan() {
|
||||
// What an interleaved scan's *publish* costs, against the per-file work it
|
||||
// is interleaved with. `docs/features/scan-interleave/README.md` chose the
|
||||
// publish rhythm from these numbers: a merge is a whole-index pass, so one
|
||||
// per file would be quadratic and one per drain is not.
|
||||
for files in [50usize, 200, 800] {
|
||||
let sources: Vec<(PathBuf, String)> = (0..files)
|
||||
.map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), 1_000)))
|
||||
.collect();
|
||||
let records: Vec<vlog_semantic::FileFacts> = sources
|
||||
.iter()
|
||||
.map(|(path, src)| vlog_semantic::FileFacts::of(path.clone(), src))
|
||||
.collect();
|
||||
let parse = mean(3, || {
|
||||
let (path, src) = &sources[0];
|
||||
black_box(vlog_semantic::FileFacts::of(black_box(path.clone()), black_box(src)));
|
||||
});
|
||||
let build = mean(3, || {
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
for facts in &records {
|
||||
builder.add_facts(facts.clone());
|
||||
}
|
||||
black_box(builder.finish());
|
||||
});
|
||||
let clone = mean(3, || {
|
||||
black_box(records.clone());
|
||||
});
|
||||
let index = WorkspaceIndex::build(
|
||||
sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::<Vec<_>>(),
|
||||
);
|
||||
let held = mean(10, || {
|
||||
let mut index = index.clone();
|
||||
index.update_facts(black_box(records[files / 2].clone()));
|
||||
black_box(index);
|
||||
});
|
||||
let index_clone = mean(10, || {
|
||||
black_box(index.clone());
|
||||
});
|
||||
eprintln!(
|
||||
"{files} files of 1k lines: one file's parse {parse:?}; \
|
||||
one whole merge {:?} (build {build:?} less {clone:?} of record cloning); \
|
||||
one update_facts on a held file {:?} (less {index_clone:?} of index cloning); \
|
||||
per-file feeding would cost {:?} of merging against {:?} of parsing",
|
||||
build.saturating_sub(clone),
|
||||
held.saturating_sub(index_clone),
|
||||
held.saturating_sub(index_clone) * files as u32,
|
||||
parse * files as u32,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::looking_up -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
@@ -340,3 +501,689 @@ fn looking_up_one_name_against_scanning_every_symbol() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::what_a_jump -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn what_a_jump_into_a_new_folder_costs_before_and_after() {
|
||||
// The owner's opentitan report, on a workspace this repository generates
|
||||
// for itself: many folders, browsed one jump at a time. Both shapes are
|
||||
// measured in the same run over the same tree, so the pair is a real
|
||||
// before/after and not two numbers from two days.
|
||||
//
|
||||
// * **before** — the whole rescan a widening `didOpen` used to run: every
|
||||
// file of every folder reached so far, re-read, re-hashed and re-merged.
|
||||
// It grows with every jump, which is the shape the report describes.
|
||||
// * **after** — the widen: the files the opened folder brings in, folded
|
||||
// into the index beside what is already there.
|
||||
let (folders, each) = (40, 25);
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_jump_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
for folder in 0..folders {
|
||||
let path = dir.join(format!("blk{folder:02}/rtl"));
|
||||
std::fs::create_dir_all(&path).expect("folder");
|
||||
for file in 0..each {
|
||||
std::fs::write(
|
||||
path.join(format!("f{file:02}.sv")),
|
||||
generated_module(&format!("b{folder:02}_f{file:02}"), 200),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
}
|
||||
|
||||
// Two workspaces over the same tree, jumped through the same folders, so
|
||||
// the only difference between the two columns is which path the widen
|
||||
// took. Neither uses the persistent store: `cache_dir` answers `None` in
|
||||
// this crate's tests unless a path is named, which is what keeps the
|
||||
// measurement about the scan and not about a warm cache.
|
||||
let mut whole = Workspace::default();
|
||||
whole.adopt_roots(vec![dir.clone()]);
|
||||
let mut incremental = Workspace::default();
|
||||
incremental.adopt_roots(vec![dir.clone()]);
|
||||
let mut rows: Vec<(usize, Duration, Duration, usize)> = Vec::new();
|
||||
for jump in 0..6 {
|
||||
let path = dir.join(format!("blk{jump:02}/rtl/f00.sv"));
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
|
||||
whole.set_document(uri.clone(), text.clone());
|
||||
let started = Instant::now();
|
||||
black_box(whole.rebuild_index());
|
||||
let rescan = started.elapsed();
|
||||
|
||||
let before = incremental.scope_dirs();
|
||||
incremental.set_document(uri, text);
|
||||
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 |_| {});
|
||||
while incremental.scan_step(&mut scan, &mut |_| {}) {}
|
||||
black_box(incremental.finish_scan(scan));
|
||||
let widen = started.elapsed();
|
||||
|
||||
assert_eq!(
|
||||
whole.index().fingerprint(),
|
||||
incremental.index().fingerprint(),
|
||||
"the two columns must describe the same index, or the numbers mean nothing"
|
||||
);
|
||||
rows.push((jump, rescan, widen, incremental.index().files().len()));
|
||||
}
|
||||
eprintln!("a jump into a new folder, {folders} folders of {each} files of 200 lines:");
|
||||
for (jump, rescan, widen, indexed) in rows {
|
||||
eprintln!(
|
||||
" jump {jump} ({indexed} files in scope after it): \
|
||||
whole rescan {rescan:?}, incremental widen {widen:?}"
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::what_a_widen_that_subsumes -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn what_a_widen_that_subsumes_the_old_scope_costs() {
|
||||
// `performance_take2.md` §5b, without opentitan: at the shipped
|
||||
// `scopeDepth: 2` the first jump from a block's testbench into its own RTL
|
||||
// raises the scope to the directory holding *every* block, which contains
|
||||
// the one already in scope. The two things this prints are the two the
|
||||
// report is about — how many files the widen actually reads (the new
|
||||
// blocks, never the old one), and how long that takes against the whole
|
||||
// rescan the same jump would otherwise cost.
|
||||
let (blocks, rtl_each, dv_each) = (20, 25, 10);
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_subsume_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
for block in 0..blocks {
|
||||
for (tag, folder, files) in [("r", "rtl", rtl_each), ("d", "dv/tb", dv_each)] {
|
||||
let path = dir.join(format!("ip/blk{block:02}/{folder}"));
|
||||
std::fs::create_dir_all(&path).expect("folder");
|
||||
for file in 0..files {
|
||||
// `corpus_file`, not `generated_module`: every name in it is
|
||||
// the file's own, so the workspace-wide word table grows with
|
||||
// the file count the way a real one does. That is the whole
|
||||
// point of this shape — a widen's cost is dominated by what it
|
||||
// does to tables the size of the workspace, not by the folder.
|
||||
std::fs::write(
|
||||
path.join(format!("f{file:02}.sv")),
|
||||
corpus_file(&format!("b{block:02}{tag}_f{file:02}"), 200),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
}
|
||||
}
|
||||
let tb = dir.join("ip/blk00/dv/tb/f00.sv");
|
||||
let rtl = dir.join("ip/blk00/rtl/f00.sv");
|
||||
let open = |ws: &mut Workspace, path: &PathBuf| {
|
||||
let uri = path_to_uri(path).expect("uri");
|
||||
ws.set_document(uri, std::fs::read_to_string(path).expect("read"));
|
||||
};
|
||||
// The shipped rung: depth 2, clamped by a root above `ip/`.
|
||||
let depth_two = |ws: &mut Workspace| {
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope_depth: 2,
|
||||
..Default::default()
|
||||
});
|
||||
ws.adopt_roots(vec![dir.clone()]);
|
||||
};
|
||||
|
||||
let mut whole = Workspace::default();
|
||||
depth_two(&mut whole);
|
||||
let mut incremental = Workspace::default();
|
||||
depth_two(&mut incremental);
|
||||
for ws in [&mut whole, &mut incremental] {
|
||||
open(ws, &tb);
|
||||
ws.rebuild_index();
|
||||
}
|
||||
let held = incremental.index().files().len();
|
||||
|
||||
open(&mut whole, &rtl);
|
||||
let started = Instant::now();
|
||||
black_box(whole.rebuild_index());
|
||||
let rescan = started.elapsed();
|
||||
|
||||
let before = incremental.scope_dirs();
|
||||
open(&mut incremental, &rtl);
|
||||
let added: Vec<PathBuf> =
|
||||
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 |_| {});
|
||||
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
|
||||
// once per new word, which is quadratic in the batch and was 40% of the
|
||||
// whole cost on opentitan's `hw/ip`.
|
||||
let landing = Instant::now();
|
||||
black_box(incremental.finish_scan(scan));
|
||||
let (finish, widen) = (landing.elapsed(), started.elapsed());
|
||||
|
||||
assert_eq!(
|
||||
whole.index().fingerprint(),
|
||||
incremental.index().fingerprint(),
|
||||
"the two columns must describe the same index, or the numbers mean nothing"
|
||||
);
|
||||
eprintln!(
|
||||
"a widen that subsumes the old scope, {blocks} blocks of {} files:\n \
|
||||
scope {held} -> {} files; the widen read {read} of them \
|
||||
(the {held} already indexed are not re-read)\n \
|
||||
whole rescan {rescan:?}, subsuming widen {widen:?} (landing it: {finish:?})",
|
||||
rtl_each + dv_each,
|
||||
incremental.index().files().len(),
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The module-name families a completion prefix lands in, so a one-character
|
||||
/// prefix names hundreds of modules and a five-character one names a handful —
|
||||
/// the shape `performance.md`'s prefix table has on the real corpus.
|
||||
const FAMILIES: [&str; 10] = [
|
||||
"aes",
|
||||
"prim",
|
||||
"kmac",
|
||||
"hmac",
|
||||
"spi_device",
|
||||
"otbn",
|
||||
"flash_ctrl",
|
||||
"rv_core",
|
||||
"clkmgr",
|
||||
"uart",
|
||||
];
|
||||
|
||||
/// A workspace the size of the corpus `performance.md` measured against: one
|
||||
/// module per file, named from [`FAMILIES`], each declaring names no other file
|
||||
/// declares so the word table grows with the file count the way a real one does.
|
||||
fn completion_corpus(dir: &std::path::Path, files: usize, body: usize) {
|
||||
for n in 0..files {
|
||||
let family = FAMILIES[n % FAMILIES.len()];
|
||||
let name = format!("{family}_{n:04}");
|
||||
std::fs::write(dir.join(format!("{name}.sv")), corpus_file(&name, body)).expect("write");
|
||||
}
|
||||
}
|
||||
|
||||
/// One corpus file: a package, then a module whose header is what a skeleton
|
||||
/// reads and whose body is the several hundred lines a real RTL file carries
|
||||
/// behind it.
|
||||
fn corpus_file(name: &str, body: usize) -> String {
|
||||
let mut text = format!(
|
||||
"package {name}_pkg;\n localparam int {name}_WIDTH = 8;\n \
|
||||
typedef logic [1:0] {name}_pair_t;\nendpackage\n\
|
||||
module {name} #(\n parameter int WIDTH = 8\n) (\n \
|
||||
input logic clk_i,\n input logic rst_ni,\n \
|
||||
input logic [WIDTH-1:0] {name}_data_i,\n \
|
||||
output logic [WIDTH-1:0] {name}_data_o\n);\n"
|
||||
);
|
||||
for n in 0..body / 4 {
|
||||
text.push_str(&format!(
|
||||
" wire [WIDTH-1:0] {name}_w{n};\n \
|
||||
assign {name}_w{n} = {name}_data_i ^ {{WIDTH{{rst_ni}}}};\n \
|
||||
reg [WIDTH-1:0] {name}_r{n};\n \
|
||||
always_ff @(posedge clk_i) {name}_r{n} <= {name}_w{n};\n"
|
||||
));
|
||||
}
|
||||
text.push_str(&format!(" assign {name}_data_o = {name}_data_i;\nendmodule\n"));
|
||||
text
|
||||
}
|
||||
|
||||
/// The buffer a completion is asked for in: a module body with `prefix` typed
|
||||
/// on a fresh item line, and the same prefix inside an expression.
|
||||
fn completion_buffer(prefix: &str, at_item: bool) -> (String, u32) {
|
||||
let text = match at_item {
|
||||
true => format!("module bench_top;\n {prefix}\nendmodule\n"),
|
||||
false => format!("module bench_top;\n logic x;\n assign x = {prefix}\nendmodule\n"),
|
||||
};
|
||||
let cursor = text.find("\nendmodule").expect("the last line") as u32;
|
||||
(text, cursor)
|
||||
}
|
||||
|
||||
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server perf::completing_over_a_real -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
|
||||
fn completing_over_a_real_project() {
|
||||
// The same measurement as `completing_one_keystroke_at_a_time`, over
|
||||
// whatever tree `LUCISV_PERF_CORPUS` names, with tier 0's bill broken out
|
||||
// over the modules that tree really declares. A generated corpus has
|
||||
// uniform files; a real one has a hundred-line header on one module and a
|
||||
// two-thousand-line body on the next, and the difference between the two
|
||||
// is worth being able to see. **Skipped when the variable is unset**, so
|
||||
// this crate's tests never depend on a checkout nobody promised.
|
||||
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
|
||||
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
|
||||
return;
|
||||
};
|
||||
let root = PathBuf::from(root);
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
let started = Instant::now();
|
||||
ws.open_whole_workspace(vec![root.clone()]);
|
||||
let scan = started.elapsed();
|
||||
let buffer = root.join("lucisv_perf_buffer.sv");
|
||||
let uri = path_to_uri(&buffer).expect("uri");
|
||||
eprintln!(
|
||||
"completion over {} indexed files of {} (scan {scan:?}), {} index names, {} words:",
|
||||
ws.index().files().len(),
|
||||
root.display(),
|
||||
ws.candidates().units("").len(),
|
||||
ws.candidates().words("").len()
|
||||
);
|
||||
|
||||
for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_reg", "zzzz"] {
|
||||
let (text, cursor) = completion_buffer(prefix, true);
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let position = {
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start
|
||||
};
|
||||
let items = match crate::completion::completions(&ws, &uri, position, true) {
|
||||
Some(lsp_types::CompletionResponse::List(list)) => list.items.len(),
|
||||
_ => 0,
|
||||
};
|
||||
let took = mean(5, || {
|
||||
black_box(crate::completion::completions(&ws, &uri, black_box(position), true));
|
||||
});
|
||||
|
||||
// Tier 0's bill over this prefix's own candidates, stage by stage, so
|
||||
// a slow row can be read rather than guessed at.
|
||||
let names: Vec<String> =
|
||||
ws.candidates().modules(prefix).iter().take(64).map(|n| n.to_string()).collect();
|
||||
let (mut read, mut slice, mut plan) = (0u128, 0u128, 0u128);
|
||||
let mut whole_files: Vec<&str> = Vec::new();
|
||||
let mut bytes = 0usize;
|
||||
for name in &names {
|
||||
let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue };
|
||||
let started = Instant::now();
|
||||
let Some(text) = ws.text_of(path) else { continue };
|
||||
read += started.elapsed().as_nanos();
|
||||
bytes += text.len();
|
||||
let started = Instant::now();
|
||||
let header = crate::completion::module_header(ws.index(), name, &text);
|
||||
slice += started.elapsed().as_nanos();
|
||||
let source = match header.as_deref() {
|
||||
Some(head) => head,
|
||||
None => {
|
||||
whole_files.push(name);
|
||||
&text
|
||||
}
|
||||
};
|
||||
let started = Instant::now();
|
||||
black_box(vlog_refactor::instantiation_plan(name, source, None).ok());
|
||||
plan += started.elapsed().as_nanos();
|
||||
}
|
||||
let each = names.len().max(1) as u128;
|
||||
eprintln!(
|
||||
" prefix {prefix:>9?}: {took:?} ({items} items); tier 0 over {} modules \
|
||||
({} KB read, parsed whole: {whole_files:?}): read {:?}, slice {:?}, plan {:?} each",
|
||||
names.len(),
|
||||
bytes / 1000,
|
||||
Duration::from_nanos((read / each) as u64),
|
||||
Duration::from_nanos((slice / each) as u64),
|
||||
Duration::from_nanos((plan / each) as u64),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::completing_one -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn completing_one_keystroke_at_a_time() {
|
||||
// `performance.md` §6d: completion cost tracks the *candidate* count before
|
||||
// the 512-item cap, so it is worst at the empty prefix — exactly where
|
||||
// every identifier starts. Two columns over the same workspace and the same
|
||||
// prefixes: the cursor at module-item position, where every tier runs, and
|
||||
// the cursor inside an expression, where the module-skeleton tier is gated
|
||||
// off. The difference between them is what tier 0 costs.
|
||||
let (files, body) = (4_000, 1_200);
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_completion_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
completion_corpus(&dir, files, body);
|
||||
std::fs::write(dir.join("bench_top.sv"), "module bench_top;\nendmodule\n").expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
let started = Instant::now();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let scan = started.elapsed();
|
||||
let uri = path_to_uri(&dir.join("bench_top.sv")).expect("uri");
|
||||
|
||||
eprintln!(
|
||||
"completion over {} indexed files (scan {scan:?}), \
|
||||
{} index names, {} project words:",
|
||||
ws.index().files().len(),
|
||||
ws.candidates().units("").len(),
|
||||
ws.candidates().words("").len()
|
||||
);
|
||||
for prefix in ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_0001", "zzzz"] {
|
||||
let mut row = String::new();
|
||||
for at_item in [true, false] {
|
||||
let (text, cursor) = completion_buffer(prefix, at_item);
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let position = {
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
doc.positions().range(vlog_parser::TextRange::new(cursor, cursor)).start
|
||||
};
|
||||
let items = match crate::completion::completions(&ws, &uri, position, true) {
|
||||
Some(lsp_types::CompletionResponse::List(list)) => list.items.len(),
|
||||
_ => 0,
|
||||
};
|
||||
let took = mean(5, || {
|
||||
black_box(crate::completion::completions(&ws, &uri, black_box(position), true));
|
||||
});
|
||||
let where_ = if at_item { "item" } else { "expr" };
|
||||
row.push_str(&format!(" {where_} {took:?} ({items} items);"));
|
||||
}
|
||||
eprintln!(" prefix {prefix:>9?}:{row}");
|
||||
}
|
||||
|
||||
// Tier 0's per-item bill, so the row above can be divided by 64.
|
||||
let module = "aes_0000";
|
||||
let path = dir.join(format!("{module}.sv"));
|
||||
let text = ws.text_of(&path).expect("readable");
|
||||
let read = mean(50, || {
|
||||
black_box(ws.text_of(black_box(&path)));
|
||||
});
|
||||
let whole = mean(50, || {
|
||||
black_box(
|
||||
vlog_refactor::instantiation_plan(black_box(module), black_box(&text), None).ok(),
|
||||
);
|
||||
});
|
||||
let header = crate::completion::module_header(ws.index(), module, &text).expect("a header");
|
||||
let sliced = mean(50, || {
|
||||
black_box(
|
||||
vlog_refactor::instantiation_plan(black_box(module), black_box(&header), None).ok(),
|
||||
);
|
||||
});
|
||||
let slicing = mean(50, || {
|
||||
black_box(crate::completion::module_header(
|
||||
ws.index(),
|
||||
black_box(module),
|
||||
black_box(&text),
|
||||
));
|
||||
});
|
||||
eprintln!(
|
||||
" one skeleton off a {}-line file: text_of {read:?}, \
|
||||
instantiation_plan over the whole file {whole:?}, \
|
||||
over its header alone {sliced:?} (slicing it: {slicing:?})",
|
||||
text.lines().count()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::what_the_scope_depth -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn what_the_scope_depth_default_costs() {
|
||||
// What moving the shipped `lucisv.index.scopeDepth` from 0 to 2 buys and
|
||||
// what it costs, on an opentitan-shaped tree this repository generates for
|
||||
// itself: blocks of `rtl/` and `dv/tb/`, with the opened buffer three
|
||||
// levels down — the layout `performance.md` §4 measured one indexed file
|
||||
// in. Every rung of the ladder over the same tree, so the columns are
|
||||
// comparable.
|
||||
let (blocks, per_folder, lines) = (12, 20, 200);
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_depth_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
for block in 0..blocks {
|
||||
for (folder, count) in [("rtl", per_folder), ("dv/tb", 1)] {
|
||||
let path = dir.join(format!("hw/ip/blk{block:02}/{folder}"));
|
||||
std::fs::create_dir_all(&path).expect("folder");
|
||||
for file in 0..count {
|
||||
let name = format!("b{block:02}_{}_{file:02}", folder.replace('/', "_"));
|
||||
std::fs::write(path.join(format!("{name}.sv")), generated_module(&name, lines))
|
||||
.expect("write");
|
||||
}
|
||||
}
|
||||
}
|
||||
let opened = dir.join("hw/ip/blk00/dv/tb/b00_dv_tb_00.sv");
|
||||
let uri = path_to_uri(&opened).expect("uri");
|
||||
let text = std::fs::read_to_string(&opened).expect("read");
|
||||
|
||||
eprintln!(
|
||||
"scopeDepth over {blocks} blocks of {} files ({per_folder} rtl + 1 dv/tb each), \
|
||||
buffer opened at hw/ip/blk00/dv/tb:",
|
||||
per_folder + 1
|
||||
);
|
||||
for depth in [0u64, 1, 2, 3] {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope_depth: depth,
|
||||
..Default::default()
|
||||
});
|
||||
ws.adopt_roots(vec![dir.clone()]);
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let started = Instant::now();
|
||||
black_box(ws.rebuild_index());
|
||||
let scan = started.elapsed();
|
||||
eprintln!(
|
||||
" depth {depth}: {} files indexed, {} index names, scan {scan:?}",
|
||||
ws.index().files().len(),
|
||||
ws.candidates().units("").len()
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::a_code_action -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn a_code_action_at_an_instantiation_before_and_after() {
|
||||
// The owner's instrumented session, on a workspace this repository
|
||||
// generates for itself: `textDocument/codeAction` answered in 3.1 s
|
||||
// against 0.01–0.44 ms for every other request. VS Code sends one on
|
||||
// nearly every cursor move, the server is single-threaded, so a cursor
|
||||
// resting on an instantiation — where F12 leaves it — held up every
|
||||
// definition and hover behind it.
|
||||
//
|
||||
// Three numbers over the same workspace and the same cursor:
|
||||
//
|
||||
// * **before** — the whole-workspace answer: `sources()` plus the engine
|
||||
// over every file, which is what the handler did until 2026-08-28;
|
||||
// * **after** — the same answer from the module's own fan-out;
|
||||
// * **`sources()` alone** — the workspace read on its own, which is the
|
||||
// floor the before column cannot go under, and the cost `rename` and
|
||||
// `prepare_rename` still pay (the follow-up recorded in
|
||||
// `docs/features/refactor-ports/README.md`).
|
||||
let (files, lines) = (500, 200);
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_action_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
|
||||
std::fs::write(dir.join("sub.sv"), sub).expect("write");
|
||||
// Three files instantiate `sub`; the rest have nothing to do with it.
|
||||
for n in 0..3 {
|
||||
std::fs::write(
|
||||
dir.join(format!("top{n}.sv")),
|
||||
format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
for n in 0..files {
|
||||
std::fs::write(
|
||||
dir.join(format!("f{n:04}.sv")),
|
||||
generated_module(&format!("f{n:04}"), lines),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let path = dir.join("sub.sv");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), sub.to_string());
|
||||
let offset = sub.find("input logic rst").expect("a port") as u32 + 12;
|
||||
|
||||
let before = mean(3, || {
|
||||
let sources = ws.sources();
|
||||
black_box(vlog_refactor::port_actions(&sources, black_box(&path), black_box(offset)));
|
||||
});
|
||||
let after = mean(20, || {
|
||||
black_box(crate::ports::code_actions(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
let read = mean(3, || {
|
||||
black_box(ws.sources());
|
||||
});
|
||||
// What `textDocument/prepareRename` cost on the same workspace when this
|
||||
// probe was written — the number the follow-up in the feature README was
|
||||
// filed with, and the one `a_rename_before_and_after` below now closes.
|
||||
let prepare = mean(3, || {
|
||||
let sources = ws.sources();
|
||||
let _ =
|
||||
black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset)));
|
||||
});
|
||||
// A measurement of an answer that was not given is worthless.
|
||||
assert_eq!(crate::ports::code_actions(&ws, &uri, 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:?} \
|
||||
(`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})",
|
||||
ws.index().files().len()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A workspace of `files` unrelated generated modules plus a `sub` module
|
||||
/// instantiated by three tops — the shape both rename probes measure over.
|
||||
/// Returns the directory, so the caller removes it.
|
||||
fn rename_corpus(tag: &str, files: usize, lines: usize) -> (PathBuf, &'static str) {
|
||||
let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_perf_{tag}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
std::fs::write(dir.join("sub.sv"), sub).expect("write");
|
||||
for n in 0..3 {
|
||||
std::fs::write(
|
||||
dir.join(format!("top{n}.sv")),
|
||||
format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
for n in 0..files {
|
||||
std::fs::write(
|
||||
dir.join(format!("f{n:04}.sv")),
|
||||
generated_module(&format!("f{n:04}"), lines),
|
||||
)
|
||||
.expect("write");
|
||||
}
|
||||
(dir, sub)
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::a_rename -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn a_rename_before_and_after() {
|
||||
// The owner's OpenTitan session: `prepareRename` 2.5–3.0 s and `rename`
|
||||
// 3.6–8.7 s, both of them `ws.sources()` followed by an index build and an
|
||||
// analysis over every in-scope file. `prepareRename` is what the rename
|
||||
// key sends *before the box opens*, so those seconds are a frozen editor
|
||||
// on a keypress that has committed to nothing.
|
||||
//
|
||||
// Four numbers over one workspace and one cursor:
|
||||
//
|
||||
// * **prepare, before** — `prepare_rename` over `sources()`;
|
||||
// * **prepare, after** — the buffer's own analysis and the index, reading
|
||||
// nothing;
|
||||
// * **rename, before** — `rename` over `sources()`;
|
||||
// * **rename, after** — `rename` over the symbol's fan-out.
|
||||
let (files, lines) = (500, 200);
|
||||
let (dir, sub) = rename_corpus("rename", files, lines);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let path = dir.join("sub.sv");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), sub.to_string());
|
||||
// The module's own name, which fans out to the three files naming it.
|
||||
let offset = sub.find("sub (").expect("the module name") as u32;
|
||||
|
||||
let prepare_before = mean(3, || {
|
||||
let sources = ws.sources();
|
||||
let _ =
|
||||
black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset)));
|
||||
});
|
||||
let prepare_after = mean(2_000, || {
|
||||
let _ = black_box(crate::rename::prepare(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
let rename_before = mean(3, || {
|
||||
let sources = ws.sources();
|
||||
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 fan_out = ws.rename_sources(&path, "sub", Some("renamed")).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 —
|
||||
// `docs/features/refactor-rename/README.md`). Measured on its own because
|
||||
// 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")));
|
||||
});
|
||||
let spelling_rung = mean(2_000, || {
|
||||
black_box(ws.index().files_spelling(black_box("renamed")).count());
|
||||
});
|
||||
|
||||
// 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");
|
||||
assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops");
|
||||
|
||||
eprintln!(
|
||||
"rename of `sub`, instantiated in 3 of {} files ({lines} lines each), fan-out {fan_out} files:\n \
|
||||
prepareRename: whole workspace {prepare_before:?} -> buffer+index {prepare_after:?}\n \
|
||||
rename: whole workspace {rename_before:?} -> fan-out {rename_after:?}\n \
|
||||
building the file set: {file_set:?}, of which `files_spelling`: {spelling_rung:?}",
|
||||
ws.index().files().len()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server perf::a_will_rename -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn a_will_rename_before_and_after() {
|
||||
// `workspace/willRenameFiles` read every in-scope file to ask each one
|
||||
// "do you write an `include?" — a question the include graph already
|
||||
// holds the answer to. Renaming any folder in the VS Code explorer sent
|
||||
// it, so it is the same `sources()` shape as the two above.
|
||||
let (files, lines) = (500, 200);
|
||||
let (dir, _) = rename_corpus("willrename", files, lines);
|
||||
std::fs::write(dir.join("defs.svh"), "`define W 8\n").expect("write");
|
||||
std::fs::write(dir.join("includer.sv"), "`include \"defs.svh\"\nmodule includer;\nendmodule\n")
|
||||
.expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri_of = |path: &std::path::Path| path_to_uri(path).expect("uri").as_str().to_string();
|
||||
let renamed = vec![lsp_types::FileRename {
|
||||
old_uri: uri_of(&dir.join("defs.svh")),
|
||||
new_uri: uri_of(&dir.join("widths.svh")),
|
||||
}];
|
||||
|
||||
let read_all = mean(3, || {
|
||||
black_box(ws.sources());
|
||||
});
|
||||
let read_includers = mean(200, || {
|
||||
black_box(ws.include_sources());
|
||||
});
|
||||
let after = mean(20, || {
|
||||
black_box(crate::file_ops::will_rename(&ws, black_box(&renamed)));
|
||||
});
|
||||
let rewrite = crate::file_ops::will_rename(&ws, &renamed);
|
||||
assert_eq!(
|
||||
rewrite.edit.and_then(|edit| edit.changes.map(|c| c.len())),
|
||||
Some(1),
|
||||
"the one includer"
|
||||
);
|
||||
eprintln!(
|
||||
"willRenameFiles over {} files, 1 of which includes anything:\n \
|
||||
reading the scope {read_all:?} -> reading the includers {read_includers:?}\n \
|
||||
whole answer, after: {after:?}",
|
||||
ws.index().files().len()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::{
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit,
|
||||
@@ -51,14 +51,17 @@ pub fn commands() -> Vec<String> {
|
||||
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() };
|
||||
// A code-action request arrives on every cursor move, and `sources()`
|
||||
// reads the whole in-scope file set from disk. The engine's one-file
|
||||
// question answers "there is nothing here" for almost every position
|
||||
// without any of that.
|
||||
if !vlog_refactor::may_have_port_action(&doc.text, offset) {
|
||||
// A code-action request arrives on every cursor move, so neither half of
|
||||
// this may walk the workspace. The engine's one-file question answers
|
||||
// "there is nothing here" for almost every position — and where it does
|
||||
// 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);
|
||||
if modules.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let sources = ws.sources();
|
||||
let sources = ws.module_sources(&path, &modules);
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
.into_iter()
|
||||
.filter_map(|action| {
|
||||
@@ -84,7 +87,6 @@ pub fn execute(
|
||||
command: &str,
|
||||
arguments: &[Value],
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let sources = ws.sources();
|
||||
let refactoring = match command {
|
||||
ADD_PORT => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
@@ -93,10 +95,12 @@ pub fn execute(
|
||||
})?;
|
||||
match module_argument(arguments.get(1)) {
|
||||
ModuleArgument::Name(name) => {
|
||||
let sources = ws.module_sources(&path, std::slice::from_ref(&name));
|
||||
vlog_refactor::add_port(&sources, ModuleRef::Name(&name), decl)?
|
||||
}
|
||||
ModuleArgument::Position(position) => {
|
||||
let offset = offset_of(ws, arguments.first(), position)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::add_port(&sources, ModuleRef::At { file: &path, offset }, decl)?
|
||||
}
|
||||
ModuleArgument::Missing => {
|
||||
@@ -109,11 +113,13 @@ pub fn execute(
|
||||
REMOVE_PORT => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, REMOVE_PORT)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::remove_port(&sources, &path, offset)?
|
||||
}
|
||||
PROPAGATE_PORTS => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, PROPAGATE_PORTS)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::propagate_ports(&sources, &path, offset)?
|
||||
}
|
||||
other => return Err(format!("`{other}` is not a lucisv command.")),
|
||||
@@ -121,6 +127,22 @@ pub fn execute(
|
||||
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
/// The files a port refactoring **at a position** reads: the fan-out of every
|
||||
/// module that position could name.
|
||||
///
|
||||
/// A command's position is looser than a code action's — `lucisv.addPort`
|
||||
/// takes one anywhere in the module it adds to — so the module the cursor sits
|
||||
/// *inside* is asked for as well as the ones its port element or its
|
||||
/// instantiation names. Both questions are the engine's own
|
||||
/// (`vlog_refactor`), so the set cannot drift from what the engine will then
|
||||
/// go looking for.
|
||||
fn sources_at(ws: &Workspace, path: &Path, offset: u32) -> Vec<(PathBuf, String)> {
|
||||
let Some(text) = ws.text_of(path) else { return ws.module_sources(path, &[]) };
|
||||
let mut modules = vlog_refactor::port_action_modules(&text, offset);
|
||||
modules.extend(vlog_refactor::enclosing_module(&text, offset));
|
||||
ws.module_sources(path, &modules)
|
||||
}
|
||||
|
||||
/// What the second argument of `lucisv.addPort` said.
|
||||
enum ModuleArgument {
|
||||
Name(String),
|
||||
@@ -357,6 +379,429 @@ mod tests {
|
||||
assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the answer is the whole workspace's answer, computed over a subset
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One action's title and the edits it carries, per file in path order.
|
||||
type Shape = (String, Vec<(String, Vec<String>)>);
|
||||
|
||||
/// A code action as a comparable value: its title and every edit it
|
||||
/// carries, per file in path order — the whole of what a client receives.
|
||||
/// `WorkspaceEdit.changes` is a `HashMap`, so it is sorted here rather
|
||||
/// than compared as it is stored.
|
||||
fn shape(actions: &[CodeActionOrCommand]) -> Vec<Shape> {
|
||||
actions
|
||||
.iter()
|
||||
.map(|action| {
|
||||
let CodeActionOrCommand::CodeAction(action) = action else {
|
||||
return ("a command".to_string(), Vec::new());
|
||||
};
|
||||
let mut changes: Vec<(String, Vec<String>)> = action
|
||||
.edit
|
||||
.as_ref()
|
||||
.and_then(|edit| edit.changes.as_ref())
|
||||
.map(|changes| {
|
||||
changes
|
||||
.iter()
|
||||
.map(|(uri, edits)| {
|
||||
let edits = edits
|
||||
.iter()
|
||||
.map(|edit| format!("{:?}{}", edit.range, edit.new_text))
|
||||
.collect();
|
||||
(uri.as_str().to_string(), edits)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
changes.sort();
|
||||
(action.title.clone(), changes)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What `code_actions` used to compute: the same engine call over every
|
||||
/// in-scope file. The equivalence tests below assert the new answer
|
||||
/// against this one rather than against a transcription of it.
|
||||
fn whole_workspace_at(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let doc = ws.document(uri).expect("an open document");
|
||||
let path = doc.path.clone().expect("a saved file");
|
||||
let sources = ws.sources();
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
.into_iter()
|
||||
.filter_map(|action| {
|
||||
let edit = workspace_edit(ws, &action.edit).ok()?;
|
||||
Some(CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: action.title,
|
||||
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
|
||||
edit: Some(edit),
|
||||
..Default::default()
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A workspace of `noise` files that have nothing to do with `sub`, plus
|
||||
/// `sub.sv` and three files that instantiate it.
|
||||
fn crowded(tree: &Tree, noise: usize) -> Workspace {
|
||||
tree.write("sub.sv", SUB);
|
||||
for n in 0..3 {
|
||||
tree.write(
|
||||
&format!("top{n}.sv"),
|
||||
&format!(
|
||||
"module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
for n in 0..noise {
|
||||
tree.write(
|
||||
&format!("noise{n}.sv"),
|
||||
&format!("module noise{n};\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()]);
|
||||
ws
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_code_action_answers_what_the_whole_workspace_would() {
|
||||
let tree = Tree::new("equivalence");
|
||||
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 subset = code_actions(&ws, &sub_uri, offset);
|
||||
assert_eq!(subset.len(), 1, "{subset:#?}");
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
assert_eq!(action.title, "lucisv: remove port `rst` (updates 3 instantiations)");
|
||||
assert_eq!(
|
||||
shape(&subset),
|
||||
shape(&whole_workspace_at(&ws, &sub_uri, offset)),
|
||||
"the subset must answer exactly what every file would have"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_files_a_code_action_reads_are_the_modules_own_fan_out() {
|
||||
let tree = Tree::new("fanout");
|
||||
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");
|
||||
let read = ws.module_sources(&sub, &["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", "top1.sv", "top2.sv"], "and not one noise file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen() {
|
||||
let tree = Tree::new("unsaved");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
// A file the index knows as instantiating nothing, whose buffer now
|
||||
// instantiates `sub`. No save, so no edge in the index.
|
||||
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());
|
||||
assert!(
|
||||
ws.index()
|
||||
.instantiations_of("sub")
|
||||
.iter()
|
||||
.all(|edge| ws.index().path(edge.file) != Some(extra.as_path())),
|
||||
"the index has not seen the unsaved instantiation"
|
||||
);
|
||||
|
||||
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());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
assert_eq!(action.title, "lucisv: remove port `rst` (updates 4 instantiations)");
|
||||
let edit = action.edit.as_ref().expect("an edit");
|
||||
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
|
||||
assert_eq!(shape(&subset), shape(&whole_workspace_at(&ws, &sub_uri, offset)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_refused_through_the_subset_as_well() {
|
||||
let tree = Tree::new("ambiguous");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
// A second declaration of `sub`, in a file nothing else names.
|
||||
tree.write("clone.sv", SUB);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().units("sub").len(), 2, "two declarations");
|
||||
|
||||
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());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
// Both definers are in the set, so the engine sees the ambiguity and
|
||||
// refuses — which is no action, exactly as over the whole workspace.
|
||||
assert!(ws
|
||||
.module_sources(&sub, &["sub".to_string()])
|
||||
.iter()
|
||||
.any(|(path, _)| path.ends_with("clone.sv")));
|
||||
assert!(code_actions(&ws, &sub_uri, offset).is_empty());
|
||||
assert!(whole_workspace_at(&ws, &sub_uri, offset).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_computes_over_the_subset_and_answers_the_same() {
|
||||
let tree = Tree::new("command");
|
||||
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());
|
||||
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&sub_uri).expect("uri"),
|
||||
Value::String("sub".into()),
|
||||
Value::String("input logic cfg".into()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
|
||||
let whole =
|
||||
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
|
||||
.expect("adds");
|
||||
assert_eq!(warnings, whole.warnings);
|
||||
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
|
||||
assert_eq!(edit.changes.as_ref().expect("changes").len(), 4, "sub.sv and its three tops");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_file_scope_instantiation_lands_in_the_subset() {
|
||||
let tree = Tree::new("qa_filescope");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
// A file-scope (owner-less) instantiation of `sub` — illegal SV, but
|
||||
// a tolerant parse still produces an Instantiation item, and the old
|
||||
// whole-workspace engine would still edit it (collect_instantiations
|
||||
// walks tree.items directly). It records no InstantiationEdge (edges_of
|
||||
// requires an owner), so only the references_to half of rung 3 can
|
||||
// possibly find it.
|
||||
let filescope_path = tree.write("filescope.sv", "sub u_fs (.clk(c), .rst(r));\n");
|
||||
ws.rebuild_index();
|
||||
assert!(
|
||||
ws.index()
|
||||
.instantiations_of("sub")
|
||||
.iter()
|
||||
.all(|edge| ws.index().path(edge.file) != Some(filescope_path.as_path())),
|
||||
"file-scope site records no edge, as documented"
|
||||
);
|
||||
|
||||
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());
|
||||
|
||||
let read = ws.module_sources(&sub, &["sub".to_string()]);
|
||||
let names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert!(
|
||||
names.contains(&"filescope.sv".to_string()),
|
||||
"file-scope instantiation site must be in the subset: {names:?}"
|
||||
);
|
||||
|
||||
// And the whole-workspace engine really would have edited it, so
|
||||
// omitting it from the subset would be a real divergence.
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let whole = whole_workspace_at(&ws, &sub_uri, offset);
|
||||
let CodeActionOrCommand::CodeAction(action) = &whole[0] else { panic!("an action") };
|
||||
let edit = action.edit.as_ref().expect("an edit");
|
||||
let fs_uri = path_to_uri(&filescope_path).expect("uri");
|
||||
assert_eq!(
|
||||
edits_for(edit, &fs_uri).len(),
|
||||
2,
|
||||
"the whole-workspace answer edits the file-scope site"
|
||||
);
|
||||
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption() {
|
||||
// The subset builder trusts the index for rungs 2/3, so a file that
|
||||
// changed on disk with nothing telling the server (no rebuild_index,
|
||||
// no didChange) is invisible to it — unlike the old `sources()` path,
|
||||
// which re-reads the directory fresh every call. Attack: write a
|
||||
// *second* definer of `sub` straight to disk, do NOT reindex, and
|
||||
// fire a code action. Judged against invariant 1 (never corrupt), not
|
||||
// against freshness: an answer that goes stale (or a refusal) is
|
||||
// fine; an edit that is not internally verified would not be.
|
||||
let tree = Tree::new("qa_stale_dup");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
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());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
// Sanity: before the duplicate exists anywhere, the subset offers the
|
||||
// action normally.
|
||||
assert_eq!(code_actions(&ws, &sub_uri, offset).len(), 1);
|
||||
|
||||
// Write a duplicate declaration straight to disk, bypassing the
|
||||
// server entirely (no rebuild_index, no set_document for this path).
|
||||
tree.write("dupe.sv", SUB);
|
||||
|
||||
// The index still knows only one definer, so the subset the server
|
||||
// computes is unaware of the ambiguity and still offers the action.
|
||||
assert_eq!(ws.index().units("sub").len(), 1, "the index has not been told");
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
assert_eq!(subset.len(), 1, "stale, but not refused — the index has not seen dupe.sv");
|
||||
|
||||
// The critical assertion: whatever it produced must still be an
|
||||
// honest, self-consistent, verified edit over the files it actually
|
||||
// read — not corruption of a file it never looked at. `dupe.sv`
|
||||
// itself must be untouched (never read, never in the edit) and the
|
||||
// edit that *was* produced must still verify against what changed.
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
let dupe_uri = path_to_uri(&tree.path.join("dupe.sv")).expect("uri");
|
||||
let edit = action.edit.as_ref().expect("an edit");
|
||||
assert!(
|
||||
edit.changes.as_ref().is_none_or(|c| !c.contains_key(&dupe_uri)),
|
||||
"the unindexed duplicate must not be touched: {edit:?}"
|
||||
);
|
||||
|
||||
// Once the index is told (rebuild_index, exactly what the watcher
|
||||
// does on a save it's told about), parity is restored: the subset
|
||||
// now sees the duplicate and refuses, exactly like the whole
|
||||
// workspace always would have.
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().units("sub").len(), 2, "now indexed");
|
||||
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "refuses once told");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_generate_block_instantiation_lands_in_the_subset() {
|
||||
let tree = Tree::new("qa_generate");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
let gen_path = tree.write(
|
||||
"gen.sv",
|
||||
"module gen;\n genvar i;\n generate\n for (i = 0; i < 2; i = i + 1) begin : g\n logic c, r;\n sub u_g (.clk(c), .rst(r));\n end\n endgenerate\nendmodule\n",
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert!(
|
||||
ws.index()
|
||||
.instantiations_of("sub")
|
||||
.iter()
|
||||
.any(|edge| ws.index().path(edge.file) == Some(gen_path.as_path())),
|
||||
"the generate-for body instantiation is a real edge"
|
||||
);
|
||||
|
||||
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());
|
||||
let read = ws.module_sources(&sub, &["sub".to_string()]);
|
||||
let names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert!(names.contains(&"gen.sv".to_string()), "{names:?}");
|
||||
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
let whole = whole_workspace_at(&ws, &sub_uri, offset);
|
||||
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_escaped_module_name_instantiation_parity_with_whole_workspace() {
|
||||
// Not a subset-specific question: does an escaped-identifier
|
||||
// instantiation (`\sub$weird u1 (...)`) even resolve to the module it
|
||||
// names, workspace-index-wise, so the subset builder's `units`/
|
||||
// `instantiations_of`/`references_to` lookups have anything to find?
|
||||
// Attacking whether the *subset* diverges from the *whole-workspace*
|
||||
// answer here, not whether escaped identifiers work at all (a
|
||||
// pre-existing question this round did not touch).
|
||||
let tree = Tree::new("qa_escaped");
|
||||
tree.write("esc.sv", "module esc;\n \\sub u_esc (.clk(c), .rst(r));\nendmodule\n");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
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());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
let whole = whole_workspace_at(&ws, &sub_uri, offset);
|
||||
// Whichever way the parser/binder treats the escaped identifier
|
||||
// `\sub ` (as `sub`, or as a distinct name), the subset and the
|
||||
// whole-workspace computation must agree either way.
|
||||
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_add_port_by_position_still_fans_out_to_instantiation_files() {
|
||||
// `a_command_computes_over_the_subset_and_answers_the_same` (the
|
||||
// dev's own equivalence test) drives `lucisv.addPort` with a
|
||||
// *module-name* argument. The *Position* argument takes a completely
|
||||
// different path to the module (`sources_at` → `port_action_modules`
|
||||
// + `enclosing_module`, rather than `module_sources` fed the name
|
||||
// directly) and is exactly the code action's own code path
|
||||
// (`ModuleArgument::Position` mirrors `ModuleRef::At`). Confirm it
|
||||
// still reaches every instantiating file, not just the declaring one.
|
||||
let tree = Tree::new("qa_add_by_position");
|
||||
let mut ws = crowded(&tree, 30);
|
||||
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());
|
||||
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&sub_uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
|
||||
Value::String("input logic cfg".into()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
|
||||
assert_eq!(warnings.len(), 3, "one TODO warning per instantiating top: {warnings:?}");
|
||||
let changes = edit.changes.as_ref().expect("changes");
|
||||
assert_eq!(changes.len(), 4, "sub.sv and its three instantiating tops: {changes:?}");
|
||||
for n in 0..3 {
|
||||
let top_uri = path_to_uri(&tree.path.join(format!("top{n}.sv"))).expect("uri");
|
||||
assert_eq!(edits_for(&edit, &top_uri).len(), 1, "top{n}.sv must gain the connection");
|
||||
}
|
||||
|
||||
let whole =
|
||||
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
|
||||
.expect("adds");
|
||||
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled() {
|
||||
// A module the index has never seen at all — not stale, genuinely
|
||||
// absent, e.g. a brand-new buffer the user has not saved yet. Rung 2
|
||||
// (`index.units`) has nothing; only rung 1 (the request's own file)
|
||||
// can supply it. The cursor sits in that same new buffer, so rung 1
|
||||
// must be enough on its own — and it must not panic or silently
|
||||
// return no action just because the index is empty for this name.
|
||||
let tree = Tree::new("qa_unsaved_new_module");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.index().units("brandnew").is_empty(), "the index has never heard of it");
|
||||
|
||||
let text = "module brandnew (\n input logic a,\n input logic b\n);\nendmodule\n";
|
||||
let new_path = tree.path.join("brandnew.sv"); // never written to disk
|
||||
let new_uri = path_to_uri(&new_path).expect("uri");
|
||||
ws.set_document(new_uri.clone(), text.to_string());
|
||||
|
||||
let offset = text.find("input logic b").expect("b") as u32 + 12;
|
||||
let subset = code_actions(&ws, &new_uri, offset);
|
||||
assert_eq!(subset.len(), 1, "{subset:#?}");
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
assert_eq!(action.title, "lucisv: remove port `b` (no instantiation in scope)");
|
||||
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_command_is_declined() {
|
||||
let tree = Tree::new("unknown");
|
||||
|
||||
@@ -24,10 +24,20 @@ use crate::uri::path_to_uri;
|
||||
/// The identifier at `offset` and its current name, or the reason it cannot
|
||||
/// be renamed. Returning the reason — rather than `null` — is what puts the
|
||||
/// engine's sentence in the editor's rename box instead of a shrug.
|
||||
///
|
||||
/// Answered from the buffer's own analysis and the index alone: no file is
|
||||
/// read, nothing is parsed. This request is what the rename key sends before
|
||||
/// the rename box even opens, and reading the workspace for it froze the whole
|
||||
/// server for 2.5–3.0 s on OpenTitan. Which refusals that costs — and which of
|
||||
/// them `rename` then delivers instead — is the table in
|
||||
/// `docs/features/refactor-rename/README.md`.
|
||||
pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameResponse, String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?;
|
||||
if doc.path.is_none() {
|
||||
return Err(UNSAVED.to_string());
|
||||
}
|
||||
let target =
|
||||
vlog_refactor::prepare_rename_here(&doc.semantics, &doc.external, ws.index(), offset)?;
|
||||
Ok(PrepareRenameResponse::RangeWithPlaceholder {
|
||||
range: doc.positions().range(target.range),
|
||||
placeholder: target.name,
|
||||
@@ -44,7 +54,16 @@ pub fn rename(
|
||||
) -> 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())?;
|
||||
let refactoring = vlog_refactor::rename(&ws.sources(), &path, offset, new_name)?;
|
||||
// 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 sources = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(&path, &name, Some(new_name)),
|
||||
None => ws.sources(),
|
||||
};
|
||||
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
|
||||
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
for (path, edits) in &refactoring.edits {
|
||||
@@ -80,7 +99,7 @@ const UNSAVED: &str = "lucisv can only rename inside a saved file.";
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
@@ -206,6 +225,617 @@ mod tests {
|
||||
assert_eq!(edits[0].range.start.character, 7);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The fan-out equivalence suite
|
||||
// ------------------------------------------------------------------
|
||||
//
|
||||
// `rename` is handed the symbol's fan-out through the index instead of
|
||||
// every in-scope file. A rename that edits fewer files than the truth is
|
||||
// corruption (CLAUDE.md invariant 1), and a refusal the narrow set cannot
|
||||
// reach is a refusal the user never sees — so every case below asks the
|
||||
// engine the same question twice, over the subset and over the whole
|
||||
// workspace, and asserts the two answers are the same bytes and the same
|
||||
// sentences. The sufficiency argument they are the evidence for is in
|
||||
// `docs/features/refactor-rename/README.md`.
|
||||
|
||||
/// The file set the server would hand `rename` for a cursor at `offset`.
|
||||
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)),
|
||||
None => ws.sources(),
|
||||
}
|
||||
.into_iter()
|
||||
.map(|(path, _)| path)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ask the engine over the fan-out and over the whole workspace, and
|
||||
/// assert the two answers are indistinguishable. Returns the answer, so a
|
||||
/// caller can also assert *what* it was.
|
||||
fn same_answer(
|
||||
ws: &Workspace,
|
||||
path: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
) -> Result<vlog_refactor::RefactorEdit, String> {
|
||||
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)),
|
||||
None => everything.clone(),
|
||||
};
|
||||
for (path, text) in &subset {
|
||||
let found = everything.iter().find(|(held, _)| held == path);
|
||||
assert_eq!(
|
||||
found.map(|(_, text)| text),
|
||||
Some(text),
|
||||
"{} is in the fan-out with text the whole scope does not have",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
let whole = vlog_refactor::rename(&everything, path, offset, new_name);
|
||||
let narrow = vlog_refactor::rename(&subset, path, offset, new_name);
|
||||
match (&whole, &narrow) {
|
||||
(Ok(whole), Ok(narrow)) => {
|
||||
assert_eq!(whole.edits, narrow.edits, "the fan-out edited different bytes");
|
||||
assert_eq!(whole.warnings, narrow.warnings, "the fan-out warned differently");
|
||||
}
|
||||
(Err(whole), Err(narrow)) => {
|
||||
assert_eq!(whole, narrow, "the fan-out refused in different words");
|
||||
}
|
||||
(Ok(whole), Err(narrow)) => panic!(
|
||||
"the fan-out invented a refusal: {narrow}, where the workspace edited {} files",
|
||||
whole.file_count()
|
||||
),
|
||||
(Err(whole), Ok(narrow)) => panic!(
|
||||
"the fan-out lost the refusal `{whole}` and edited {} files instead",
|
||||
narrow.file_count()
|
||||
),
|
||||
}
|
||||
narrow
|
||||
}
|
||||
|
||||
/// A workspace of `files`, every one of them also opened as a buffer when
|
||||
/// `open` names it, with the first named file's URI returned.
|
||||
fn tree_with(tree: &Tree, files: &[(&str, &str)], open: &[&str]) -> (Workspace, Vec<PathBuf>) {
|
||||
let paths: Vec<PathBuf> = files.iter().map(|(name, text)| tree.write(name, text)).collect();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
for name in open {
|
||||
let path = tree.path.join(name);
|
||||
let text = fs::read_to_string(&path).expect("written above");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, text);
|
||||
}
|
||||
(ws, paths)
|
||||
}
|
||||
|
||||
const MOD: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n";
|
||||
const ONE: &str = "module one;\n logic c, d;\n sub u_a (.clk(c), .q(d));\nendmodule\n";
|
||||
const TWO: &str =
|
||||
"module two;\n logic c, d;\n sub #(.W(3)) u_b (.clk(c), .q(d));\nendmodule\n";
|
||||
const GEN: &str = "module three;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_c (.clk(1'b0), .q());\n end\n endgenerate\nendmodule\n";
|
||||
const QUIET: &str = "module quiet;\n wire unrelated;\n assign unrelated = 1'b0;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn the_fan_out_answers_a_cross_file_module_rename_exactly_as_the_workspace_does() {
|
||||
let tree = Tree::new("fanout_module");
|
||||
let files = [
|
||||
("sub.sv", MOD),
|
||||
("one.sv", ONE),
|
||||
("two.sv", TWO),
|
||||
("three.sv", GEN),
|
||||
("quiet.sv", QUIET),
|
||||
];
|
||||
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let path = tree.path.join("one.sv");
|
||||
let at = at(ONE, "sub u_a");
|
||||
|
||||
let edit = same_answer(&ws, &path, at, "child").expect("renames");
|
||||
assert_eq!(edit.file_count(), 4, "the declaration and the three files naming it");
|
||||
|
||||
// And the narrowing is real: the file that never spells the name is
|
||||
// not read at all.
|
||||
let fan = fan_out(&ws, &path, at, "child");
|
||||
assert!(!fan.contains(&tree.path.join("quiet.sv")), "{fan:?}");
|
||||
assert!(fan.contains(&tree.path.join("three.sv")), "the generate-block site: {fan:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fan_out_keeps_the_end_label_and_the_declaration_together() {
|
||||
let tree = Tree::new("fanout_endlabel");
|
||||
let (ws, _) = tree_with(&tree, &[("sub.sv", MOD), ("one.sv", ONE)], &["sub.sv"]);
|
||||
let path = tree.path.join("sub.sv");
|
||||
let edit = same_answer(&ws, &path, at(MOD, "sub #"), "child").expect("renames");
|
||||
let own = edit.edits_for(&path);
|
||||
assert_eq!(own.len(), 2, "the header name and the `endmodule : sub` label");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fan_out_carries_a_port_rename_to_every_connection() {
|
||||
let tree = Tree::new("fanout_port");
|
||||
let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", TWO), ("quiet.sv", QUIET)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["sub.sv"]);
|
||||
let path = tree.path.join("sub.sv");
|
||||
let edit = same_answer(&ws, &path, at(MOD, "clk,"), "clock").expect("renames");
|
||||
assert_eq!(edit.file_count(), 3, "the module and both files connecting `.clk`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fan_out_carries_a_package_member_rename_to_every_importer() {
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
const IMPORTER: &str =
|
||||
"module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
|
||||
const QUALIFIER: &str =
|
||||
"module qualifier;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_pkg");
|
||||
let files =
|
||||
[("pkg.sv", PKG), ("reader.sv", IMPORTER), ("qual.sv", QUALIFIER), ("quiet.sv", QUIET)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["reader.sv"]);
|
||||
let path = tree.path.join("reader.sv");
|
||||
let edit = same_answer(&ws, &path, at(IMPORTER, "DEPTH;"), "SIZE").expect("renames");
|
||||
assert_eq!(edit.file_count(), 3, "the package and both files reading it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fan_out_sees_a_reference_only_an_unsaved_buffer_has() {
|
||||
let tree = Tree::new("fanout_unsaved");
|
||||
// On disk `two.sv` says nothing about `sub`; the buffer instantiates
|
||||
// it. The index has never seen the buffer's text.
|
||||
let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", QUIET)];
|
||||
let (mut ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let two = tree.path.join("two.sv");
|
||||
ws.set_document(path_to_uri(&two).expect("uri"), TWO.to_string());
|
||||
assert!(
|
||||
ws.index().instantiations_of("sub").len() < 2,
|
||||
"premise: the index has not seen the buffer's instantiation"
|
||||
);
|
||||
|
||||
let path = tree.path.join("one.sv");
|
||||
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
|
||||
assert!(!edit.edits_for(&two).is_empty(), "the unsaved instantiation is renamed too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fan_out_refuses_a_name_the_workspace_declares_twice_in_the_same_words() {
|
||||
let tree = Tree::new("fanout_dup");
|
||||
let files = [("sub.sv", MOD), ("copy.sv", MOD), ("one.sv", ONE)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let path = tree.path.join("one.sv");
|
||||
let refusal =
|
||||
same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect_err("declared twice");
|
||||
assert!(refusal.contains("more than one indexed file"), "{refusal}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere() {
|
||||
// `three.sv` names `sub`; `taken.sv` declares the module the rename
|
||||
// wants to become. Renaming `sub` to `taken` makes every `sub` site
|
||||
// ambiguous — a file the postings for `sub` alone would never name.
|
||||
const TAKEN: &str = "module taken;\nendmodule\n";
|
||||
const USES_TAKEN: &str = "module holder;\n taken u_t ();\nendmodule\n";
|
||||
let tree = Tree::new("fanout_capture");
|
||||
let files =
|
||||
[("sub.sv", MOD), ("one.sv", ONE), ("taken.sv", TAKEN), ("uses.sv", USES_TAKEN)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let path = tree.path.join("one.sv");
|
||||
let refusal =
|
||||
same_answer(&ws, &path, at(ONE, "sub u_a"), "taken").expect_err("would capture");
|
||||
assert!(refusal.contains("would change what"), "{refusal}");
|
||||
|
||||
let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "taken");
|
||||
assert!(fan.contains(&tree.path.join("uses.sv")), "the new name's own fan-out: {fan:?}");
|
||||
}
|
||||
|
||||
/// The two `` `define`` warnings come from files the index's own define
|
||||
/// tables name, so both survive the narrowing: a macro *called* the name,
|
||||
/// and a macro whose **body** spells it, each in a file that has nothing
|
||||
/// else to do with the symbol.
|
||||
#[test]
|
||||
fn the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read() {
|
||||
const NAMED: &str = "`define sub 1\nmodule named_holder;\nendmodule\n";
|
||||
const BODY: &str = "`define WRAP(x) sub x\nmodule body_holder;\n wire w;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_macro");
|
||||
let files = [
|
||||
("sub.sv", MOD),
|
||||
("one.sv", ONE),
|
||||
("named.sv", NAMED),
|
||||
("body.svh", BODY),
|
||||
("quiet.sv", QUIET),
|
||||
];
|
||||
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let path = tree.path.join("one.sv");
|
||||
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
|
||||
assert!(
|
||||
edit.warnings.iter().any(|w| w.contains("is also a macro defined")),
|
||||
"{:?}",
|
||||
edit.warnings
|
||||
);
|
||||
assert!(
|
||||
edit.warnings.iter().any(|w| w.contains("in the body of macro `WRAP`")),
|
||||
"{:?}",
|
||||
edit.warnings
|
||||
);
|
||||
let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "child");
|
||||
assert!(fan.contains(&tree.path.join("named.sv")), "the macro's own name: {fan:?}");
|
||||
assert!(fan.contains(&tree.path.join("body.svh")), "the macro's body: {fan:?}");
|
||||
assert!(!fan.contains(&tree.path.join("quiet.sv")), "and nothing else: {fan:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_the_workspace_rename_edits_is_in_the_fan_out() {
|
||||
// The invariant-1 assertion, made directly rather than through an
|
||||
// equality: whatever the whole workspace would rewrite, the narrow set
|
||||
// must contain — otherwise a rename edits fewer files than the truth.
|
||||
let tree = Tree::new("fanout_covers");
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
const IMPORTER: &str = "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\n sub u (.clk(1'b0), .q());\nendmodule\n";
|
||||
let files = [
|
||||
("sub.sv", MOD),
|
||||
("one.sv", ONE),
|
||||
("two.sv", TWO),
|
||||
("three.sv", GEN),
|
||||
("pkg.sv", PKG),
|
||||
("reader.sv", IMPORTER),
|
||||
("quiet.sv", QUIET),
|
||||
];
|
||||
let (ws, _) = tree_with(&tree, &files, &["reader.sv"]);
|
||||
let path = tree.path.join("reader.sv");
|
||||
let everything = ws.sources();
|
||||
let text = fs::read_to_string(&path).expect("written");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let Ok(whole) = vlog_refactor::rename(&everything, &path, offset, "renamed_thing")
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let fan = fan_out(&ws, &path, offset, "renamed_thing");
|
||||
for (edited, _) in &whole.edits {
|
||||
assert!(
|
||||
fan.contains(edited),
|
||||
"byte {offset} renames {} and the fan-out does not hold it: {fan:?}",
|
||||
edited.display()
|
||||
);
|
||||
}
|
||||
let _ = same_answer(&ws, &path, offset, "renamed_thing");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA, 2026-08-28 attack: an instantiation spelled with an escaped
|
||||
/// identifier (`` \sub ``) is a *different* name from `sub` to
|
||||
/// `vlog_semantic` today (a pre-existing simplification, noted in this
|
||||
/// feature's own 2026-08-24 QA round for a declaration, not an
|
||||
/// instantiation) — it resolves to nothing, so it is renamed by neither
|
||||
/// path. The question this pins is narrower: does narrowing the file set
|
||||
/// change that answer? It must not, since both paths call the identical
|
||||
/// engine; the risk would be the fan-out *dropping* the file outright
|
||||
/// while the whole-workspace run still watches it (`\sub` contains the
|
||||
/// word `sub`, so `contains_word` — and hence `watched_files` — still
|
||||
/// picks it up in the whole run). `same_answer` checks the observable
|
||||
/// output only (edits, warnings, or refusal), which is what must agree.
|
||||
#[test]
|
||||
fn an_escaped_identifier_instantiation_does_not_break_fan_out_parity() {
|
||||
const ESCAPED: &str = "module holder;\n \\sub u_weird (.clk(1'b0), .q());\nendmodule\n";
|
||||
let tree = Tree::new("fanout_escaped");
|
||||
let files = [("sub.sv", MOD), ("one.sv", ONE), ("escaped.sv", ESCAPED)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let path = tree.path.join("one.sv");
|
||||
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
|
||||
assert!(
|
||||
edit.edits_for(&tree.path.join("escaped.sv")).is_empty(),
|
||||
"the escaped spelling is a different name to vlog_semantic and must stay untouched"
|
||||
);
|
||||
}
|
||||
|
||||
/// QA, 2026-08-28 attack: a same-spelling but *different* symbol (a
|
||||
/// module unit named `sub` vs. a port/member also named `sub` in an
|
||||
/// unrelated module) must not cross-contaminate the fan-out — renaming
|
||||
/// the unit must not touch the member's own declaration or its file.
|
||||
#[test]
|
||||
fn a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out() {
|
||||
const OTHER_MODULE_WITH_A_PORT_NAMED_SUB: &str =
|
||||
"module other;\n wire sub;\n assign sub = 1'b0;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_same_spelling_different_symbol");
|
||||
let files =
|
||||
[("sub.sv", MOD), ("one.sv", ONE), ("other.sv", OTHER_MODULE_WITH_A_PORT_NAMED_SUB)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let path = tree.path.join("one.sv");
|
||||
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
|
||||
assert!(
|
||||
edit.edits_for(&tree.path.join("other.sv")).is_empty(),
|
||||
"the unrelated wire named `sub` must not be touched: {:?}",
|
||||
edit.edits_for(&tree.path.join("other.sv"))
|
||||
);
|
||||
// other.sv may legitimately be *watched* by the whole-word text
|
||||
// search (it spells "sub"), but it must never be *edited* — checked
|
||||
// above — nor must its own local wire's meaning change, which
|
||||
// `same_answer`'s byte-identical edits/warnings assertion already
|
||||
// confirmed by passing at all.
|
||||
}
|
||||
|
||||
/// QA, 2026-08-28 attack: the escape hatch (refusal 10 / ambiguous
|
||||
/// posting) must fire even when the ambiguity is on the **new** name,
|
||||
/// discovered on the second spelling `fan_out_of` walks, not the first.
|
||||
/// `Workspace::rename_sources` iterates `[name, new_name]` in that order
|
||||
/// and bails to `sources()` on the first ambiguous hit — this attacks the
|
||||
/// case where the *old* name's rung is completely unambiguous and only
|
||||
/// the second iteration finds the problem, to check the early return
|
||||
/// doesn't leak a partially-built (too-narrow) `wanted` set instead of
|
||||
/// truly falling back to the whole scope.
|
||||
#[test]
|
||||
fn the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous() {
|
||||
const A: &str = "package taken_pkg;\n parameter int DEPTH = 1;\nendpackage\n";
|
||||
const B: &str = "package taken_pkg;\n parameter int DEPTH = 2;\nendpackage\n";
|
||||
const READER: &str =
|
||||
"module reader;\n import taken_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_ambig_on_new_name");
|
||||
let files =
|
||||
[("sub.sv", MOD), ("one.sv", ONE), ("a.sv", A), ("b.sv", B), ("reader.sv", READER)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
|
||||
let path = tree.path.join("one.sv");
|
||||
let at = at(ONE, "sub u_a");
|
||||
// `sub` (the old name) has an unambiguous, tiny fan-out on its own.
|
||||
let fan = fan_out(&ws, &path, at, "taken_pkg");
|
||||
assert_eq!(
|
||||
fan.len(),
|
||||
ws.sources().len(),
|
||||
"the new name's own ambiguity must still hand back the whole scope: {fan:?}"
|
||||
);
|
||||
same_answer(&ws, &path, at, "taken_pkg").expect_err("ambiguous new name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope() {
|
||||
// Two files declare the *same* package, so `cfg_pkg::DEPTH` names
|
||||
// either declaration equally. The index records that the declarations
|
||||
// are ambiguously referenced but not which file does it, so the
|
||||
// fan-out refuses to narrow at all — which is how the refusal
|
||||
// survives.
|
||||
const A: &str = "package cfg_pkg;\n parameter int DEPTH = 1;\nendpackage\n";
|
||||
const B: &str = "package cfg_pkg;\n parameter int DEPTH = 2;\nendpackage\n";
|
||||
const READER: &str =
|
||||
"module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_ambig");
|
||||
let files = [("a.sv", A), ("b.sv", B), ("reader.sv", READER), ("quiet.sv", QUIET)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["a.sv"]);
|
||||
let path = tree.path.join("a.sv");
|
||||
let at = at(A, "DEPTH =");
|
||||
let fan = fan_out(&ws, &path, at, "SIZE");
|
||||
assert_eq!(
|
||||
fan.len(),
|
||||
ws.sources().len(),
|
||||
"an ambiguous posting hands back the whole scope: {fan:?}"
|
||||
);
|
||||
same_answer(&ws, &path, at, "SIZE").expect_err("ambiguous");
|
||||
}
|
||||
|
||||
/// Found by QA on 2026-08-28 as a **lost refusal**, and closed by the
|
||||
/// sixth rung the lead ruled for the same day; kept as the regression
|
||||
/// test for it, now asserting parity rather than pinning the divergence.
|
||||
///
|
||||
/// A file whose only mention of the **new** name is a bare use that
|
||||
/// resolves to nothing today — `import taken_pkg::*` of a package nobody
|
||||
/// declares yet — declares nothing, references nothing under the *old*
|
||||
/// name, instantiates nothing and defines no macro, so the first five
|
||||
/// rungs of the fan-out cannot see it. The rename is exactly what gives
|
||||
/// that import a meaning, which is what capture rule 12 refuses over, so
|
||||
/// the narrow path used to answer `Ok` where the whole workspace refused
|
||||
/// — a materially weaker answer, not a lost warning.
|
||||
/// `WorkspaceIndex::files_spelling` is the rung that finds it: the
|
||||
/// per-file records keep every external use under the name it spells,
|
||||
/// including the ones that resolved to nothing.
|
||||
#[test]
|
||||
fn a_dangling_import_of_the_new_name_is_refused_by_both_paths() {
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
const STRAY_IMPORT: &str = "module strayer;\n import taken_pkg::*;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_dangling_import");
|
||||
let files = [("pkg.sv", PKG), ("stray.sv", STRAY_IMPORT)];
|
||||
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_pkg");
|
||||
assert!(
|
||||
fan.contains(&tree.path.join("stray.sv")),
|
||||
"the dangling import's file is in the fan-out through `files_spelling`: {fan:?}"
|
||||
);
|
||||
|
||||
let refusal =
|
||||
same_answer(&ws, &path, at, "taken_pkg").expect_err("would capture the import");
|
||||
assert!(refusal.contains("would change what"), "{refusal}");
|
||||
assert!(refusal.contains("taken_pkg"), "{refusal}");
|
||||
}
|
||||
|
||||
/// The other half of the ruling: the **old** name needs no such rung, and
|
||||
/// this is the case that would expose it if it did. `stray.sv`'s only tie
|
||||
/// to the rename is an `import cfg_pkg::*`-shaped use of a name that
|
||||
/// resolves to nothing — spelled with the name being renamed *away*.
|
||||
/// A rename only ever removes declarations of the old name, so a lookup
|
||||
/// that failed before still fails after; the answer cannot move, and both
|
||||
/// paths agree without `stray.sv` being read.
|
||||
#[test]
|
||||
fn a_dangling_use_of_the_old_name_needs_no_rung_of_its_own() {
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
// `absent_pkg` is declared nowhere, and is what the rename renames to
|
||||
// nothing: the file's only spelling of it stays unresolved throughout.
|
||||
const STRAY: &str = "module strayer;\n import absent_pkg::*;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_dangling_old");
|
||||
let files = [("pkg.sv", PKG), ("stray.sv", STRAY)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
|
||||
let path = tree.path.join("pkg.sv");
|
||||
|
||||
// Rename the *package* to `absent_pkg` — the new-name rung must pull
|
||||
// `stray.sv` in and both paths must refuse …
|
||||
let package = at(PKG, "cfg_pkg;");
|
||||
same_answer(&ws, &path, package, "absent_pkg").expect_err("would capture the import");
|
||||
|
||||
// … while a rename whose *old* name is the dangling one has nothing to
|
||||
// capture: renaming `DEPTH`, which `stray.sv` never spells, leaves it
|
||||
// out of the set and both paths agree.
|
||||
let depth = at(PKG, "DEPTH =");
|
||||
let edit = same_answer(&ws, &path, depth, "SIZE").expect("renames");
|
||||
assert_eq!(edit.file_count(), 1, "only the package's own file");
|
||||
let fan = fan_out(&ws, &path, depth, "SIZE");
|
||||
assert!(!fan.contains(&tree.path.join("stray.sv")), "{fan:?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA, 2026-08-29: re-verification of rung 6 (files_spelling) after the
|
||||
// lead-authorized fix for the dangling-import residue.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Attack on rung 6's completeness: the new name spelled **only** as the
|
||||
/// base of an `extends` clause the workspace does not (yet) declare. This
|
||||
/// goes through `Target::Unit`, not `Target::Package` — a different
|
||||
/// resolution path than the import case rung 6 was built for — so it is
|
||||
/// worth checking on its own rather than trusting the same mechanism
|
||||
/// covers it by analogy.
|
||||
#[test]
|
||||
fn a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6() {
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
const STRAY_EXTENDS: &str =
|
||||
"class derived extends taken_base;\n function void go();\n endfunction\nendclass\n";
|
||||
let tree = Tree::new("fanout_extends_base");
|
||||
let files = [("pkg.sv", PKG), ("stray.sv", STRAY_EXTENDS)];
|
||||
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_base");
|
||||
assert!(
|
||||
fan.contains(&tree.path.join("stray.sv")),
|
||||
"the extends base is a Target::Unit miss, always non-empty paths: {fan:?}"
|
||||
);
|
||||
let refusal =
|
||||
same_answer(&ws, &path, at, "taken_base").expect_err("would give the base a meaning");
|
||||
assert!(refusal.contains("would change what"), "{refusal}");
|
||||
}
|
||||
|
||||
/// Attack on rung 6's completeness: a bare, unqualified reference to the
|
||||
/// new name written inside a class that `extends` an **existing,
|
||||
/// unrelated** base, with no import in scope — the one shape that
|
||||
/// produces `Resolution::InheritedCandidate` with genuinely **empty**
|
||||
/// paths (`miss()`'s branch when `nearest_extends` finds a base but no
|
||||
/// import supplied anything), which `files_spelling` cannot see (it reads
|
||||
/// only facts with non-empty paths). The argument this pins: such a
|
||||
/// reference is resolved *purely* from the file's own unedited text and
|
||||
/// never depends on the workspace (`resolve_external` never even tries
|
||||
/// `follow_paths` against an empty list), so it cannot change meaning
|
||||
/// under any rename — excluding the file costs nothing, on this rung or
|
||||
/// the whole-workspace path alike.
|
||||
#[test]
|
||||
fn an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung() {
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
const EXISTING_BASE: &str = "class existing_base;\nendclass\n";
|
||||
// No import anywhere in `stray.sv`, so the lexical miss on
|
||||
// `taken_member` inside `derived` (which extends `existing_base`)
|
||||
// collects an empty `external` list and becomes an `InheritedCandidate`
|
||||
// with `paths: []` — recorded nowhere, per `facts_from_analysis`.
|
||||
const STRAY: &str = "class derived extends existing_base;\n function void go();\n taken_member = 1;\n endfunction\nendclass\n";
|
||||
let tree = Tree::new("fanout_inherited_empty_paths");
|
||||
let files = [("pkg.sv", PKG), ("base.sv", EXISTING_BASE), ("stray.sv", STRAY)];
|
||||
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_member");
|
||||
assert!(
|
||||
!fan.contains(&tree.path.join("stray.sv")),
|
||||
"an empty-paths InheritedCandidate is invisible to files_spelling by design: {fan:?}"
|
||||
);
|
||||
// Parity must still hold: excluding the file must not change the
|
||||
// answer, because the reference inside it can never resolve
|
||||
// differently regardless of what `cfg_pkg` becomes.
|
||||
same_answer(&ws, &path, at, "taken_member").expect("renames, no capture possible");
|
||||
}
|
||||
|
||||
/// Attack on rung 6's soundness: a **local-only** symbol in a third file
|
||||
/// that happens to share the new name's spelling must not trigger a
|
||||
/// bogus refusal. `files_spelling` explicitly excludes `ReferenceFact::Local`
|
||||
/// facts (a local declaration/use resolves inside its own file and the
|
||||
/// 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.
|
||||
#[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";
|
||||
let tree = Tree::new("fanout_local_only");
|
||||
let files = [("pkg.sv", PKG), ("local.sv", LOCAL_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_local");
|
||||
assert!(
|
||||
!fan.contains(&tree.path.join("local.sv")),
|
||||
"a purely local declaration/use is not an external fact: {fan:?}"
|
||||
);
|
||||
let edit =
|
||||
same_answer(&ws, &path, at, "taken_local").expect("renames, no capture possible");
|
||||
assert!(edit.edits_for(&tree.path.join("local.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
|
||||
/// "first-written import wins" resolves `shared_name` to `p_pkg`'s
|
||||
/// declaration. Renaming *away* `p_pkg::shared_name` removes the winning
|
||||
/// candidate, so the same reference should fall through to `q_pkg`'s
|
||||
/// pre-existing, completely unrelated declaration — a meaning change the
|
||||
/// whole-workspace verifier must refuse over (rule 12, in the direction
|
||||
/// "an existing use is captured by nothing new — it silently rebinds to
|
||||
/// another *existing* declaration"). The old-name argument says this
|
||||
/// cannot be missed because rung 1 walks *every* declaration named
|
||||
/// `shared_name` (both `p_pkg`'s and `q_pkg`'s, not just the target's),
|
||||
/// so the importer is pulled in via `references_to` of `p_pkg`'s
|
||||
/// declaration regardless.
|
||||
#[test]
|
||||
fn removing_the_old_names_winning_declaration_does_not_escape_the_fan_out() {
|
||||
const P: &str = "package p_pkg;\n parameter int shared_name = 1;\nendpackage\n";
|
||||
const Q: &str = "package q_pkg;\n parameter int shared_name = 2;\nendpackage\n";
|
||||
const USER: &str = "module user;\n import p_pkg::*;\n import q_pkg::*;\n localparam int X = shared_name;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_shadow_unmask");
|
||||
let files = [("p.sv", P), ("q.sv", Q), ("user.sv", USER)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["p.sv"]);
|
||||
let path = tree.path.join("p.sv");
|
||||
let at = at(P, "shared_name =");
|
||||
|
||||
let fan = fan_out(&ws, &path, at, "renamed_thing");
|
||||
assert!(
|
||||
fan.contains(&tree.path.join("user.sv")),
|
||||
"the importer is posted against p_pkg's declaration today: {fan:?}"
|
||||
);
|
||||
assert!(
|
||||
fan.contains(&tree.path.join("q.sv")),
|
||||
"rung 1 walks every declaration named `shared_name`, not only the target's: {fan:?}"
|
||||
);
|
||||
// Whichever way the whole-workspace path answers this (refuse, since
|
||||
// `user.sv`'s meaning silently moves from p_pkg to q_pkg; or edit,
|
||||
// if some other rule intervenes first), the subset must answer
|
||||
// identically — that is the property under attack, not a specific
|
||||
// outcome.
|
||||
// The hunt comes up empty, and reading why is the point: `user.sv`'s
|
||||
// `shared_name` currently resolves to `p_pkg`'s declaration — the
|
||||
// rename target itself — so it is not a bystander a removal could
|
||||
// silently unmask, it is an *edit site*: the rename rewrites it to
|
||||
// `renamed_thing` along with the declaration, so the text never says
|
||||
// `shared_name` again for `follow_paths` to re-resolve against
|
||||
// `q_pkg`. A reference can only be affected by a name's removal by
|
||||
// spelling that exact name, and by the Lemma any such reference
|
||||
// either resolves to the target (edited away, as here) or to some
|
||||
// *other* declaration of the same name (already covered by rung 1/2's
|
||||
// sweep over every declarer, not only the target's) — there is no
|
||||
// third case for the old name to fall into.
|
||||
let edit = same_answer(&ws, &path, at, "renamed_thing").expect("renames");
|
||||
assert_eq!(edit.file_count(), 2, "the declaration and the importer's edited reference");
|
||||
assert!(
|
||||
edit.edits_for(&tree.path.join("q.sv")).is_empty(),
|
||||
"q_pkg's own unrelated declaration is never touched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_beats_disk_when_the_rename_is_computed() {
|
||||
let tree = Tree::new("buffer");
|
||||
|
||||
+1388
-95
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,25 @@ pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;
|
||||
/// `docs/features/large-file-mode/README.md`.
|
||||
pub const DEFAULT_LARGE_FILE_THRESHOLD: u64 = 4 * 1024 * 1024;
|
||||
|
||||
/// `lucisv.index.scopeDepth`'s default: 2 levels above the open file's own
|
||||
/// folder, clamped at the workspace root that contains it.
|
||||
///
|
||||
/// **Changed from 0 on 2026-08-28**, and it is a behaviour change, not a
|
||||
/// tuning one. At 0 the folder scope indexed the opened file's directory and
|
||||
/// nothing else, and the measurement that forced the change is in
|
||||
/// `performance.md` §4: opening `hw/ip/aes/dv/tb/tb.sv` in opentitan gave an
|
||||
/// index of **one file**, so definition, hover, references, `workspace/symbol`
|
||||
/// and signature help all answered *nothing* until some later jump widened the
|
||||
/// scope. A user's first experience of the server was silence.
|
||||
///
|
||||
/// Two levels is the smallest raise that turns a `dv/tb` or an `rtl` file into
|
||||
/// the IP block it belongs to — `hw/ip/aes`, a few hundred files — which is
|
||||
/// the unit an engineer actually works in. What keeps the cost bounded is
|
||||
/// everything the scope ladder already has: the size cap, the persistent
|
||||
/// cache, the interleaved scan and the incremental widen. See
|
||||
/// `docs/features/index-scope/README.md`.
|
||||
pub const DEFAULT_SCOPE_DEPTH: u64 = 2;
|
||||
|
||||
/// What `lucisv.index.scope` chooses: how wide the workspace walk goes.
|
||||
///
|
||||
/// The default is deliberately the narrow one. A large project is the case
|
||||
@@ -89,6 +108,11 @@ pub struct ClientSettings {
|
||||
/// Unset means on, which is what the VS Code default declares — see
|
||||
/// `docs/features/inline-templates/README.md`.
|
||||
pub inline_templates: Option<bool>,
|
||||
/// `lucisv.inlineInstantiation`: whether a module name the workspace
|
||||
/// declares grows a ghost instantiation once it is spelled exactly and
|
||||
/// followed by a space. Unset means on, the same way `inline_templates`
|
||||
/// does — see `docs/features/inline-instantiation/README.md`.
|
||||
pub inline_instantiation: Option<bool>,
|
||||
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
|
||||
/// the buffer. A plain `bool` rather than an `Option`, because unset and
|
||||
/// off are the same answer here: an editor with a format-on-save of its
|
||||
@@ -115,9 +139,9 @@ pub struct ClientSettings {
|
||||
pub index_scope: IndexScope,
|
||||
/// `lucisv.index.scopeDepth`: how many directory levels above an open
|
||||
/// file's own folder the folder scope starts, clamped so it never climbs
|
||||
/// out of the workspace folder containing it. `0` — the default — is the
|
||||
/// file's own folder. Ignored when `index_scope` is
|
||||
/// [`IndexScope::Workspace`] or when a filelist defines the scope.
|
||||
/// out of the workspace folder containing it. `0` is the file's own folder
|
||||
/// and the default is [`DEFAULT_SCOPE_DEPTH`]. Ignored when `index_scope`
|
||||
/// is [`IndexScope::Workspace`] or when a filelist defines the scope.
|
||||
pub index_scope_depth: u64,
|
||||
/// `lucisv.index.persist`: whether what a scan parsed is written to disk
|
||||
/// so the next session can skip parsing the files that have not changed.
|
||||
@@ -152,11 +176,12 @@ impl Default for ClientSettings {
|
||||
exclude: Vec::new(),
|
||||
filelist: None,
|
||||
inline_templates: None,
|
||||
inline_instantiation: None,
|
||||
format_on_save: false,
|
||||
max_file_size: DEFAULT_MAX_FILE_SIZE,
|
||||
log_files: true,
|
||||
index_scope: IndexScope::Folder,
|
||||
index_scope_depth: 0,
|
||||
index_scope_depth: DEFAULT_SCOPE_DEPTH,
|
||||
index_persist: true,
|
||||
index_cache_path: None,
|
||||
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
|
||||
@@ -195,6 +220,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
exclude: strings(lucisv.get("exclude")),
|
||||
filelist: path(lucisv.get("filelist")),
|
||||
inline_templates: flag(lucisv.get("inlineTemplates")),
|
||||
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
|
||||
// Anything that is not `true` leaves the hook declining, wrong-typed
|
||||
// values included: the safe direction for a setting that rewrites the
|
||||
// user's buffer on every save is the one that does nothing.
|
||||
@@ -210,7 +236,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// silently costs a user minutes of scanning is the wrong one to
|
||||
// guess in.
|
||||
index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(),
|
||||
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth"))).unwrap_or(0),
|
||||
// A junk depth leaves the shipped default standing, like every
|
||||
// other setting here: an unreadable value must never be the reason a
|
||||
// user's index is narrower than the server promised.
|
||||
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth")))
|
||||
.unwrap_or(DEFAULT_SCOPE_DEPTH),
|
||||
// A wrong-typed `persist` leaves the cache on. The direction that
|
||||
// costs something is turning it *off* by accident — a user who never
|
||||
// touched the setting would silently pay for every parse again — and
|
||||
@@ -342,10 +372,11 @@ mod tests {
|
||||
"exclude": exclude,
|
||||
"filelist": "",
|
||||
"inlineTemplates": true,
|
||||
"inlineInstantiation": true,
|
||||
"formatOnSave": false,
|
||||
"index": {
|
||||
"maxFileSize": 1048576, "logFiles": true,
|
||||
"scope": "folder", "scopeDepth": 0
|
||||
"scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -380,7 +411,7 @@ mod tests {
|
||||
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored");
|
||||
assert!(found.log_files, "and so is its logFiles");
|
||||
assert_eq!(found.index_scope, IndexScope::Folder, "and its scope");
|
||||
assert_eq!(found.index_scope_depth, 0, "and its scopeDepth");
|
||||
assert_eq!(found.index_scope_depth, DEFAULT_SCOPE_DEPTH, "and its scopeDepth");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,11 +511,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scope_depth_is_zero_until_a_client_raises_it() {
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, 0);
|
||||
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope_depth, 0);
|
||||
fn the_scope_depth_is_two_until_a_client_says_otherwise() {
|
||||
// Two, not zero, since 2026-08-28: `performance.md` §4 measured the
|
||||
// file's-own-folder default indexing exactly one file in opentitan's
|
||||
// `dv/tb` layout, so every cross-file answer was empty until some
|
||||
// later jump widened the scope. See [`DEFAULT_SCOPE_DEPTH`].
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, DEFAULT_SCOPE_DEPTH);
|
||||
assert_eq!(
|
||||
settings(json!({ "lucisv": { "index": {} } })).index_scope_depth,
|
||||
DEFAULT_SCOPE_DEPTH
|
||||
);
|
||||
let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } }));
|
||||
assert_eq!(raised.index_scope_depth, 3);
|
||||
// Zero is still exactly what it always was — the file's own folder and
|
||||
// nothing above it — and asking for it still gets it.
|
||||
let narrow = settings(json!({ "lucisv": { "index": { "scopeDepth": 0 } } }));
|
||||
assert_eq!(narrow.index_scope_depth, 0, "an explicit 0 is honoured, not defaulted");
|
||||
// No upper bound here: the clamp is structural — `state.rs` stops at
|
||||
// the workspace root — so an absurd number is not wrong, just fully
|
||||
// clamped.
|
||||
@@ -492,7 +534,10 @@ mod tests {
|
||||
assert_eq!(absurd.index_scope_depth, 9999);
|
||||
for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] {
|
||||
let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } }));
|
||||
assert_eq!(found.index_scope_depth, 0, "scopeDepth {bad} must be ignored");
|
||||
assert_eq!(
|
||||
found.index_scope_depth, DEFAULT_SCOPE_DEPTH,
|
||||
"scopeDepth {bad} must be ignored"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -519,17 +564,52 @@ mod tests {
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
|
||||
}
|
||||
|
||||
/// [`vscode_payload`] above is a hand-written copy of what the extension
|
||||
/// declares, and a copy that drifts proves nothing. The extension's own
|
||||
/// `package.json` is the thing a user's settings UI reads, so the two
|
||||
/// defaults that are not "no opinion" are checked against it directly.
|
||||
#[test]
|
||||
fn the_extensions_declared_defaults_are_the_ones_this_module_ships() {
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../editors/vscode/package.json");
|
||||
let text = std::fs::read_to_string(&path).expect("the extension manifest");
|
||||
let manifest: Value = serde_json::from_str(&text).expect("valid json");
|
||||
let properties = &manifest["contributes"]["configuration"]["properties"];
|
||||
assert_eq!(
|
||||
properties["lucisv.index.scopeDepth"]["default"],
|
||||
json!(DEFAULT_SCOPE_DEPTH),
|
||||
"the settings UI and the server must ship the same scope depth"
|
||||
);
|
||||
assert_eq!(
|
||||
properties["lucisv.index.maxFileSize"]["default"],
|
||||
json!(DEFAULT_MAX_FILE_SIZE),
|
||||
"and the same size cap"
|
||||
);
|
||||
// The two ghost-text settings are the ones whose absence resolves to
|
||||
// `true` here, so a `false` default in the manifest would make the
|
||||
// settings UI and the server disagree about a feature being on.
|
||||
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
|
||||
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
|
||||
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_vscode_payload_is_no_opinion_about_anything() {
|
||||
// Every setting at its `package.json` default: nulls and an empty
|
||||
// list, which must leave today's behaviour exactly unchanged.
|
||||
// `inlineTemplates` is the one default that is not "no opinion" — it
|
||||
// defaults to `true`, and `None` resolves to the same thing.
|
||||
// The two ghost-text settings are the defaults that are not "no
|
||||
// opinion" — both default to `true`, and `None` resolves to the same
|
||||
// thing.
|
||||
let found = settings(vscode_payload(json!(null), json!(null), json!([])));
|
||||
assert_eq!(
|
||||
found,
|
||||
ClientSettings { inline_templates: Some(true), ..Default::default() },
|
||||
"the only difference from silence must be the one setting whose \
|
||||
ClientSettings {
|
||||
inline_templates: Some(true),
|
||||
inline_instantiation: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
"the only difference from silence must be the settings whose \
|
||||
default is not null"
|
||||
);
|
||||
}
|
||||
@@ -548,6 +628,23 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_instantiation_is_a_boolean_and_nothing_else() {
|
||||
let found = settings(json!({ "lucisv": { "inlineInstantiation": false } }));
|
||||
assert_eq!(found.inline_instantiation, Some(false));
|
||||
let found = settings(json!({ "lucisv": { "inlineInstantiation": true } }));
|
||||
assert_eq!(found.inline_instantiation, Some(true));
|
||||
// Absence is not `false`: the feature is on unless a client says no.
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).inline_instantiation, None);
|
||||
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
|
||||
let found = settings(json!({ "lucisv": { "inlineInstantiation": bad } }));
|
||||
assert_eq!(found.inline_instantiation, None, "inlineInstantiation {bad} ignored");
|
||||
}
|
||||
// The two ghost settings are independent: one off leaves the other on.
|
||||
let found = settings(json!({ "lucisv": { "inlineInstantiation": false } }));
|
||||
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_is_off_until_a_client_asks_for_it() {
|
||||
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
|
||||
|
||||
+1869
-68
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,9 @@ use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT};
|
||||
pub fn kind_label(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Module => "module",
|
||||
SymbolKind::Interface => "interface",
|
||||
SymbolKind::Modport => "modport",
|
||||
SymbolKind::Clocking => "clocking",
|
||||
SymbolKind::Package => "package",
|
||||
SymbolKind::Port => "port",
|
||||
SymbolKind::Net => "net",
|
||||
@@ -34,6 +37,11 @@ pub fn kind_label(kind: SymbolKind) -> &'static str {
|
||||
pub fn lsp_kind(kind: SymbolKind) -> LspKind {
|
||||
match kind {
|
||||
SymbolKind::Module => LspKind::CLASS,
|
||||
// A modport is a named view *of* an interface, so it takes the same
|
||||
// icon; a clocking block is an event-driven grouping and takes LSP's
|
||||
// own `EVENT`.
|
||||
SymbolKind::Interface | SymbolKind::Modport => LspKind::INTERFACE,
|
||||
SymbolKind::Clocking => LspKind::EVENT,
|
||||
SymbolKind::Package => LspKind::NAMESPACE,
|
||||
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar => {
|
||||
LspKind::VARIABLE
|
||||
@@ -145,6 +153,31 @@ mod tests {
|
||||
assert_eq!(symbols[1].kind, LspKind::NAMESPACE);
|
||||
}
|
||||
|
||||
/// The labels and icons coverage_gaps C2 was about: an interface that used
|
||||
/// to read "module", and a modport and a clocking block that used to be no
|
||||
/// outline entry at all (`docs/features/interface-semantics/README.md`).
|
||||
#[test]
|
||||
fn an_interface_its_modport_and_its_clocking_block_are_named_and_iconed() {
|
||||
assert_eq!(kind_label(SymbolKind::Interface), "interface");
|
||||
assert_eq!(kind_label(SymbolKind::Modport), "modport");
|
||||
assert_eq!(kind_label(SymbolKind::Clocking), "clocking");
|
||||
assert_eq!(lsp_kind(SymbolKind::Interface), LspKind::INTERFACE);
|
||||
assert_eq!(lsp_kind(SymbolKind::Modport), LspKind::INTERFACE);
|
||||
assert_eq!(lsp_kind(SymbolKind::Clocking), LspKind::EVENT);
|
||||
|
||||
let (ws, uri) = document(
|
||||
"interface bus_if;\n logic clk;\n modport mp (input clk);\n clocking cb @(posedge clk);\n endclocking\nendinterface\n",
|
||||
);
|
||||
let symbols = document_symbols(ws.document(&uri).expect("open"));
|
||||
assert_eq!(symbols.len(), 1);
|
||||
assert_eq!(symbols[0].kind, LspKind::INTERFACE);
|
||||
let children = symbols[0].children.as_ref().expect("interface contents");
|
||||
let shape: Vec<(&str, LspKind)> =
|
||||
children.iter().map(|c| (c.name.as_str(), c.kind)).collect();
|
||||
assert!(shape.contains(&("mp", LspKind::INTERFACE)), "{shape:?}");
|
||||
assert!(shape.contains(&("cb", LspKind::EVENT)), "{shape:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_range_is_always_inside_the_full_range() {
|
||||
let (ws, uri) = document("module top;\n wire [7:0] wide;\nendmodule\n");
|
||||
|
||||
@@ -235,7 +235,15 @@ fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
|
||||
|
||||
fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
match kind {
|
||||
SymbolKind::Module | SymbolKind::Class => Highlight::Class,
|
||||
// The legend this server advertises has no `interface` token type,
|
||||
// and its indices are the wire contract — adding one would renumber
|
||||
// every highlight a live client already holds. An interface and a
|
||||
// modport are type-like names, so they keep the `class` highlight a
|
||||
// module has always had; a clocking block is a named block, and takes
|
||||
// the `variable` one a block label takes.
|
||||
SymbolKind::Module | SymbolKind::Class | SymbolKind::Interface | SymbolKind::Modport => {
|
||||
Highlight::Class
|
||||
}
|
||||
SymbolKind::Package => Highlight::Namespace,
|
||||
SymbolKind::Typedef => Highlight::Type,
|
||||
SymbolKind::EnumVariant => Highlight::EnumMember,
|
||||
@@ -247,6 +255,7 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::Clocking
|
||||
| SymbolKind::Block => Highlight::Variable,
|
||||
}
|
||||
}
|
||||
@@ -665,6 +674,26 @@ mod tests {
|
||||
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
|
||||
}
|
||||
|
||||
/// The legend's indices are the wire contract, so the three kinds added
|
||||
/// on 2026-09-01 take existing highlights rather than new token types
|
||||
/// (`docs/features/interface-semantics/README.md`). Pinned so a later
|
||||
/// round that wants an `interface` token type has to *append* it — and
|
||||
/// notice it is doing so.
|
||||
#[test]
|
||||
fn the_new_kinds_reuse_the_legend_rather_than_growing_it() {
|
||||
assert_eq!(token_types().len(), 14, "the legend is a wire contract");
|
||||
assert_eq!(symbol_type(SymbolKind::Interface), Highlight::Class);
|
||||
assert_eq!(symbol_type(SymbolKind::Modport), Highlight::Class);
|
||||
assert_eq!(symbol_type(SymbolKind::Clocking), Highlight::Variable);
|
||||
|
||||
let src = "interface bus_if;\nendinterface\n";
|
||||
let name = decode(&tokens_of(src))
|
||||
.into_iter()
|
||||
.find(|&(line, col, ..)| line == 0 && col == 10)
|
||||
.expect("the interface's name");
|
||||
assert_eq!(name.3, Highlight::Class as u32);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the large-file fast path's window
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -96,10 +96,13 @@ fn type_name(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
fn type_use_at(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
let reference = doc.semantics.reference_at(offset)?;
|
||||
let kind = doc.semantics.symbol(reference.resolved()?)?.kind;
|
||||
// `Module` is also an `interface` and a `program` — one node, one kind
|
||||
// (`vlog_parser::ast::Module`).
|
||||
// `Module` is also a `program` — one node, one kind
|
||||
// (`vlog_parser::ast::Module`); an `interface` has its own since
|
||||
// 2026-09-01, and is just as much a type a declaration may name.
|
||||
match kind {
|
||||
SymbolKind::Typedef | SymbolKind::Class | SymbolKind::Module => Some(reference.name_span),
|
||||
SymbolKind::Typedef | SymbolKind::Class | SymbolKind::Module | SymbolKind::Interface => {
|
||||
Some(reference.name_span)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -282,6 +285,11 @@ fn stmt_site(stmt: &Stmt, offset: u32) -> Option<Site<'_>> {
|
||||
return None;
|
||||
}
|
||||
match &stmt.kind {
|
||||
// A block-scoped typedef answers exactly as the item form does: the
|
||||
// cursor on the alias name jumps one hop to the aliased type. Added
|
||||
// when `StmtKind::Typedef` landed (testbench-mopup, 2026-08-29) —
|
||||
// QA's blast-radius audit caught this arm missing.
|
||||
StmtKind::Typedef(t) => alias_site(t, stmt.span),
|
||||
StmtKind::VarDecl(d) => declarator_site(&d.ty, stmt.span, &d.declarators),
|
||||
StmtKind::ParamDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators),
|
||||
StmtKind::PortDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators),
|
||||
@@ -364,6 +372,27 @@ mod tests {
|
||||
// in-file types
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_block_scoped_typedefs_alias_jumps_one_hop_to_its_type() {
|
||||
// QA (testbench-mopup, 2026-08-29): the item-level alias hop worked,
|
||||
// the new statement-level typedef silently answered nothing. Both
|
||||
// forms now answer through the same alias_site.
|
||||
let text = "\
|
||||
module m;
|
||||
typedef logic [7:0] byte_t;
|
||||
initial begin
|
||||
typedef byte_t word_t;
|
||||
word_t w;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (ws, uri) = document(text);
|
||||
assert!(
|
||||
!jumps(&ws, &uri, at(text, "word_t;") + 3).is_empty(),
|
||||
"the block-scoped alias hops to byte_t instead of answering nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_jumps_to_the_typedef_of_its_type() {
|
||||
let text = "\
|
||||
|
||||
+1582
-17
File diff suppressed because it is too large.
Load diff
@@ -413,9 +413,16 @@ impl<'a> Fmt<'a> {
|
||||
/// printing every comment and then every attribute moves a comment across
|
||||
/// an attribute in the token stream, which the safety net rejects.
|
||||
fn leading(&self, meta: &Meta) -> Vec<Doc> {
|
||||
self.leading_from(meta, 0)
|
||||
}
|
||||
|
||||
/// The same, minus the first `skip` leading comments — the ones a
|
||||
/// statement header already printed inside its own parentheses. See
|
||||
/// [`Fmt::header_parens`].
|
||||
fn leading_from(&self, meta: &Meta, skip: usize) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
let mut attrs = meta.attrs.iter().peekable();
|
||||
for c in &meta.leading {
|
||||
for c in meta.leading.iter().skip(skip) {
|
||||
while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) {
|
||||
Self::push_leading(&mut docs, self.raw_text(attr), false);
|
||||
}
|
||||
@@ -832,25 +839,118 @@ impl<'a> Fmt<'a> {
|
||||
group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")])
|
||||
}
|
||||
|
||||
/// `( expr )` with the comments the source wrote just inside the
|
||||
/// parentheses. A comment there forces them open, the same way a comment
|
||||
/// inside a port list does.
|
||||
fn paren_comments(&self, inner: &Expr, before: &[&Comment], after: &[&Comment]) -> Doc {
|
||||
let mut docs = vec![Doc::SoftLine];
|
||||
for c in before {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.expr(inner));
|
||||
let mut outer = vec![text("("), indent(docs)];
|
||||
for c in after {
|
||||
outer.push(text(" "));
|
||||
outer.push(self.comment(c));
|
||||
}
|
||||
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
|
||||
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
|
||||
outer.push(text(")"));
|
||||
group(outer)
|
||||
}
|
||||
|
||||
/// The `(cond)` of a statement header, taking back the comments the parser
|
||||
/// handed to the construct's *body* because they were written before the
|
||||
/// closing `)`.
|
||||
///
|
||||
/// Nothing between `(` and `)` owns trivia, so a comment written inside a
|
||||
/// header's parentheses stays queued and lands on the next node that takes
|
||||
/// meta — the body statement, or a `case`'s first item. Printed there it
|
||||
/// would sit *after* a `)` it was written before, and `verify.rs` refuses
|
||||
/// the file, rightly: the comment moved across a token.
|
||||
///
|
||||
/// Returns the header doc and how many of `body`'s leading comments it
|
||||
/// consumed, which the caller must then skip. When the source does not
|
||||
/// have the expected shape nothing is taken and the plain parentheses are
|
||||
/// printed, so an unrecognized header is left exactly as it was.
|
||||
fn header_parens(&self, cond: &Expr, body: &Meta) -> (Doc, usize) {
|
||||
let close = match skip_trivia(self.src, cond.span.end as usize) {
|
||||
Some(i) if self.src.as_bytes().get(i) == Some(&b')') => i as u32,
|
||||
_ => return (self.parens(cond), 0),
|
||||
};
|
||||
let taken = body.leading.iter().take_while(|c| c.span.start < close).count();
|
||||
if taken == 0 {
|
||||
return (self.parens(cond), 0);
|
||||
}
|
||||
let (before, after): (Vec<&Comment>, Vec<&Comment>) =
|
||||
body.leading[..taken].iter().partition(|c| c.span.start < cond.span.start);
|
||||
(self.paren_comments(cond, &before, &after), taken)
|
||||
}
|
||||
|
||||
/// True when the source wrote the optional `:` after a `default` case
|
||||
/// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and
|
||||
/// the token stream has to come back with exactly what was written.
|
||||
fn default_has_colon(&self, span: TextRange) -> bool {
|
||||
let after = span.start as usize + "default".len();
|
||||
matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':')
|
||||
}
|
||||
|
||||
/// Sequence of items at one indent level, preserving single blank lines
|
||||
/// between them. An item a fenced region swallowed emits nothing, and
|
||||
/// contributes no separator either.
|
||||
fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
|
||||
let aligns = self.param_decl_aligns(items, depth);
|
||||
let mut docs = Vec::new();
|
||||
// The last item that actually emitted something, which is what a
|
||||
// glued null item glues to.
|
||||
let mut prev: Option<&Item> = None;
|
||||
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() {
|
||||
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 });
|
||||
}
|
||||
docs.extend(item_docs);
|
||||
prev = Some(item);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// 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;`, `;;`.
|
||||
///
|
||||
/// The question is asked of the source rather than of the AST because it
|
||||
/// is a layout fact about the gap between two siblings, and this is the
|
||||
/// one place that gap is laid out — the same reason `eq_offset` and
|
||||
/// `default_has_colon` read `src` here. A null item that begins a body has
|
||||
/// no sibling to glue to and prints on its own line.
|
||||
///
|
||||
/// Anything that gives the `;` docs of its own — a leading comment, an
|
||||
/// attribute, a blank line, a format-off fence opening on it — takes the
|
||||
/// own-line path instead, so the glue only ever appends a bare `;`. Note
|
||||
/// that a `//` comment cannot stand in a newline-free gap: it would
|
||||
/// swallow the `;` that follows it. The only comment that fits is a
|
||||
/// one-line block comment, which prints inline before the `;`, in the
|
||||
/// order it was written.
|
||||
fn glued_null_item(&self, prev: &Item, item: &Item) -> bool {
|
||||
if !matches!(item.kind, ItemKind::Empty) {
|
||||
return false;
|
||||
}
|
||||
if item.meta.blank_before || !item.meta.leading.is_empty() || !item.meta.attrs.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if self.is_verbatim(item.span) || self.opens_at(item.span.start as usize).is_some() {
|
||||
return false;
|
||||
}
|
||||
self.src
|
||||
.get(prev.span.end as usize..item.span.start as usize)
|
||||
.is_some_and(|gap| !gap.contains('\n'))
|
||||
}
|
||||
|
||||
fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for (i, s) in stmts.iter().enumerate() {
|
||||
@@ -1049,6 +1149,9 @@ impl<'a> Fmt<'a> {
|
||||
ItemKind::Modport(decls) => self.modport(decls),
|
||||
ItemKind::Clocking(c) => self.clocking(c),
|
||||
ItemKind::Verbatim(raw) => self.raw_text(raw),
|
||||
// A null item is its `;`. Whether it keeps the previous item's
|
||||
// line or takes one of its own is `item_seq`'s call.
|
||||
ItemKind::Empty => text(";"),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
let parts: Vec<Doc> = pairs
|
||||
.iter()
|
||||
@@ -1541,6 +1644,9 @@ impl<'a> Fmt<'a> {
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let mut d = vec![text(m.name.clone())];
|
||||
// Tight against the name: `OtbnDmem[16]` is one enum name
|
||||
// range, not a name with a dimension beside it.
|
||||
d.extend(m.range.iter().map(|r| self.dim(r)));
|
||||
if let Some(v) = &m.value {
|
||||
d.push(text(" = "));
|
||||
d.push(self.expr(v));
|
||||
@@ -1576,6 +1682,9 @@ impl<'a> Fmt<'a> {
|
||||
inner.push(Doc::HardLine);
|
||||
inner.extend(self.leading(&m.meta));
|
||||
let mut d = Vec::new();
|
||||
for q in &m.qualifiers {
|
||||
d.push(text(format!("{q} ")));
|
||||
}
|
||||
if let Some(ty) = self.data_type(&m.ty) {
|
||||
d.push(ty);
|
||||
d.push(text(" "));
|
||||
@@ -1609,7 +1718,7 @@ impl<'a> Fmt<'a> {
|
||||
fn cont_assign(&self, a: &ContAssign) -> Doc {
|
||||
let mut docs = vec![text("assign ")];
|
||||
if let Some(s) = &a.strength {
|
||||
docs.push(text(format!("({}, {}) ", s.first, s.second)));
|
||||
docs.push(text(format!("{} ", drive_strength(s))));
|
||||
}
|
||||
if let Some(delay) = &a.delay {
|
||||
docs.push(text("#"));
|
||||
@@ -1880,9 +1989,23 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn gate_instantiation(&self, g: &GateInstantiation) -> Doc {
|
||||
let mut docs = vec![text(g.gate.clone())];
|
||||
if let Some(delay) = &g.delay {
|
||||
if let Some(s) = &g.strength {
|
||||
docs.push(text(format!(" {}", drive_strength(s))));
|
||||
}
|
||||
if let [delay] = g.delay.as_slice() {
|
||||
// One value prints itself, brackets and all (`#5`, `#(5)`).
|
||||
docs.push(text(" #"));
|
||||
docs.push(self.expr(delay));
|
||||
} else if !g.delay.is_empty() {
|
||||
// `#(rise, fall[, turn-off])` — the parens are the list's own.
|
||||
docs.push(text(" #("));
|
||||
for (i, d) in g.delay.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
}
|
||||
docs.push(self.expr(d));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
}
|
||||
for (i, inst) in g.instances.iter().enumerate() {
|
||||
docs.push(if i > 0 { text(", ") } else { text(" ") });
|
||||
@@ -1981,7 +2104,7 @@ impl<'a> Fmt<'a> {
|
||||
for item in &g.items {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading(&item.meta));
|
||||
let mut item_docs = vec![self.case_labels(&item.labels)];
|
||||
let mut item_docs = vec![self.case_labels(&item.labels, item.span)];
|
||||
self.gen_block(&mut item_docs, &item.body, depth + 1);
|
||||
body.push(concat(item_docs));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
@@ -2169,6 +2292,10 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One clocking-block item. A `= expression` binding
|
||||
/// (`output tms = _tms_internal;`) prints on the item's own line: the
|
||||
/// bound expression is a signal name, never long enough to be worth a
|
||||
/// breakable group.
|
||||
fn clocking_item(&self, kind: &ClockingItemKind) -> Doc {
|
||||
match kind {
|
||||
ClockingItemKind::Default { input, output } => {
|
||||
@@ -2183,15 +2310,25 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
text(s)
|
||||
}
|
||||
ClockingItemKind::Signals { dir, skew, names } => {
|
||||
let mut s = dir.clone();
|
||||
ClockingItemKind::Signals { dir, skew, signals } => {
|
||||
let mut head = dir.clone();
|
||||
if let Some(skew) = skew {
|
||||
s.push(' ');
|
||||
s.push_str(skew);
|
||||
head.push(' ');
|
||||
head.push_str(skew);
|
||||
}
|
||||
s.push(' ');
|
||||
s.push_str(&join_names(names));
|
||||
text(s)
|
||||
head.push(' ');
|
||||
let mut docs = vec![text(head)];
|
||||
for (i, sig) in signals.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
}
|
||||
docs.push(text(sig.name.text.clone()));
|
||||
if let Some(value) = &sig.value {
|
||||
docs.push(text(" = "));
|
||||
docs.push(self.expr(value));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2320,10 +2457,17 @@ impl<'a> Fmt<'a> {
|
||||
/// blocks cuddle onto the prefix line, single statements go on the same
|
||||
/// line if they fit, otherwise indented on the next line.
|
||||
fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc {
|
||||
self.stmt_as_body_from(prefix, s, 0)
|
||||
}
|
||||
|
||||
/// The same, skipping the body's first `skip` leading comments because
|
||||
/// `prefix` already printed them inside its parentheses. See
|
||||
/// [`Fmt::header_parens`].
|
||||
fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
|
||||
match &s.kind {
|
||||
StmtKind::Block { label, stmts, dangling, end_label, .. } => {
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading(&s.meta));
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
docs.push(self.block_doc(label, stmts, dangling, end_label));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
@@ -2331,13 +2475,19 @@ impl<'a> Fmt<'a> {
|
||||
StmtKind::Timing { control, stmt: Some(inner) } => {
|
||||
// e.g. `always @(posedge clk) begin ... end`
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading(&s.meta));
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
let control_doc = self.timing_control(control);
|
||||
docs.push(self.stmt_as_body(control_doc, inner));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
}
|
||||
_ => group(vec![prefix, indent(vec![Doc::Line, self.stmt(s)])]),
|
||||
// The same three parts `stmt` prints, with the skip applied.
|
||||
_ => {
|
||||
let mut body = self.leading_from(&s.meta, skip);
|
||||
body.push(self.stmt_kind(&s.kind));
|
||||
body.extend(self.trailing(&s.meta));
|
||||
group(vec![prefix, indent(vec![Doc::Line, concat(body)])])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2425,6 +2575,12 @@ impl<'a> Fmt<'a> {
|
||||
parts.push(text(format!("{e} ")));
|
||||
}
|
||||
parts.push(self.expr(&i.expr));
|
||||
// `posedge clk iff enable` — the gate belongs to this
|
||||
// term, so it prints before the separator, not after it.
|
||||
if let Some(iff) = &i.iff {
|
||||
parts.push(text(" iff "));
|
||||
parts.push(self.expr(iff));
|
||||
}
|
||||
if self.inline_comments(&i.meta.before_sep, &mut parts) {
|
||||
parts.push(Doc::HardLine);
|
||||
}
|
||||
@@ -2469,17 +2625,21 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
head.push_str(kw);
|
||||
head.push(' ');
|
||||
let mut docs = vec![text(head), self.parens(expr)];
|
||||
let (parens, taken) = match items.first() {
|
||||
Some(first) => self.header_parens(expr, &first.meta),
|
||||
None => (self.parens(expr), 0),
|
||||
};
|
||||
let mut docs = vec![text(head), parens];
|
||||
if *inside {
|
||||
docs.push(text(" inside"));
|
||||
}
|
||||
docs.push(self.case_body(items, dangling));
|
||||
docs.push(self.case_body(items, dangling, taken));
|
||||
concat(docs)
|
||||
}
|
||||
// `randcase` is a `case` body with weights for labels and no
|
||||
// selector, so it shares the body layout.
|
||||
StmtKind::RandCase { items, dangling } => {
|
||||
concat(vec![text("randcase"), self.case_body(items, dangling)])
|
||||
concat(vec![text("randcase"), self.case_body(items, dangling, 0)])
|
||||
}
|
||||
StmtKind::For { init, cond, step, body } => {
|
||||
let mut header = vec![text("for (")];
|
||||
@@ -2511,7 +2671,8 @@ impl<'a> Fmt<'a> {
|
||||
self.stmt_as_body(concat(header), body)
|
||||
}
|
||||
StmtKind::While { cond, body } => {
|
||||
self.stmt_as_body(concat(vec![text("while "), self.parens(cond)]), body)
|
||||
let (parens, taken) = self.header_parens(cond, &body.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken)
|
||||
}
|
||||
StmtKind::DoWhile { body, cond } => {
|
||||
let mut docs = vec![text("do")];
|
||||
@@ -2532,7 +2693,8 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::Repeat { count, body } => {
|
||||
self.stmt_as_body(concat(vec![text("repeat "), self.parens(count)]), body)
|
||||
let (parens, taken) = self.header_parens(count, &body.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken)
|
||||
}
|
||||
StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body),
|
||||
StmtKind::Foreach { target, vars, body } => {
|
||||
@@ -2589,16 +2751,18 @@ impl<'a> Fmt<'a> {
|
||||
None => concat(vec![control_doc, text(";")]),
|
||||
}
|
||||
}
|
||||
StmtKind::Wait { cond, stmt } => {
|
||||
let head = concat(vec![text("wait "), self.parens(cond)]);
|
||||
match stmt {
|
||||
Some(s) => self.stmt_as_body(head, s),
|
||||
None => concat(vec![head, text(";")]),
|
||||
StmtKind::Wait { cond, stmt } => match stmt {
|
||||
Some(s) => {
|
||||
let (parens, taken) = self.header_parens(cond, &s.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken)
|
||||
}
|
||||
}
|
||||
None => concat(vec![text("wait "), self.parens(cond), text(";")]),
|
||||
},
|
||||
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]),
|
||||
StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]),
|
||||
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]),
|
||||
// The item form prints its own `;`.
|
||||
StmtKind::Typedef(t) => self.typedef(t),
|
||||
StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d, None), text(";")]),
|
||||
StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]),
|
||||
StmtKind::Return(e) => match e {
|
||||
@@ -2660,9 +2824,13 @@ impl<'a> Fmt<'a> {
|
||||
head.push(' ');
|
||||
}
|
||||
head.push_str("if ");
|
||||
let prefix = concat(vec![text(head), self.parens(cond)]);
|
||||
let then_is_block = matches!(then.kind, StmtKind::Block { .. });
|
||||
let mut docs = vec![self.stmt_as_body(prefix, then)];
|
||||
let (parens, taken) = self.header_parens(cond, &then.meta);
|
||||
let prefix = concat(vec![text(head), parens]);
|
||||
// A line comment trailing the then-branch runs to end of line, so a
|
||||
// cuddled `else` would be swallowed into its text.
|
||||
let then_is_block =
|
||||
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
|
||||
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
|
||||
if let Some(els) = els {
|
||||
// A comment written before `else` prints before it, each on its
|
||||
// own line: it is where the source put it, and after the keyword
|
||||
@@ -2700,9 +2868,9 @@ impl<'a> Fmt<'a> {
|
||||
/// Labels normally share one line; as soon as any of them carries a
|
||||
/// comment they go one per line, so a comment written between two labels
|
||||
/// is printed between the same two labels instead of drifting past them.
|
||||
fn case_labels(&self, labels: &[ExprItem]) -> Doc {
|
||||
fn case_labels(&self, labels: &[ExprItem], item: TextRange) -> Doc {
|
||||
if labels.is_empty() {
|
||||
return text("default:");
|
||||
return text(if self.default_has_colon(item) { "default:" } else { "default" });
|
||||
}
|
||||
let plain = labels.iter().all(|l| {
|
||||
l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none()
|
||||
@@ -2744,16 +2912,27 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
|
||||
fn case_item(&self, item: &CaseItem) -> Doc {
|
||||
self.stmt_as_body(self.case_labels(&item.labels), &item.stmt)
|
||||
// `default;` — the colon IEEE 1800 §12.5 makes optional, with a null
|
||||
// body. The `;` closes the keyword rather than standing as a body of
|
||||
// its own, so it hugs instead of going through `stmt_as_body`.
|
||||
if item.labels.is_empty()
|
||||
&& matches!(item.stmt.kind, StmtKind::Null)
|
||||
&& is_bare(&item.stmt.meta)
|
||||
&& !self.default_has_colon(item.span)
|
||||
{
|
||||
return text("default;");
|
||||
}
|
||||
self.stmt_as_body(self.case_labels(&item.labels, item.span), &item.stmt)
|
||||
}
|
||||
|
||||
/// The indented items of a `case`/`randcase` body and the `endcase` that
|
||||
/// closes it.
|
||||
fn case_body(&self, items: &[CaseItem], dangling: &[Comment]) -> Doc {
|
||||
/// The items of a `case`/`randcase` body. `skip` is the number of leading
|
||||
/// comments of the *first* item the `case (...)` header already printed
|
||||
/// inside its parentheses (see [`Fmt::header_parens`]).
|
||||
fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc {
|
||||
let mut body = Vec::new();
|
||||
for item in items {
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading(&item.meta));
|
||||
body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 }));
|
||||
body.push(self.case_item(item));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
@@ -2874,25 +3053,16 @@ impl<'a> Fmt<'a> {
|
||||
if before.is_empty() && after.is_empty() {
|
||||
return self.parens(inner);
|
||||
}
|
||||
// A comment inside the parens forces them open, the same way
|
||||
// a comment inside a port list does.
|
||||
let mut docs = vec![Doc::SoftLine];
|
||||
for c in before {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.expr(inner));
|
||||
let mut outer = vec![text("("), indent(docs)];
|
||||
for c in after {
|
||||
outer.push(text(" "));
|
||||
outer.push(self.comment(c));
|
||||
}
|
||||
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
|
||||
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
|
||||
outer.push(text(")"));
|
||||
group(outer)
|
||||
let before: Vec<&Comment> = before.iter().collect();
|
||||
let after: Vec<&Comment> = after.iter().collect();
|
||||
self.paren_comments(inner, &before, &after)
|
||||
}
|
||||
ExprKind::Cast { ty, expr } => {
|
||||
// `ty'{...}` prints no brackets of its own: the assignment
|
||||
// pattern already carries the `'{` and the `}`.
|
||||
ExprKind::Cast { ty, expr, pattern: true } => {
|
||||
concat(vec![self.expr(ty), self.expr(expr)])
|
||||
}
|
||||
ExprKind::Cast { ty, expr, .. } => {
|
||||
concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")])
|
||||
}
|
||||
ExprKind::AssignPattern(items) => {
|
||||
@@ -3052,6 +3222,14 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write.
|
||||
fn drive_strength(s: &DriveStrength) -> String {
|
||||
match &s.second {
|
||||
Some(second) => format!("({}, {})", s.first, second),
|
||||
None => format!("({})", s.first),
|
||||
}
|
||||
}
|
||||
|
||||
/// A comma-separated list of names, as the source wrote them. The parser
|
||||
/// keeps each name's byte range alongside its text, so the joined spelling is
|
||||
/// rebuilt here rather than stored.
|
||||
@@ -3102,3 +3280,53 @@ fn strip_blanks(line: &str, n: usize) -> &str {
|
||||
fn is_line_comment(text: &str) -> bool {
|
||||
text.starts_with("//")
|
||||
}
|
||||
|
||||
/// True when a node carries no trivia at all, so printing it cannot move a
|
||||
/// comment anywhere.
|
||||
fn is_bare(meta: &Meta) -> bool {
|
||||
meta.leading.is_empty()
|
||||
&& meta.trailing.is_none()
|
||||
&& meta.before_sep.is_empty()
|
||||
&& meta.attrs.is_empty()
|
||||
}
|
||||
|
||||
/// True when a node's trailing comments end in a line comment, so anything
|
||||
/// printed after them on the same line would be swallowed into the comment's
|
||||
/// text. `trailing` prints `before_sep` first and `trailing` last.
|
||||
fn trailing_ends_line(meta: &Meta) -> bool {
|
||||
match &meta.trailing {
|
||||
Some(tr) => is_line_comment(&tr.text),
|
||||
None => meta.before_sep.last().is_some_and(|c| is_line_comment(&c.text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Offset of the first byte at or after `from` that is neither whitespace nor
|
||||
/// part of a comment, or `None` if the text ends first.
|
||||
///
|
||||
/// Used to ask what a node is followed by in the source — a `)` that closes
|
||||
/// the header it sits in, the optional `:` of a `default` case label — when
|
||||
/// the AST does not record it.
|
||||
fn skip_trivia(src: &str, from: usize) -> Option<usize> {
|
||||
let bytes = src.as_bytes();
|
||||
let mut i = from;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'/' if bytes.get(i + 1) == Some(&b'/') => {
|
||||
i += 2;
|
||||
while i < bytes.len() && bytes[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
b'/' if bytes.get(i + 1) == Some(&b'*') => {
|
||||
i += 2;
|
||||
while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
|
||||
i += 1;
|
||||
}
|
||||
i = (i + 2).min(bytes.len());
|
||||
}
|
||||
c if c.is_ascii_whitespace() => i += 1,
|
||||
_ => return Some(i),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
# Round 2 of the testbench wave: clocking-block signal bindings, the standing
|
||||
# `default disable iff`, `iff` on an event-control term, a bare event control
|
||||
# naming an indexed hierarchical path, a gate's drive strength, and `program`.
|
||||
# See docs/features/clocking-wave/README.md. Every case here is a shape the
|
||||
# OpenTitan sweep contains.
|
||||
|
||||
# --- clocking_decl_assign: `output tms = _tms_internal;` (IEEE 1800 §14.4) ---
|
||||
# The binding prints on the item's own line. Nothing here is breakable: the
|
||||
# bound expression is a signal name, and the body was already one item per line.
|
||||
interface jtag_if;
|
||||
clocking host_cb @(negedge tck);
|
||||
default output #1ns;
|
||||
output tms = _tms_internal;
|
||||
output tdi = _tdi_internal;
|
||||
input tdo;
|
||||
endclocking
|
||||
endinterface
|
||||
----
|
||||
interface jtag_if;
|
||||
clocking host_cb @(negedge tck);
|
||||
default output #1ns;
|
||||
output tms = _tms_internal;
|
||||
output tdi = _tdi_internal;
|
||||
input tdo;
|
||||
endclocking
|
||||
endinterface
|
||||
====
|
||||
# a direction group may bind several signals, and the value is a real expression
|
||||
interface i;
|
||||
clocking cb @(posedge clk_i);
|
||||
input pwrmgr_data = pwrmgr_data_o_i, keymgr_data = keymgr_data_o_i;
|
||||
output #2 h2d = h2d_int[1], d2h;
|
||||
inout x = a.b.c;
|
||||
endclocking
|
||||
endinterface
|
||||
----
|
||||
interface i;
|
||||
clocking cb @(posedge clk_i);
|
||||
input pwrmgr_data = pwrmgr_data_o_i, keymgr_data = keymgr_data_o_i;
|
||||
output #2 h2d = h2d_int[1], d2h;
|
||||
inout x = a.b.c;
|
||||
endclocking
|
||||
endinterface
|
||||
====
|
||||
# a clocking block in a module, with comments around the bindings
|
||||
module tb;
|
||||
clocking cb @(posedge clk);
|
||||
// driven by the sequence
|
||||
output req = req_int; // through the internal net
|
||||
input rsp;
|
||||
endclocking
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
clocking cb @(posedge clk);
|
||||
// driven by the sequence
|
||||
output req = req_int; // through the internal net
|
||||
input rsp;
|
||||
endclocking
|
||||
endmodule
|
||||
====
|
||||
# --- `default disable iff expr;` (IEEE 1800 §16.12), kept verbatim ---
|
||||
# It governs the concurrent assertions in its scope, which are verbatim too, so
|
||||
# it is copied out by span: the bytes are reproduced, the indent is the item's.
|
||||
module m;
|
||||
bit disable_sva;
|
||||
default disable iff disable_sva || !rst_ni;
|
||||
default disable iff !rst_n;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
bit disable_sva;
|
||||
default disable iff disable_sva || !rst_ni;
|
||||
default disable iff !rst_n;
|
||||
endmodule
|
||||
====
|
||||
# it stands inside a generate block next to a `default clocking` and assertions
|
||||
module m;
|
||||
if (1) begin : gen_checks
|
||||
default disable iff !rst_n || en != On;
|
||||
default clocking @(posedge clk); endclocking
|
||||
CheckA: assert property (a |=> b) else `uvm_error("CheckA", "no")
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
if (1) begin : gen_checks
|
||||
default disable iff !rst_n || en != On;
|
||||
default clocking @(posedge clk);
|
||||
endclocking
|
||||
CheckA: assert property (a |=> b) else `uvm_error("CheckA", "no")
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# --- `iff` on an event-control term (IEEE 1800 §9.4.2) ---
|
||||
module m;
|
||||
initial begin
|
||||
@(posedge clk iff rvalid);
|
||||
@(negedge clk_i iff (write ? sram_we : sram_req));
|
||||
@(posedge cfg.vif.enable iff cfg.vif.rst_n);
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
@(posedge clk iff rvalid);
|
||||
@(negedge clk_i iff (write ? sram_we : sram_req));
|
||||
@(posedge cfg.vif.enable iff cfg.vif.rst_n);
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# the gate belongs to its own term: both separators keep working around it
|
||||
module m;
|
||||
always @(posedge a iff en or negedge b) x <= 1;
|
||||
always @(posedge a iff en, negedge b iff en2) y <= 1;
|
||||
always @(a iff b) z <= 1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(posedge a iff en or negedge b) x <= 1;
|
||||
always @(posedge a iff en, negedge b iff en2) y <= 1;
|
||||
always @(a iff b) z <= 1;
|
||||
endmodule
|
||||
====
|
||||
# --- a bare event control naming an indexed hierarchical path ---
|
||||
# `@name` is printed back without parens; the bit-selects on the path are part
|
||||
# of the name (IEEE 1800 §A.9.3), so nothing about the shape changes.
|
||||
class c;
|
||||
task wait_for_ready();
|
||||
forever @cfg.m_alert_agent_cfgs["fatal_cnsty_fault"].vif.sender_cb begin
|
||||
if (done) return;
|
||||
end
|
||||
endtask
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
task wait_for_ready();
|
||||
forever @cfg.m_alert_agent_cfgs["fatal_cnsty_fault"].vif.sender_cb begin
|
||||
if (done) return;
|
||||
end
|
||||
endtask
|
||||
endclass
|
||||
====
|
||||
# --- a gate's drive strength, single and paired (IEEE 1800 §28.3) ---
|
||||
module m;
|
||||
for (genvar i = 0; i < 4; i++) begin : gen_tri_state
|
||||
pullup (weak1) pd_in_i (si_pulldown[i]);
|
||||
pulldown (supply0, supply1) pd_out_i (so_pulldown[i]);
|
||||
end
|
||||
and (strong0, strong1) g1 (o, a, b), g2 (o2, c, d);
|
||||
assign (weak0, pull1) w = 1'b1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
for (genvar i = 0; i < 4; i++) begin : gen_tri_state
|
||||
pullup (weak1) pd_in_i (si_pulldown[i]);
|
||||
pulldown (supply0, supply1) pd_out_i (so_pulldown[i]);
|
||||
end
|
||||
and (strong0, strong1) g1 (o, a, b), g2 (o2, c, d);
|
||||
assign (weak0, pull1) w = 1'b1;
|
||||
endmodule
|
||||
====
|
||||
# a gate whose first argument is parenthesized is still an argument, not a
|
||||
# strength: only a strength keyword after the `(` opens one.
|
||||
module m;
|
||||
buf b1 ((a & b), c);
|
||||
not (o, (x | y));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
buf b1 ((a & b), c);
|
||||
not (o, (x | y));
|
||||
endmodule
|
||||
====
|
||||
# --- `program ... endprogram` (IEEE 1800 §24.3): a module header, a module
|
||||
# body, a different closer.
|
||||
program spiflash #(
|
||||
parameter int unsigned FlashSize = 1024,
|
||||
parameter bit EnFastSim = 1'b1
|
||||
) (
|
||||
input logic csb,
|
||||
input logic sck
|
||||
);
|
||||
logic [7:0] cmd;
|
||||
initial begin
|
||||
cmd = 8'h0;
|
||||
end
|
||||
task automatic step();
|
||||
@(posedge sck iff !csb);
|
||||
endtask
|
||||
endprogram : spiflash
|
||||
----
|
||||
program spiflash #(
|
||||
parameter int unsigned FlashSize = 1024,
|
||||
parameter bit EnFastSim = 1'b1
|
||||
) (input logic csb, input logic sck);
|
||||
logic [7:0] cmd;
|
||||
initial begin
|
||||
cmd = 8'h0;
|
||||
end
|
||||
task automatic step();
|
||||
@(posedge sck iff !csb);
|
||||
endtask
|
||||
endprogram : spiflash
|
||||
====
|
||||
# --- a macro invocation as a concurrent assertion's action statement ---
|
||||
# `else `ASSERT_ERROR(A)` ends with the macro; there is no `;` to scan to.
|
||||
module m;
|
||||
FsmStateSwReset_A:
|
||||
assert property (rst |=> state == Reset)
|
||||
else `ASSERT_ERROR(FsmStateSwReset_A)
|
||||
assign x = 1;
|
||||
Other_A: assert property (c) else `uvm_error("a", "b");
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
FsmStateSwReset_A:
|
||||
assert property (rst |=> state == Reset)
|
||||
else `ASSERT_ERROR(FsmStateSwReset_A)
|
||||
assign x = 1;
|
||||
Other_A: assert property (c) else `uvm_error("a", "b");
|
||||
endmodule
|
||||
====
|
||||
# ... and the other side of that decision: when the macro expands to a signal
|
||||
# name, the statement runs on past it and ends at its own `;`. All four shapes
|
||||
# round-trip byte-for-byte, exactly as they did before the macro case existed.
|
||||
module m;
|
||||
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
|
||||
B_B: assert property (b) else `MSG(x) + 1;
|
||||
C_C: assert property (c) else `CNT <= `CNT + 1;
|
||||
D_D: assert property (d) else `CNT++;
|
||||
assign y = 1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
|
||||
B_B: assert property (b) else `MSG(x) + 1;
|
||||
C_C: assert property (c) else `CNT <= `CNT + 1;
|
||||
D_D: assert property (d) else `CNT++;
|
||||
assign y = 1;
|
||||
endmodule
|
||||
@@ -1191,3 +1191,227 @@ endmodule
|
||||
module m;
|
||||
sub /* the one */ u (.a(b));
|
||||
endmodule
|
||||
====
|
||||
# a line comment trailing `end` pushes `else if` onto the next line
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // addr_phase_write
|
||||
else if (b) begin
|
||||
x = 2;
|
||||
end
|
||||
else begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // addr_phase_write
|
||||
else if (b) begin
|
||||
x = 2;
|
||||
end else begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a line comment trailing `end` pushes a one-statement `else` down too
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // fell through
|
||||
else if (b) x = 2;
|
||||
else x = 3;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // fell through
|
||||
else if (b) x = 2;
|
||||
else x = 3;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a block comment trailing `end` still lets `else` cuddle
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end /* why */ else begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end /* why */ else begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment after `if (` stays inside the parentheses
|
||||
module m;
|
||||
always_comb begin
|
||||
if (// the first transaction
|
||||
a ||
|
||||
// or the last one
|
||||
b) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (
|
||||
// the first transaction
|
||||
a || // or the last one
|
||||
b
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a block comment before an if condition's `)` stays inside them
|
||||
module m;
|
||||
always_comb begin
|
||||
if (bitstuff /* && !serial_tx_se0 */) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (bitstuff /* && !serial_tx_se0 */) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# an if condition keeps comments on both sides of it
|
||||
module m;
|
||||
always_comb begin
|
||||
if (// only the leading one
|
||||
a) begin
|
||||
x = 1;
|
||||
end
|
||||
if (b /* and a trailing one */) begin
|
||||
x = 2;
|
||||
end
|
||||
if (// both ends
|
||||
c /* like this */) begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (
|
||||
// only the leading one
|
||||
a
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
if (b /* and a trailing one */) begin
|
||||
x = 2;
|
||||
end
|
||||
if (
|
||||
// both ends
|
||||
c /* like this */
|
||||
) begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment after `while (` stays inside the parentheses
|
||||
module m;
|
||||
initial begin
|
||||
while (// keep adding while the agent wants more
|
||||
rcvd < sent ||
|
||||
// and while there are transactions left to drive
|
||||
cnt < num) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
while (
|
||||
// keep adding while the agent wants more
|
||||
rcvd < sent || // and while there are transactions left to drive
|
||||
cnt < num
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# `repeat` and `wait` keep a comment written before their `)`
|
||||
module m;
|
||||
initial begin
|
||||
repeat (n // how many
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
wait (w // until this settles
|
||||
) begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
repeat (
|
||||
n // how many
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
wait (
|
||||
w // until this settles
|
||||
) begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment after `case (` stays inside the parentheses
|
||||
module m;
|
||||
always_comb begin
|
||||
case (// the decoded opcode
|
||||
op)
|
||||
A: y = 1;
|
||||
default: y = 0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
case (
|
||||
// the decoded opcode
|
||||
op
|
||||
)
|
||||
A: y = 1;
|
||||
default: y = 0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,263 @@
|
||||
# a `ifdef opened part-way through an assign, each arm carrying the
|
||||
# construct's own `;` -- the block ends at the `endif, because there is no
|
||||
# `;` after it to stop at
|
||||
# hw/top_earlgrey/dv/env/chip_if.sv:1189 (the anchor)
|
||||
module m;
|
||||
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
|
||||
wire [3:0] aes_ctrl_rnd_ctr;
|
||||
assign aes_ctrl_rnd_ctr =
|
||||
`ifdef GATE_LEVEL
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
|
||||
`else
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
|
||||
`endif
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
|
||||
wire [3:0] aes_ctrl_rnd_ctr;
|
||||
assign aes_ctrl_rnd_ctr =
|
||||
`ifdef GATE_LEVEL
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
|
||||
`else
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
|
||||
`endif
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# the same shape at *statement* level: a region between two call arguments,
|
||||
# balanced inside the parens, so the statement ends at its own `;`. Only the
|
||||
# statement is captured -- the function around it still formats
|
||||
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173
|
||||
class c;
|
||||
virtual function void build();
|
||||
abits = (dv_base_reg_field::type_id::create("abits"));
|
||||
abits.configure(
|
||||
.parent(this),
|
||||
.size(6),
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
.reset(32'h10),
|
||||
`else
|
||||
.reset(32'h07),
|
||||
`endif
|
||||
.has_reset(1));
|
||||
dmistat = 1;
|
||||
endfunction
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
virtual function void build();
|
||||
abits = (dv_base_reg_field::type_id::create("abits"));
|
||||
abits.configure(
|
||||
.parent(this),
|
||||
.size(6),
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
.reset(32'h10),
|
||||
`else
|
||||
.reset(32'h07),
|
||||
`endif
|
||||
.has_reset(1));
|
||||
dmistat = 1;
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
# a region between the elements of a concatenation, three brackets deep inside
|
||||
# an instantiation's parameter override -- the whole instantiation becomes the
|
||||
# block, ending at its `;`
|
||||
# hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621
|
||||
module chip;
|
||||
padring #(
|
||||
.DioPadType ({
|
||||
AnalogIn0, // RRAM_ANALOG
|
||||
`ifdef ANALOGSIM
|
||||
'0,
|
||||
`else
|
||||
CC2,
|
||||
`endif
|
||||
DualBidirTol // USB_N
|
||||
})
|
||||
) u_padring (
|
||||
.clk_scan_i(ast_base_clks.clk_sys),
|
||||
.scanmode_i(scanmode)
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module chip;
|
||||
padring #(
|
||||
.DioPadType ({
|
||||
AnalogIn0, // RRAM_ANALOG
|
||||
`ifdef ANALOGSIM
|
||||
'0,
|
||||
`else
|
||||
CC2,
|
||||
`endif
|
||||
DualBidirTol // USB_N
|
||||
})
|
||||
) u_padring (
|
||||
.clk_scan_i(ast_base_clks.clk_sys),
|
||||
.scanmode_i(scanmode)
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# two instantiation *heads* behind one `ifdef, sharing a connection list. The
|
||||
# region opened before the item, so this is the closing shape the
|
||||
# `directive-split` recovery already knew -- what changed is that
|
||||
# `take_list_directives` no longer harvests the `else as a list element and
|
||||
# reads the second arm's head as a positional connection
|
||||
# hw/top_earlgrey/dv/tb/tb.sv:105
|
||||
module tb;
|
||||
`ifdef DISABLE_ROM_INTEGRITY_CHECK
|
||||
chip_earlgrey_asic #(
|
||||
// This is to be used carefully, and should never be on for synthesis.
|
||||
.SecRomCtrlDisableScrambling(1'b1)
|
||||
) dut (
|
||||
`else
|
||||
chip_earlgrey_asic dut (
|
||||
`endif
|
||||
// Dedicated Pads
|
||||
.POR_N(dut.chip_if.dios[DioPadPorN]),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(cc1),
|
||||
`else
|
||||
.CC1(dut.chip_if.dios[DioPadCc1]),
|
||||
`endif
|
||||
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
`ifdef DISABLE_ROM_INTEGRITY_CHECK
|
||||
chip_earlgrey_asic #(
|
||||
// This is to be used carefully, and should never be on for synthesis.
|
||||
.SecRomCtrlDisableScrambling(1'b1)
|
||||
) dut (
|
||||
`else
|
||||
chip_earlgrey_asic dut (
|
||||
`endif
|
||||
// Dedicated Pads
|
||||
.POR_N(dut.chip_if.dios[DioPadPorN]),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(cc1),
|
||||
`else
|
||||
.CC1(dut.chip_if.dios[DioPadCc1]),
|
||||
`endif
|
||||
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# a split `function` header: the header's own `;` closes a *header*, so the
|
||||
# block runs to `endfunction` and takes the `: label` with it
|
||||
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273
|
||||
class jtag_dtm_reg_dmi;
|
||||
function new(string name = "",
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
int unsigned n_bits = 50,
|
||||
`else
|
||||
int unsigned n_bits = 41,
|
||||
`endif
|
||||
int has_coverage = UVM_NO_COVERAGE);
|
||||
super.new(name, n_bits, has_coverage);
|
||||
endfunction : new
|
||||
|
||||
int after;
|
||||
endclass
|
||||
----
|
||||
class jtag_dtm_reg_dmi;
|
||||
function new(string name = "",
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
int unsigned n_bits = 50,
|
||||
`else
|
||||
int unsigned n_bits = 41,
|
||||
`endif
|
||||
int has_coverage = UVM_NO_COVERAGE);
|
||||
super.new(name, n_bits, has_coverage);
|
||||
endfunction : new
|
||||
|
||||
int after;
|
||||
endclass
|
||||
====
|
||||
# the control: a region opened *and* closed inside the connection list still
|
||||
# conditions list elements, even with an outer region live, and the
|
||||
# instantiation still parses as an instantiation rather than becoming opaque
|
||||
module m;
|
||||
`ifdef OUTER
|
||||
chip dut (
|
||||
.A(a),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(c1),
|
||||
`else
|
||||
.CC1(d1),
|
||||
`endif
|
||||
.B(b)
|
||||
);
|
||||
`endif
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
`ifdef OUTER
|
||||
chip dut (
|
||||
.A(a),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(c1),
|
||||
`else
|
||||
.CC1(d1),
|
||||
`endif
|
||||
.B(b)
|
||||
);
|
||||
`endif
|
||||
endmodule
|
||||
====
|
||||
# comments survive: the ones written inside the block print once, as part of
|
||||
# its bytes, and the ones around it stay outside
|
||||
module m;
|
||||
// before the block
|
||||
assign y =
|
||||
`ifdef A
|
||||
a; // inside the first arm
|
||||
`else
|
||||
b; /* inside the second */
|
||||
`endif
|
||||
// after the block
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// before the block
|
||||
assign y =
|
||||
`ifdef A
|
||||
a; // inside the first arm
|
||||
`else
|
||||
b; /* inside the second */
|
||||
`endif
|
||||
// after the block
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# the keymgr shape: the take_gap parser fix and header_parens in one tree —
|
||||
# the comment written after `if (` stays inside the parens (the last of
|
||||
# bucket 2's 12; merged-tree pin the serial round could not add itself)
|
||||
module m;
|
||||
function automatic int f();
|
||||
if (// why
|
||||
!en() || b
|
||||
) begin
|
||||
return 1;
|
||||
end
|
||||
endfunction
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
function automatic int f();
|
||||
if (
|
||||
// why
|
||||
!en() || b
|
||||
) begin
|
||||
return 1;
|
||||
end
|
||||
endfunction
|
||||
endmodule
|
||||
@@ -0,0 +1,230 @@
|
||||
# The mop-up round: the small parser buckets of syntax_coverage.md, bundled.
|
||||
# See docs/features/testbench-mopup/README.md. Every case here is a shape the
|
||||
# OpenTitan sweep contains; none of them needed a layout decision, because in
|
||||
# every one the new surface is data the source already laid out (a bracket, a
|
||||
# qualifier word, a modport suffix) rather than a construct to break.
|
||||
|
||||
# --- bucket 4: a block-scoped `typedef` statement (IEEE 1800 §6.18) ---
|
||||
# The statement form is the item form, indented to the block. Same node, same
|
||||
# printer, so `typedef enum` still fits on one line if it fits.
|
||||
class c;
|
||||
task access_data_fifo(ref bit [7:0] data_q[$]);
|
||||
typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e;
|
||||
rdwr_e rw = WRITE;
|
||||
endtask
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
task access_data_fifo(ref bit [7:0] data_q [$]);
|
||||
typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e;
|
||||
rdwr_e rw = WRITE;
|
||||
endtask
|
||||
endclass
|
||||
====
|
||||
# every typedef spelling reaches statement position, comments included
|
||||
module m;
|
||||
initial begin
|
||||
// a block-scoped alias, a dynamic-array alias and a struct
|
||||
typedef logic [2*$bits(mubi4_t) - 1:0] extclk_ctrl_t;
|
||||
typedef bit data_result[];
|
||||
typedef struct {
|
||||
trans_e unit;
|
||||
uvm_reg_field hint_bit;
|
||||
} hint_t;
|
||||
typedef class fwd;
|
||||
data_result data_array;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
// a block-scoped alias, a dynamic-array alias and a struct
|
||||
typedef logic [2*$bits(mubi4_t)-1:0] extclk_ctrl_t;
|
||||
typedef bit data_result [];
|
||||
typedef struct {
|
||||
trans_e unit;
|
||||
uvm_reg_field hint_bit;
|
||||
} hint_t;
|
||||
typedef class fwd;
|
||||
data_result data_array;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# --- bucket 6: a system function call as the casting type ---
|
||||
# `$bits(x)'(y)` / `$clog2(N)'(y)` — a `constant_primary` per IEEE 1800
|
||||
# §6.24.1, and the only call shape admitted left of a cast's `'`.
|
||||
module m;
|
||||
assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0});
|
||||
assign a = $clog2(RomSize)'(RomSize);
|
||||
assign b = data_q[$clog2(dm::DataCount)'(autoexecdata_idx)];
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0});
|
||||
assign a = $clog2(RomSize)'(RomSize);
|
||||
assign b = data_q[$clog2(dm::DataCount)'(autoexecdata_idx)];
|
||||
endmodule
|
||||
====
|
||||
# --- bucket 8: enum member ranges (IEEE 1800 §6.19) ---
|
||||
# The bracket prints tight against the name: it is part of the name, not a
|
||||
# dimension standing beside it, and there is no layout decision in it.
|
||||
package p;
|
||||
typedef enum logic [ResetWidths-1:0] {
|
||||
ReqPeriResetIdx[0:1],
|
||||
ReqMainPwrResetIdx,
|
||||
ReqEscResetIdx
|
||||
} reset_idx_e;
|
||||
|
||||
typedef enum {
|
||||
OtbnDmem[16],
|
||||
OtbnImem,
|
||||
RamMain[16] = 5,
|
||||
Otp
|
||||
} mem_e;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
typedef enum logic [ResetWidths-1:0] {
|
||||
ReqPeriResetIdx[0:1],
|
||||
ReqMainPwrResetIdx,
|
||||
ReqEscResetIdx
|
||||
} reset_idx_e;
|
||||
|
||||
typedef enum {OtbnDmem[16], OtbnImem, RamMain[16] = 5, Otp} mem_e;
|
||||
endpackage
|
||||
====
|
||||
# --- bucket 10: a cast applied to an assignment pattern, `ty'{...}` ---
|
||||
# The pattern brings its own `'{` and `}`, so the cast prints no brackets of
|
||||
# its own. The last line is the reason the two spellings stay distinguishable
|
||||
# in the tree: `ty'('{...})` is a different token stream and must survive as
|
||||
# itself.
|
||||
class c;
|
||||
function void f();
|
||||
exp_alert_q[alert_name].push_back(expected_alert_t'{1, is_fatal, max_delay});
|
||||
q.push_back(mem_item_t'{addr: a, data: d});
|
||||
x = pkg::cfg_t'{default: 0};
|
||||
endfunction
|
||||
endclass
|
||||
|
||||
module m;
|
||||
assign tag = {ibex_pkg::IC_NUM_WAYS{prim_ram_1p_pkg::ram_1p_cfg_req_t'{req: spram_rm.cfg}}};
|
||||
assign y = bar_t'('{a: 1});
|
||||
endmodule
|
||||
----
|
||||
class c;
|
||||
function void f();
|
||||
exp_alert_q[alert_name].push_back(expected_alert_t'{1, is_fatal, max_delay});
|
||||
q.push_back(mem_item_t'{addr: a, data: d});
|
||||
x = pkg::cfg_t'{default: 0};
|
||||
endfunction
|
||||
endclass
|
||||
|
||||
module m;
|
||||
assign tag = {ibex_pkg::IC_NUM_WAYS{prim_ram_1p_pkg::ram_1p_cfg_req_t'{req: spram_rm.cfg}}};
|
||||
assign y = bar_t'('{a: 1});
|
||||
endmodule
|
||||
====
|
||||
# --- bucket 11: a gate's `#(rise, fall[, turn-off])` delay list (§28.14) ---
|
||||
# The one-value spellings keep the node they always had, so `#(5)` and `#5`
|
||||
# still print exactly as written; only a real comma list prints its own parens.
|
||||
module m;
|
||||
buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i));
|
||||
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);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i));
|
||||
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);
|
||||
endmodule
|
||||
====
|
||||
# --- bucket 12: `virtual iface.modport name;` (IEEE 1800 §25.9) ---
|
||||
# The modport is glued onto the interface name, exactly as an interface
|
||||
# *port*'s already is, so the type prints as the one string it is.
|
||||
module tb;
|
||||
virtual spi_if.tb tb_sif = sif.tb;
|
||||
virtual spi_if.dut dut_sif;
|
||||
virtual interface bus_if plain_vif;
|
||||
|
||||
task automatic spi_transaction(virtual spi_if.tb sif, ref spi_fifo_t d_in[$]);
|
||||
endtask
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
virtual spi_if.tb tb_sif = sif.tb;
|
||||
virtual spi_if.dut dut_sif;
|
||||
virtual interface bus_if plain_vif;
|
||||
|
||||
task automatic spi_transaction(virtual spi_if.tb sif, ref spi_fifo_t d_in [$]);
|
||||
endtask
|
||||
endmodule
|
||||
====
|
||||
# --- bucket 14: `rand`/`randc` on a plain struct member ---
|
||||
# Not LRM-legal, but vendor-accepted and real. Carried and printed; lucisv
|
||||
# models no randomization semantics either way.
|
||||
package p;
|
||||
typedef struct {
|
||||
rand bit cpol;
|
||||
randc bit [3:0] csnlead;
|
||||
rand mubi4_t en; // enable this region
|
||||
bit plain;
|
||||
} cfg_t;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
typedef struct {
|
||||
rand bit cpol;
|
||||
randc bit [3:0] csnlead;
|
||||
rand mubi4_t en; // enable this region
|
||||
bit plain;
|
||||
} cfg_t;
|
||||
endpackage
|
||||
====
|
||||
# --- bucket 15: a `foreach` with a skipped dimension (IEEE 1800 §12.7.3) ---
|
||||
# A skipped slot is an empty name written where the source wrote nothing: it
|
||||
# declares no loop variable, and it prints as nothing.
|
||||
module m;
|
||||
initial begin
|
||||
foreach (cfg.mem_bkdr_util_h[, bank]) x = 1;
|
||||
foreach (h[i, , k]) y = 2;
|
||||
foreach (q[i, j]) w = 4;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
foreach (cfg.mem_bkdr_util_h[, bank]) x = 1;
|
||||
foreach (h[i, , k]) y = 2;
|
||||
foreach (q[i, j]) w = 4;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# --- bucket 16: a hierarchical path in a `bind`'s instance list ---
|
||||
# The dots are glued into the one name the list already carries, the way
|
||||
# `bind`'s own target path is.
|
||||
module tb;
|
||||
bind prim_packer_fifo : dut.u_entropy_src_core.u_prim_packer_fifo_precon
|
||||
entropy_subsys_fifo_exception_if #(
|
||||
.IsPackerFifo(1)
|
||||
) u_fifo_exc_if (
|
||||
.clk_i,
|
||||
.rst_ni
|
||||
);
|
||||
|
||||
bind foo : a.b, plain_inst bar u (.x);
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
bind prim_packer_fifo : dut.u_entropy_src_core.u_prim_packer_fifo_precon entropy_subsys_fifo_exception_if #(
|
||||
.IsPackerFifo(1)
|
||||
) u_fifo_exc_if (.clk_i, .rst_ni);
|
||||
|
||||
bind foo : a.b, plain_inst bar u (.x);
|
||||
endmodule
|
||||
@@ -0,0 +1,327 @@
|
||||
# the owner's report: a stray `;` after `endgenerate`
|
||||
module m #(parameter int N = 4) (input logic [N-1:0] a, output logic [N-1:0] y);
|
||||
generate
|
||||
for (genvar i = 0; i < N; i++) begin : g
|
||||
assign y[i] = ~a[i];
|
||||
end
|
||||
endgenerate;
|
||||
endmodule
|
||||
----
|
||||
module m #(parameter int N = 4) (input logic [N-1:0] a, output logic [N-1:0] y);
|
||||
generate
|
||||
for (genvar i = 0; i < N; i++) begin : g
|
||||
assign y[i] = ~a[i];
|
||||
end
|
||||
endgenerate;
|
||||
endmodule
|
||||
====
|
||||
# a null item on its own line at module scope
|
||||
module m (input logic clk, output logic q);
|
||||
always_ff @(posedge clk) q <= ~q;
|
||||
;
|
||||
endmodule
|
||||
----
|
||||
module m (input logic clk, output logic q);
|
||||
always_ff @(posedge clk) q <= ~q;
|
||||
;
|
||||
endmodule
|
||||
====
|
||||
# slang's -Wempty-member example: `module m; ; endmodule`
|
||||
module m; ; endmodule
|
||||
----
|
||||
module m;
|
||||
;
|
||||
endmodule
|
||||
====
|
||||
# a null item that opens a generate region takes its own line
|
||||
module m; generate ; endgenerate endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
;
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# `end;` after a generate block inside a region
|
||||
module m #(parameter int N = 2) (output logic [N-1:0] y);
|
||||
generate
|
||||
for (genvar i = 0; i < N; i++) begin : g
|
||||
assign y[i] = 1'b0;
|
||||
end;
|
||||
endgenerate
|
||||
endmodule
|
||||
----
|
||||
module m #(parameter int N = 2) (output logic [N-1:0] y);
|
||||
generate
|
||||
for (genvar i = 0; i < N; i++) begin : g
|
||||
assign y[i] = 1'b0;
|
||||
end;
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# region-less `end;`, and `;;` after it
|
||||
module m #(parameter int N = 2) (output logic [N-1:0] y);
|
||||
if (N > 1) begin : g1
|
||||
assign y = '0;
|
||||
end;
|
||||
;;
|
||||
endmodule
|
||||
----
|
||||
module m #(parameter int N = 2) (output logic [N-1:0] y);
|
||||
if (N > 1) begin : g1
|
||||
assign y = '0;
|
||||
end;
|
||||
;;
|
||||
endmodule
|
||||
====
|
||||
# a null item in a package body
|
||||
package p;
|
||||
localparam int W = 1;
|
||||
;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
localparam int W = 1;
|
||||
;
|
||||
endpackage
|
||||
====
|
||||
# a null item in an interface body
|
||||
interface ifc;
|
||||
logic a;
|
||||
;
|
||||
endinterface
|
||||
----
|
||||
interface ifc;
|
||||
logic a;
|
||||
;
|
||||
endinterface
|
||||
====
|
||||
# a null item in a class body
|
||||
class c;
|
||||
int x;
|
||||
;
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
int x;
|
||||
;
|
||||
endclass
|
||||
====
|
||||
# `endmodule;` — a null item at file scope
|
||||
module m;
|
||||
endmodule;
|
||||
----
|
||||
module m;
|
||||
endmodule;
|
||||
====
|
||||
# glued stays glued: the output of the owner's shape formats to itself
|
||||
module m;
|
||||
generate
|
||||
endgenerate;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
endgenerate;
|
||||
endmodule
|
||||
====
|
||||
# own-line stays own-line
|
||||
module m;
|
||||
wire a;
|
||||
;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
;
|
||||
endmodule
|
||||
====
|
||||
# a trailing comment after a glued `;` stays on that line
|
||||
module m;
|
||||
generate
|
||||
endgenerate; // note
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
endgenerate; // note
|
||||
endmodule
|
||||
====
|
||||
# a leading comment keeps the `;` on a line of its own
|
||||
module m;
|
||||
wire a;
|
||||
// why the semicolon is here
|
||||
;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
// why the semicolon is here
|
||||
;
|
||||
endmodule
|
||||
====
|
||||
# a blank line before a null item is kept, and unglues it
|
||||
module m;
|
||||
wire a;
|
||||
|
||||
;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
|
||||
;
|
||||
endmodule
|
||||
====
|
||||
# a block comment between the item and its `;` keeps its place
|
||||
module m;
|
||||
generate endgenerate /* b */ ;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
endgenerate /* b */;
|
||||
endmodule
|
||||
====
|
||||
# a null item splits an alignment group
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
;
|
||||
localparam int B = 3;
|
||||
localparam int OTHER = 44;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
;
|
||||
localparam int B = 3;
|
||||
localparam int OTHER = 44;
|
||||
endmodule
|
||||
====
|
||||
# the null *statement* is untouched (slang's -Wempty-stmt example)
|
||||
module m;
|
||||
initial begin
|
||||
;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# `endfunction;`/`endtask;` still print through `end_semi`, not as null items
|
||||
module m;
|
||||
function int f(); return 1; endfunction;
|
||||
task t(); endtask;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
function int f();
|
||||
return 1;
|
||||
endfunction;
|
||||
task t();
|
||||
endtask;
|
||||
endmodule
|
||||
====
|
||||
# systemverilog.io: a 16-input mux built with a generate for
|
||||
module mux16 (input logic [3:0] select, input logic [15:0] mux_in, output logic mux_out);
|
||||
logic [15:0] temp;
|
||||
genvar i;
|
||||
generate
|
||||
for (i=0; i < 16; i++) begin
|
||||
assign temp[i] = (select == i) ? mux_in[i] : 0;
|
||||
end
|
||||
endgenerate
|
||||
assign mux_out = |temp;
|
||||
endmodule
|
||||
----
|
||||
module mux16 (input logic [3:0] select, input logic [15:0] mux_in, output logic mux_out);
|
||||
logic [15:0] temp;
|
||||
genvar i;
|
||||
generate
|
||||
for (i = 0; i < 16; i++) begin
|
||||
assign temp[i] = (select == i) ? mux_in[i] : 0;
|
||||
end
|
||||
endgenerate
|
||||
assign mux_out = |temp;
|
||||
endmodule
|
||||
====
|
||||
# systemverilog.io: `assert property` inside a generate for
|
||||
module arb_sva (input logic clk, input logic [7:0] req, input logic [7:0] ack);
|
||||
genvar k;
|
||||
generate
|
||||
for (k=0; k < 8; k++) begin
|
||||
req_a: assert property (@(posedge clk) req[k] |=> ack[k]);
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
----
|
||||
module arb_sva (input logic clk, input logic [7:0] req, input logic [7:0] ack);
|
||||
genvar k;
|
||||
generate
|
||||
for (k = 0; k < 8; k++) begin
|
||||
req_a: assert property (@(posedge clk) req[k] |=> ack[k]);
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# systemverilog.io: a generate case with a nested for and instantiations
|
||||
module mem #(parameter MEM_SIZE = 8, parameter MEM_WIDTH = 16) (
|
||||
input clk, input csx, input cke, input [1:0] ba, input [11:0] addr,
|
||||
input rasx, input casx, input wex, input [7:0] dqm, inout [63:0] data, input [3:0] dev_id);
|
||||
genvar i;
|
||||
case ({MEM_SIZE, MEM_WIDTH})
|
||||
{32'd8, 32'd16}:
|
||||
begin: memory
|
||||
for (i=0; i<4; i=i+1) begin:word16
|
||||
sms_08b216t0 p(.clk(clk), .csb(csx), .cke(cke),.ba(ba),
|
||||
.addr(addr), .rasb(rasx), .casb(casx),
|
||||
.web(wex), .udqm(dqm[2*i+1]), .ldqm(dqm[2*i]),
|
||||
.dqi(data[15+16*i:16*i]), .dev_id(dev_id));
|
||||
end
|
||||
end
|
||||
endcase
|
||||
endmodule
|
||||
----
|
||||
module mem #(
|
||||
parameter MEM_SIZE = 8,
|
||||
parameter MEM_WIDTH = 16
|
||||
) (
|
||||
input clk,
|
||||
input csx,
|
||||
input cke,
|
||||
input [1:0] ba,
|
||||
input [11:0] addr,
|
||||
input rasx,
|
||||
input casx,
|
||||
input wex,
|
||||
input [7:0] dqm,
|
||||
inout [63:0] data,
|
||||
input [3:0] dev_id
|
||||
);
|
||||
genvar i;
|
||||
case ({MEM_SIZE, MEM_WIDTH})
|
||||
{32'd8, 32'd16}: begin : memory
|
||||
for (i = 0; i < 4; i = i + 1) begin : word16
|
||||
sms_08b216t0 p (
|
||||
.clk(clk),
|
||||
.csb(csx),
|
||||
.cke(cke),
|
||||
.ba(ba),
|
||||
.addr(addr),
|
||||
.rasb(rasx),
|
||||
.casb(casx),
|
||||
.web(wex),
|
||||
.udqm(dqm[2*i+1]),
|
||||
.ldqm(dqm[2*i]),
|
||||
.dqi(data[15+16*i:16*i]),
|
||||
.dev_id(dev_id)
|
||||
);
|
||||
end
|
||||
end
|
||||
endcase
|
||||
endmodule
|
||||
@@ -0,0 +1,86 @@
|
||||
# Out-of-block constraint definitions (IEEE 1800 §18.5.2), the constraint
|
||||
# sibling of `function C::method`. See
|
||||
# docs/features/out-of-class-constraints/README.md. The whole item is an
|
||||
# ItemKind::Verbatim leaf, so the body is reproduced byte for byte; only the
|
||||
# block's absolute indent is re-set, exactly as for an in-class constraint.
|
||||
|
||||
# an extern constraint prototype and its out-of-block definition
|
||||
class my_item;
|
||||
rand int delay;
|
||||
extern constraint delay_c;
|
||||
endclass : my_item
|
||||
|
||||
constraint my_item::delay_c {
|
||||
soft delay dist {0 :/ 5, [1:10] :/ 5};
|
||||
solve delay before other;
|
||||
}
|
||||
----
|
||||
class my_item;
|
||||
rand int delay;
|
||||
extern constraint delay_c;
|
||||
endclass : my_item
|
||||
|
||||
constraint my_item::delay_c {
|
||||
soft delay dist {0 :/ 5, [1:10] :/ 5};
|
||||
solve delay before other;
|
||||
}
|
||||
====
|
||||
# inside a package: the block is re-indented, its relative layout is not
|
||||
package p;
|
||||
constraint my_item::delay_c {
|
||||
soft delay dist {0 :/ 5};
|
||||
}
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
constraint my_item::delay_c {
|
||||
soft delay dist {0 :/ 5};
|
||||
}
|
||||
endpackage
|
||||
====
|
||||
# a scope chain, a stray `;`, and comments on both sides of the block
|
||||
// why this constraint exists
|
||||
constraint pkg::cls::deep_c { x < 4; }; // and a trailing note
|
||||
int b;
|
||||
----
|
||||
// why this constraint exists
|
||||
constraint pkg::cls::deep_c { x < 4; }; // and a trailing note
|
||||
int b;
|
||||
====
|
||||
# an empty body and a prototype next to a definition
|
||||
class c;
|
||||
extern constraint empty_c;
|
||||
endclass
|
||||
|
||||
constraint c::empty_c {}
|
||||
----
|
||||
class c;
|
||||
extern constraint empty_c;
|
||||
endclass
|
||||
|
||||
constraint c::empty_c {}
|
||||
====
|
||||
# the body's own second grammar survives untouched: dist, ->, foreach, if
|
||||
constraint seq::mode_c {
|
||||
r_esc_rsp == 1 -> (!s_alert_send && !r_alert_rsp);
|
||||
foreach (ranges[i]) {
|
||||
ranges[i].base % 4 == 0;
|
||||
}
|
||||
if (enabled) {
|
||||
delay dist {0 :/ 5, [1:10] :/ 5};
|
||||
} else {
|
||||
delay == 0;
|
||||
}
|
||||
}
|
||||
----
|
||||
constraint seq::mode_c {
|
||||
r_esc_rsp == 1 -> (!s_alert_send && !r_alert_rsp);
|
||||
foreach (ranges[i]) {
|
||||
ranges[i].base % 4 == 0;
|
||||
}
|
||||
if (enabled) {
|
||||
delay dist {0 :/ 5, [1:10] :/ 5};
|
||||
} else {
|
||||
delay == 0;
|
||||
}
|
||||
}
|
||||
@@ -587,3 +587,54 @@ endmodule
|
||||
module m;
|
||||
always @(a or b or c) y = a & b & c;
|
||||
endmodule
|
||||
====
|
||||
# `default;` keeps IEEE 1800 §12.5's optional colon off; `default: ;` keeps it
|
||||
module m;
|
||||
always_comb begin
|
||||
unique case (digest_size_i)
|
||||
SHA2_256: y = 1;
|
||||
default;
|
||||
endcase
|
||||
unique case (other)
|
||||
SHA2_256: y = 1;
|
||||
default: ;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
unique case (digest_size_i)
|
||||
SHA2_256: y = 1;
|
||||
default;
|
||||
endcase
|
||||
unique case (other)
|
||||
SHA2_256: y = 1;
|
||||
default: ;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a trailing comment on a colon-less `default;` keeps the comment and the
|
||||
# missing colon; the null statement is no longer bare, so the hug shortcut
|
||||
# does not fire and a space appears before the `;` (QA-found nit: a real
|
||||
# statement or comment on the null body falls through to the general path,
|
||||
# which spaces `default` off whatever follows it the same way it would any
|
||||
# other case label)
|
||||
module m;
|
||||
always_comb begin
|
||||
case (s)
|
||||
A: y = 1;
|
||||
default; // fallback
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
case (s)
|
||||
A: y = 1;
|
||||
default ; // fallback
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
@@ -9,10 +9,10 @@
|
||||
use vlog_formatter::{format_source, Config, FormatError};
|
||||
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH, PARSE_STACK_SIZE};
|
||||
|
||||
/// Formatting the deepest legal tree peaks around 5.9 MiB of stack in an
|
||||
/// unoptimized build, more than a default test thread's 2 MiB. The size is
|
||||
/// Formatting the deepest legal tree peaks around 9.7 MiB of stack in an
|
||||
/// unoptimized build, far more than a default test thread's 2 MiB. The size is
|
||||
/// the one every production parse site is given, so these tests fail if the
|
||||
/// guarantee is ever cut below what the depth limit needs.
|
||||
/// guarantee is ever cut below what the two limits need.
|
||||
fn format_deep(source: String) -> Result<String, FormatError> {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
@@ -70,12 +70,29 @@ fn longest_legal_chain_formats() {
|
||||
assert_eq!(out, again, "formatting a maximal chain is a fixed point");
|
||||
}
|
||||
|
||||
/// The stack worst case: a maximal chain inside statement nesting. The two
|
||||
/// peak in different phases — nesting while parsing, chains while formatting —
|
||||
/// so this is the input `PARSE_STACK_SIZE` is measured against.
|
||||
#[test]
|
||||
fn a_maximal_chain_inside_deep_nesting_formats() {
|
||||
let depth = MAX_NESTING_DEPTH as usize / 2 - 4;
|
||||
let src = format!(
|
||||
"module m;\ninitial\n{}x <= a{};\n{}\nendmodule\n",
|
||||
"begin\n".repeat(depth),
|
||||
".b".repeat(MAX_CHAIN_LENGTH as usize),
|
||||
"end\n".repeat(depth)
|
||||
);
|
||||
let out = format_deep(src).expect("a maximal chain inside deep nesting must format");
|
||||
let again = format_deep(out.clone()).expect("reformat");
|
||||
assert_eq!(out, again, "the combined worst case is a fixed point");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_past_the_limit_never_reaches_the_formatter() {
|
||||
let cases = [
|
||||
(nested_begins(400), "nesting too deep"),
|
||||
(nested_parens(400), "nesting too deep"),
|
||||
(member_chain(1500), "expression chain too long"),
|
||||
(member_chain(MAX_CHAIN_LENGTH as usize + 1), "expression chain too long"),
|
||||
];
|
||||
for (src, expected) in cases {
|
||||
match format_deep(src) {
|
||||
|
||||
@@ -1257,3 +1257,304 @@ fn an_opaque_body_cannot_launder_a_stray_endif_into_a_split() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Assert `format_source` refuses `input` with a verification error, i.e. the
|
||||
/// safety net caught the layout and the caller keeps the original bytes.
|
||||
fn expect_refusal(input: &str) {
|
||||
match format_source(input, &Config::default()) {
|
||||
Err(FormatError::Verification(_)) => {}
|
||||
Ok(out) => panic!("expected a refusal, got:\n{out}"),
|
||||
Err(e) => panic!("expected a verification refusal, got {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The header shapes `header_parens` deliberately does *not* cover, pinned as
|
||||
/// clean refusals so a future round sees them move rather than appear.
|
||||
///
|
||||
/// `for` and `foreach` do not end their header in a single condition
|
||||
/// expression, and a `do ... while (c);` has no body after its parentheses to
|
||||
/// take the comment back from. All three still leave the file untouched.
|
||||
#[test]
|
||||
fn a_comment_in_a_for_foreach_or_do_while_header_is_still_refused() {
|
||||
for input in [
|
||||
"module m;\n initial begin\n for (int i = 0; i < 4; i++ // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
|
||||
"module m;\n initial begin\n foreach (arr[i] // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
|
||||
"module m;\n initial begin\n do begin\n y = 1;\n end while (c // why\n );\n end\nendmodule\n",
|
||||
] {
|
||||
expect_refusal(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The three bucket-2 shapes, formatted for real: every comment comes back
|
||||
/// with its own text, none merged into the code that follows it, and the
|
||||
/// second pass is a fixed point.
|
||||
#[test]
|
||||
fn the_repaired_comment_shapes_keep_every_comment_intact() {
|
||||
for (input, kept, banned) in [
|
||||
(
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // addr_phase_write\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
"// addr_phase_write",
|
||||
"// addr_phase_write else",
|
||||
),
|
||||
(
|
||||
"module m;\n always_comb begin\n if (// why not\n a || b) begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
"// why not",
|
||||
") // why not",
|
||||
),
|
||||
(
|
||||
"module m;\n always_comb begin\n if (a /* and here */) begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
"/* and here */",
|
||||
") /* and here */",
|
||||
),
|
||||
] {
|
||||
let out = format_source(input, &Config::default()).expect("formats cleanly");
|
||||
assert!(out.contains(kept), "comment lost:\n{out}");
|
||||
assert!(!out.contains(banned), "comment merged or moved:\n{out}");
|
||||
let again = format_source(&out, &Config::default()).expect("formats again");
|
||||
assert_eq!(out, again, "not idempotent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Standing rule (`topo.md` §2.1): `verify.rs` was not widened for any of
|
||||
/// these fixes, and the corruptions they used to produce must still be
|
||||
/// rejected if a future layout change reintroduces them.
|
||||
#[test]
|
||||
fn the_bucket_two_corruptions_are_still_rejected() {
|
||||
// A trailing line comment swallowing the `else if` that followed it.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
);
|
||||
// A comment written inside the condition, printed after the `)`.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n if (// note\n a) begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n if (a) // note\n begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
);
|
||||
// The `:` a `default;` did not write, invented by the printer.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
|
||||
);
|
||||
// And its mirror: a `default: ;` losing the colon it did write.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
/// A comment written just after a statement header's `(` is queued by the
|
||||
/// parser and drained onto the first bracket it meets — so when the condition
|
||||
/// started with a call, `CallComments::before_open` swallowed it and the
|
||||
/// comment printed between the callee and its `(`. This was pinned as a
|
||||
/// refusal until the directive-in-statements round delivered the parser's
|
||||
/// `take_gap` fix (2026-08-29); the pin flips exactly as the Handshake said
|
||||
/// it should: the shape now formats, the comment keeps its place inside the
|
||||
/// parens, and the round trip is a fixed point. The last of bucket 2's 12.
|
||||
#[test]
|
||||
fn a_comment_before_a_call_in_a_condition_now_formats() {
|
||||
let input = "module m;\n function automatic int f();\n if (// why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
|
||||
let expected = "module m;\n function automatic int f();\n if (\n // why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
|
||||
let config = Config::default();
|
||||
let once = format_source(input, &config).expect("the delivered handshake formats this");
|
||||
assert_eq!(once, expected, "the comment stays inside the parens");
|
||||
let twice = format_source(&once, &config).expect("and the result still formats");
|
||||
assert_eq!(twice, once, "fixed point");
|
||||
}
|
||||
|
||||
/// The standing template applied to directive-in-statements' verbatim
|
||||
/// capture (the round could not add these itself — this file was Lane B's
|
||||
/// during the wave): crafted (input, corrupted output) pairs the capture
|
||||
/// could plausibly produce if its extent scan slipped, each asserted
|
||||
/// rejected. An `` `else `` arm dropped, the arms swapped, and the
|
||||
/// `` `endif `` lost — every one is a divergence the safety net must see.
|
||||
#[test]
|
||||
fn a_corrupted_directive_capture_is_rejected() {
|
||||
// The `` `else `` arm dropped from the captured region.
|
||||
expect_divergence(
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`endif\nendmodule\n",
|
||||
);
|
||||
// The two arms swapped.
|
||||
expect_divergence(
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
|
||||
"module m;\n assign x =\n`ifdef A\n b;\n`else\n a;\n`endif\nendmodule\n",
|
||||
);
|
||||
// The `` `endif `` lost, leaking the region into the module tail.
|
||||
expect_divergence(
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
/// QA (2026-08-29, Lane B): `trailing_ends_line` decides whether `end`'s
|
||||
/// trailing comments swallow a cuddled `else` by checking whether the
|
||||
/// *merged* trailing text starts with `//` (`is_line_comment` is a prefix
|
||||
/// test). A block comment followed by a line comment on the same trailing
|
||||
/// group — `end /* a */ // b` — merges into one string that starts with
|
||||
/// `/*`, so the check says "does not end in a line comment" and `else` still
|
||||
/// tries to cuddle, which does produce the merge this whole fix exists to
|
||||
/// prevent. The safety net catches it (the reparsed output has one big
|
||||
/// comment where the input had two), so the file is refused rather than
|
||||
/// corrupted — this pins that it stays a safe refusal, not a fix for the
|
||||
/// gap. If a later round teaches `trailing_ends_line` to look at the last
|
||||
/// merged comment instead of the first, this test should flip to a `.cases`
|
||||
/// entry the same way the parser handshake above is meant to.
|
||||
#[test]
|
||||
fn a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused() {
|
||||
expect_refusal(
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end /* a */ // b\n else if (c) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The clocking wave's new verbatim capture: `default disable iff expr;`
|
||||
// (`docs/features/clocking-wave/README.md`).
|
||||
//
|
||||
// It is copied out of the source by span and re-indented, exactly like
|
||||
// `constraint` and a concurrent assertion, so the net must still see every
|
||||
// token inside it. Per CLAUDE.md hard invariant #4 these are the attack
|
||||
// pairs for that capture: **no normalization was added or widened for it**,
|
||||
// and each pair below is a real change inside the captured bytes that the
|
||||
// existing forgiveness could plausibly have masked (indentation, a moved
|
||||
// line break, a dropped comment) — asserted rejected.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_default_disable_iff_may_be_reindented() {
|
||||
let input = "module m;\n default disable iff !rst_ni;\nendmodule\n";
|
||||
let output = "module m;\n default disable iff !rst_ni;\nendmodule\n";
|
||||
verify_equivalence(input, output).expect("only per-line indentation changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_default_disable_condition_is_rejected() {
|
||||
// The polarity of a disable condition is the difference between an
|
||||
// assertion that runs in reset and one that does not.
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff !rst_ni;\nendmodule\n",
|
||||
"module m;\n default disable iff rst_ni;\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff a || !b;\nendmodule\n",
|
||||
"module m;\n default disable iff a && !b;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_default_disable_operand_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff disable_sva || !rst_ni;\nendmodule\n",
|
||||
"module m;\n default disable iff !rst_ni;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_default_disable_item_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff !rst_ni;\n wire w;\nendmodule\n",
|
||||
"module m;\n wire w;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_inside_a_default_disable_may_not_be_dropped() {
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff /* why */ !rst_ni;\nendmodule\n",
|
||||
"module m;\n default disable iff !rst_ni;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_disable_split_over_lines_may_not_lose_a_token() {
|
||||
// The capture spans several source lines, so the line-break normalization
|
||||
// is exactly what a masked corruption here would ride on.
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff\n !rst_ni ||\n !en;\nendmodule\n",
|
||||
"module m;\n default disable iff !rst_ni || en;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_disable_carrying_a_dist_set_keeps_every_byte() {
|
||||
// A `;` inside the set does not end the item, so the whole set is in the
|
||||
// captured bytes — and a changed weight there must still be refused.
|
||||
let input = "module m;\n default disable iff x dist {1 := 1, 2 := 2};\nendmodule\n";
|
||||
let output = format_source(input, &Config::default()).expect("must format");
|
||||
assert!(output.contains("dist {1 := 1, 2 := 2}"), "the set's bytes changed:\n{output}");
|
||||
expect_divergence(
|
||||
input,
|
||||
"module m;\n default disable iff x dist {1 := 1, 2 := 9};\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Null items (`;` where an item belongs) — `docs/features/null-items/README.md`
|
||||
//
|
||||
// `verify.rs` was not widened for null items and needs no new forgiveness:
|
||||
// a `;` is an ordinary token and the net compares token streams. These pairs
|
||||
// are the standing attack tests anyway (CLAUDE.md invariant 4), one per way
|
||||
// the layout rule could plausibly go wrong.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_dropped_null_item_is_rejected() {
|
||||
// What the `empty-item` lint's fix does deliberately, the formatter must
|
||||
// never do silently — in either direction.
|
||||
expect_divergence(
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n wire a;\n ;;\nendmodule\n",
|
||||
"module m;\n wire a;\n ;\nendmodule\n",
|
||||
);
|
||||
// And a `;` invented where the source wrote none.
|
||||
expect_divergence(
|
||||
"module m;\n generate\n endgenerate\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_item_moved_across_a_comment_is_rejected() {
|
||||
// The glue prints a null item onto the previous item's line. A one-line
|
||||
// block comment is the only comment that can stand in that gap, and the
|
||||
// `;` must stay on the far side of it.
|
||||
expect_divergence(
|
||||
"module m;\n generate\n endgenerate /* b */ ;\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate; /* b */\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n wire a;\n // why\n ;\nendmodule\n",
|
||||
"module m;\n wire a;\n ;\n // why\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_item_moved_into_a_procedural_block_is_rejected() {
|
||||
// An item-level `;` and a procedural null statement print identically, so
|
||||
// nothing but token order tells the net that one became the other.
|
||||
expect_divergence(
|
||||
"module m;\n initial begin\n x = 1;\n end\n ;\nendmodule\n",
|
||||
"module m;\n initial begin\n x = 1;\n ;\n end\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n generate\n ;\n endgenerate\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// QA addition (2026-09-01): the item list is flat across `` `ifdef ``/``
|
||||
// `else ``/`` `endif `` — a null item inside one arm is a sibling of the
|
||||
// `Directive` items, not nested under them — so a corruption that carries a
|
||||
// null item from one arm to the other is a plain token-stream reorder around
|
||||
// a `Directive` token rather than around an ordinary item. Confirmed rejected
|
||||
// (checklist item 4's suggested gap; `verify.rs`'s comparison is positional
|
||||
// and directive-token-agnostic, so this was expected to hold, not a bug).
|
||||
#[test]
|
||||
fn a_null_item_moved_from_one_ifdef_arm_to_the_other_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n`ifdef A\n ;\n`else\n wire x;\n`endif\nendmodule\n",
|
||||
"module m;\n`ifdef A\n`else\n wire x;\n ;\n`endif\nendmodule\n",
|
||||
);
|
||||
}
|
||||
@@ -44,6 +44,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
&rules::always_comb_blocking::AlwaysCombBlocking,
|
||||
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
|
||||
&rules::case_missing_default::CaseMissingDefault,
|
||||
&rules::empty_item::EmptyItem,
|
||||
&rules::enum_name_style::EnumNameStyle,
|
||||
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
|
||||
&rules::module_filename::ModuleFilename,
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
//! `empty-item` — no stray `;` where an item belongs.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct EmptyItem;
|
||||
|
||||
const NAME: &str = "empty-item";
|
||||
|
||||
impl Rule for EmptyItem {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"drop a `;` that stands where an item belongs"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A lone `;` in a module, generate, package, interface, program or class \
|
||||
body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \
|
||||
nothing, so it is almost always a typo — the habit of ending a block \
|
||||
with a semicolon, carried over from C or from a statement context: \
|
||||
`endgenerate;`, `end;`, `endmodule;`. slang reports the same thing as \
|
||||
`-Wempty-member` (\"an unnecessary semicolon is located in a \
|
||||
non-procedural scope\"). The fix deletes the `;`, and the line with it \
|
||||
when the line held nothing else; a comment written on that line is \
|
||||
kept. The procedural null *statement* (`begin ; end`) is a different \
|
||||
construct and is not reported here."
|
||||
}
|
||||
|
||||
fn fix(&self) -> Option<Applicability> {
|
||||
Some(Applicability::Safe)
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let src = ctx.source();
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
if !matches!(item.kind, ItemKind::Empty) {
|
||||
return;
|
||||
}
|
||||
let mut violation =
|
||||
Violation::new(NAME, "unnecessary `;`; a null item does nothing", item.span);
|
||||
if let Some(range) = deletion(src, item.span) {
|
||||
violation = violation.with_fix(Fix::safe(vec![(range, String::new())]));
|
||||
}
|
||||
out.push(violation);
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes to delete for the null item at `semi`: the `;`, the horizontal
|
||||
/// whitespace before it on its line, and — when nothing but whitespace and
|
||||
/// other null items shared that line — the line's newline too.
|
||||
///
|
||||
/// `None` when the range would cover anything but `;` and whitespace, which
|
||||
/// cannot happen given how it is built and is checked anyway: a fix that
|
||||
/// swallowed a comment would break a hard invariant, so the guard is cheaper
|
||||
/// than the risk.
|
||||
fn deletion(src: &str, semi: TextRange) -> Option<TextRange> {
|
||||
let bytes = src.as_bytes();
|
||||
let mut start = semi.start as usize;
|
||||
while start > 0 && matches!(bytes[start - 1], b' ' | b'\t') {
|
||||
start -= 1;
|
||||
}
|
||||
let mut end = semi.end as usize;
|
||||
// The rest of the line: only whitespace means the line can go, but only if
|
||||
// what stood before this `;` on it was whitespace and null items — a `;`
|
||||
// written after real code leaves that code, and its line, alone.
|
||||
let mut after = end;
|
||||
while matches!(bytes.get(after), Some(b' ' | b'\t' | b'\r')) {
|
||||
after += 1;
|
||||
}
|
||||
let line_is_ours = src[line_start(src, start)..start]
|
||||
.bytes()
|
||||
.all(|b| matches!(b, b' ' | b'\t' | b';' | b'\r'));
|
||||
if line_is_ours {
|
||||
match bytes.get(after) {
|
||||
Some(b'\n') => end = after + 1,
|
||||
// A last line with no newline of its own.
|
||||
None => end = after,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let range = TextRange::new(start as u32, end as u32);
|
||||
src.get(range.as_range())?
|
||||
.bytes()
|
||||
.all(|b| matches!(b, b';' | b' ' | b'\t' | b'\r' | b'\n'))
|
||||
.then_some(range)
|
||||
}
|
||||
|
||||
/// Byte offset of the start of the line `at` sits on.
|
||||
fn line_start(src: &str, at: usize) -> usize {
|
||||
src[..at].rfind('\n').map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
EmptyItem.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn fix(src: &str) -> String {
|
||||
apply_fixes(src, &violations(src), false).output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_owners_shape_is_reported_and_the_semicolon_alone_is_removed() {
|
||||
let src = "module m;\n generate\n endgenerate;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].rule, NAME);
|
||||
assert_eq!(&src[found[0].span.as_range()], ";");
|
||||
assert_eq!(fix(src), "module m;\n generate\n endgenerate\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_item_on_its_own_line_takes_the_line_with_it() {
|
||||
let src = "module m;\n wire a;\n ;\nendmodule\n";
|
||||
assert_eq!(fix(src), "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_on_the_line_survives_the_fix() {
|
||||
let src = "module m;\n generate\n endgenerate; // note\nendmodule\n";
|
||||
assert_eq!(fix(src), "module m;\n generate\n endgenerate // note\nendmodule\n");
|
||||
|
||||
let src = "module m;\n wire a;\n ; // why\nendmodule\n";
|
||||
let fixed = fix(src);
|
||||
assert!(fixed.contains("// why"), "the comment was dropped:\n{fixed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_comment_is_left_where_it_was() {
|
||||
let src = "module m;\n // why\n ;\nendmodule\n";
|
||||
assert_eq!(fix(src), "module m;\n // why\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_null_items_is_one_finding_each_and_the_line_goes() {
|
||||
let src = "module m;\n wire a;\n ;;;\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 3);
|
||||
assert_eq!(fix(src), "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_item_scope_is_reached() {
|
||||
let sources = [
|
||||
"module m;\nendmodule;\n",
|
||||
"module m;\n ;\nendmodule\n",
|
||||
"interface ifc;\n ;\nendinterface\n",
|
||||
"package p;\n ;\nendpackage\n",
|
||||
"class c;\n ;\nendclass\n",
|
||||
"module m;\n generate\n ;\n endgenerate\nendmodule\n",
|
||||
"module m;\n for (genvar i = 0; i < 2; i++) begin : g\n ;\n end\nendmodule\n",
|
||||
];
|
||||
for src in sources {
|
||||
assert_eq!(violations(src).len(), 1, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_procedural_null_statement_is_not_this_rule() {
|
||||
assert!(violations("module m;\n initial begin\n ;\n end\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endfunction_and_endtask_semicolons_are_not_reported() {
|
||||
// They are recorded on the declaration, not as null items.
|
||||
let src =
|
||||
"module m;\n function int f();\n endfunction;\n task t();\n endtask;\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_file_is_clean() {
|
||||
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
pub mod always_comb_blocking;
|
||||
pub mod always_ff_non_blocking;
|
||||
pub mod case_missing_default;
|
||||
pub mod empty_item;
|
||||
pub mod enum_name_style;
|
||||
pub mod explicit_parameter_storage_type;
|
||||
pub mod module_filename;
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
# the owner's report: a stray `;` after `endgenerate`
|
||||
module m;
|
||||
generate
|
||||
endgenerate;
|
||||
//^ 14 empty-item
|
||||
endmodule
|
||||
====
|
||||
# a null item on its own line at module scope
|
||||
module m;
|
||||
wire a;
|
||||
;
|
||||
//^ 3 empty-item
|
||||
endmodule
|
||||
====
|
||||
# `endmodule;` — a null item at file scope
|
||||
module m;
|
||||
endmodule;
|
||||
//^ 10 empty-item
|
||||
====
|
||||
# every non-procedural scope is reached: package
|
||||
package p;
|
||||
localparam int W = 1;
|
||||
;
|
||||
//^ 3 empty-item
|
||||
endpackage
|
||||
====
|
||||
# every non-procedural scope is reached: interface
|
||||
interface ifc;
|
||||
logic a;
|
||||
;
|
||||
//^ 3 empty-item
|
||||
endinterface
|
||||
====
|
||||
# every non-procedural scope is reached: class
|
||||
class c;
|
||||
int x;
|
||||
;
|
||||
//^ 3 empty-item
|
||||
endclass
|
||||
====
|
||||
# every non-procedural scope is reached: inside a generate region
|
||||
module m;
|
||||
generate
|
||||
;
|
||||
//^ 5 empty-item
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# every non-procedural scope is reached: inside a generate-for body
|
||||
module m;
|
||||
for (genvar i = 0; i < 2; i++) begin : g
|
||||
;
|
||||
//^ 5 empty-item
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# `end;` after a generate block, and a run of null items after it
|
||||
module m;
|
||||
if (N > 1) begin : g1
|
||||
wire x;
|
||||
end;
|
||||
//^ 6 empty-item
|
||||
;;
|
||||
//^ 3 empty-item
|
||||
//^ 4 empty-item
|
||||
endmodule
|
||||
====
|
||||
# the procedural null statement is a different construct and is quiet
|
||||
module m;
|
||||
initial begin
|
||||
;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# `endfunction;` / `endtask;` are recorded on the declaration, not as null items
|
||||
module m;
|
||||
function int f();
|
||||
endfunction;
|
||||
task t();
|
||||
endtask;
|
||||
endmodule
|
||||
====
|
||||
# waived on the same line
|
||||
module m;
|
||||
wire a;
|
||||
; // lucisv: waive empty-item
|
||||
endmodule
|
||||
====
|
||||
# a clean file is clean
|
||||
module m;
|
||||
wire a;
|
||||
endmodule
|
||||
====
|
||||
# fix: the `;` alone goes, the closing keyword stays
|
||||
module m;
|
||||
generate
|
||||
endgenerate;
|
||||
//^ 14 empty-item
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
endgenerate
|
||||
//^ 14 empty-item
|
||||
endmodule
|
||||
====
|
||||
# fix: a null item alone on its line takes the line with it
|
||||
module m;
|
||||
wire a;
|
||||
;
|
||||
//^ 3 empty-item
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
//^ 3 empty-item
|
||||
endmodule
|
||||
====
|
||||
# fix: a run of null items leaves no blank line behind
|
||||
module m;
|
||||
wire a;
|
||||
;;;
|
||||
//^ 3 empty-item
|
||||
//^ 4 empty-item
|
||||
//^ 5 empty-item
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
//^ 3 empty-item
|
||||
//^ 4 empty-item
|
||||
//^ 5 empty-item
|
||||
endmodule
|
||||
====
|
||||
# fix: a comment written after the `;` survives it
|
||||
module m;
|
||||
generate
|
||||
endgenerate; // note
|
||||
//^ 14 empty-item
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
endgenerate // note
|
||||
//^ 14 empty-item
|
||||
endmodule
|
||||
====
|
||||
# fix: a comment on a null item's own line keeps the line alive
|
||||
module m;
|
||||
wire a;
|
||||
; // why it was here
|
||||
//^ 3 empty-item
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire a;
|
||||
// why it was here
|
||||
//^ 3 empty-item
|
||||
endmodule
|
||||
====
|
||||
# fix: a comment written above a null item stays where it was
|
||||
module m;
|
||||
// why it was here
|
||||
;
|
||||
//^ 3 empty-item
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// why it was here
|
||||
//^ 3 empty-item
|
||||
endmodule
|
||||
====
|
||||
# fix: `endmodule;` at file scope
|
||||
module m;
|
||||
endmodule;
|
||||
//^ 10 empty-item
|
||||
----
|
||||
module m;
|
||||
endmodule
|
||||
//^ 10 empty-item
|
||||
====
|
||||
@@ -23,3 +23,21 @@ endmodule
|
||||
module foo_bar; // lucisv: waive module-name-style
|
||||
//^ 17 unused-waiver
|
||||
endmodule
|
||||
====
|
||||
# a `program` reuses `ItemKind::Module`, so every rule that matches a module
|
||||
# matches it — deliberately, and pinned here so the decision is not silently
|
||||
# reversed. The rule's *message* still says "module"; that wording is
|
||||
# pre-existing for `interface` and filed, not fixed, in
|
||||
# docs/features/clocking-wave/README.md's Handshakes.
|
||||
#select module-name-style,unused-waiver
|
||||
program FooBar;
|
||||
//^ 9 module-name-style
|
||||
endprogram
|
||||
====
|
||||
# ... and the body of a program is descended into like a module's
|
||||
#select module-name-style,unused-waiver
|
||||
program top;
|
||||
module Inner;
|
||||
//^ 10 module-name-style
|
||||
endmodule
|
||||
endprogram
|
||||
@@ -116,3 +116,33 @@ module m (input logic c, output logic q);
|
||||
assign a = c;
|
||||
assign q = a;
|
||||
endmodule
|
||||
====
|
||||
# a clocking block is opaque: the signals it names — and the expressions its
|
||||
# items bind them to — are taken out through the token-level guard, so neither
|
||||
# the clocking signal nor what it drives is ever reported.
|
||||
# See docs/features/clocking-wave/README.md.
|
||||
#select unused-signal,unused-waiver
|
||||
module m;
|
||||
wire tms_int;
|
||||
wire tdo;
|
||||
clocking cb @(posedge clk);
|
||||
output tms = tms_int;
|
||||
input tdo;
|
||||
endclocking
|
||||
endmodule
|
||||
====
|
||||
# a `default disable iff` is a verbatim item, so it is opaque the same way a
|
||||
# concurrent assertion is: it neither reports nor rescues the names it mentions
|
||||
#select unused-signal,unused-waiver
|
||||
module m;
|
||||
wire rst_n;
|
||||
default disable iff !rst_n;
|
||||
endmodule
|
||||
====
|
||||
# an `iff` gate on an event-control term is an ordinary read, so the signal it
|
||||
# names is not reported unused
|
||||
#select unused-signal,unused-waiver
|
||||
module m (input logic clk, output logic q);
|
||||
wire enable;
|
||||
always @(posedge clk iff enable) q <= 1;
|
||||
endmodule
|
||||
@@ -247,6 +247,18 @@ pub enum ItemKind {
|
||||
/// `docs/features/assertions/README.md` for why each one is verbatim.
|
||||
Verbatim(RawText),
|
||||
Defparam(Vec<(Expr, Expr)>),
|
||||
/// A **null item**: a lone `;` standing where an item belongs
|
||||
/// (IEEE 1800-2017 A.1.4 `package_or_generate_item_declaration ::= … | ;`
|
||||
/// and `class_item ::= … | ;`). Legal and meaningless in every item
|
||||
/// scope, and written constantly after `endgenerate`, after a generate
|
||||
/// block's `end` and after `endmodule`. The span is the `;` itself; the
|
||||
/// `empty-item` lint is what tells the user about it.
|
||||
///
|
||||
/// The `;` after `endfunction`/`endtask` is *not* one of these: it is
|
||||
/// consumed inside the declaration and recorded as
|
||||
/// [`FunctionDecl::end_semi`] / [`TaskDecl::end_semi`], which predates
|
||||
/// this variant.
|
||||
Empty,
|
||||
/// Source that could not be parsed as an item, kept verbatim.
|
||||
///
|
||||
/// Only error-tolerant parsing
|
||||
@@ -300,12 +312,13 @@ pub struct Module {
|
||||
}
|
||||
|
||||
impl Module {
|
||||
/// The keyword that closes this declaration: `endmodule` or `endinterface`.
|
||||
/// The keyword that closes this declaration: `endmodule`, `endinterface`
|
||||
/// or `endprogram`.
|
||||
pub fn end_kw(&self) -> &'static str {
|
||||
if self.kw == "interface" {
|
||||
"endinterface"
|
||||
} else {
|
||||
"endmodule"
|
||||
match self.kw.as_str() {
|
||||
"interface" => "endinterface",
|
||||
"program" => "endprogram",
|
||||
_ => "endmodule",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -532,6 +545,12 @@ pub struct EnumMember {
|
||||
pub name: String,
|
||||
/// Byte range of `name`.
|
||||
pub name_span: TextRange,
|
||||
/// The enum name range of IEEE 1800 §6.19 — `Name[N]` or `Name[hi:lo]`,
|
||||
/// which declares a run of sequentially-valued members. One dimension is
|
||||
/// all the LRM allows; it is kept as an ordinary [`Dim`] so the existing
|
||||
/// dimension parser and printer serve it, and it is printed back tight
|
||||
/// against the name because it is part of the name, not a layout choice.
|
||||
pub range: Vec<Dim>,
|
||||
pub value: Option<Expr>,
|
||||
/// True when a `,` followed this element in the source; see
|
||||
/// [`NonAnsiPort::comma`].
|
||||
@@ -553,6 +572,12 @@ pub struct StructType {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StructMember {
|
||||
pub meta: Meta,
|
||||
/// `rand` / `randc` written before the member's type. The LRM allows the
|
||||
/// randomization qualifiers only on a class property, but vendor tools
|
||||
/// accept them on a plain struct member and real code uses them
|
||||
/// (`spi_host/dv/env/spi_host_env_pkg.sv:64`); lucisv models no
|
||||
/// randomization semantics, so the words are simply carried and printed.
|
||||
pub qualifiers: Vec<String>,
|
||||
pub ty: DataType,
|
||||
pub declarators: Vec<Declarator>,
|
||||
/// Code extent of the member, its `;` included.
|
||||
@@ -617,13 +642,15 @@ pub struct ContAssign {
|
||||
pub assigns: Vec<AssignPair>,
|
||||
}
|
||||
|
||||
/// The `( strength0 , strength1 )` pair of a continuous assignment. The two
|
||||
/// strengths are stored in the order the source wrote them — the language
|
||||
/// The `( strength0 , strength1 )` of a continuous assignment or a gate. The
|
||||
/// two strengths are stored in the order the source wrote them — the language
|
||||
/// allows either order and lucisv is not a legality checker.
|
||||
#[derive(Debug)]
|
||||
pub struct DriveStrength {
|
||||
pub first: String,
|
||||
pub second: String,
|
||||
/// `None` for the single-strength spelling `pullup (weak1) p (x);`
|
||||
/// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes.
|
||||
pub second: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -665,6 +692,9 @@ pub struct SensItem {
|
||||
pub sep: Option<SensSep>,
|
||||
pub edge: Option<String>,
|
||||
pub expr: Expr,
|
||||
/// The gating condition of `@(posedge clk iff enable)` — IEEE 1800
|
||||
/// §9.4.2's optional `iff expression` on one event expression term.
|
||||
pub iff: Option<Expr>,
|
||||
}
|
||||
|
||||
/// How two event-list items were separated in the source. Both spellings are
|
||||
@@ -789,7 +819,14 @@ pub struct BindDirective {
|
||||
pub struct GateInstantiation {
|
||||
/// `and`, `or`, `not`, ...
|
||||
pub gate: String,
|
||||
pub delay: Option<Expr>,
|
||||
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
|
||||
/// `(strong0, strong1)` pair every driving gate also accepts.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// The delay written after `#`: empty when there is none, one element for
|
||||
/// every spelling a net or a continuous assignment also accepts, and two
|
||||
/// or three for the `(rise, fall[, turn-off])` list that only a gate
|
||||
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
|
||||
pub delay: Vec<Expr>,
|
||||
pub instances: Vec<GateInstance>,
|
||||
}
|
||||
|
||||
@@ -993,7 +1030,18 @@ pub enum ClockingItemKind {
|
||||
Default { input: Option<String>, output: Option<String> },
|
||||
/// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay
|
||||
/// or edge as written (`#2`, `negedge`), or `None` when omitted.
|
||||
Signals { dir: String, skew: Option<String>, names: Vec<Name> },
|
||||
Signals { dir: String, skew: Option<String>, signals: Vec<ClockingSignal> },
|
||||
}
|
||||
|
||||
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
|
||||
/// §14.4's `clocking_decl_assign`. The expression binds the clocking signal to
|
||||
/// something other than the same-named signal in the enclosing scope:
|
||||
/// `output tms = _tms_internal;`.
|
||||
#[derive(Debug)]
|
||||
pub struct ClockingSignal {
|
||||
pub name: Name,
|
||||
/// `None` for the plain `input tdo;` spelling.
|
||||
pub value: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -1193,6 +1241,11 @@ pub enum StmtKind {
|
||||
/// declarations (IEEE 1800 §13.4.2) — the statement twin of
|
||||
/// [`ItemKind::Import`].
|
||||
Import(Vec<ImportPath>),
|
||||
/// `typedef enum bit {WRITE, READ} rdwr_e;` written inside a
|
||||
/// function/task body or a `begin` block, scoping the type to that block
|
||||
/// (IEEE 1800 §6.18) — the statement twin of [`ItemKind::Typedef`], with
|
||||
/// the same payload and the same layout.
|
||||
Typedef(Typedef),
|
||||
/// `name : stmt` — a statement label (IEEE 1800 §9.3.5).
|
||||
///
|
||||
/// `begin`/`fork` keep their label inside their own node, because the
|
||||
@@ -1414,11 +1467,18 @@ pub enum ExprKind {
|
||||
},
|
||||
/// `ty'(expr)` cast. The casting type is an expression because it may be
|
||||
/// a name (`int`, `my_t`), a package-scoped name
|
||||
/// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`) or a parenthesized
|
||||
/// constant expression (`(DepthW + 3)'(1'b1)`) — IEEE 1800 §6.24.1.
|
||||
/// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`), a parenthesized
|
||||
/// constant expression (`(DepthW + 3)'(1'b1)`) or a system function call
|
||||
/// (`$bits(x)'(y)`) — IEEE 1800 §6.24.1.
|
||||
Cast {
|
||||
ty: Box<Expr>,
|
||||
expr: Box<Expr>,
|
||||
/// True for the `ty'{...}` spelling (IEEE 1800 §10.9.1), where the
|
||||
/// argument is an assignment pattern. The pattern brings its own
|
||||
/// `'{` and `}`, so such a cast prints no brackets of its own —
|
||||
/// which is also why the two spellings must stay distinguishable:
|
||||
/// `ty'('{a: 1})` is a different token stream from `ty'{a: 1}`.
|
||||
pattern: bool,
|
||||
},
|
||||
/// `'{...}` assignment pattern.
|
||||
AssignPattern(Vec<PatternItem>),
|
||||
|
||||
@@ -46,6 +46,30 @@ impl LineIndex {
|
||||
(line as u32, offset - self.line_starts[line - 1] + 1)
|
||||
}
|
||||
|
||||
/// The **0-based** line and **UTF-16** column of a byte offset — the units
|
||||
/// a language-server `Position` counts in, as opposed to
|
||||
/// [`line_col`](Self::line_col)'s 1-based bytes. `text` must be the text
|
||||
/// this index was built from.
|
||||
///
|
||||
/// An offset inside a multi-byte character is floored to that character's
|
||||
/// start, and the `\r` of a CRLF line ending is not part of its line's
|
||||
/// content. It lives here, beside the table it reads, because two callers
|
||||
/// need the same answer: a server converting a span for the wire, and the
|
||||
/// semantic index recording a declaration's position so no one has to.
|
||||
pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32) {
|
||||
let mut floored = (offset as usize).min(text.len());
|
||||
while floored > 0 && !text.is_char_boundary(floored) {
|
||||
floored -= 1;
|
||||
}
|
||||
let (line, _) = self.line_col(floored as u32);
|
||||
let start = self.line_range(line).map_or(0, |r| r.start) as usize;
|
||||
let slice = text.get(start..floored).unwrap_or("");
|
||||
// LSP line content excludes the whole `\r\n`; this index keeps the
|
||||
// `\r` as an ordinary byte of its line, so drop it here.
|
||||
let slice = slice.strip_suffix('\r').unwrap_or(slice);
|
||||
(line - 1, utf16_len(slice))
|
||||
}
|
||||
|
||||
/// The byte offset of a 1-based line and column, or `None` if the text
|
||||
/// has no such line. A column past the end of its line is clamped to the
|
||||
/// line's end, so the result never lands on another line.
|
||||
@@ -77,6 +101,17 @@ impl LineIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
|
||||
///
|
||||
/// ASCII is answered by the length, which is what source text almost always
|
||||
/// is; the decoding loop is for the rest.
|
||||
fn utf16_len(s: &str) -> u32 {
|
||||
if s.is_ascii() {
|
||||
return s.len() as u32;
|
||||
}
|
||||
s.chars().map(|c| c.len_utf16() as u32).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -141,6 +176,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_positions_are_zero_based_and_count_code_units() {
|
||||
let src = "module m;\n// 🎉 é\nendmodule";
|
||||
let idx = LineIndex::new(src);
|
||||
assert_eq!(idx.utf16_position(src, 0), (0, 0));
|
||||
assert_eq!(idx.utf16_position(src, 7), (0, 7));
|
||||
assert_eq!(idx.utf16_position(src, 10), (1, 0));
|
||||
let party = src.find('🎉').unwrap() as u32;
|
||||
assert_eq!(idx.utf16_position(src, party), (1, 3));
|
||||
// Four UTF-8 bytes, two UTF-16 units — the surrogate pair.
|
||||
assert_eq!(idx.utf16_position(src, party + 4), (1, 5));
|
||||
// An offset inside the pair floors to its start.
|
||||
for inside in 1..4 {
|
||||
assert_eq!(idx.utf16_position(src, party + inside), (1, 3));
|
||||
}
|
||||
assert_eq!(idx.utf16_position(src, src.len() as u32 + 99), (2, 9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_is_not_part_of_its_lines_utf16_content() {
|
||||
let src = "ab\r\ncd\r\n";
|
||||
let idx = LineIndex::new(src);
|
||||
assert_eq!(idx.utf16_position(src, 2), (0, 2), "at the `\\r`");
|
||||
assert_eq!(idx.utf16_position(src, 3), (0, 2), "at the `\\n`, past the `\\r`");
|
||||
assert_eq!(idx.utf16_position(src, 4), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_positions_are_clamped() {
|
||||
let src = "abc\nde";
|
||||
|
||||
+1799
-150
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::parser::PARSE_STACK_SIZE;
|
||||
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -248,6 +249,83 @@ fn tolerant_parse_equals_strict_parse_on_valid_sources() {
|
||||
println!("{valid} valid sources agreed with the strict parser, {invalid} reported errors");
|
||||
}
|
||||
|
||||
/// The out-of-block constraint cascade, pinned as a regression
|
||||
/// (`docs/features/out-of-class-constraints/README.md`).
|
||||
///
|
||||
/// Before the fix, `constraint C::name { ... }` failed one token into the
|
||||
/// header (`expected `{` (found "::")`); the recovery loop then resynchronized
|
||||
/// inside the constraint body, and every out-of-block item after it produced
|
||||
/// its own diagnostics. On the real corpus that turned one construct into 322
|
||||
/// diagnostics in `cip_base_vseq.sv` and 274 in `hmac_base_vseq.sv` — a buffer
|
||||
/// an editor cannot show usefully. This fixture is that shape in miniature:
|
||||
/// with the fix it must be silent, not merely quieter.
|
||||
#[test]
|
||||
fn out_of_block_constraints_do_not_cascade() {
|
||||
let src = "\
|
||||
class my_seq;
|
||||
rand int num_trans;
|
||||
rand int delay;
|
||||
extern constraint num_trans_c;
|
||||
extern constraint delay_c;
|
||||
extern function void configure();
|
||||
endclass : my_seq
|
||||
|
||||
constraint my_seq::num_trans_c {
|
||||
num_trans inside {[1:20]};
|
||||
solve num_trans before delay;
|
||||
}
|
||||
|
||||
constraint my_seq::delay_c {
|
||||
soft delay dist {0 :/ 5, [1:10] :/ 5};
|
||||
}
|
||||
|
||||
function void my_seq::configure();
|
||||
num_trans = 1;
|
||||
endfunction : my_seq
|
||||
";
|
||||
let (_, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "out-of-block constraints still report: {diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant");
|
||||
}
|
||||
|
||||
/// The mop-up round's nine shapes, all in one buffer: the strict parser
|
||||
/// accepts them, so the tolerant parser must report nothing at all. A gap
|
||||
/// that still failed here would be worse than a plain refusal — an editor
|
||||
/// would show the diagnostic on every keystroke.
|
||||
///
|
||||
/// See `docs/features/testbench-mopup/README.md`.
|
||||
#[test]
|
||||
fn the_mopup_shapes_report_nothing_in_tolerant_mode() {
|
||||
let src = "\
|
||||
package p;
|
||||
typedef enum logic [1:0] {ReqPeriResetIdx[0:1], ReqMainPwrResetIdx} reset_idx_e;
|
||||
typedef struct {
|
||||
rand bit cpol;
|
||||
randc bit [3:0] csnlead;
|
||||
} cfg_t;
|
||||
endpackage
|
||||
|
||||
module tb;
|
||||
virtual spi_if.tb tb_sif = sif.tb;
|
||||
buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i));
|
||||
assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0});
|
||||
|
||||
bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u_fifo_exc_if (.clk_i);
|
||||
|
||||
initial begin
|
||||
typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e;
|
||||
typedef bit data_result[];
|
||||
foreach (cfg.mem_bkdr_util_h[, bank]) begin
|
||||
q.push_back(mem_item_t'{addr, mask});
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (_, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "a mop-up shape still reports: {diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Guarantee 2: diagnostics and error nodes stay inside the file
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -466,7 +544,7 @@ fn the_depth_limit_still_fires_and_is_recovered_from() {
|
||||
")".repeat(400)
|
||||
);
|
||||
let (file, diags) = std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || {
|
||||
let (f, d) = parse_source_tolerant(&src);
|
||||
(format!("{:?}", f.items.iter().map(kind_name).collect::<Vec<_>>()), d)
|
||||
@@ -495,7 +573,7 @@ fn recovery_does_not_reset_the_nesting_budget() {
|
||||
"end\n".repeat(outer),
|
||||
);
|
||||
let diags = std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || parse_source_tolerant(&src).1)
|
||||
.expect("spawn parser thread")
|
||||
.join()
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! The null item — a lone `;` where an item belongs (IEEE 1800-2017 A.1.4
|
||||
//! `package_or_generate_item_declaration ::= … | ;` and `class_item ::= … | ;`).
|
||||
//! See `docs/features/null-items/README.md`.
|
||||
//!
|
||||
//! Every item list in the parser reaches `parse_item_kind` through
|
||||
//! `item_or_recover`, so one branch is meant to cover all eight scopes. That
|
||||
//! claim is checked here by parsing one source per scope rather than by
|
||||
//! reading the parser.
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::{parse_source, parse_source_tolerant};
|
||||
|
||||
/// Parses `src` strictly and returns the tree; panics with the parse error.
|
||||
fn tree(src: &str) -> SourceFile {
|
||||
parse_source(src).unwrap_or_else(|e| panic!("{src}\n=> {e}"))
|
||||
}
|
||||
|
||||
/// Every null item in `file`, as its source slice — which must be `";"`.
|
||||
fn null_item_slices(src: &str, file: &SourceFile) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
walk(&file.items, &mut |item| {
|
||||
if matches!(item.kind, ItemKind::Empty) {
|
||||
out.push(src[item.span.as_range()].to_string());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn walk(items: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
for item in items {
|
||||
f(item);
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => walk(&m.items, f),
|
||||
ItemKind::Package { items, .. } => walk(items, f),
|
||||
ItemKind::Class(c) => walk(&c.items, f),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, f),
|
||||
ItemKind::GenFor(g) => walk(&g.body.items, f),
|
||||
ItemKind::GenIf(g) => {
|
||||
walk(&g.then.items, f);
|
||||
let mut els = g.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
walk(&nested.then.items, f);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
walk(&block.items, f);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenCase(g) => {
|
||||
for case_item in &g.items {
|
||||
walk(&case_item.body.items, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `;` per scope, and every one of them is an `ItemKind::Empty` whose span
|
||||
/// is exactly the semicolon.
|
||||
#[test]
|
||||
fn a_null_item_parses_in_every_item_scope() {
|
||||
let scopes = [
|
||||
("file scope", "module m;\nendmodule;\n"),
|
||||
("module body", "module m;\n wire a;\n ;\nendmodule\n"),
|
||||
("interface body", "interface ifc;\n logic a;\n ;\nendinterface\n"),
|
||||
("program body", "program p;\n ;\nendprogram\n"),
|
||||
("package body", "package p;\n localparam int W = 1;\n ;\nendpackage\n"),
|
||||
("class body", "class c;\n int x;\n ;\nendclass\n"),
|
||||
("generate region", "module m;\n generate\n ;\n endgenerate\nendmodule\n"),
|
||||
(
|
||||
"generate-for body",
|
||||
"module m;\n for (genvar i = 0; i < 2; i++) begin : g\n ;\n end\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"generate-if body",
|
||||
"module m;\n if (A) begin : g\n ;\n end else begin : h\n ;\n end\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"generate-case body",
|
||||
"module m;\n case (A)\n 1: begin : g\n ;\n end\n endcase\nendmodule\n",
|
||||
),
|
||||
];
|
||||
for (what, src) in scopes {
|
||||
let file = tree(src);
|
||||
let found = null_item_slices(src, &file);
|
||||
assert!(!found.is_empty(), "{what}: no null item parsed from\n{src}");
|
||||
assert!(found.iter().all(|s| s == ";"), "{what}: span is not the `;`: {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape the owner reported, and its neighbours: a `;` after a closing
|
||||
/// keyword rather than on a line of its own.
|
||||
#[test]
|
||||
fn a_semicolon_after_a_closing_keyword_is_a_null_item() {
|
||||
let sources = [
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
"module m;\n generate\n if (A) begin : g\n wire x;\n end;\n endgenerate\nendmodule\n",
|
||||
"module m;\n if (A) begin : g\n wire x;\n end;\nendmodule\n",
|
||||
"module m;\nendmodule;\n",
|
||||
];
|
||||
for src in sources {
|
||||
let file = tree(src);
|
||||
assert_eq!(null_item_slices(src, &file), vec![";"], "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `;;` is two of them, not one.
|
||||
#[test]
|
||||
fn repeated_semicolons_are_one_null_item_each() {
|
||||
let src = "module m;\n ;;;\nendmodule\n";
|
||||
let file = tree(src);
|
||||
assert_eq!(null_item_slices(src, &file).len(), 3);
|
||||
}
|
||||
|
||||
/// Comments ride the ordinary `Meta`, like any other item's.
|
||||
#[test]
|
||||
fn comments_around_a_null_item_are_kept() {
|
||||
let src = "module m;\n // lead\n ; // trail\nendmodule\n";
|
||||
let file = tree(src);
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let item = m.items.iter().find(|i| matches!(i.kind, ItemKind::Empty)).expect("a null item");
|
||||
assert_eq!(item.meta.leading.iter().map(|c| c.text.as_str()).collect::<Vec<_>>(), ["// lead"]);
|
||||
assert_eq!(item.meta.trailing.as_ref().map(|c| c.text.as_str()), Some("// trail"));
|
||||
}
|
||||
|
||||
/// Tolerant mode is silent about a null item: it is a successful parse, not a
|
||||
/// recovery, so an editor shows the `empty-item` lint and no parse error.
|
||||
#[test]
|
||||
fn tolerant_parsing_reports_no_diagnostic() {
|
||||
let sources = [
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
"module m;\n ;;\nendmodule\n",
|
||||
"package p;\n ;\nendpackage\n",
|
||||
"class c;\n ;\nendclass\n",
|
||||
"module m;\nendmodule;\n",
|
||||
];
|
||||
for src in sources {
|
||||
let (file, diagnostics) = parse_source_tolerant(src);
|
||||
assert!(diagnostics.is_empty(), "{src}=> {diagnostics:?}");
|
||||
assert!(!null_item_slices(src, &file).is_empty(), "{src}");
|
||||
assert!(
|
||||
null_item_slices(src, &file).iter().all(|s| s == ";"),
|
||||
"an error leaf, not a null item: {src}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `;` after `endfunction`/`endtask` stays where it always was — on
|
||||
/// `FunctionDecl::end_semi` / `TaskDecl::end_semi`, consumed inside the
|
||||
/// declaration — so the two mechanisms do not both claim it.
|
||||
#[test]
|
||||
fn endfunction_and_endtask_keep_their_own_semicolon_flag() {
|
||||
let src = "module m;\n function int f();\n return 1;\n endfunction;\n task t();\n endtask;\nendmodule\n";
|
||||
let file = tree(src);
|
||||
assert!(null_item_slices(src, &file).is_empty(), "the `;` must not become a null item");
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let mut seen = 0;
|
||||
for item in &m.items {
|
||||
match &item.kind {
|
||||
ItemKind::Function(f) => {
|
||||
assert!(f.end_semi);
|
||||
seen += 1;
|
||||
}
|
||||
ItemKind::Task(t) => {
|
||||
assert!(t.end_semi);
|
||||
seen += 1;
|
||||
}
|
||||
_ => panic!("unexpected item"),
|
||||
}
|
||||
}
|
||||
assert_eq!(seen, 2);
|
||||
}
|
||||
@@ -71,6 +71,16 @@ const SOURCES: &[&str] = &[
|
||||
"virtual class base #(parameter int W = 8) extends pkg::top #(.A(1), b) implements i, j;\n rand bit [W-1:0] v;\n local int n;\n virtual my_if h;\n pure virtual function void f();\n extern task t(int x);\nendclass : base\n",
|
||||
"class c;\n port_t #(bit [3:0]) p;\n constraint x {\n a == 0; // why\n } // after\n covergroup g;\n coverpoint a;\n endgroup : g\n function new(string name);\n super.new(name);\n x = db#(virtual bus_if)::get(this);\n endfunction : new\nendclass\n",
|
||||
"typedef class fwd;\npackage p;\n class inner extends fwd;\n endclass\nendpackage\nfunction void inner::configure(int x);\nendfunction\n",
|
||||
// Out-of-block constraints: the verbatim leaf reached from item position,
|
||||
// at file scope and inside a package, with a scope chain and a stray `;`.
|
||||
"class c;\n extern constraint x;\nendclass\nconstraint c::x {\n a == 0; // why\n}; // after\npackage p;\n constraint q::inner::deep_c { b < 4; }\nendpackage\n",
|
||||
// The mop-up round: a block-scoped typedef, enum name ranges, a cast over
|
||||
// an assignment pattern and one over a system function call, a gate delay
|
||||
// list, a modport-qualified virtual interface, a `rand` struct member, a
|
||||
// skipped `foreach` dimension, and a hierarchical `bind` instance path.
|
||||
"package p;\n typedef enum logic [1:0] {A[0:1], B, C[4] = 5} e_t;\n typedef struct {\n rand bit cpol;\n randc int n;\n } cfg_t;\nendpackage\n",
|
||||
"module m;\n virtual spi_if.tb tb_sif = sif.tb;\n buf #(RDLY, 0) b0 (o, a);\n and #(1, 2, 3) g (o, a, b);\n assign y = $bits(x)'({a, b});\n assign z = item_t'{addr: a, data: d};\n initial begin\n typedef enum bit {W = 1'b1} rdwr_e;\n typedef bit dyn_t[];\n foreach (h[, bank]) x = 1;\n foreach (h[i, , k]) y = 2;\n end\nendmodule\n",
|
||||
"bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u (.clk_i);\nbind foo : a.b, plain bar u (.x);\n",
|
||||
// Dynamic types: queues, dynamic and associative arrays, `$` indexes,
|
||||
// named call arguments, `case ... inside`, a bare event control.
|
||||
"class c;\n string q[$] = {};\n rand int offset[];\n logic hits[*];\n string lut[string];\n item_t #(A, B) rq[NumInp-1:0][$:8];\n function void f(string ops[$], output int outs[]);\n q[$].label = ops[$-1];\n offset = new[n];\n endfunction\nendclass\n",
|
||||
@@ -82,6 +92,13 @@ const SOURCES: &[&str] = &[
|
||||
"class c;\n task t();\n if (!req.randomize() with {\n a == 1;\n b dist { 0 :/ 1 };\n }) $fatal(1, \"no\");\n endtask : t;\nendclass\n",
|
||||
// DPI imports and exports, plus package re-exports.
|
||||
"package p;\n import \"DPI-C\"\n function void env_final();\n import \"DPI-C\" context function chandle mk(int unsigned k, bit [7:0] v);\n import \"DPI-C\" function chandle get;\n import \"DPI-C\" pure c_name = task tick(input int n);\n export \"DPI-C\" function f;\n export \"DPI-C\" ex_name = task t;\n export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\n",
|
||||
// The clocking wave: clocking signals bound to an expression, the
|
||||
// verbatim `default disable iff`, an `iff` on an event-control term, a
|
||||
// bare event control over an indexed hierarchical path, a gate's single
|
||||
// and paired drive strengths, and a `program` block.
|
||||
"interface i;\n clocking cb @(negedge tck);\n default output #1ns;\n output tms = _tms_internal, tdi = _tdi[0]; // bound\n input tdo;\n endclocking\n modport host_mp(clocking cb, output trst_n);\nendinterface\n",
|
||||
"module m;\n default disable iff disable_sva || !rst_ni;\n default clocking @(posedge clk_i); endclocking\n always @(posedge clk iff en or negedge rst_n) x <= 1;\n pullup (weak1) pd (x);\n pulldown (supply0, supply1) pd2 (y);\n initial forever @cfg.cfgs[\"a\"].vif.cb z <= 1;\nendmodule\n",
|
||||
"program p #(parameter int W = 1) (input logic csb);\n logic [7:0] cmd;\n initial cmd = 8'h0;\nendprogram : p\n",
|
||||
];
|
||||
|
||||
/// A token or a comment, in source order.
|
||||
@@ -463,30 +480,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => {
|
||||
assert_inside(src, "raw text", raw.span, here);
|
||||
}
|
||||
ItemKind::Typedef(t) => {
|
||||
check_name(src, "typedef name", &t.name, t.name_span, here);
|
||||
if let TypedefKind::Enum(e) = &t.kind {
|
||||
for d in &e.directives {
|
||||
assert_inside(src, "list directive", d.raw.span, here);
|
||||
}
|
||||
for member in &e.members {
|
||||
assert_inside(src, "enum member", member.span, here);
|
||||
check_name(
|
||||
src,
|
||||
"enum member name",
|
||||
&member.name,
|
||||
member.name_span,
|
||||
member.span,
|
||||
);
|
||||
}
|
||||
}
|
||||
if let TypedefKind::Struct(s) = &t.kind {
|
||||
for member in &s.members {
|
||||
assert_inside(src, "struct member", member.span, here);
|
||||
check_declarators(src, &member.declarators, member.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Typedef(t) => check_typedef(src, t, here),
|
||||
ItemKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
ItemKind::DataDecl(d) => check_declarators(src, &d.declarators, here),
|
||||
ItemKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
@@ -512,10 +506,22 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
despace(&b.target),
|
||||
"the bind target span does not slice back to its name"
|
||||
);
|
||||
check_names(src, "bind instance name", &b.instances, here);
|
||||
// An instance may itself be a hierarchical path, glued the same
|
||||
// way, so it gets the same modulo-whitespace comparison.
|
||||
for i in &b.instances {
|
||||
assert_inside(src, "bind instance name", i.span, here);
|
||||
assert_eq!(
|
||||
despace(slice(src, i.span)),
|
||||
despace(&i.text),
|
||||
"the bind instance span does not slice back to its name"
|
||||
);
|
||||
}
|
||||
check_instantiation(src, &b.inst, here);
|
||||
}
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
for d in &g.delay {
|
||||
check_expr(src, d, here);
|
||||
}
|
||||
for i in &g.instances {
|
||||
assert_inside(src, "gate instance", i.span, here);
|
||||
check_opt_name(src, "gate instance name", i.name.as_ref(), i.name_span, i.span);
|
||||
@@ -589,14 +595,18 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
check_opt_name(src, "endclocking label", c.end_label.as_ref(), c.end_label_span, here);
|
||||
for item in &c.items {
|
||||
assert_inside(src, "clocking item", item.span, here);
|
||||
if let ClockingItemKind::Signals { names, .. } = &item.kind {
|
||||
check_names(src, "clocking signal", names, item.span);
|
||||
if let ClockingItemKind::Signals { signals, .. } = &item.kind {
|
||||
for s in signals {
|
||||
check_name(src, "clocking signal", &s.name.text, s.name.span, item.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A `constraint`/`covergroup` block: one verbatim leaf whose span is
|
||||
// the item's own, checked above.
|
||||
ItemKind::Verbatim(_) => {}
|
||||
// the item's own, checked above. A null item is a leaf too — its span
|
||||
// is the `;`, which the caller has already asserted sits inside its
|
||||
// parent.
|
||||
ItemKind::Verbatim(_) | ItemKind::Empty => {}
|
||||
ItemKind::Function(f) => {
|
||||
check_name(src, "function name", &f.name, f.name_span, here);
|
||||
check_dpi_import(src, f.dpi.as_ref(), here);
|
||||
@@ -712,6 +722,30 @@ fn check_gen_block(src: &str, b: &GenBlock, parent: TextRange) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared by the item form and the block-scoped statement form, which carry
|
||||
/// the same [`Typedef`] payload.
|
||||
fn check_typedef(src: &str, t: &Typedef, here: TextRange) {
|
||||
check_name(src, "typedef name", &t.name, t.name_span, here);
|
||||
if let TypedefKind::Enum(e) = &t.kind {
|
||||
for d in &e.directives {
|
||||
assert_inside(src, "list directive", d.raw.span, here);
|
||||
}
|
||||
for member in &e.members {
|
||||
assert_inside(src, "enum member", member.span, here);
|
||||
check_name(src, "enum member name", &member.name, member.name_span, member.span);
|
||||
for dim in &member.range {
|
||||
assert_inside(src, "enum member range", dim.span, member.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let TypedefKind::Struct(s) = &t.kind {
|
||||
for member in &s.members {
|
||||
assert_inside(src, "struct member", member.span, here);
|
||||
check_declarators(src, &member.declarators, member.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_declarators(src: &str, declarators: &[Declarator], parent: TextRange) {
|
||||
for d in declarators {
|
||||
assert_inside(src, "declarator", d.span, parent);
|
||||
@@ -792,6 +826,7 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
|
||||
}
|
||||
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here),
|
||||
StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here),
|
||||
StmtKind::Typedef(t) => check_typedef(src, t, here),
|
||||
StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
StmtKind::Return(e) => check_opt_expr(src, e.as_ref(), here),
|
||||
@@ -842,7 +877,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
|
||||
ExprKind::Unary { expr, .. }
|
||||
| ExprKind::Postfix { expr, .. }
|
||||
| ExprKind::Paren { inner: expr, .. } => check_expr(src, expr, here),
|
||||
ExprKind::Cast { ty, expr } => {
|
||||
ExprKind::Cast { ty, expr, .. } => {
|
||||
check_expr(src, ty, here);
|
||||
check_expr(src, expr, here);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ use std::path::Path;
|
||||
use vlog_parser::ast::{AnsiPort, ItemKind, Module, ParamPort, PortList};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind, WorkspaceIndex};
|
||||
use vlog_semantic::{Semantics, WorkspaceIndex};
|
||||
|
||||
use crate::ports::{find_module, visible_in};
|
||||
|
||||
@@ -114,7 +114,7 @@ impl Default for Layout {
|
||||
/// completing.
|
||||
pub fn module_definition<'i>(index: &'i WorkspaceIndex, module: &str) -> Result<&'i Path, String> {
|
||||
let defs: Vec<_> =
|
||||
index.units(module).iter().filter(|def| def.kind == SymbolKind::Module).collect();
|
||||
index.units(module).iter().filter(|def| def.kind.is_instantiable()).collect();
|
||||
let [def] = defs.as_slice() else {
|
||||
return Err(match defs.len() {
|
||||
0 => format!("lucisv indexes no module named `{module}`."),
|
||||
@@ -468,7 +468,7 @@ pub fn module_names<'i>(index: &'i WorkspaceIndex, query: &str) -> Vec<&'i str>
|
||||
let mut out: Vec<&str> = index
|
||||
.workspace_symbols(query)
|
||||
.into_iter()
|
||||
.filter(|hit| hit.container.is_none() && hit.def.kind == SymbolKind::Module)
|
||||
.filter(|hit| hit.container.is_none() && hit.def.kind.is_instantiable())
|
||||
.map(|hit| hit.name)
|
||||
.collect();
|
||||
out.dedup();
|
||||
@@ -513,6 +513,26 @@ endmodule
|
||||
.expect("a plan")
|
||||
}
|
||||
|
||||
/// An interface is instantiated exactly as a module is, and since
|
||||
/// 2026-09-01 it carries `SymbolKind::Interface`
|
||||
/// (`docs/features/interface-semantics/README.md`) — so both unit lookups
|
||||
/// here ask `is_instantiable()` and answer what they always did.
|
||||
#[test]
|
||||
fn an_interface_is_a_unit_this_module_will_instantiate() {
|
||||
let index = index_of(&[
|
||||
("/rtl/bus_if.sv", "interface bus_if (input logic clk);\nendinterface\n"),
|
||||
("/rtl/sub.sv", SUB),
|
||||
]);
|
||||
assert_eq!(
|
||||
module_definition(&index, "bus_if").map(|p| p.display().to_string()),
|
||||
Ok("/rtl/bus_if.sv".to_string())
|
||||
);
|
||||
assert_eq!(module_names(&index, ""), ["bus_if", "sub"]);
|
||||
let plan = plan("interface bus_if (input logic clk);\nendinterface\n", "bus_if");
|
||||
let names: Vec<&str> = plan.ports.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["clk"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_reads_the_parameters_and_ports_in_declaration_order() {
|
||||
let plan = plan(SUB, "sub");
|
||||
|
||||
@@ -40,10 +40,12 @@ pub use instantiate::{
|
||||
PlanPort, Site,
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, may_have_port_action, port_actions, propagate_ports, remove_port, ModuleRef,
|
||||
PortAction,
|
||||
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
|
||||
propagate_ports, remove_port, ModuleRef, PortAction,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
};
|
||||
pub use rename::{prepare_rename, rename, RenameTarget};
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -155,29 +155,70 @@ pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Ve
|
||||
/// microseconds. It never says `false` where a refactoring would have
|
||||
/// succeeded: every one of the three starts by locating exactly one of these
|
||||
/// three constructs.
|
||||
///
|
||||
/// Exactly [`port_action_modules`] asked for emptiness — one walk, two
|
||||
/// readers, so the gate and the fan-out cannot come to disagree about which
|
||||
/// positions carry an action.
|
||||
pub fn may_have_port_action(text: &str, offset: u32) -> bool {
|
||||
!port_action_modules(text, offset).is_empty()
|
||||
}
|
||||
|
||||
/// Every module name a port refactoring at this position could act on: the
|
||||
/// module an instantiation under the cursor names, or the module whose port
|
||||
/// the cursor sits on.
|
||||
///
|
||||
/// [`may_have_port_action`]'s own walk, saying *which* module it found rather
|
||||
/// than only that it found one — which is what lets a server hand
|
||||
/// [`port_actions`] the handful of files that module fans out to instead of
|
||||
/// the whole workspace. Empty for exactly the positions the gate refuses.
|
||||
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
let at_instantiation = instantiations.iter().any(|instantiation| {
|
||||
instantiation.module_span.contains(offset)
|
||||
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
|
||||
});
|
||||
if at_instantiation {
|
||||
return true;
|
||||
let named: Vec<String> = instantiations
|
||||
.iter()
|
||||
.filter(|instantiation| {
|
||||
instantiation.module_span.contains(offset)
|
||||
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
|
||||
})
|
||||
.map(|instantiation| instantiation.module.clone())
|
||||
.collect();
|
||||
if !named.is_empty() {
|
||||
return named;
|
||||
}
|
||||
let mut module = None;
|
||||
module_at(&tree.items, offset, &mut module);
|
||||
let Some((module, _)) = module.and_then(|name| find_module(&tree, &name)) else {
|
||||
return false;
|
||||
let Some((name, (module, _))) =
|
||||
module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?)))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
if declared_ports(module).iter().any(|port| port.span.contains(offset)) {
|
||||
return true;
|
||||
return vec![name];
|
||||
}
|
||||
module.items.iter().any(|item| match &item.kind {
|
||||
let on_body_declaration = module.items.iter().any(|item| match &item.kind {
|
||||
ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
match on_body_declaration {
|
||||
true => vec![name],
|
||||
false => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module whose declaration covers this offset — what
|
||||
/// `ModuleRef::At { file, offset }` will resolve to.
|
||||
///
|
||||
/// The fan-out question for the *command* path, which takes a position
|
||||
/// anywhere in a module rather than on one of its ports: `lucisv.addPort` with
|
||||
/// a `Position` names the module the cursor is inside, and a server working
|
||||
/// out which files that refactoring needs has to name it the same way
|
||||
/// `locate_module` will.
|
||||
pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let mut module = None;
|
||||
module_at(&tree.items, offset, &mut module);
|
||||
module
|
||||
}
|
||||
|
||||
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
|
||||
@@ -354,7 +395,7 @@ fn locate_module(scope: &mut Scope, module: ModuleRef<'_>) -> Result<ModuleSite,
|
||||
.index()
|
||||
.units(&name)
|
||||
.iter()
|
||||
.filter(|def| def.kind == SymbolKind::Module)
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.cloned()
|
||||
.collect();
|
||||
let [def] = defs.as_slice() else {
|
||||
@@ -1742,6 +1783,33 @@ mod tests {
|
||||
text.find(needle).expect("needle present") as u32
|
||||
}
|
||||
|
||||
/// An interface is `SymbolKind::Interface` since 2026-09-01
|
||||
/// (`docs/features/interface-semantics/README.md`), and `locate_module`
|
||||
/// asks `is_instantiable()` rather than `kind == Module` — so adding a
|
||||
/// port to an interface, and rewriting every instantiation of it, works
|
||||
/// exactly as it did when an interface was indexed as a module.
|
||||
#[test]
|
||||
fn a_port_refactoring_finds_an_interface_the_way_it_finds_a_module() {
|
||||
let files = vec![
|
||||
(
|
||||
std::path::PathBuf::from("/rtl/bus_if.sv"),
|
||||
"interface bus_if (input logic clk);\nendinterface\n".to_string(),
|
||||
),
|
||||
(
|
||||
std::path::PathBuf::from("/rtl/top.sv"),
|
||||
"module top;\n logic c;\n bus_if u_bus (.clk(c));\nendmodule\n".to_string(),
|
||||
),
|
||||
];
|
||||
let edit = crate::add_port(&files, crate::ModuleRef::Name("bus_if"), "input logic rst_n")
|
||||
.expect("an interface's port list is refactored like a module's");
|
||||
let paths: Vec<String> = edit.edits.iter().map(|(p, _)| p.display().to_string()).collect();
|
||||
assert!(paths.contains(&"/rtl/bus_if.sv".to_string()), "{paths:?}");
|
||||
assert!(
|
||||
paths.contains(&"/rtl/top.sv".to_string()),
|
||||
"the instantiation is rewritten too: {paths:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_declaration_must_be_exactly_one_directed_port() {
|
||||
assert_eq!(parse_port_decl("input logic [7:0] cfg").map(|p| p.name), Ok("cfg".into()));
|
||||
|
||||
@@ -15,7 +15,7 @@ use vlog_parser::token::{is_keyword, TokenKind};
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, ExternalResolutions, ExternalTarget, FileId, ReferenceId,
|
||||
Resolution, Semantics, SymbolId, WorkspaceIndex,
|
||||
Resolution, Semantics, Symbol, SymbolId, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
@@ -44,6 +44,93 @@ pub fn prepare_rename(
|
||||
Ok(RenameTarget { range: target.cursor, name: target.name })
|
||||
}
|
||||
|
||||
/// [`prepare_rename`] answered from one buffer's finished analysis and the
|
||||
/// workspace index, reading no file at all.
|
||||
///
|
||||
/// `textDocument/prepareRename` fires the instant the rename key is pressed,
|
||||
/// and its whole answer — the identifier's range and its placeholder — is in
|
||||
/// the buffer already. Answering it through [`prepare_rename`] meant reading,
|
||||
/// parsing and indexing every in-scope file first: 2.5–3.0 s on OpenTitan, on
|
||||
/// a keypress that has committed to nothing, with a single-threaded server
|
||||
/// answering nothing else meanwhile.
|
||||
///
|
||||
/// Every refusal [`prepare_rename`] can reach without the *declaring file's*
|
||||
/// own text is reached here too, in the same words. The ones that need that
|
||||
/// text are deferred to [`rename`], which reads it — LSP allows an optimistic
|
||||
/// `prepareRename` whose rename then refuses, and never the other way round.
|
||||
/// The refusal-by-refusal table is in `docs/features/refactor-rename/README.md`.
|
||||
pub fn prepare_rename_here(
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
index: &WorkspaceIndex,
|
||||
offset: u32,
|
||||
) -> Result<RenameTarget, String> {
|
||||
let found =
|
||||
semantics.reference_id_at(offset).and_then(|id| Some((id, semantics.reference(id)?)));
|
||||
let Some((id, reference)) = found else {
|
||||
// The cursor is on a declaration, or on nothing at all.
|
||||
let here = semantics.symbol_at(offset).and_then(|symbol| semantics.symbol(symbol));
|
||||
let Some(declaration) = here else { return Err(NOTHING_HERE.to_string()) };
|
||||
renameable_here(semantics, index, declaration)?;
|
||||
return Ok(RenameTarget { range: declaration.name_span, name: declaration.name.clone() });
|
||||
};
|
||||
let cursor = reference.name_span;
|
||||
match &reference.resolution {
|
||||
Resolution::Resolved(symbol) => {
|
||||
let Some(declaration) = semantics.symbol(*symbol) else {
|
||||
return Err(NOTHING_HERE.to_string());
|
||||
};
|
||||
renameable_here(semantics, index, declaration)?;
|
||||
Ok(RenameTarget { range: cursor, name: declaration.name.clone() })
|
||||
}
|
||||
Resolution::NotFound => Err(unresolved(&reference.name)),
|
||||
Resolution::InheritedCandidate { base, .. } => Err(from_base(&reference.name, base)),
|
||||
// The overlay is `resolve_external` against this very index, which is
|
||||
// the same call `Scope::declaration_across_files` makes — so which
|
||||
// declaration the use names, and whether several do, is settled here.
|
||||
// What is *not* settled is anything about that declaration's own file.
|
||||
Resolution::ExternalCandidate { .. } => match external.get(id) {
|
||||
Some(ExternalTarget::Resolved(_)) => {
|
||||
Ok(RenameTarget { range: cursor, name: reference.name.clone() })
|
||||
}
|
||||
Some(ExternalTarget::Ambiguous(_)) => Err(ambiguous(&reference.name)),
|
||||
_ => Err(declared_outside(&reference.name)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The two refusals [`Scope::declaration`] applies to a declaration written in
|
||||
/// the file the request named, asked of that buffer and the index.
|
||||
fn renameable_here(
|
||||
semantics: &Semantics,
|
||||
index: &WorkspaceIndex,
|
||||
declaration: &Symbol,
|
||||
) -> Result<(), String> {
|
||||
if declaration.name_span.is_empty() {
|
||||
return Err(unspelled(&declaration.name));
|
||||
}
|
||||
if declaration.scope == semantics.file_scope() && index.units(&declaration.name).len() > 1 {
|
||||
return Err(ambiguous(&declaration.name));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The identifier a rename at `offset` would act on, read from one buffer's
|
||||
/// analysis alone: the name, with no opinion on whether it may be renamed.
|
||||
///
|
||||
/// What the server needs to ask the index for the rename's fan-out. Every
|
||||
/// refusal stays with [`rename`], which is the call that sees the files — a
|
||||
/// second opinion here could only disagree with it.
|
||||
pub fn rename_name_at(semantics: &Semantics, offset: u32) -> Option<String> {
|
||||
match semantics.reference_id_at(offset).and_then(|id| semantics.reference(id)) {
|
||||
Some(reference) => Some(reference.name.clone()),
|
||||
None => semantics
|
||||
.symbol_at(offset)
|
||||
.and_then(|symbol| semantics.symbol(symbol))
|
||||
.map(|declaration| declaration.name.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename the symbol at `offset` in `file` to `new_name`, across every file in
|
||||
/// `files`.
|
||||
///
|
||||
@@ -230,12 +317,10 @@ impl<'a> Scope<'a> {
|
||||
let (name, cursor) = (reference.name.clone(), reference.name_span);
|
||||
match &reference.resolution {
|
||||
Resolution::Resolved(symbol) => Found::Here(*symbol, cursor),
|
||||
Resolution::NotFound => return Err(format!(
|
||||
"`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean."
|
||||
)),
|
||||
Resolution::InheritedCandidate { base, .. } => return Err(format!(
|
||||
"`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess."
|
||||
)),
|
||||
Resolution::NotFound => return Err(unresolved(&name)),
|
||||
Resolution::InheritedCandidate { base, .. } => {
|
||||
return Err(from_base(&name, base))
|
||||
}
|
||||
Resolution::ExternalCandidate { .. } => {
|
||||
Found::Elsewhere(name, cursor, analysis.external.get(id).cloned())
|
||||
}
|
||||
@@ -282,9 +367,7 @@ impl<'a> Scope<'a> {
|
||||
)
|
||||
};
|
||||
if name_span.is_empty() {
|
||||
return Err(format!(
|
||||
"lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it."
|
||||
));
|
||||
return Err(unspelled(&name));
|
||||
}
|
||||
if at_file_scope && self.index.units(&name).len() > 1 {
|
||||
return Err(ambiguous(&name));
|
||||
@@ -302,11 +385,7 @@ impl<'a> Scope<'a> {
|
||||
let def = match target {
|
||||
Some(ExternalTarget::Resolved(def)) => def,
|
||||
Some(ExternalTarget::Ambiguous(_)) => return Err(ambiguous(name)),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
|
||||
))
|
||||
}
|
||||
_ => return Err(declared_outside(name)),
|
||||
};
|
||||
let Some(file) = self.index.path(def.file).and_then(|p| self.index_of(p)) else {
|
||||
return Err(format!("`{name}`'s declaring file is not in scope."));
|
||||
@@ -631,12 +710,41 @@ pub(crate) struct ArgumentSite {
|
||||
|
||||
const NOTHING_HERE: &str = "there is no symbol to rename at this position.";
|
||||
|
||||
// The refusal sentences, each written once. Two callers reach four of them
|
||||
// now: the whole-workspace `Scope::locate` and the buffer-and-index
|
||||
// `prepare_rename_here`, which must refuse in exactly the same words or the
|
||||
// user gets two different explanations for one situation.
|
||||
|
||||
fn ambiguous(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is declared in more than one indexed file; lucisv will not guess which declaration this rename means."
|
||||
)
|
||||
}
|
||||
|
||||
fn unresolved(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean."
|
||||
)
|
||||
}
|
||||
|
||||
fn from_base(name: &str, base: &str) -> String {
|
||||
format!(
|
||||
"`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess."
|
||||
)
|
||||
}
|
||||
|
||||
fn declared_outside(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
|
||||
)
|
||||
}
|
||||
|
||||
fn unspelled(name: &str) -> String {
|
||||
format!(
|
||||
"lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it."
|
||||
)
|
||||
}
|
||||
|
||||
/// Why an identifier spelling the name is not a reference lucisv can edit,
|
||||
/// read off its neighbours in the token stream. Naming the actual construct
|
||||
/// is the difference between a warning the user can act on and one they have
|
||||
@@ -679,7 +787,12 @@ pub(crate) fn display(path: &Path) -> String {
|
||||
/// True when `needle` occurs in `haystack` as a whole identifier — the test
|
||||
/// macro text and the verification pass's file filter get, where there is no
|
||||
/// token stream to consult (or where the token is opaque).
|
||||
pub(crate) fn contains_word(haystack: &str, needle: &str) -> bool {
|
||||
///
|
||||
/// Public because the server asks the same question of a `` `define`` body it
|
||||
/// reads out of the index, to put that macro's file in a rename's fan-out:
|
||||
/// [`Scope::define_sites`] decides with this function, so the fan-out must
|
||||
/// decide with it too or the two disagree about which files carry a warning.
|
||||
pub fn contains_word(haystack: &str, needle: &str) -> bool {
|
||||
if needle.is_empty() {
|
||||
return false;
|
||||
}
|
||||
@@ -719,6 +832,185 @@ mod tests {
|
||||
assert!(check_new_name("a ").is_err(), "trailing space");
|
||||
}
|
||||
|
||||
/// A `(path, text)` list from `(name, text)` pairs, the shape both entry
|
||||
/// points take.
|
||||
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
files.iter().map(|(name, text)| (PathBuf::from(name), (*text).to_string())).collect()
|
||||
}
|
||||
|
||||
/// [`prepare_rename_here`] and [`prepare_rename`] asked the same question
|
||||
/// at **every byte** of one file, with the parity contract asserted at
|
||||
/// each: a refusal is never invented and never reworded, and an answer is
|
||||
/// never a different answer. The one asymmetry the contract allows is the
|
||||
/// deferral — the cheap path saying yes where the whole-workspace path
|
||||
/// refuses for a reason only the declaring file's own text carries.
|
||||
///
|
||||
/// Returns how many offsets were deferrals, so a test can assert it found
|
||||
/// the case it was built to find.
|
||||
fn parity_at_every_offset(files: &[(&str, &str)], file: &str) -> usize {
|
||||
let sources = workspace(files);
|
||||
let path = PathBuf::from(file);
|
||||
let text = sources
|
||||
.iter()
|
||||
.find(|(p, _)| *p == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let semantics = analyze(&parse_source_tolerant(&text).0, &text);
|
||||
let external = resolve_external(&semantics, &index);
|
||||
|
||||
let mut deferred = 0usize;
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let whole = prepare_rename(&sources, &path, offset);
|
||||
let here = prepare_rename_here(&semantics, &external, &index, offset);
|
||||
match (&whole, &here) {
|
||||
(Ok(whole), Ok(here)) => {
|
||||
assert_eq!(whole, here, "at byte {offset} of {file}");
|
||||
}
|
||||
(Err(whole), Err(here)) => {
|
||||
assert_eq!(whole, here, "refusal reworded at byte {offset} of {file}");
|
||||
}
|
||||
// Allowed, and only in this direction: the buffer said yes,
|
||||
// the workspace refused for something only the declaring
|
||||
// file's own analysis knows. `rename` still delivers it.
|
||||
(Err(_), Ok(_)) => deferred += 1,
|
||||
(Ok(whole), Err(here)) => panic!(
|
||||
"a refusal was invented at byte {offset} of {file}: the workspace answered {whole:?}, the buffer refused with {here:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
deferred
|
||||
}
|
||||
|
||||
const SUB: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n";
|
||||
const TOP: &str = "module top;\n logic c, d;\n sub #(.W(2)) u_sub (.clk(c), .q(d));\n sub u_two (.clk(c), .q(d));\nendmodule\n";
|
||||
const PKG: &str =
|
||||
"package cfg_pkg;\n parameter int DEPTH = 4;\n typedef logic [1:0] mode_t;\nendpackage\n";
|
||||
const USER: &str = "module user;\n import cfg_pkg::*;\n cfg_pkg::mode_t m;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn the_buffer_answers_a_prepare_exactly_as_the_workspace_does() {
|
||||
let files = [("sub.sv", SUB), ("top.sv", TOP)];
|
||||
parity_at_every_offset(&files, "top.sv");
|
||||
parity_at_every_offset(&files, "sub.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_over_packages_and_qualified_names_keeps_parity() {
|
||||
let files = [("pkg.sv", PKG), ("user.sv", USER)];
|
||||
parity_at_every_offset(&files, "user.sv");
|
||||
parity_at_every_offset(&files, "pkg.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_where_the_workspace_declares_a_name_twice() {
|
||||
// Two modules called `sub`, so every route to that declaration must
|
||||
// refuse — from the use in `top.sv`, and from either declaration.
|
||||
let files =
|
||||
[("a.sv", SUB), ("b.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)];
|
||||
parity_at_every_offset(&files, "top.sv");
|
||||
parity_at_every_offset(&files, "a.sv");
|
||||
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let semantics = analyze(&parse_source_tolerant(TOP).0, TOP);
|
||||
let external = resolve_external(&semantics, &index);
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let refusal =
|
||||
prepare_rename_here(&semantics, &external, &index, at).expect_err("declared twice");
|
||||
assert_eq!(refusal, ambiguous("sub"), "the index-shaped refusal, in its own words");
|
||||
assert_eq!(refusal, prepare_rename(&sources, &path, at).expect_err("declared twice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_where_nothing_resolves() {
|
||||
// `missing` is instantiated and declared nowhere; `base_t` comes from
|
||||
// a base class this workspace does not hold.
|
||||
const STRAY: &str = "class kid extends absent_base;\n function void go();\n inherited_thing = 1;\n endfunction\nendclass\nmodule holder;\n missing u_missing (.a(b));\nendmodule\n";
|
||||
parity_at_every_offset(&[("stray.sv", STRAY), ("sub.sv", SUB)], "stray.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_through_generate_blocks_and_macros() {
|
||||
const GEN: &str = "`define BUMP(x) x + 1\n`define WIDTH 8\nmodule gen_holder;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_lane (.clk(1'b0), .q());\n end\n endgenerate\n wire [`WIDTH-1:0] w;\n assign w = `BUMP(sub);\nendmodule\n";
|
||||
parity_at_every_offset(&[("gen.sv", GEN), ("sub.sv", SUB)], "gen.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_on_an_unparseable_buffer_keeps_parity() {
|
||||
const BROKEN: &str =
|
||||
"module broken (input logic clk;\n wire a\n assign a = clk\nendmodule\n";
|
||||
parity_at_every_offset(&[("broken.sv", BROKEN), ("sub.sv", SUB)], "broken.sv");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA, 2026-08-28: prepare parity fuzz beyond the dev's six buffers
|
||||
// ------------------------------------------------------------------
|
||||
//
|
||||
// Same contract, hostile shapes the dev's suite didn't try: a valid head
|
||||
// followed by garbage (as opposed to garbage throughout), CRLF line
|
||||
// endings (byte offsets a naive line-based tool would get wrong), and
|
||||
// multi-byte UTF-8 text sitting before the identifiers being probed.
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_with_a_valid_head_and_an_unparseable_tail() {
|
||||
const HEAD_THEN_GARBAGE: &str = "module ok_head;\n wire a;\n assign a = 1'b0;\nendmodule\n\n)}]224$@#(garbage tail not even lexable as verilog{{{\n";
|
||||
parity_at_every_offset(&[("tail.sv", HEAD_THEN_GARBAGE), ("sub.sv", SUB)], "tail.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_over_crlf_line_endings() {
|
||||
const CRLF: &str = "module crlf_mod;\r\n wire local_net;\r\n sub u_inst (.clk(1'b0), .q());\r\n assign local_net = 1'b0;\r\nendmodule\r\n";
|
||||
parity_at_every_offset(&[("crlf.sv", CRLF), ("sub.sv", SUB)], "crlf.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_with_multi_byte_text_before_the_identifiers() {
|
||||
const MULTI_BYTE: &str = "// \u{00e9}\u{00e9} \u{1f389} a comment with accents and an emoji before anything else\nmodule multi_byte_mod;\n // \u{4e2d}\u{6587}\u{6ce8}\u{91ca} more non-ascii, mid-file\n wire local_net;\n sub u_inst (.clk(1'b0), .q());\n assign local_net = 1'b0;\nendmodule\n";
|
||||
parity_at_every_offset(&[("multibyte.sv", MULTI_BYTE), ("sub.sv", SUB)], "multibyte.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_over_a_macro_heavy_buffer() {
|
||||
const MACRO_HEAVY: &str = "`define WIDTH 8\n`define BUMP(x) x = x + 1\n`ifdef NEVER_DEFINED\n `define shadow_sub sub\n`else\n module macro_heavy;\n wire [`WIDTH-1:0] w;\n sub u_real (.clk(1'b0), .q());\n initial `BUMP(w);\n endmodule\n`endif\n";
|
||||
parity_at_every_offset(&[("macro.sv", MACRO_HEAVY), ("sub.sv", SUB)], "macro.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cheap_prepare_reads_nothing_but_the_buffer_and_the_index() {
|
||||
// The declaring file is *not* in the index, so nothing about it can be
|
||||
// consulted — and the answer is still the refusal that says so.
|
||||
let sources = workspace(&[("top.sv", TOP)]);
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let semantics = analyze(&parse_source_tolerant(TOP).0, TOP);
|
||||
let external = resolve_external(&semantics, &index);
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
assert_eq!(
|
||||
prepare_rename_here(&semantics, &external, &index, at).expect_err("not indexed"),
|
||||
declared_outside("sub")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on() {
|
||||
let files = [("sub.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)];
|
||||
let sources = workspace(&files);
|
||||
for (path, text) in &sources {
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let Ok(target) = prepare_rename(&sources, path, offset) else { continue };
|
||||
assert_eq!(
|
||||
rename_name_at(&semantics, offset).as_deref(),
|
||||
Some(target.name.as_str()),
|
||||
"at byte {offset} of {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_word_search_ignores_substrings() {
|
||||
assert!(contains_word("a + WIDTH - 1", "WIDTH"));
|
||||
|
||||
@@ -642,6 +642,41 @@ fn the_cheap_pre_check_says_yes_exactly_where_an_action_could_be_offered() {
|
||||
assert!(may_have_port_action(non_ansi, at(non_ansi, "input a") + 6), "a non-ANSI declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pre_check_names_the_module_whose_files_the_action_will_need() {
|
||||
use vlog_refactor::{may_have_port_action, port_action_modules};
|
||||
let text = "module sub (\n input a,\n input b\n);\n wire c;\n assign c = a;\n other u1 (.x(c));\nendmodule\n";
|
||||
// On a port of `sub`, the module whose signature would change; on the
|
||||
// instantiation, the module instantiated — never the one it is written in.
|
||||
assert_eq!(port_action_modules(text, at(text, "input b") + 6), ["sub"]);
|
||||
assert_eq!(port_action_modules(text, at(text, "u1")), ["other"]);
|
||||
assert_eq!(port_action_modules(text, at(text, "other")), ["other"]);
|
||||
assert!(port_action_modules(text, at(text, "assign")).is_empty());
|
||||
|
||||
let non_ansi = "module sub (a);\n input a;\nendmodule\n";
|
||||
assert_eq!(port_action_modules(non_ansi, at(non_ansi, "input a") + 6), ["sub"]);
|
||||
|
||||
// The gate is this walk asked for emptiness, at every byte of the file.
|
||||
for offset in 0..text.len() as u32 {
|
||||
assert_eq!(
|
||||
may_have_port_action(text, offset),
|
||||
!port_action_modules(text, offset).is_empty(),
|
||||
"at byte {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_enclosing_module_is_the_one_a_position_would_add_a_port_to() {
|
||||
use vlog_refactor::enclosing_module;
|
||||
let text = "module sub (input a);\n wire c;\nendmodule\n\nmodule top;\n sub u1 (.a(c));\nendmodule\n";
|
||||
// A position `lucisv.addPort` would take: inside the module, nowhere near
|
||||
// a port element — which is exactly where `port_action_modules` is empty.
|
||||
assert_eq!(enclosing_module(text, at(text, "wire c")).as_deref(), Some("sub"));
|
||||
assert_eq!(enclosing_module(text, at(text, "sub u1")).as_deref(), Some("top"));
|
||||
assert_eq!(enclosing_module(text, at(text, "\n\nmodule top") + 1), None, "between modules");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what the preprocessor owns
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -357,20 +357,31 @@ fn an_interface_renames_through_a_direction_less_ansi_port() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_the_modport_half_of_a_port_type_is_refused() {
|
||||
// QA attack (`docs/features/ansi-first-port/README.md`): `bus_if.mp bus`
|
||||
// glues the modport onto the type name, but only the interface half is
|
||||
// bound (`ItemKind::Modport` is a leaf in `vlog_semantic`, `bind.rs:364`).
|
||||
// A rename request on the `mp` half must find nothing to rename — never
|
||||
// silently rename the interface instead, and never corrupt the modport
|
||||
// spelling.
|
||||
let iface = "interface bus_if;\n modport mp (input a);\nendinterface\n";
|
||||
let top = "module top (bus_if.mp bus);\nendmodule\n";
|
||||
fn renaming_the_modport_half_of_a_port_type_renames_the_modport() {
|
||||
// Flipped at lead review of interface-semantics (2026-09-01). Until then
|
||||
// `bus_if.mp bus` bound only the interface half and a rename request on
|
||||
// `mp` had nothing to rename (`ItemKind::Modport` was a leaf); now a
|
||||
// modport is a symbol and the `mp` half of a glued type name is a
|
||||
// reference to it, so renaming from the type position rewrites the
|
||||
// declaration and every type-position use — and nothing else: the
|
||||
// interface's own name is untouched, as is every other spelling of `mp`.
|
||||
let iface = "interface bus_if;\n logic a;\n modport mp (input a);\n modport other (output a);\nendinterface\n";
|
||||
let top = "module top (bus_if.mp bus, bus_if.other o);\n logic mp;\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
|
||||
let offset = at(top, "bus_if.", "mp");
|
||||
let err = rename(&files, &path("top.sv"), offset, "mp2")
|
||||
.expect_err("the modport half of the type name is not a bound symbol");
|
||||
assert!(!err.is_empty());
|
||||
let edit = rename(&files, &path("top.sv"), offset, "mp2").expect("a modport renames");
|
||||
let iface_after = apply(iface, &edit, &path("bus_if.sv"));
|
||||
let top_after = apply(top, &edit, &path("top.sv"));
|
||||
assert!(iface_after.contains("modport mp2 (input a);"), "{iface_after}");
|
||||
assert!(iface_after.contains("modport other (output a);"), "{iface_after}");
|
||||
assert!(top_after.contains("bus_if.mp2 bus"), "{top_after}");
|
||||
assert!(top_after.contains("bus_if.other o"), "the other modport is untouched: {top_after}");
|
||||
assert!(top_after.contains("logic mp;"), "an unrelated `mp` is untouched: {top_after}");
|
||||
assert!(
|
||||
iface_after.contains("interface bus_if;"),
|
||||
"the interface keeps its name: {iface_after}"
|
||||
);
|
||||
assert_eq!(edit.edit_count(), 2, "declaration + the one type-position use: {edit:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -815,7 +826,13 @@ fn a_mismatched_end_label_is_left_alone_and_says_which_construct_it_is() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_tail_is_left_alone_and_named_as_such() {
|
||||
fn a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration() {
|
||||
// Since class-member-access round 2 (2026-09-01) an instance head's tail
|
||||
// resolves through the instance's module, so `u_sub.sig` *is* sub's
|
||||
// `wire sig` and a rename must rewrite it — leaving it would hand back a
|
||||
// design that no longer elaborates. Before that round this test pinned
|
||||
// the opposite as an honest limitation ("the tail is not resolved, so
|
||||
// not edited"); the limitation is gone and the truth flipped with it.
|
||||
let text = concat!(
|
||||
"module sub;\n wire sig;\nendmodule\n",
|
||||
"module top;\n",
|
||||
@@ -828,10 +845,41 @@ fn a_hierarchical_tail_is_left_alone_and_named_as_such() {
|
||||
let edit = rename(&files, &path("m.sv"), at(text, "wire", "sig"), "signal").expect("renames");
|
||||
let after = apply(text, &edit, &path("m.sv"));
|
||||
assert!(after.contains("wire signal;"), "{after}");
|
||||
assert!(after.contains("u_sub.sig;"), "the tail is not resolved, so not edited: {after}");
|
||||
assert!(after.contains("u_sub.signal;"), "the tail resolves, so it is edited: {after}");
|
||||
assert!(
|
||||
edit.warnings.iter().any(|w| w.contains("hierarchical or member tail")),
|
||||
"{:?}",
|
||||
!edit.warnings.iter().any(|w| w.contains("hierarchical or member tail")),
|
||||
"a resolved tail is an edit, not a warning: {:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such() {
|
||||
// The module behind the instance is nowhere in the workspace, so the tail
|
||||
// records nothing and the rename can only say so: the old-spelled tail is
|
||||
// left as written and the warning names it.
|
||||
let text = concat!(
|
||||
"module top;\n",
|
||||
" wire sig;\n",
|
||||
" unknown_mod u_x ();\n",
|
||||
" wire w;\n",
|
||||
" assign w = u_x.sig;\n",
|
||||
"endmodule\n"
|
||||
);
|
||||
let files = workspace(&[("m.sv", text)]);
|
||||
let edit = rename(&files, &path("m.sv"), at(text, "wire", "sig"), "signal").expect("renames");
|
||||
let after = apply(text, &edit, &path("m.sv"));
|
||||
assert!(after.contains("wire signal;"), "{after}");
|
||||
assert!(after.contains("u_x.sig;"), "an unresolved tail is not edited: {after}");
|
||||
// Known gap, filed as `docs/topo.md` §2.9-20 (lead, 2026-09-01): before
|
||||
// class-member-access such a tail had no reference at all and the stray
|
||||
// scan (`stray_reason`) warned about it; now it carries an
|
||||
// `ExternalCandidate` the workspace cannot answer, which the engine
|
||||
// neither edits nor warns about. The edit behavior is right; the missing
|
||||
// heads-up is the same class as §2.9-18's lost macro-argument warnings.
|
||||
assert!(
|
||||
!edit.warnings.iter().any(|w| w.contains("u_x")),
|
||||
"premise of the filed gap — no warning names the tail today: {:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,35 @@ pub(crate) enum Target {
|
||||
UnitMember(String),
|
||||
/// The `.port` of a connection to the named module.
|
||||
Port(String),
|
||||
/// A name that may only be looked up in the scope it is **written in**,
|
||||
/// never outward: a modport's port list (IEEE 1800 §25.5 — every name it
|
||||
/// governs is declared in that very interface) and a clocking block's
|
||||
/// signal list (§14.4). Walking outward here would be a wrong answer
|
||||
/// waiting to happen: `modport mp (input other_if)` must not find a
|
||||
/// file-scope `other_if` because the interface itself declares no such
|
||||
/// signal. A miss records **nothing**.
|
||||
InScope,
|
||||
/// The `mp` of a glued interface type name — `bus_if.mp bus`,
|
||||
/// `virtual bus_if.mp vif` (IEEE 1800 §25.4/§25.9). `unit` is the
|
||||
/// interface half, which [`Binder::bind_data_type`] binds beside this as
|
||||
/// an ordinary [`Target::Type`]; the tail is a *member* of it, looked up
|
||||
/// in the interface's own scope when this file declares it and handed to
|
||||
/// the workspace as `unit::name` when it does not. A tail an interface
|
||||
/// this file declares whole does not bind records nothing, on the same
|
||||
/// rule [`Target::MemberOf`] follows.
|
||||
TypeMember { unit: String },
|
||||
/// The `member` of `head.mids….member`, where `head` is a plain
|
||||
/// identifier this file may declare: looked up in the scope of the head's
|
||||
/// **declared type**, then up that type's `extends` chain, one hop per
|
||||
/// name in `mids`.
|
||||
///
|
||||
/// Carries the *spellings* rather than the inner tails' resolutions,
|
||||
/// because the type of a link is only known once the link before it is
|
||||
/// resolved, which is pass two's job — and because a spelling is all the
|
||||
/// workspace layer gets either way: a chain that leaves this file becomes
|
||||
/// one composed path (`pkt_t::hdr::addr`), read by the same
|
||||
/// `follow_one` every other path goes through.
|
||||
MemberOf { head: String, mids: Vec<String> },
|
||||
/// The `x` of `this.x`: the enclosing class's scope only.
|
||||
ThisMember,
|
||||
/// The `x` of `super.x`: always the base class's business.
|
||||
@@ -143,6 +172,7 @@ impl<'a> Binder<'a> {
|
||||
name_span,
|
||||
decl_span,
|
||||
detail_span: None,
|
||||
type_name: None,
|
||||
scope,
|
||||
child_scope: None,
|
||||
});
|
||||
@@ -152,6 +182,31 @@ impl<'a> Binder<'a> {
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// [`Binder::declare`] for a declaration written with a type, recording
|
||||
/// that type's name on the symbol — what `handle.member` is looked up
|
||||
/// with. A redeclaration binds nothing and records nothing here either.
|
||||
///
|
||||
/// `ty` is `None` where the declared name is not itself a value of the
|
||||
/// type: an **unpacked** declarator (`c1 q[$]`, `item_t pool[4]`) names a
|
||||
/// container, and `q.size()` is a built-in array method, not a member of
|
||||
/// `c1` — the element is reached through an index, which is a head this
|
||||
/// crate does not type (TODO.md §15, round 2).
|
||||
fn declare_typed(
|
||||
&mut self,
|
||||
scope: ScopeId,
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
name_span: TextRange,
|
||||
decl_span: TextRange,
|
||||
ty: Option<&DataType>,
|
||||
) -> Option<SymbolId> {
|
||||
let id = self.declare(scope, name, kind, name_span, decl_span);
|
||||
if let Some(id) = id {
|
||||
self.symbols[id.0 as usize].type_name = ty.and_then(type_name_of);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Declare `name` and open the scope it owns.
|
||||
fn declare_with_scope(
|
||||
&mut self,
|
||||
@@ -308,7 +363,9 @@ impl<'a> Binder<'a> {
|
||||
// Handshakes.
|
||||
ItemKind::Bind(b) => self.bind_instantiation_module(&b.inst, scope),
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
self.bind_opt_expr(g.delay.as_ref(), scope);
|
||||
for d in &g.delay {
|
||||
self.bind_expr(d, scope);
|
||||
}
|
||||
for inst in &g.instances {
|
||||
if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) {
|
||||
self.declare(scope, name, SymbolKind::Instance, ns, inst.span);
|
||||
@@ -341,6 +398,12 @@ impl<'a> Binder<'a> {
|
||||
ItemKind::Function(f) => self.bind_function(f, item.span, scope),
|
||||
ItemKind::Task(t) => self.bind_task(t, item.span, scope),
|
||||
ItemKind::Class(c) => self.bind_class(c, item.span, scope),
|
||||
ItemKind::Modport(decls) => {
|
||||
for d in decls {
|
||||
self.bind_modport(d, scope);
|
||||
}
|
||||
}
|
||||
ItemKind::Clocking(c) => self.bind_clocking(c, item.span, scope),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
for (lhs, rhs) in pairs {
|
||||
self.bind_expr(lhs, scope);
|
||||
@@ -356,32 +419,29 @@ impl<'a> Binder<'a> {
|
||||
// (an `import` alongside it does that). Resolving either one is a
|
||||
// vlog_semantic decision, not the parser's — see
|
||||
// `docs/features/dpi-export/README.md` Handshakes.
|
||||
// `modport` and `clocking` are leaves here for now: both name
|
||||
// signals that are declared in the enclosing interface, so
|
||||
// resolving them is a reference-binding question rather than a
|
||||
// declaration one, and whether a modport or a clocking block
|
||||
// should itself be a symbol is a vlog_semantic decision — see
|
||||
// `docs/features/interfaces/README.md` Handshakes.
|
||||
ItemKind::Modport(_)
|
||||
| ItemKind::Clocking(_)
|
||||
| ItemKind::Export(_)
|
||||
ItemKind::Export(_)
|
||||
| ItemKind::Directive(_)
|
||||
| ItemKind::MacroItem(_)
|
||||
| ItemKind::Timeunit(_)
|
||||
| ItemKind::Error(_)
|
||||
// A null item (`;`) declares nothing and references nothing.
|
||||
| ItemKind::Empty
|
||||
| ItemKind::Verbatim(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_module(&mut self, m: &'a Module, span: TextRange, scope: ScopeId) {
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&m.name,
|
||||
SymbolKind::Module,
|
||||
m.name_span,
|
||||
span,
|
||||
ScopeKind::Module,
|
||||
);
|
||||
// One AST node, three keywords. `interface` gets its own kind — its
|
||||
// signals are its surface and another file may reach them, which is
|
||||
// exactly what a module never grants. `program` stays a `Module`: it is
|
||||
// a module body with a different closing keyword and no export rule of
|
||||
// its own to write (`docs/features/interface-semantics/README.md`).
|
||||
let kind = match m.kw.as_str() {
|
||||
"interface" => SymbolKind::Interface,
|
||||
_ => SymbolKind::Module,
|
||||
};
|
||||
let inner =
|
||||
self.declare_with_scope(scope, &m.name, kind, m.name_span, span, ScopeKind::Module);
|
||||
for import in &m.imports {
|
||||
for path in &import.paths {
|
||||
self.bind_import_path(path, inner);
|
||||
@@ -396,7 +456,14 @@ impl<'a> Binder<'a> {
|
||||
TextRange::new(p.span.start, p.name_span.start),
|
||||
inner,
|
||||
);
|
||||
self.declare(inner, &p.name, SymbolKind::Port, p.name_span, p.span);
|
||||
self.declare_typed(
|
||||
inner,
|
||||
&p.name,
|
||||
SymbolKind::Port,
|
||||
p.name_span,
|
||||
p.span,
|
||||
p.unpacked.is_empty().then_some(&p.ty),
|
||||
);
|
||||
self.bind_dims(&p.unpacked, inner);
|
||||
self.bind_opt_expr(p.default.as_ref(), inner);
|
||||
}
|
||||
@@ -416,7 +483,8 @@ impl<'a> Binder<'a> {
|
||||
fn bind_param_ports(&mut self, ports: impl Iterator<Item = &'a ParamPort>, scope: ScopeId) {
|
||||
for p in ports {
|
||||
self.bind_data_type(&p.ty, TextRange::new(p.span.start, p.name_span.start), scope);
|
||||
self.declare(scope, &p.name, SymbolKind::Param, p.name_span, p.span);
|
||||
let ty = p.unpacked.is_empty().then_some(&p.ty);
|
||||
self.declare_typed(scope, &p.name, SymbolKind::Param, p.name_span, p.span, ty);
|
||||
self.bind_dims(&p.unpacked, scope);
|
||||
self.bind_opt_expr(p.default.as_ref(), scope);
|
||||
}
|
||||
@@ -447,9 +515,15 @@ impl<'a> Binder<'a> {
|
||||
fn bind_typedef(&mut self, t: &Typedef, span: TextRange, scope: ScopeId) {
|
||||
let ns = t.name_span;
|
||||
match &t.kind {
|
||||
// The aliased type is recorded on the alias, so `typedef c1 my_t;
|
||||
// my_t h; h.x` can follow the alias to the class (round 2). An
|
||||
// alias **with unpacked dimensions** (`typedef c1 q_t[4];`) names
|
||||
// a container, not a value of the type, and is left untyped on
|
||||
// the same rule every other unpacked declarator follows.
|
||||
TypedefKind::Alias(ty) => {
|
||||
self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope);
|
||||
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
|
||||
let ty = t.unpacked.is_empty().then_some(ty);
|
||||
self.declare_typed(scope, &t.name, SymbolKind::Typedef, ns, span, ty);
|
||||
}
|
||||
TypedefKind::Enum(e) => {
|
||||
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
|
||||
@@ -514,13 +588,26 @@ impl<'a> Binder<'a> {
|
||||
// `input [7:0] a;`) is the same header-names-it, body-completes-it
|
||||
// shape and merges through the same `declare`, so it is recorded on
|
||||
// the same terms — matching on `kind` rather than on `Port` alone.
|
||||
//
|
||||
// The type is recorded on the same terms: a header port is named
|
||||
// without one, and the body declaration is where it is written.
|
||||
let names = &self.scopes[scope.0 as usize].names;
|
||||
for d in &p.declarators {
|
||||
if let Some(&existing) = names.get(d.name.as_str()) {
|
||||
let symbol = &mut self.symbols[existing.0 as usize];
|
||||
if symbol.kind == kind && symbol.detail_span.is_none() {
|
||||
symbol.detail_span = Some(span);
|
||||
}
|
||||
let existing: Vec<(SymbolId, bool)> = p
|
||||
.declarators
|
||||
.iter()
|
||||
.filter_map(|d| Some((names.get(d.name.as_str()).copied()?, d.unpacked.is_empty())))
|
||||
.collect();
|
||||
for (id, plain) in existing {
|
||||
let type_name = plain.then(|| type_name_of(&p.ty)).flatten();
|
||||
let symbol = &mut self.symbols[id.0 as usize];
|
||||
if symbol.kind != kind {
|
||||
continue;
|
||||
}
|
||||
if symbol.detail_span.is_none() {
|
||||
symbol.detail_span = Some(span);
|
||||
}
|
||||
if symbol.type_name.is_none() {
|
||||
symbol.type_name = type_name;
|
||||
}
|
||||
}
|
||||
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
|
||||
@@ -537,7 +624,14 @@ impl<'a> Binder<'a> {
|
||||
let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end);
|
||||
self.bind_data_type(ty, TextRange::new(span.start, first), scope);
|
||||
for d in declarators {
|
||||
self.declare(scope, &d.name, kind, d.name_span, d.span);
|
||||
self.declare_typed(
|
||||
scope,
|
||||
&d.name,
|
||||
kind,
|
||||
d.name_span,
|
||||
d.span,
|
||||
d.unpacked.is_empty().then_some(ty),
|
||||
);
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
@@ -552,7 +646,23 @@ impl<'a> Binder<'a> {
|
||||
self.bind_connection(c, &i.module, scope);
|
||||
}
|
||||
for inst in &i.instances {
|
||||
self.declare(scope, &inst.name, SymbolKind::Instance, inst.name_span, inst.span);
|
||||
let id =
|
||||
self.declare(scope, &inst.name, SymbolKind::Instance, inst.name_span, inst.span);
|
||||
// An instance's "declared type" is the module it instantiates, so
|
||||
// `u.port` and `u.internal_sig` are looked up exactly as a class
|
||||
// handle's members are — in the module's own scope, or in the
|
||||
// workspace's member table when the module is another file's.
|
||||
// An **array** of instances (`sub u[3:0] (...)`) is not one of
|
||||
// them, on the same rule an unpacked declarator follows: the
|
||||
// element is reached through an index, which is not a head this
|
||||
// crate types.
|
||||
// A macro standing where the module name belongs (`` `REGS u ()``)
|
||||
// names no declaration, exactly as it names none in `use_name`.
|
||||
let named =
|
||||
!i.module.is_empty() && !i.module.starts_with('`') && !is_keyword(&i.module);
|
||||
if let (Some(id), true) = (id, inst.dims.is_empty() && named) {
|
||||
self.symbols[id.0 as usize].type_name = Some(i.module.clone());
|
||||
}
|
||||
self.bind_dims(&inst.dims, scope);
|
||||
match &inst.conns {
|
||||
Connections::Named(conns) => {
|
||||
@@ -678,12 +788,100 @@ impl<'a> Binder<'a> {
|
||||
fn bind_tf_args(&mut self, args: &'a [TfArg], scope: ScopeId) {
|
||||
for a in args {
|
||||
self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope);
|
||||
self.declare(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span);
|
||||
let ty = a.unpacked.is_empty().then_some(&a.ty);
|
||||
self.declare_typed(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span, ty);
|
||||
self.bind_dims(&a.unpacked, scope);
|
||||
self.bind_opt_expr(a.default.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Interfaces
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `modport mp (input a, output b)` of a `modport` declaration.
|
||||
///
|
||||
/// The name is a **declaration**: it is what an interface port's
|
||||
/// `bus_if.mp` type names, what a connection's `b_if.mp` names, and what a
|
||||
/// hover on either should show. Every name in the port list is a *use* of
|
||||
/// something the interface itself declares — a signal for
|
||||
/// `input`/`output`/`inout`/`ref`, a method for `import`/`export`, the
|
||||
/// clocking block for `clocking cb` — and all of them are one lookup in
|
||||
/// this very scope ([`Target::InScope`]), because IEEE 1800 §25.5 says a
|
||||
/// modport port names a member of the interface and nothing else.
|
||||
fn bind_modport(&mut self, d: &ModportDecl, scope: ScopeId) {
|
||||
self.declare(scope, &d.name, SymbolKind::Modport, d.name_span, d.span);
|
||||
for port in &d.ports {
|
||||
for name in &port.names {
|
||||
self.use_name(scope, &name.text, name.span, Target::InScope);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `clocking cb @(posedge clk); … endclocking` block.
|
||||
///
|
||||
/// A **named** block with an event declares a symbol whose declared type is
|
||||
/// the enclosing unit's own name. A clocking signal is an alias of the
|
||||
/// same-named signal in that unit (IEEE 1800 §14.4), so pointing the
|
||||
/// block's "type" back at the interface makes `vif.cb.data` and `cb.data`
|
||||
/// answer with `data`'s own declaration — the honest answer — through
|
||||
/// exactly the member chase round 2 already built, with no new machinery.
|
||||
///
|
||||
/// `default clocking cb;` selects a block declared elsewhere in the same
|
||||
/// scope and is therefore a *use*; an anonymous `default clocking @(...)`
|
||||
/// names nothing and declares nothing.
|
||||
fn bind_clocking(&mut self, c: &ClockingDecl, span: TextRange, scope: ScopeId) {
|
||||
match (&c.name, &c.event) {
|
||||
(Some(name), Some(_)) => {
|
||||
let ty = self.enclosing_unit_name(scope);
|
||||
let id = self.declare(scope, &name.text, SymbolKind::Clocking, name.span, span);
|
||||
if let Some(id) = id {
|
||||
self.symbols[id.0 as usize].type_name = ty;
|
||||
}
|
||||
}
|
||||
(Some(name), None) => self.use_name(scope, &name.text, name.span, Target::InScope),
|
||||
(None, _) => {}
|
||||
}
|
||||
if let Some(event) = &c.event {
|
||||
self.bind_sens_list(event, scope);
|
||||
}
|
||||
for item in &c.items {
|
||||
let ClockingItemKind::Signals { signals, .. } = &item.kind else {
|
||||
continue;
|
||||
};
|
||||
for signal in signals {
|
||||
match &signal.value {
|
||||
// `output tms = _tms_internal;` binds the clocking name to
|
||||
// something *else*, so the name on the left is the block's
|
||||
// own and names no signal of the enclosing scope
|
||||
// (IEEE 1800 §14.4). Only the value is a use.
|
||||
Some(value) => self.bind_expr(value, scope),
|
||||
None => {
|
||||
self.use_name(scope, &signal.name.text, signal.name.span, Target::InScope)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the nearest enclosing `module` or `interface` — what a
|
||||
/// clocking block records as its declared type. `None` at file scope, and
|
||||
/// inside a class, where a clocking block cannot stand anyway.
|
||||
fn enclosing_unit_name(&self, scope: ScopeId) -> Option<String> {
|
||||
let mut current = Some(scope);
|
||||
while let Some(id) = current {
|
||||
let s = self.scopes.get(id.0 as usize)?;
|
||||
if let Some(owner) = s.owner {
|
||||
let symbol = self.symbols.get(owner.0 as usize)?;
|
||||
if symbol.kind.is_instantiable() {
|
||||
return Some(symbol.name.clone());
|
||||
}
|
||||
}
|
||||
current = s.parent;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Classes
|
||||
// ------------------------------------------------------------------
|
||||
@@ -836,8 +1034,22 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
|
||||
// The method's home: the class scope when the class is in this file,
|
||||
// else the scope the definition is written in.
|
||||
let home = self.find_unit_scope(decl_scope, path).unwrap_or(decl_scope);
|
||||
// else a scope standing in for that class — empty, so every lookup
|
||||
// falls straight through it to the writing scope, but marked with the
|
||||
// class path as its `extends`, so a name nothing else binds is an
|
||||
// `InheritedCandidate` against the class rather than a `NotFound`.
|
||||
// That is what lets `task c2::update(...)` see `c2`'s properties when
|
||||
// `c2` is declared in another file: the workspace index finishes the
|
||||
// candidate through its member table.
|
||||
let home = match self.find_unit_scope(decl_scope, path) {
|
||||
Some(scope) => scope,
|
||||
None if path.is_empty() => decl_scope,
|
||||
None => {
|
||||
let stand_in = self.new_scope(ScopeKind::Class, decl_scope, span);
|
||||
self.scopes[stand_in.0 as usize].extends = Some(path.to_string());
|
||||
stand_in
|
||||
}
|
||||
};
|
||||
let sym = self.declare(home, name, kind, name_span, span);
|
||||
let body = self.new_scope(scope_kind, home, span);
|
||||
match sym {
|
||||
@@ -997,6 +1209,8 @@ impl<'a> Binder<'a> {
|
||||
StmtKind::Foreach { target, vars, body } => {
|
||||
let inner = self.new_scope(ScopeKind::Block, scope, stmt.span);
|
||||
self.bind_expr(target, scope);
|
||||
// A skipped dimension (`arr[, j]`) arrives as an empty name;
|
||||
// `declare` already ignores those, so it declares nothing.
|
||||
for v in vars {
|
||||
self.declare(inner, &v.text, SymbolKind::Var, v.span, v.span);
|
||||
}
|
||||
@@ -1027,6 +1241,10 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope),
|
||||
StmtKind::VarDecl(d) => self.bind_data_decl(d, stmt.span, scope),
|
||||
// A block-scoped type binds exactly as an item-level one does; the
|
||||
// scope it lands in is the enclosing block's, which is what
|
||||
// IEEE 1800 §6.18 asks for.
|
||||
StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope),
|
||||
StmtKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, stmt.span, scope)
|
||||
}
|
||||
@@ -1073,14 +1291,27 @@ impl<'a> Binder<'a> {
|
||||
fn bind_timing(&mut self, t: &'a TimingControl, scope: ScopeId) {
|
||||
match t {
|
||||
TimingControl::Delay(e) => self.bind_expr(e, scope),
|
||||
TimingControl::Event(SensList::List(items)) => {
|
||||
TimingControl::Event(list) => self.bind_sens_list(list, scope),
|
||||
}
|
||||
}
|
||||
|
||||
/// An `@( ... )` sensitivity list — a statement's timing control, and a
|
||||
/// clocking block's event, which is the same grammar.
|
||||
fn bind_sens_list(&mut self, list: &SensList, scope: ScopeId) {
|
||||
match list {
|
||||
SensList::List(items) => {
|
||||
for i in items {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
// `@(posedge clk iff enable)` reads `enable` as ordinarily
|
||||
// as it reads `clk`.
|
||||
if let Some(iff) = &i.iff {
|
||||
self.bind_expr(iff, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
TimingControl::Event(SensList::Star { .. }) => {}
|
||||
SensList::Star { .. } => {}
|
||||
// `@name;` without parens — the expression is an ordinary use.
|
||||
TimingControl::Event(SensList::Bare(e)) => self.bind_expr(e, scope),
|
||||
SensList::Bare(e) => self.bind_expr(e, scope),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1140,8 +1371,17 @@ impl<'a> Binder<'a> {
|
||||
self.bind_expr(msb, scope);
|
||||
self.bind_expr(lsb, scope);
|
||||
}
|
||||
// `a.b`: only the head is resolved (see the README) — except
|
||||
// `this.b` and `super.b`, whose member is the whole point.
|
||||
// `a.b`, `a.b.c`, `tb.dut.u_core.sig`: every link is bound —
|
||||
// the head as an ordinary use, each `.name` as a tail against the
|
||||
// type of what precedes it (`Target::MemberOf`) — because the
|
||||
// recursion below meets each `Member` node in turn. `this.b` and
|
||||
// `super.b` go to the enclosing class instead, and a spine that
|
||||
// starts at one of them stops there: `this.a.b` records `a` and
|
||||
// nothing more (`this` is not a name this crate binds, so there
|
||||
// is no head to walk from). An indexed or called head
|
||||
// (`a[i].b`, `f().b`) still resolves its own head and stops:
|
||||
// chasing those needs the element type of a container, which
|
||||
// this crate does not model (TODO.md §15).
|
||||
ExprKind::Member { base, name } => match &base.kind {
|
||||
ExprKind::Ident(head) if head == "this" => {
|
||||
self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember)
|
||||
@@ -1149,7 +1389,19 @@ impl<'a> Binder<'a> {
|
||||
ExprKind::Ident(head) if head == "super" => {
|
||||
self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember)
|
||||
}
|
||||
_ => self.bind_expr(base, scope),
|
||||
_ => {
|
||||
self.bind_expr(base, scope);
|
||||
if let Some((head, mids)) = spine(base) {
|
||||
// The tail's range is derived from the whole
|
||||
// expression's, so it is verified before use: a
|
||||
// spelling this crate cannot place costs a reference,
|
||||
// never a wrong span.
|
||||
let tail = self.exact_or_empty(member_tail(e.span, name), name);
|
||||
if !tail.is_empty() {
|
||||
self.use_member(scope, name, tail, Target::MemberOf { head, mids });
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ExprKind::Scope { base, name } => self.bind_scoped(base, name, e.span, scope),
|
||||
// The `#( ... )` is verbatim text this crate makes no claims
|
||||
@@ -1248,22 +1500,79 @@ impl<'a> Binder<'a> {
|
||||
self.use_name(scope, unit, unit_span, Target::Unit);
|
||||
self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string()));
|
||||
}
|
||||
// `bus_if.mp bus`, `virtual bus_if.mp vif` — the parser glues
|
||||
// an interface port's modport onto the type name (IEEE 1800
|
||||
// §25.4, §25.9). The interface is the type and the modport is
|
||||
// a **member** of it, so both halves are bound: the head as
|
||||
// any other type name, the tail against the interface's own
|
||||
// scope (or, cross-file, as `bus_if::mp` in the workspace's
|
||||
// member table). "The tail is where to bind them" —
|
||||
// `docs/features/ansi-first-port/README.md`.
|
||||
None => {
|
||||
// `bus_if.mp bus` — the parser glues an interface port's
|
||||
// modport onto the type name (IEEE 1800 §25.4). The
|
||||
// interface is the type; the modport is a member of it,
|
||||
// and this crate declares no symbol for a modport
|
||||
// (`ItemKind::Modport` is a leaf here), so the tail is
|
||||
// left unbound rather than recorded as a name that can
|
||||
// never resolve.
|
||||
let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface);
|
||||
let (name, modport) = match ty.name.split_once('.') {
|
||||
Some((iface, modport)) => (iface, Some(modport)),
|
||||
None => (ty.name.as_str(), None),
|
||||
};
|
||||
let ns = crate::scan::name_span(self.src, window, name);
|
||||
self.use_name(scope, name, ns, Target::Type);
|
||||
if let Some(modport) = modport {
|
||||
let tail = self.modport_tail(ns, modport);
|
||||
if !tail.is_empty() {
|
||||
self.use_member(
|
||||
scope,
|
||||
modport,
|
||||
tail,
|
||||
Target::TypeMember { unit: name.to_string() },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bind_dims(&ty.packed, scope);
|
||||
}
|
||||
|
||||
/// The byte range of the `mp` in a glued `bus_if.mp` type name, given the
|
||||
/// range the interface half was located at.
|
||||
///
|
||||
/// Derived rather than received — a `DataType` carries no spans at all —
|
||||
/// so it is verified twice over: the byte after the interface half must be
|
||||
/// a literal `.`, and the bytes after that must spell the modport exactly.
|
||||
/// A source that wrote the two apart, or a name a macro produced, costs the
|
||||
/// reference and never mislocates it.
|
||||
fn modport_tail(&self, iface: TextRange, modport: &str) -> TextRange {
|
||||
if iface.is_empty() || self.src.as_bytes().get(iface.end as usize) != Some(&b'.') {
|
||||
return TextRange::empty(iface.end);
|
||||
}
|
||||
let start = iface.end.saturating_add(1);
|
||||
let span = TextRange::new(start, start.saturating_add(modport.len() as u32));
|
||||
self.exact_or_empty(span, modport)
|
||||
}
|
||||
}
|
||||
|
||||
/// The chain of names written before a member access's tail: the plain
|
||||
/// identifier it starts at, and the members already selected from it, in the
|
||||
/// order they are written (`a.b.c`'s tail `c` gives `("a", ["b"])`).
|
||||
///
|
||||
/// `None` for a spine this crate cannot start walking — an index, a call, a
|
||||
/// cast, or `this`/`super`, which name no declaration to take a type from.
|
||||
fn spine(base: &Expr) -> Option<(String, Vec<String>)> {
|
||||
let mut mids = Vec::new();
|
||||
let mut current = base;
|
||||
loop {
|
||||
match ¤t.kind {
|
||||
ExprKind::Ident(name) if matches!(name.as_str(), "this" | "super") => return None,
|
||||
ExprKind::Ident(name) => {
|
||||
mids.reverse();
|
||||
return Some((name.clone(), mids));
|
||||
}
|
||||
ExprKind::Member { base, name } => {
|
||||
mids.push(name.clone());
|
||||
current = base;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte range of a member access's tail: the construct's last token, so
|
||||
@@ -1272,6 +1581,15 @@ fn member_tail(span: TextRange, name: &str) -> TextRange {
|
||||
TextRange::new(span.end.saturating_sub(name.len() as u32), span.end)
|
||||
}
|
||||
|
||||
/// The type name to record on a declaration: the name as written, minus the
|
||||
/// interface port's glued-on modport (`bus_if.mp bus` — the interface is the
|
||||
/// type, exactly as [`Binder::bind_data_type`] reads it). `None` for a
|
||||
/// built-in type, whose keyword names no declaration to look members up in.
|
||||
fn type_name_of(ty: &DataType) -> Option<String> {
|
||||
let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface);
|
||||
(!name.is_empty() && !is_keyword(name)).then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`).
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
|
||||
@@ -20,13 +20,37 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::model::SymbolKind;
|
||||
use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact};
|
||||
use crate::workspace::{
|
||||
Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, ReferenceFact,
|
||||
SiteFact, Utf16Pos, Utf16Range,
|
||||
};
|
||||
|
||||
/// The version of the encoding below. Bump it on **any** change to what a
|
||||
/// record holds or to how it is written: a store stamped with another number
|
||||
/// is discarded whole, which is the only way a reader can be sure it is not
|
||||
/// reading last month's field order as this month's.
|
||||
pub const FACTS_FORMAT: u32 = 3;
|
||||
///
|
||||
/// 5 → 6 (2026-09-01, class-member-access): the field *layout* is unchanged,
|
||||
/// but the reference census a record carries is not — `head.member` tails and
|
||||
/// names inside an out-of-class method body are references now, so a store
|
||||
/// written by an older build would silently hold fewer `R` entries than the
|
||||
/// same file produces today, and half the workspace's postings would be
|
||||
/// missing depending on which files happened to be cached.
|
||||
///
|
||||
/// 6 → 7 (2026-09-01, class-member-access round 2): the layout **and** the
|
||||
/// census. Every declaration carries its declared type name (what a member
|
||||
/// chain `a.b.c` hops through across files), and an external reference
|
||||
/// carries the base class an inherited miss was recorded against (what gives
|
||||
/// `this.x` an index posting) — two new fields, plus the chain tails and
|
||||
/// instance-head tails that are now references at all.
|
||||
///
|
||||
/// 7 → 8 (2026-09-01, interface-semantics): three new kind names —
|
||||
/// `interface`, `modport`, `clocking` — which an older reader has no name for
|
||||
/// at all, and once more a wider census. An interface exports its signals now,
|
||||
/// a modport and a named clocking block are declarations, and every name
|
||||
/// written inside either is a reference, so a store written by an older build
|
||||
/// holds a strictly smaller `M` and `R` group for the same file.
|
||||
pub const FACTS_FORMAT: u32 = 8;
|
||||
|
||||
impl FileFacts {
|
||||
/// These facts as one line's worth of fields, tab-separated.
|
||||
@@ -47,6 +71,10 @@ impl FileFacts {
|
||||
out.tag("U", self.units.len());
|
||||
for decl in &self.units {
|
||||
out.decl(decl);
|
||||
// Only the `U` group carries client positions, so the `M` group
|
||||
// below stays exactly as wide as it was — see
|
||||
// `vlog_semantic::DeclPositions` for why members are left out.
|
||||
out.positions(&decl.lines.positions.unwrap_or_default());
|
||||
}
|
||||
out.tag("M", self.members.len());
|
||||
for (unit, decl) in &self.members {
|
||||
@@ -58,6 +86,14 @@ impl FileFacts {
|
||||
out.text(module);
|
||||
out.site(&site.owner);
|
||||
out.range(site.site_span);
|
||||
out.num(site.instances.len() as u32);
|
||||
for instance in &site.instances {
|
||||
out.text(&instance.name);
|
||||
out.range(instance.name_span);
|
||||
out.range(instance.span);
|
||||
out.utf16(instance.name_positions);
|
||||
out.utf16(instance.positions);
|
||||
}
|
||||
}
|
||||
out.tag("S", self.subclasses.len());
|
||||
for (base, subclass) in &self.subclasses {
|
||||
@@ -89,7 +125,9 @@ impl FileFacts {
|
||||
}
|
||||
let mut units = Vec::new();
|
||||
for _ in 0..input.tag("U")? {
|
||||
units.push(input.decl()?);
|
||||
let mut decl = input.decl()?;
|
||||
decl.lines.positions = Some(input.positions()?);
|
||||
units.push(decl);
|
||||
}
|
||||
let mut members = Vec::new();
|
||||
for _ in 0..input.tag("M")? {
|
||||
@@ -99,7 +137,18 @@ impl FileFacts {
|
||||
for _ in 0..input.tag("I")? {
|
||||
let module = input.text()?;
|
||||
let owner = input.site()?;
|
||||
instantiations.push((module, SiteFact { owner, site_span: input.range()? }));
|
||||
let site_span = input.range()?;
|
||||
let mut instances = Vec::new();
|
||||
for _ in 0..input.num()? {
|
||||
instances.push(InstanceOccurrence {
|
||||
name: input.text()?,
|
||||
name_span: input.range()?,
|
||||
span: input.range()?,
|
||||
name_positions: input.utf16()?,
|
||||
positions: input.utf16()?,
|
||||
});
|
||||
}
|
||||
instantiations.push((module, SiteFact { owner, site_span, instances }));
|
||||
}
|
||||
let mut subclasses = Vec::new();
|
||||
for _ in 0..input.tag("S")? {
|
||||
@@ -185,6 +234,7 @@ impl Writer {
|
||||
self.field();
|
||||
self.out.push_str(kind_name(decl.kind));
|
||||
self.range(decl.name_span);
|
||||
self.range(decl.decl_span);
|
||||
// The detail span is written unconditionally — `0 0` for the `None`
|
||||
// every ordinary declaration has — so the stream stays flat. Adding it
|
||||
// changed what a record holds, so `FACTS_FORMAT` is bumped and a store
|
||||
@@ -197,6 +247,33 @@ impl Writer {
|
||||
self.num(0);
|
||||
}
|
||||
}
|
||||
// The declaration's lines, on the same unconditional-pair rule: the
|
||||
// name's line, then the detail span's or `0` for the `None` above.
|
||||
// `FACTS_FORMAT` is bumped for these two fields, so a store written
|
||||
// before them is discarded rather than read short by two
|
||||
// (`docs/features/hover-line-index/README.md`).
|
||||
self.num(decl.lines.name);
|
||||
self.num(decl.lines.detail.unwrap_or(0));
|
||||
// The declared type, or the empty string for the `None` most
|
||||
// declarations have — a type name is never empty, so the two cannot be
|
||||
// confused. One more field per declaration, and the `FACTS_FORMAT`
|
||||
// bump that goes with it
|
||||
// (`docs/features/class-member-access/README.md`, round 2).
|
||||
self.text(decl.type_name.as_deref().unwrap_or(""));
|
||||
}
|
||||
|
||||
/// One [`Utf16Range`]: four numbers, in the order a reader takes them.
|
||||
fn utf16(&mut self, range: Utf16Range) {
|
||||
self.num(range.start.line);
|
||||
self.num(range.start.character);
|
||||
self.num(range.end.line);
|
||||
self.num(range.end.character);
|
||||
}
|
||||
|
||||
/// A file-scope declaration's two client ranges, written after its decl.
|
||||
fn positions(&mut self, positions: &DeclPositions) {
|
||||
self.utf16(positions.name);
|
||||
self.utf16(positions.decl);
|
||||
}
|
||||
|
||||
fn site(&mut self, site: &DeclSite) {
|
||||
@@ -240,10 +317,14 @@ impl Writer {
|
||||
self.range(*definition);
|
||||
self.range(*occurrence);
|
||||
}
|
||||
ReferenceFact::External { name, paths, occurrence } => {
|
||||
ReferenceFact::External { name, base, paths, occurrence } => {
|
||||
self.field();
|
||||
self.out.push('e');
|
||||
self.text(name);
|
||||
// The base class, or the empty string for the `None` every
|
||||
// ordinary external reference has — on the same rule as a
|
||||
// declaration's type name above.
|
||||
self.text(base.as_deref().unwrap_or(""));
|
||||
self.num(paths.len() as u32);
|
||||
for path in paths {
|
||||
self.text(path);
|
||||
@@ -311,13 +392,40 @@ impl<'a> Reader<'a> {
|
||||
let name = self.text()?;
|
||||
let kind = kind_of(self.next()?)?;
|
||||
let name_span = self.range()?;
|
||||
let decl_span = self.range()?;
|
||||
// The mirror of the encoder's unconditional pair: `(0, 0)` is the
|
||||
// `None`, and a real span can never be, because a declaration's span
|
||||
// is never empty.
|
||||
let start = self.num()?;
|
||||
let end = self.num()?;
|
||||
let detail_span = (start != 0 || end != 0).then_some(TextRange::new(start, end));
|
||||
Some(Decl { name, name_span, kind, detail_span })
|
||||
// A line is 1-based, so `0` is the `None` here too — and a detail line
|
||||
// is present exactly when a detail span is, which a record written by
|
||||
// this format always agrees with.
|
||||
let name_line = self.num()?;
|
||||
let detail_line = self.num()?;
|
||||
let type_name = self.text()?;
|
||||
let type_name = (!type_name.is_empty()).then_some(type_name);
|
||||
// Client positions are not one of a declaration's shared fields: a
|
||||
// caller reading the `U` group takes them from `positions()` next, and
|
||||
// a member has none at all (`vlog_semantic::DeclPositions`).
|
||||
let lines = DeclLines {
|
||||
name: name_line,
|
||||
detail: (detail_line != 0).then_some(detail_line),
|
||||
positions: None,
|
||||
};
|
||||
Some(Decl { name, name_span, decl_span, kind, detail_span, lines, type_name })
|
||||
}
|
||||
|
||||
fn utf16(&mut self) -> Option<Utf16Range> {
|
||||
Some(Utf16Range {
|
||||
start: Utf16Pos { line: self.num()?, character: self.num()? },
|
||||
end: Utf16Pos { line: self.num()?, character: self.num()? },
|
||||
})
|
||||
}
|
||||
|
||||
fn positions(&mut self) -> Option<DeclPositions> {
|
||||
Some(DeclPositions { name: self.utf16()?, decl: self.utf16()? })
|
||||
}
|
||||
|
||||
fn site(&mut self) -> Option<DeclSite> {
|
||||
@@ -359,12 +467,18 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
"e" => {
|
||||
let name = self.text()?;
|
||||
let base = self.text()?;
|
||||
let count = self.num()? as usize;
|
||||
let mut paths = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
paths.push(self.text()?);
|
||||
}
|
||||
Some(ReferenceFact::External { name, paths, occurrence: self.range()? })
|
||||
Some(ReferenceFact::External {
|
||||
name,
|
||||
base: (!base.is_empty()).then_some(base),
|
||||
paths,
|
||||
occurrence: self.range()?,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
@@ -398,6 +512,9 @@ fn unescape(field: &str) -> Option<String> {
|
||||
fn kind_name(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Module => "module",
|
||||
SymbolKind::Interface => "interface",
|
||||
SymbolKind::Modport => "modport",
|
||||
SymbolKind::Clocking => "clocking",
|
||||
SymbolKind::Package => "package",
|
||||
SymbolKind::Port => "port",
|
||||
SymbolKind::Net => "net",
|
||||
@@ -421,6 +538,9 @@ fn kind_name(kind: SymbolKind) -> &'static str {
|
||||
fn kind_of(name: &str) -> Option<SymbolKind> {
|
||||
Some(match name {
|
||||
"module" => SymbolKind::Module,
|
||||
"interface" => SymbolKind::Interface,
|
||||
"modport" => SymbolKind::Modport,
|
||||
"clocking" => SymbolKind::Clocking,
|
||||
"package" => SymbolKind::Package,
|
||||
"port" => SymbolKind::Port,
|
||||
"net" => SymbolKind::Net,
|
||||
@@ -451,6 +571,9 @@ mod tests {
|
||||
fn every_symbol_kind_has_a_name_and_only_its_own() {
|
||||
let kinds = [
|
||||
SymbolKind::Module,
|
||||
SymbolKind::Interface,
|
||||
SymbolKind::Modport,
|
||||
SymbolKind::Clocking,
|
||||
SymbolKind::Package,
|
||||
SymbolKind::Port,
|
||||
SymbolKind::Net,
|
||||
|
||||
@@ -31,9 +31,10 @@ pub use model::{
|
||||
SymbolId, SymbolKind,
|
||||
};
|
||||
pub use workspace::{
|
||||
index_order, resolve_external, DeclSite, Def, Definition, DefinitionKey, ExternalResolutions,
|
||||
ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge,
|
||||
InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
|
||||
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
|
||||
DefinitionKey, ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder,
|
||||
IndexCounts, InheritanceEdge, InstanceOccurrence, InstantiationEdge, ReferenceSite, Utf16Pos,
|
||||
Utf16Range, WorkspaceIndex, WorkspaceSymbol,
|
||||
};
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -75,11 +76,18 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
||||
|
||||
let mut references = Vec::with_capacity(pending.len());
|
||||
for p in &pending {
|
||||
// A pending use pass two has nothing to say about is not a reference
|
||||
// at all — the member tail of `a.b` where `a`'s type is not one this
|
||||
// crate can look members up in (`resolve::member_of`). Every other
|
||||
// target always resolves, `NotFound` included.
|
||||
let Some(resolution) = resolve::resolve(&scopes, &symbols, p) else {
|
||||
continue;
|
||||
};
|
||||
references.push(Reference {
|
||||
name: p.name.clone(),
|
||||
name_span: p.name_span,
|
||||
scope: p.scope,
|
||||
resolution: resolve::resolve(&scopes, &symbols, p),
|
||||
resolution,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,24 @@ pub struct ReferenceId(pub u32);
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SymbolKind {
|
||||
Module,
|
||||
/// An `interface … endinterface`. The parser models it as a
|
||||
/// [`vlog_parser::ast::Module`] with a different keyword, and everything an
|
||||
/// instantiation, a connection or a hierarchical name may do to a module it
|
||||
/// may do to an interface — so this kind travels beside `Module` almost
|
||||
/// everywhere ([`SymbolKind::is_instantiable`]). What it buys is the two
|
||||
/// places the two really differ: an editor label that says "interface", and
|
||||
/// an export rule that lets another file reach an interface's *signals*,
|
||||
/// which is what a `virtual bus_if vif; vif.sig` needs and what a module
|
||||
/// never grants. `program … endprogram` is still a `Module` — see
|
||||
/// `docs/features/interface-semantics/README.md`.
|
||||
Interface,
|
||||
/// A `modport mp (...)` inside an interface (IEEE 1800 §25.5): a named view
|
||||
/// of the interface's signals.
|
||||
Modport,
|
||||
/// A **named** `clocking cb @(...); … endclocking` block (IEEE 1800 §14.3).
|
||||
/// An anonymous `default clocking @(...)` declares no name and so no
|
||||
/// symbol.
|
||||
Clocking,
|
||||
Package,
|
||||
/// A module port, from either header style.
|
||||
Port,
|
||||
@@ -47,6 +65,18 @@ pub enum SymbolKind {
|
||||
Class,
|
||||
}
|
||||
|
||||
impl SymbolKind {
|
||||
/// True for the kinds an *instantiation* may name: a `module` and an
|
||||
/// `interface`. An interface is instantiated exactly as a module is
|
||||
/// (`bus_if u_bus ();`), connected exactly as a module is, and shows up in
|
||||
/// the design hierarchy and the code lens on exactly the same terms — so
|
||||
/// every filter that used to spell `kind == Module` for "a thing you can
|
||||
/// instantiate" asks this instead, and answers what it always did.
|
||||
pub fn is_instantiable(self) -> bool {
|
||||
matches!(self, SymbolKind::Module | SymbolKind::Interface)
|
||||
}
|
||||
}
|
||||
|
||||
/// A declaration: a name bound in one scope.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Symbol {
|
||||
@@ -64,6 +94,17 @@ pub struct Symbol {
|
||||
/// width — while `name_span`/`decl_span` stay in the header. `None` for
|
||||
/// every declaration that is complete where it is named.
|
||||
pub detail_span: Option<TextRange>,
|
||||
/// The declared type **as written**, for the declarations that have one:
|
||||
/// `c1` for `c1 in_item`, `pkg::c1` for a qualified spelling,
|
||||
/// `clk_rst_if` for `virtual clk_rst_if vif`. `None` for a built-in type
|
||||
/// (`logic`, `bit`, `int` — a keyword names no declaration) and for every
|
||||
/// declaration that has no type at all (a module, a block label, an
|
||||
/// instance). It is a *name*, not a resolved type: what member access
|
||||
/// (`handle.member`) needs is the spelling to look the type up with, and
|
||||
/// resolving it is `resolve.rs`'s business, on the same lexical chain the
|
||||
/// type reference itself takes. See
|
||||
/// `docs/features/class-member-access/README.md`.
|
||||
pub type_name: Option<String>,
|
||||
/// The scope the name is bound in.
|
||||
pub scope: ScopeId,
|
||||
/// The scope this declaration opens, for the kinds that open one
|
||||
@@ -89,12 +130,13 @@ pub enum Resolution {
|
||||
/// `extends` could: `base` is the base-class path as written
|
||||
/// (`uvm_component`, `pkg::base`), and `paths` are the import paths the
|
||||
/// lexical walk collected — plus the use's own name when it was written in
|
||||
/// a type position — any of which could supply it. Nothing chases `base`,
|
||||
/// in this file or out of it; the
|
||||
/// workspace overlay may answer from `paths` without displacing what this
|
||||
/// says, because a resolved base would have been `Resolved` already. See
|
||||
/// `docs/features/class-semantics/README.md` and
|
||||
/// `docs/features/overlay-promotion/README.md`.
|
||||
/// a type position — any of which could supply it. The single-file layer
|
||||
/// never chases `base`; the workspace overlay now does, upward through
|
||||
/// [`crate::WorkspaceIndex::base_of`] after its `paths` miss, without
|
||||
/// displacing what this says — a base resolved *in this file* would have
|
||||
/// been `Resolved` already. See `docs/features/class-semantics/README.md`,
|
||||
/// `docs/features/overlay-promotion/README.md` and
|
||||
/// `docs/features/class-member-access/README.md`.
|
||||
InheritedCandidate { base: String, paths: Vec<String> },
|
||||
/// Nothing in this file binds it and no external unit could: a member of a
|
||||
/// package this file fully declares, a `.port` of a module it declares, a
|
||||
@@ -141,6 +183,12 @@ impl Reference {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ScopeKind {
|
||||
File,
|
||||
/// A `module`, an `interface` or a `program` body. One kind for all three
|
||||
/// because a scope's kind governs *lookup rules*, and those are identical:
|
||||
/// names bind in declaration order, imports are consulted, the enclosing
|
||||
/// scope is the file. What differs between a module and an interface is
|
||||
/// which of its members another file may reach, and that is a property of
|
||||
/// the declaration ([`SymbolKind::Interface`]), not of the scope.
|
||||
Module,
|
||||
Package,
|
||||
Function,
|
||||
@@ -215,6 +263,12 @@ impl Scope {
|
||||
pub fn lookup_local(&self, name: &str) -> Option<SymbolId> {
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
|
||||
/// The `extends` path this class scope was written with, as written.
|
||||
/// `None` for every other scope, and for a class that extends nothing.
|
||||
pub fn extends(&self) -> Option<&str> {
|
||||
self.extends.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
/// One node of the outline tree returned by
|
||||
|
||||
@@ -8,18 +8,27 @@ use crate::bind::{Pending, Target};
|
||||
use crate::model::{Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind};
|
||||
|
||||
/// Resolve one pending use against the finished scope tree.
|
||||
pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Resolution {
|
||||
match &p.target {
|
||||
///
|
||||
/// `None` means **record no reference at all**: the targets that can arrive
|
||||
/// here with nothing to say are [`Target::MemberOf`] (the tail of `a.b`),
|
||||
/// [`Target::InScope`] (a modport or clocking name) and [`Target::TypeMember`]
|
||||
/// (the `mp` of `bus_if.mp`) — each answered only when this crate can say
|
||||
/// something honest about it. Every other target always produces a resolution,
|
||||
/// `NotFound` included, exactly as it did before.
|
||||
pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Option<Resolution> {
|
||||
Some(match &p.target {
|
||||
// An end label names the construct it closes; the binder already knew
|
||||
// which symbol that is, so there is nothing to look up.
|
||||
Target::Declaration(id) => Resolution::Resolved(*id),
|
||||
Target::Lexical => lexical(scopes, p.scope, &p.name, false),
|
||||
Target::Type => lexical(scopes, p.scope, &p.name, true),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Package),
|
||||
Target::Module => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Module),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, is_package),
|
||||
// An interface is instantiated, connected and hierarchically named
|
||||
// exactly as a module is, so both kinds answer here.
|
||||
Target::Module => named_at_file_scope(scopes, symbols, &p.name, is_instantiable),
|
||||
Target::Unit => unit(scopes, symbols, p.scope, &p.name),
|
||||
Target::UnitMember(unit) => unit_member(scopes, symbols, p.scope, unit, &p.name),
|
||||
Target::Port(module) => match owning_scope(scopes, symbols, module, SymbolKind::Module) {
|
||||
Target::Port(module) => match owning_scope(scopes, symbols, module, is_instantiable) {
|
||||
Some(scope) => match scopes[scope.0 as usize].lookup_local(&p.name) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::NotFound,
|
||||
@@ -27,11 +36,335 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Reso
|
||||
// The port list lives in whatever file declares the module.
|
||||
None => Resolution::ExternalCandidate { paths: vec![module.clone()] },
|
||||
},
|
||||
Target::ThisMember => this_member(scopes, p.scope, &p.name),
|
||||
Target::InScope => return in_scope(scopes, p.scope, &p.name),
|
||||
Target::TypeMember { unit } => return type_member(scopes, symbols, p.scope, unit, &p.name),
|
||||
Target::MemberOf { head, mids } => {
|
||||
return member_of(scopes, symbols, p.scope, head, mids, &p.name)
|
||||
}
|
||||
Target::ThisMember => this_member(scopes, symbols, p.scope, &p.name),
|
||||
Target::SuperMember => super_member(scopes, p.scope),
|
||||
})
|
||||
}
|
||||
|
||||
/// A name looked up **only** in the scope it is written in, never outward: a
|
||||
/// modport's port list and a clocking block's signal list, both of which name
|
||||
/// members of the interface (or module) they are written in and nothing else.
|
||||
///
|
||||
/// `None` — no reference recorded at all — when that scope does not bind the
|
||||
/// name. The construct is written here whole, so no other file can supply the
|
||||
/// name; and walking outward to find *something* is exactly the wrong answer
|
||||
/// this crate refuses to give, because a file-scope `other_if` is not the
|
||||
/// signal `modport mp (input other_if)` was meant to name.
|
||||
fn in_scope(scopes: &[Scope], scope: ScopeId, name: &str) -> Option<Resolution> {
|
||||
scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved)
|
||||
}
|
||||
|
||||
/// The `mp` of a glued `bus_if.mp` type name: a member of the *type*, looked
|
||||
/// up on exactly the terms [`member_of`]'s last link is.
|
||||
///
|
||||
/// The interface's scope when this file declares it — a hit is the modport's
|
||||
/// declaration, a miss is nothing at all, because this file has answered what
|
||||
/// `bus_if` is and it holds no such modport. A name this file declares as
|
||||
/// something without members ([`TypeHere::NotAUnit`]) is nothing either. Only a
|
||||
/// name **nothing here declares** reaches the workspace, as the one composed
|
||||
/// path `follow_one` reads back as `member(bus_if, mp)`.
|
||||
fn type_member(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
unit: &str,
|
||||
name: &str,
|
||||
) -> Option<Resolution> {
|
||||
match type_here(scopes, symbols, from, unit) {
|
||||
TypeHere::Scope(scope) => {
|
||||
scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved)
|
||||
}
|
||||
TypeHere::NotAUnit => None,
|
||||
TypeHere::Absent => Some(Resolution::ExternalCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(unit))],
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `member` of `head.mids….member`: the head is resolved on the ordinary
|
||||
/// lexical chain, its **declared type** is resolved on the same chain, each
|
||||
/// name in `mids` is looked up in that type's scope (and up its `extends`
|
||||
/// chain) to give the next type, and the tail is looked up in the last one.
|
||||
///
|
||||
/// `None` — no reference recorded at all — whenever this crate has nothing to
|
||||
/// say, which is the shape every pre-2026-09-01 hierarchical name had: a head
|
||||
/// nothing in this file declares, a head that is neither typed nor a unit a
|
||||
/// hierarchical name may start at (a `logic [3:0]`, a block label, a
|
||||
/// built-in), a type **this file declares** as something with no members to
|
||||
/// search (a struct or enum typedef — see [`TypeHere::NotAUnit`]), or a
|
||||
/// member genuinely absent from a class this file declares whole. Recording a
|
||||
/// `NotFound` for those would move `reference_at` under every `a.b` in the
|
||||
/// corpus to answer "a name that resolves to nothing", which is a different
|
||||
/// claim than "not modelled". **A link that cannot be resolved honestly stops
|
||||
/// the chain**: nothing is recorded for it or for anything after it.
|
||||
///
|
||||
/// Only a type name **nothing in this file declares** reaches the workspace.
|
||||
/// The distinction is the whole of QA finding 1 (2026-09-01): a `bus_t` this
|
||||
/// file declares as a struct typedef must not be asked about in a workspace
|
||||
/// where some unrelated file declares a *class* `bus_t`, or `s.field` lands on
|
||||
/// a stranger's property — a wrong answer, where recording nothing is merely a
|
||||
/// missing one.
|
||||
fn member_of(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
head: &str,
|
||||
mids: &[String],
|
||||
name: &str,
|
||||
) -> Option<Resolution> {
|
||||
let Resolution::Resolved(id) = lexical(scopes, from, head, false) else {
|
||||
return None;
|
||||
};
|
||||
let mut here = link_type(scopes, symbols, id)?;
|
||||
for mid in mids {
|
||||
here = match here {
|
||||
Link::Scope(scope) => match member_in_chain(scopes, symbols, scope, mid) {
|
||||
Ok(id) => link_type(scopes, symbols, id)?,
|
||||
// The chain leaves this file at a base class: everything from
|
||||
// here on is one composed path for the workspace to walk.
|
||||
Err(Some(base)) => Link::Path(format!("{}::{mid}", last_segment(&base))),
|
||||
Err(None) => return None,
|
||||
},
|
||||
// Already outside this file — each further name is one more
|
||||
// segment of the path `follow_one` walks member by member.
|
||||
Link::Path(path) => Link::Path(format!("{path}::{mid}")),
|
||||
};
|
||||
}
|
||||
match here {
|
||||
Link::Scope(scope) => match member_in_chain(scopes, symbols, scope, name) {
|
||||
Ok(id) => Some(Resolution::Resolved(id)),
|
||||
// The chain leaves this file: the base, plus the path the
|
||||
// workspace's member table answers it by. Only a **direct**
|
||||
// `head.member` reports the base — for a longer chain the base is
|
||||
// the owner of an earlier link, not of this name, and claiming it
|
||||
// here would send the overlay's inheritance chase after the wrong
|
||||
// class.
|
||||
Err(Some(base)) if mids.is_empty() => Some(Resolution::InheritedCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(&base))],
|
||||
base,
|
||||
}),
|
||||
Err(Some(base)) => Some(Resolution::ExternalCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(&base))],
|
||||
}),
|
||||
// A class this file declares whole, with no such member: nothing
|
||||
// to say that `NotFound` would not overstate.
|
||||
Err(None) => None,
|
||||
},
|
||||
// A type this file does not declare: the workspace's member table is
|
||||
// the only layer that can say. The last `::` segment names the unit,
|
||||
// the spelling `follow_one` turns back into `member(unit, name)`.
|
||||
Link::Path(path) => {
|
||||
Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the next `.name` of a chain is looked up in: a scope this file holds,
|
||||
/// or the path the workspace answers by.
|
||||
enum Link {
|
||||
Scope(ScopeId),
|
||||
/// The unit name, plus any member names already selected from it —
|
||||
/// `pkt_t`, `pkt_t::hdr` — in the spelling [`crate::WorkspaceIndex`]'s
|
||||
/// `follow_one` walks.
|
||||
Path(String),
|
||||
}
|
||||
|
||||
/// Where the members of one declaration live: its **declared type**'s scope
|
||||
/// when this file declares that type, else the workspace path for it.
|
||||
///
|
||||
/// A declaration with no declared type at all can still be a chain's head when
|
||||
/// it opens a scope a `.` may name members of — a module or an interface,
|
||||
/// which is how `tb.dut.u_core.sig` reaches into `tb` (IEEE 1800 §23.6: a
|
||||
/// top-level module name is the root of a hierarchical path), or a class,
|
||||
/// where the answer can only ever be that very class's own member. Everything
|
||||
/// else — a `logic` net, a genvar, a block label, a package — answers `None`,
|
||||
/// which stops the chain.
|
||||
fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<Link> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
let Some(type_name) = symbol.type_name.as_deref() else {
|
||||
return member_scope(symbols, id).map(Link::Scope);
|
||||
};
|
||||
// The type name is looked up where the declaration is written, by the same
|
||||
// walk the type *reference* itself took.
|
||||
match type_here(scopes, symbols, symbol.scope, type_name) {
|
||||
TypeHere::Scope(scope) => Some(Link::Scope(scope)),
|
||||
// This file says what the type is, and it is not something with
|
||||
// members. No other file can override that, so nothing is recorded.
|
||||
TypeHere::NotAUnit => None,
|
||||
TypeHere::Absent => Some(Link::Path(last_segment(type_name).to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` in a class (or interface) scope this file holds, then up its
|
||||
/// `extends` chain as far as this file goes.
|
||||
///
|
||||
/// `Ok` is the declaration; `Err(Some(base))` means the chain left this file
|
||||
/// at `base`, which the workspace index chases further
|
||||
/// ([`crate::WorkspaceIndex::base_of`]); `Err(None)` means the chain ended
|
||||
/// here — every class on it is declared in this file and none of them binds
|
||||
/// the name.
|
||||
fn member_in_chain(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
scope: ScopeId,
|
||||
name: &str,
|
||||
) -> Result<SymbolId, Option<String>> {
|
||||
// `extends` can be written in a cycle; the visited set is what makes this
|
||||
// terminate on `class a extends b; class b extends a;`.
|
||||
let mut visited = Vec::new();
|
||||
let mut current = scope;
|
||||
loop {
|
||||
if visited.contains(¤t) {
|
||||
return Err(None);
|
||||
}
|
||||
visited.push(current);
|
||||
if let Some(id) = scopes[current.0 as usize].lookup_local(name) {
|
||||
return Ok(id);
|
||||
}
|
||||
let Some(base) = &scopes[current.0 as usize].extends else {
|
||||
return Err(None);
|
||||
};
|
||||
match type_here(scopes, symbols, enclosing(scopes, current), base) {
|
||||
TypeHere::Scope(next) => current = next,
|
||||
// Whether the base is absent from this file or declared here as
|
||||
// something without a member scope — a `typedef class base;`
|
||||
// forward declaration is exactly that — it is the workspace's to
|
||||
// finish. `extends` names a class by the grammar's own claim, so
|
||||
// asking the index about it is not the guess `member_of`'s
|
||||
// `NotAUnit` arm refuses to make about a data declaration's type.
|
||||
TypeHere::NotAUnit | TypeHere::Absent => return Err(Some(base.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The scope enclosing one — a class's base is resolved from *outside* it, as
|
||||
/// `extends` itself is (class-semantics rule 5).
|
||||
fn enclosing(scopes: &[Scope], scope: ScopeId) -> ScopeId {
|
||||
scopes[scope.0 as usize].parent.unwrap_or(ScopeId(0))
|
||||
}
|
||||
|
||||
/// What **this file** says about a type name — the three-way answer
|
||||
/// `handle.member` needs, where a two-way one is a wrong answer waiting to
|
||||
/// happen (QA finding 1, 2026-09-01).
|
||||
enum TypeHere {
|
||||
/// Declared here as something with members to look in: a class, a module,
|
||||
/// or an interface — so `virtual clk_rst_if vif; vif.clk` reaches the
|
||||
/// interface's signals.
|
||||
Scope(ScopeId),
|
||||
/// Declared here as something else — a struct, enum or alias `typedef`, a
|
||||
/// parameter, a variable shadowing the name. This file has *answered* the
|
||||
/// question "what is this type", and the answer is one with no members
|
||||
/// this crate models (struct fields are round 2, `docs/topo.md` §2.9-13).
|
||||
/// No other file can override that answer, so the workspace is never
|
||||
/// asked — which is what keeps a locally-declared `bus_t` from being
|
||||
/// looked up in a stranger's class of the same name.
|
||||
NotAUnit,
|
||||
/// Nothing in this file declares the name at all — the only case the
|
||||
/// workspace's tables can honestly answer.
|
||||
Absent,
|
||||
}
|
||||
|
||||
/// Look a written type name up in this file: on the lexical chain for its
|
||||
/// first segment, then descended segment by segment for `pkg::cls`.
|
||||
///
|
||||
/// The first segment goes through [`lexical`] itself — the same walk, the same
|
||||
/// shadowing, the same import precedence the type *reference* took — so what
|
||||
/// this says and what go-to-definition on the type name answers cannot
|
||||
/// disagree. A qualified path then descends only through containers: a
|
||||
/// package, class or module scope. A segment missing from a container this
|
||||
/// file holds is [`TypeHere::NotAUnit`], not [`TypeHere::Absent`] — the
|
||||
/// container is fully known here, the same reason [`unit_member`] answers a
|
||||
/// missing package member with `NotFound` rather than sending it to the
|
||||
/// workspace (vlog-semantic rule 6).
|
||||
///
|
||||
/// A name landing on a `typedef` **that aliases another type** is followed to
|
||||
/// what it aliases (`typedef c1 my_t;` → `c1`), from the typedef's own scope,
|
||||
/// as many hops as are written; `seen` is what makes a chain of aliases that
|
||||
/// meets itself terminate. A typedef with no aliased type — a `struct`, an
|
||||
/// `enum`, an alias of a built-in, a `typedef class c;` forward declaration —
|
||||
/// stays [`TypeHere::NotAUnit`] exactly as it was: this file has answered what
|
||||
/// the type is, and the answer has no members this crate models.
|
||||
fn type_here(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, path: &str) -> TypeHere {
|
||||
type_here_seen(scopes, symbols, from, path, &mut Vec::new())
|
||||
}
|
||||
|
||||
fn type_here_seen(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
path: &str,
|
||||
seen: &mut Vec<SymbolId>,
|
||||
) -> TypeHere {
|
||||
let mut segments = path.split("::");
|
||||
let Some(head) = segments.next() else {
|
||||
return TypeHere::Absent;
|
||||
};
|
||||
let Resolution::Resolved(mut current) = lexical(scopes, from, head, false) else {
|
||||
return TypeHere::Absent;
|
||||
};
|
||||
for segment in segments {
|
||||
let Some(scope) = container_scope(symbols, current) else {
|
||||
return TypeHere::NotAUnit;
|
||||
};
|
||||
match scopes.get(scope.0 as usize).and_then(|s| s.lookup_local(segment)) {
|
||||
Some(next) => current = next,
|
||||
None => return TypeHere::NotAUnit,
|
||||
}
|
||||
}
|
||||
if let Some(scope) = member_scope(symbols, current) {
|
||||
return TypeHere::Scope(scope);
|
||||
}
|
||||
match alias_target(symbols, current) {
|
||||
Some((aliased, written_in)) if !seen.contains(¤t) => {
|
||||
seen.push(current);
|
||||
type_here_seen(scopes, symbols, written_in, &aliased, seen)
|
||||
}
|
||||
_ => TypeHere::NotAUnit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The type a `typedef` aliases, and the scope the alias is written in —
|
||||
/// `None` for every other declaration, and for a typedef whose target names no
|
||||
/// declaration at all (a `struct` or `enum` body, an alias of a built-in, a
|
||||
/// forward class declaration).
|
||||
fn alias_target(symbols: &[Symbol], id: SymbolId) -> Option<(String, ScopeId)> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
if symbol.kind != SymbolKind::Typedef {
|
||||
return None;
|
||||
}
|
||||
Some((symbol.type_name.clone()?, symbol.scope))
|
||||
}
|
||||
|
||||
/// The scope a symbol opens when it is a container a type path may pass
|
||||
/// *through*: a package, a class or a module.
|
||||
fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
matches!(symbol.kind, SymbolKind::Package | SymbolKind::Class)
|
||||
.then_some(symbol.child_scope)
|
||||
.or_else(|| symbol.kind.is_instantiable().then_some(symbol.child_scope))?
|
||||
}
|
||||
|
||||
/// The scope a symbol opens when a `.` may name its members: a class, a
|
||||
/// module, or an interface — which is what makes `vif.sig` and `u.internal`
|
||||
/// reach into one. A package is a container to pass through, never a thing a
|
||||
/// handle can be.
|
||||
fn member_scope(symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
(symbol.kind == SymbolKind::Class || symbol.kind.is_instantiable())
|
||||
.then_some(symbol.child_scope)?
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`) —
|
||||
/// the segment the workspace's member table is keyed by.
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
}
|
||||
|
||||
/// Walk the scope chain outward: names declared in a scope first, then the
|
||||
/// packages that scope imports, then the enclosing scope. A miss inside a
|
||||
/// class whose header says `extends` becomes an inheritance candidate — the
|
||||
@@ -180,18 +513,20 @@ fn unit_member(
|
||||
Resolution::ExternalCandidate { paths: vec![format!("{unit}::{name}")] }
|
||||
}
|
||||
|
||||
/// `this.x`: the enclosing class's own scope only — a member access cannot
|
||||
/// name a method local or an enclosing module net.
|
||||
fn this_member(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
/// `this.x`: the enclosing class's own scope and the classes it extends — a
|
||||
/// member access cannot name a method local or an enclosing module net, but it
|
||||
/// can name an inherited member, and since 2026-09-01 the `extends` chain is
|
||||
/// walked as far as this file declares it (topo §2.9-9). A chain that leaves
|
||||
/// the file keeps the answer it has always given — the base, no paths — which
|
||||
/// the workspace overlay now chases through the member tables.
|
||||
fn this_member(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, name: &str) -> Resolution {
|
||||
let Some(class) = nearest_class(scopes, from) else {
|
||||
return Resolution::NotFound;
|
||||
};
|
||||
if let Some(sym) = scopes[class.0 as usize].lookup_local(name) {
|
||||
return Resolution::Resolved(sym);
|
||||
}
|
||||
match &scopes[class.0 as usize].extends {
|
||||
Some(base) => Resolution::InheritedCandidate { base: base.clone(), paths: Vec::new() },
|
||||
None => Resolution::NotFound,
|
||||
match member_in_chain(scopes, symbols, class, name) {
|
||||
Ok(id) => Resolution::Resolved(id),
|
||||
Err(Some(base)) => Resolution::InheritedCandidate { base, paths: Vec::new() },
|
||||
Err(None) => Resolution::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,13 +600,23 @@ fn is_unit_kind(symbols: &[Symbol], sym: SymbolId) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// The kind an `import p::…` may name.
|
||||
fn is_package(kind: SymbolKind) -> bool {
|
||||
kind == SymbolKind::Package
|
||||
}
|
||||
|
||||
/// The kinds an instantiation may name — a module or an interface.
|
||||
fn is_instantiable(kind: SymbolKind) -> bool {
|
||||
kind.is_instantiable()
|
||||
}
|
||||
|
||||
fn named_at_file_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
wanted: fn(SymbolKind) -> bool,
|
||||
) -> Resolution {
|
||||
match file_symbol(scopes, symbols, name, kind) {
|
||||
match file_symbol(scopes, symbols, name, wanted) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::ExternalCandidate { paths: vec![name.to_string()] },
|
||||
}
|
||||
@@ -281,23 +626,20 @@ fn owning_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
wanted: fn(SymbolKind) -> bool,
|
||||
) -> Option<ScopeId> {
|
||||
let id = file_symbol(scopes, symbols, name, kind)?;
|
||||
let id = file_symbol(scopes, symbols, name, wanted)?;
|
||||
symbols[id.0 as usize].child_scope
|
||||
}
|
||||
|
||||
/// Modules and packages are file-scope names, so one lookup finds them.
|
||||
/// Modules, interfaces and packages are file-scope names, so one lookup finds
|
||||
/// them.
|
||||
fn file_symbol(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
wanted: fn(SymbolKind) -> bool,
|
||||
) -> Option<SymbolId> {
|
||||
let id = scopes.first()?.lookup_local(name)?;
|
||||
if symbols.get(id.0 as usize)?.kind == kind {
|
||||
Some(id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
wanted(symbols.get(id.0 as usize)?.kind).then_some(id)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ use std::path::{Path, PathBuf};
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
|
||||
|
||||
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
|
||||
use crate::{analyze, classes, instantiations, Semantics};
|
||||
@@ -35,12 +35,116 @@ pub struct Def {
|
||||
pub file: FileId,
|
||||
/// Byte range of the declared name inside that file.
|
||||
pub name_span: TextRange,
|
||||
/// Byte range of the complete construct that declares the name.
|
||||
pub decl_span: TextRange,
|
||||
/// What kind of declaration it is, for an icon and for hover text.
|
||||
pub kind: SymbolKind,
|
||||
/// Where the declaration is *completed* when not at `name_span` — a
|
||||
/// non-ANSI port's body `input wire clk;`. A cross-file hover shows these
|
||||
/// lines; `None` for every declaration complete where it is named.
|
||||
pub detail_span: Option<TextRange>,
|
||||
/// Which lines those spans fall on, read while the file was indexed.
|
||||
pub lines: DeclLines,
|
||||
/// The declared type **as written**, on the same terms as
|
||||
/// [`crate::Symbol::type_name`] — which is where it is copied from. This
|
||||
/// is what lets a member access chain across files: the type of
|
||||
/// `pkt_t::hdr` is what `item.hdr.addr`'s last link is looked up in, and
|
||||
/// only the index knows it when `pkt_t` is another file's. `None` for a
|
||||
/// built-in type, an unpacked declarator, and every declaration written
|
||||
/// without a type.
|
||||
pub type_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Where a declaration sits in its file, counted in **lines**, computed when
|
||||
/// that file is indexed.
|
||||
///
|
||||
/// The index keeps no file text, so before this every `file:line` a server
|
||||
/// printed for an indexed declaration cost a read of the declaring file and a
|
||||
/// whole [`LineIndex`] over it — the thing a cross-file hover into a closed
|
||||
/// file was mostly spending its time on. A line is four bytes per declaration,
|
||||
/// a few tens of KB for a workspace of 20 000 modules, and it is the whole of
|
||||
/// what a heading needs.
|
||||
///
|
||||
/// **One value per declaration, so it extends by gaining a field.** Members
|
||||
/// are [`Decl`]s exactly as units are, so a module's ports already carry their
|
||||
/// own lines here; a column, or a rendered preview, is another field written
|
||||
/// beside these two — plus the [`crate::FACTS_FORMAT`] bump any change to a
|
||||
/// record owes — and not a second table to keep in step with this one.
|
||||
/// [`DeclPositions`] is the first of those added fields.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct DeclLines {
|
||||
/// 1-based line the declared name is on.
|
||||
pub name: u32,
|
||||
/// 1-based line the `detail_span` starts on, `None` exactly when there is
|
||||
/// no detail span.
|
||||
pub detail: Option<u32>,
|
||||
/// The same two spans as a *client* counts positions — `Some` for a
|
||||
/// file-scope declaration, `None` for a member. See [`DeclPositions`].
|
||||
pub positions: Option<DeclPositions>,
|
||||
}
|
||||
|
||||
impl DeclLines {
|
||||
/// The lines a declaration's spans fall on, read off its file's line
|
||||
/// index. 1-based, so `name` is what `LineIndex::line_col` reports and
|
||||
/// what a `file:line` prints.
|
||||
fn of(lines: &LineIndex, name_span: TextRange, detail_span: Option<TextRange>) -> DeclLines {
|
||||
DeclLines {
|
||||
name: lines.line_col(name_span.start).0,
|
||||
detail: detail_span.map(|span| lines.line_col(span.start).0),
|
||||
positions: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One position as a language-server client counts one: a **0-based** line and
|
||||
/// **UTF-16 code units** into it — not [`LineIndex`]'s 1-based bytes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
|
||||
pub struct Utf16Pos {
|
||||
/// 0-based line.
|
||||
pub line: u32,
|
||||
/// UTF-16 code units from the start of that line's content.
|
||||
pub character: u32,
|
||||
}
|
||||
|
||||
/// A byte [`TextRange`] as a client sees it, both ends converted once when the
|
||||
/// file was scanned.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
|
||||
pub struct Utf16Range {
|
||||
pub start: Utf16Pos,
|
||||
pub end: Utf16Pos,
|
||||
}
|
||||
|
||||
impl Utf16Range {
|
||||
/// A span's two ends, converted through the file's own line index.
|
||||
pub(crate) fn of(src: &str, lines: &LineIndex, span: TextRange) -> Utf16Range {
|
||||
Utf16Range { start: pos(src, lines, span.start), end: pos(src, lines, span.end) }
|
||||
}
|
||||
}
|
||||
|
||||
fn pos(src: &str, lines: &LineIndex, offset: u32) -> Utf16Pos {
|
||||
let (line, character) = lines.utf16_position(src, offset);
|
||||
Utf16Pos { line, character }
|
||||
}
|
||||
|
||||
/// Where a **file-scope** declaration sits in its file, in the units a client
|
||||
/// speaks — so pointing an editor at a module declared in a file nobody has
|
||||
/// open costs no read of that file at all.
|
||||
///
|
||||
/// **Why only file-scope declarations carry this.** A member — a port, a
|
||||
/// parameter, a class field — is a [`Decl`] exactly as a unit is, and there are
|
||||
/// two orders of magnitude more of them: on opentitan, 1 544 modules against
|
||||
/// hundreds of thousands of members, so giving every declaration eight more
|
||||
/// numbers would have roughly doubled the persistent store to serve a caller
|
||||
/// that does not exist. The units and the members are written in two separate
|
||||
/// groups of a record, so "units carry positions, members do not" costs a
|
||||
/// member no field at all — and the day a member wants them, it is the same
|
||||
/// eight fields in the other group plus the [`crate::FACTS_FORMAT`] bump.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct DeclPositions {
|
||||
/// The declared name's own range — an editor's selection range.
|
||||
pub name: Utf16Range,
|
||||
/// The whole declaring construct's range.
|
||||
pub decl: Utf16Range,
|
||||
}
|
||||
|
||||
/// Stable identity of one indexed declaration inside the current index.
|
||||
@@ -116,6 +220,30 @@ pub struct InstantiationEdge {
|
||||
pub owner: DeclSite,
|
||||
/// Byte range of the instantiated module's name at the site.
|
||||
pub site_span: TextRange,
|
||||
/// The individual instances the statement declares, in source order.
|
||||
///
|
||||
/// The edge itself deliberately remains one-per-statement: call hierarchy
|
||||
/// and code lenses have always treated `sub u1 (), u2 ();` as one written
|
||||
/// call site. Instance-oriented clients can flatten this list without
|
||||
/// changing that census.
|
||||
pub instances: Vec<InstanceOccurrence>,
|
||||
}
|
||||
|
||||
/// One named instance inside an [`InstantiationEdge`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InstanceOccurrence {
|
||||
/// Instance name as written (`u_fifo`).
|
||||
pub name: String,
|
||||
/// Byte range of the instance name.
|
||||
pub name_span: TextRange,
|
||||
/// Byte range of the whole instance, including dimensions and connections.
|
||||
pub span: TextRange,
|
||||
/// `name_span` as a client counts positions, converted when the file was
|
||||
/// scanned — the same reason [`DeclPositions`] exists, for the other half
|
||||
/// of what a design-hierarchy row points at.
|
||||
pub name_positions: Utf16Range,
|
||||
/// `span` likewise.
|
||||
pub positions: Utf16Range,
|
||||
}
|
||||
|
||||
/// One class that extends another.
|
||||
@@ -152,6 +280,11 @@ pub struct WorkspaceIndex {
|
||||
/// Base class name → every class extending it, in file order then walk
|
||||
/// order.
|
||||
subclasses: BTreeMap<String, Vec<InheritanceEdge>>,
|
||||
/// The same census read the other way: class name → the base it extends,
|
||||
/// as written. Built in [`WorkspaceIndex::merge`] from the very edges that
|
||||
/// fill `subclasses`, so the two cannot disagree and no [`FileFacts`]
|
||||
/// field was added for it. See [`WorkspaceIndex::base_of`].
|
||||
bases: BTreeMap<String, String>,
|
||||
/// Macro name → `(file, entry-in-that-file)` for each definition.
|
||||
macro_definitions: BTreeMap<String, Vec<(FileId, usize)>>,
|
||||
/// Declaration → every unambiguous use, in file then source order.
|
||||
@@ -242,6 +375,19 @@ impl WorkspaceIndex {
|
||||
self.subclasses.get(name).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// What the class `name` extends, **as written** (`base`, `pkg::base`) —
|
||||
/// the reverse of [`WorkspaceIndex::subclasses_of`], and the one hop an
|
||||
/// inherited-member lookup needs.
|
||||
///
|
||||
/// One base per class name: a workspace declaring the name twice takes the
|
||||
/// first in disambiguation order (by file path, then by walk order), the
|
||||
/// same policy every other duplicate-name table here applies. `None` for a
|
||||
/// class that extends nothing, and for a name the workspace does not
|
||||
/// declare — which is what ends the chase in [`resolve_external`].
|
||||
pub fn base_of(&self, name: &str) -> Option<&str> {
|
||||
self.bases.get(name).map(String::as_str)
|
||||
}
|
||||
|
||||
/// Every instantiated module name the workspace names, with its sites.
|
||||
pub fn instantiations(&self) -> impl Iterator<Item = (&str, &[InstantiationEdge])> {
|
||||
self.instantiations.iter().map(|(name, edges)| (name.as_str(), edges.as_slice()))
|
||||
@@ -295,6 +441,47 @@ impl WorkspaceIndex {
|
||||
self.ambiguous_references.contains(&DefinitionKey::of(def))
|
||||
}
|
||||
|
||||
/// Every file holding a use spelled `name` that this index had to look
|
||||
/// **outside that file** to answer — whether or not it found anything.
|
||||
///
|
||||
/// [`WorkspaceIndex::references_to`] is keyed by the declaration a use
|
||||
/// landed on, so a use that landed on nothing is in no posting at all.
|
||||
/// That is the right shape for "who refers to this declaration" and the
|
||||
/// wrong shape for "which files would notice if this name suddenly
|
||||
/// started meaning something" — the question a rename has to ask about
|
||||
/// the name it is renaming *to*, because an `import p::*` of a package
|
||||
/// that does not exist yet changes meaning the moment a package `p`
|
||||
/// appears. Answered from the per-file records, which keep every external
|
||||
/// reference by its spelled name; a resolved one is here too, since a use
|
||||
/// that already means something can equally start meaning something else.
|
||||
///
|
||||
/// A linear walk over the records, in [`FileId`] order and deduplicated:
|
||||
/// no source is read and nothing is parsed. See
|
||||
/// `docs/features/refactor-rename/README.md` for the rename's use of it
|
||||
/// and the measurement.
|
||||
pub fn files_spelling(&self, name: &str) -> impl Iterator<Item = FileId> + '_ {
|
||||
let name = name.to_string();
|
||||
self.facts.iter().enumerate().filter_map(move |(id, facts)| {
|
||||
let spelled = facts.references.iter().any(|reference| match reference {
|
||||
// A fact with **no paths at all** is not one of these: it is
|
||||
// an inherited-member miss, answered only through the base
|
||||
// class this file already names, and it is recorded (since
|
||||
// round 2, for its index posting) rather than dropped. What
|
||||
// `rename`'s fan-out reads here is unchanged by that: the set
|
||||
// is still every use whose *paths* the workspace was asked
|
||||
// about. See the class-member-access README's Handshakes for
|
||||
// the question this leaves open for `rename`.
|
||||
ReferenceFact::External { name: spelled, paths, .. } => {
|
||||
!paths.is_empty() && *spelled == name
|
||||
}
|
||||
// A local fact resolved inside its own file, so that file
|
||||
// declares the name and every caller already has it.
|
||||
ReferenceFact::Local { .. } => false,
|
||||
});
|
||||
spelled.then_some(FileId(id as u32))
|
||||
})
|
||||
}
|
||||
|
||||
/// Every indexed name containing `query`, case-insensitively — LSP's
|
||||
/// `workspace/symbol`. An empty query matches everything; the result is
|
||||
/// sorted by name and is not truncated, so a caller with a result limit
|
||||
@@ -328,11 +515,42 @@ impl WorkspaceIndex {
|
||||
out
|
||||
}
|
||||
|
||||
/// Every file-scope declaration of one kind, under its name, in name
|
||||
/// order.
|
||||
///
|
||||
/// The cheap half of [`WorkspaceIndex::workspace_symbols`] for a caller
|
||||
/// that wants units and never members: it walks the unit table alone and
|
||||
/// sorts nothing, where `workspace_symbols("")` walks every member of every
|
||||
/// unit and sorts the lot. On opentitan that is 1 544 modules out of
|
||||
/// hundreds of thousands of declarations, and the difference is 15 ms per
|
||||
/// call (`docs/features/vscode-hierarchy-sidebar/README.md`).
|
||||
pub fn units_of(&self, kind: SymbolKind) -> impl Iterator<Item = (&str, &Def)> {
|
||||
self.units
|
||||
.iter()
|
||||
.flat_map(|(name, defs)| defs.iter().map(move |def| (name.as_str(), def)))
|
||||
.filter(move |(_, def)| def.kind == kind)
|
||||
}
|
||||
|
||||
/// Every file-scope declaration an instantiation may name — a `module` or
|
||||
/// an `interface` — under its name, in name order.
|
||||
///
|
||||
/// [`WorkspaceIndex::units_of`] with the one filter that is two kinds. An
|
||||
/// interface instance is an instantiation edge exactly as a module instance
|
||||
/// is, so the design hierarchy, the code lens and the instantiate ghost all
|
||||
/// read this rather than spelling the pair for themselves.
|
||||
pub fn instantiable_units(&self) -> impl Iterator<Item = (&str, &Def)> {
|
||||
self.units
|
||||
.iter()
|
||||
.flat_map(|(name, defs)| defs.iter().map(move |def| (name.as_str(), def)))
|
||||
.filter(|(_, def)| def.kind.is_instantiable())
|
||||
}
|
||||
|
||||
/// How many unit names and member names are indexed.
|
||||
pub fn counts(&self) -> IndexCounts {
|
||||
IndexCounts {
|
||||
files: self.files.len(),
|
||||
modules: self.units_of_kind(SymbolKind::Module),
|
||||
interfaces: self.units_of_kind(SymbolKind::Interface),
|
||||
packages: self.units_of_kind(SymbolKind::Package),
|
||||
typedefs: self.units_of_kind(SymbolKind::Typedef),
|
||||
classes: self.units_of_kind(SymbolKind::Class)
|
||||
@@ -412,6 +630,52 @@ impl WorkspaceIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
|
||||
/// many files at once — and for **one** merge rather than one each.
|
||||
///
|
||||
/// Same contract as both — what comes out is the index a full
|
||||
/// [`WorkspaceIndex::build`] over the records it now holds would have
|
||||
/// produced — **provided each path appears once in `records`**. It holds
|
||||
/// for the same reason theirs does: the records are kept path-sorted and
|
||||
/// one file to a path, and [`WorkspaceIndex::merge`] is then the same loop
|
||||
/// [`IndexBuilder::finish`] runs over the same list. A batch that names
|
||||
/// one path twice is an update applied twice, so the **last** record wins,
|
||||
/// where a `build` over the same duplicated input keeps the *first*
|
||||
/// (`index_order` dedups) — the update semantic is the right one for an
|
||||
/// "absorb what changed" API, and the one caller that feeds a scan
|
||||
/// (`Scan::work`) is deduped before anything is staged. QA pinned the
|
||||
/// divergence
|
||||
/// (`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`).
|
||||
///
|
||||
/// One merge, because a merge is a pass over **every** record the index
|
||||
/// holds: a scan that merged after each of its files would be quadratic in
|
||||
/// the size of the workspace, which is measured rather than argued in
|
||||
/// `docs/features/scan-interleave/README.md`. A caller feeding a scan
|
||||
/// therefore batches — it stages records as it takes them and folds a
|
||||
/// batch in only when something is about to read the index.
|
||||
///
|
||||
/// `gone` is dropped first, so a path in both lists ends up held: a file
|
||||
/// that moved out of one scan's scope and back into the next's is one
|
||||
/// file, not a removal that happens to run second.
|
||||
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]) {
|
||||
for path in gone {
|
||||
if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) {
|
||||
self.files.remove(at);
|
||||
self.facts.remove(at);
|
||||
}
|
||||
}
|
||||
for facts in records {
|
||||
match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) {
|
||||
Ok(at) => self.facts[at] = facts,
|
||||
Err(at) => {
|
||||
self.files.insert(at, facts.path.clone());
|
||||
self.facts.insert(at, facts);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.merge(None);
|
||||
}
|
||||
|
||||
/// Drop one file from the index, reporting whether it was there.
|
||||
///
|
||||
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
|
||||
@@ -441,13 +705,19 @@ impl WorkspaceIndex {
|
||||
}
|
||||
for symbol in self.workspace_symbols("") {
|
||||
out.push_str(&format!(
|
||||
"sym {} in {:?} {:?} {}:{}..{}\n",
|
||||
"sym {} in {:?} {:?} {}:{}..{} decl={}..{} line={} detail={:?} at={:?} type={:?}\n",
|
||||
symbol.name,
|
||||
symbol.container,
|
||||
symbol.def.kind,
|
||||
symbol.def.file.0,
|
||||
symbol.def.name_span.start,
|
||||
symbol.def.name_span.end
|
||||
symbol.def.name_span.end,
|
||||
symbol.def.decl_span.start,
|
||||
symbol.def.decl_span.end,
|
||||
symbol.def.lines.name,
|
||||
symbol.def.lines.detail,
|
||||
symbol.def.lines.positions,
|
||||
symbol.def.type_name
|
||||
));
|
||||
}
|
||||
for (definition, sites) in &self.reference_sites {
|
||||
@@ -482,6 +752,18 @@ impl WorkspaceIndex {
|
||||
edge.site_span.start,
|
||||
edge.site_span.end
|
||||
));
|
||||
for instance in &edge.instances {
|
||||
out.push_str(&format!(
|
||||
" instance {} name {}..{} span {}..{} at {:?} {:?}\n",
|
||||
instance.name,
|
||||
instance.name_span.start,
|
||||
instance.name_span.end,
|
||||
instance.span.start,
|
||||
instance.span.end,
|
||||
instance.name_positions,
|
||||
instance.positions
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, edges) in self.subclasses() {
|
||||
@@ -559,6 +841,7 @@ impl WorkspaceIndex {
|
||||
file,
|
||||
owner: edge.owner.clone(),
|
||||
site_span: edge.site_span,
|
||||
instances: edge.instances.clone(),
|
||||
});
|
||||
}
|
||||
for (base, subclass) in &facts.subclasses {
|
||||
@@ -579,6 +862,17 @@ impl WorkspaceIndex {
|
||||
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
|
||||
}
|
||||
}
|
||||
// The reverse inheritance edge is rebuilt whole every time, whatever
|
||||
// `affected` says: it is one entry per `extends` written anywhere (a
|
||||
// few thousand on opentitan), and rebuilding it is both cheaper to
|
||||
// reason about and the reason a restricted merge cannot leave it
|
||||
// half-updated. First in file order wins, which is `units`' rule.
|
||||
self.bases.clear();
|
||||
for facts in &self.facts {
|
||||
for (base, subclass) in &facts.subclasses {
|
||||
self.bases.entry(subclass.name.clone()).or_insert_with(|| base.clone());
|
||||
}
|
||||
}
|
||||
// A changed declaration can change how references in any file resolve,
|
||||
// even when only one file's facts moved. Re-resolving compact facts is
|
||||
// one in-memory pass; no source is read or parsed.
|
||||
@@ -602,8 +896,8 @@ impl WorkspaceIndex {
|
||||
};
|
||||
sites.entry(key).or_default().push(site);
|
||||
}
|
||||
ReferenceFact::External { name, paths, .. } => {
|
||||
match follow_paths(self, name, paths) {
|
||||
ReferenceFact::External { name, base, paths, .. } => {
|
||||
match resolve_fact(self, name, base.as_deref(), paths) {
|
||||
ExternalTarget::Resolved(def) => {
|
||||
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
|
||||
}
|
||||
@@ -659,22 +953,49 @@ impl Affected {
|
||||
pub(crate) struct Decl {
|
||||
pub(crate) name: String,
|
||||
pub(crate) name_span: TextRange,
|
||||
pub(crate) decl_span: TextRange,
|
||||
pub(crate) kind: SymbolKind,
|
||||
pub(crate) detail_span: Option<TextRange>,
|
||||
pub(crate) lines: DeclLines,
|
||||
pub(crate) type_name: Option<String>,
|
||||
}
|
||||
|
||||
impl Decl {
|
||||
fn of(symbol: &Symbol) -> Decl {
|
||||
/// A member's declaration: lines only, no client positions — see
|
||||
/// [`DeclPositions`] for why the cheap half is the only half a member gets.
|
||||
fn member(symbol: &Symbol, lines: &LineIndex) -> Decl {
|
||||
Decl {
|
||||
name: symbol.name.clone(),
|
||||
name_span: symbol.name_span,
|
||||
decl_span: symbol.decl_span,
|
||||
kind: symbol.kind,
|
||||
detail_span: symbol.detail_span,
|
||||
lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span),
|
||||
type_name: symbol.type_name.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A file-scope declaration: the same, plus the two ranges a client is
|
||||
/// pointed at, converted here so no one converts them later.
|
||||
fn unit(symbol: &Symbol, src: &str, lines: &LineIndex) -> Decl {
|
||||
let mut decl = Decl::member(symbol, lines);
|
||||
decl.lines.positions = Some(DeclPositions {
|
||||
name: Utf16Range::of(src, lines, symbol.name_span),
|
||||
decl: Utf16Range::of(src, lines, symbol.decl_span),
|
||||
});
|
||||
decl
|
||||
}
|
||||
|
||||
fn def(&self, file: FileId) -> Def {
|
||||
Def { file, name_span: self.name_span, kind: self.kind, detail_span: self.detail_span }
|
||||
Def {
|
||||
file,
|
||||
name_span: self.name_span,
|
||||
decl_span: self.decl_span,
|
||||
kind: self.kind,
|
||||
detail_span: self.detail_span,
|
||||
lines: self.lines,
|
||||
type_name: self.type_name.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -684,6 +1005,7 @@ impl Decl {
|
||||
pub(crate) struct SiteFact {
|
||||
pub(crate) owner: DeclSite,
|
||||
pub(crate) site_span: TextRange,
|
||||
pub(crate) instances: Vec<InstanceOccurrence>,
|
||||
}
|
||||
|
||||
/// Everything one file contributes to an index: read while the file is parsed,
|
||||
@@ -722,7 +1044,14 @@ pub(crate) enum ReferenceFact {
|
||||
/// A use resolved to an exported declaration in this same file.
|
||||
Local { definition: TextRange, occurrence: TextRange },
|
||||
/// A use whose recorded paths need the workspace declaration tables.
|
||||
External { name: String, paths: Vec<String>, occurrence: TextRange },
|
||||
///
|
||||
/// `base` is the class an inherited-member miss was recorded against
|
||||
/// ([`Resolution::InheritedCandidate`]) — chased through the member
|
||||
/// tables when the paths say nothing, exactly as [`resolve_external`]
|
||||
/// chases it. Without it a `this.x` whose class is another file's had no
|
||||
/// posting at all, so a cross-file find-references from the property's
|
||||
/// own declaration did not list it (round 1's residue).
|
||||
External { name: String, base: Option<String>, paths: Vec<String>, occurrence: TextRange },
|
||||
}
|
||||
|
||||
impl ReferenceFact {
|
||||
@@ -757,15 +1086,23 @@ impl FileFacts {
|
||||
/// server holding an open buffer's finished analysis) gets the record the
|
||||
/// parse would have produced without paying for the parse a second time.
|
||||
/// The two paths are the same code and cannot drift; what the caller
|
||||
/// promises is only that `tree`, `defines` and `sem` are the analysis of
|
||||
/// promises is only that `tree`, `defines`, `sem` and `lines` all describe
|
||||
/// the text `path` currently holds.
|
||||
///
|
||||
/// `src` and `lines` are asked for rather than built here because a caller
|
||||
/// with a finished analysis in hand — a server holding an open buffer —
|
||||
/// already has both, and because a record now carries each declaration's
|
||||
/// line ([`DeclLines`]) and each file-scope declaration's client position
|
||||
/// ([`DeclPositions`]), neither of which can be read off a tree alone.
|
||||
pub fn from_analysis(
|
||||
path: PathBuf,
|
||||
tree: &SourceFile,
|
||||
defines: &DefineTable,
|
||||
sem: &Semantics,
|
||||
src: &str,
|
||||
lines: &LineIndex,
|
||||
) -> FileFacts {
|
||||
facts_from_analysis(path, tree, defines.clone(), sem)
|
||||
facts_from_analysis(path, tree, defines.clone(), sem, src, lines)
|
||||
}
|
||||
|
||||
/// The file these facts were read from.
|
||||
@@ -778,7 +1115,11 @@ impl FileFacts {
|
||||
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
|
||||
let (tree, defines) = parse_and_collect(src);
|
||||
let sem = analyze(&tree, src);
|
||||
facts_from_analysis(path, &tree, defines, &sem)
|
||||
// One pass over the source's newlines, so every declaration below can be
|
||||
// given its line without anyone reading the file again later. It is a
|
||||
// percent of the parse it sits beside (`docs/perf/README.md`).
|
||||
let lines = LineIndex::new(src);
|
||||
facts_from_analysis(path, &tree, defines, &sem, src, &lines)
|
||||
}
|
||||
|
||||
/// Read off what one file contributes, from its finished analysis.
|
||||
@@ -787,13 +1128,15 @@ fn facts_from_analysis(
|
||||
tree: &SourceFile,
|
||||
defines: DefineTable,
|
||||
sem: &Semantics,
|
||||
src: &str,
|
||||
lines: &LineIndex,
|
||||
) -> FileFacts {
|
||||
let mut facts = FileFacts {
|
||||
path,
|
||||
defines,
|
||||
units: Vec::new(),
|
||||
members: Vec::new(),
|
||||
instantiations: edges_of(tree),
|
||||
instantiations: edges_of(tree, src, lines),
|
||||
subclasses: inheritance_of(tree),
|
||||
references: Vec::new(),
|
||||
};
|
||||
@@ -807,8 +1150,8 @@ fn facts_from_analysis(
|
||||
if !is_unit(unit.kind) || unit.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
facts.units.push(Decl::of(unit));
|
||||
collect_members(sem, unit, &mut facts.members);
|
||||
facts.units.push(Decl::unit(unit, src, lines));
|
||||
collect_members(sem, unit, lines, &mut facts.members);
|
||||
}
|
||||
let exported: HashSet<(u32, u32)> = facts
|
||||
.units
|
||||
@@ -824,16 +1167,23 @@ fn facts_from_analysis(
|
||||
.contains(&(definition.start, definition.end))
|
||||
.then_some(ReferenceFact::Local { definition, occurrence: reference.name_span })
|
||||
}),
|
||||
Resolution::ExternalCandidate { paths }
|
||||
| Resolution::InheritedCandidate { paths, .. }
|
||||
if !paths.is_empty() =>
|
||||
{
|
||||
Resolution::ExternalCandidate { paths } if !paths.is_empty() => {
|
||||
Some(ReferenceFact::External {
|
||||
name: reference.name.clone(),
|
||||
base: None,
|
||||
paths: paths.clone(),
|
||||
occurrence: reference.name_span,
|
||||
})
|
||||
}
|
||||
// An inherited candidate is recorded even with **no** paths: the
|
||||
// base alone is a handle on the declaration, and the merge chases
|
||||
// it through the same member tables the overlay does.
|
||||
Resolution::InheritedCandidate { base, paths } => Some(ReferenceFact::External {
|
||||
name: reference.name.clone(),
|
||||
base: Some(base.clone()),
|
||||
paths: paths.clone(),
|
||||
occurrence: reference.name_span,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(fact) = fact {
|
||||
@@ -850,7 +1200,7 @@ fn facts_from_analysis(
|
||||
/// hierarchy reads a buffer with — so the workspace-wide census and the
|
||||
/// per-file one cannot disagree. A site written at file scope has no
|
||||
/// instantiating module and is not an edge.
|
||||
fn edges_of(tree: &SourceFile) -> Vec<(String, SiteFact)> {
|
||||
fn edges_of(tree: &SourceFile, src: &str, lines: &LineIndex) -> Vec<(String, SiteFact)> {
|
||||
instantiations::sites(&tree.items)
|
||||
.into_iter()
|
||||
.filter_map(|site| {
|
||||
@@ -864,6 +1214,18 @@ fn edges_of(tree: &SourceFile) -> Vec<(String, SiteFact)> {
|
||||
span: owner.span,
|
||||
},
|
||||
site_span: site.inst.module_span,
|
||||
instances: site
|
||||
.inst
|
||||
.instances
|
||||
.iter()
|
||||
.map(|instance| InstanceOccurrence {
|
||||
name: instance.name.clone(),
|
||||
name_span: instance.name_span,
|
||||
span: instance.span,
|
||||
name_positions: Utf16Range::of(src, lines, instance.name_span),
|
||||
positions: Utf16Range::of(src, lines, instance.span),
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
))
|
||||
})
|
||||
@@ -889,7 +1251,12 @@ fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> {
|
||||
}
|
||||
|
||||
/// Read off the names another file may reach *into* this unit for.
|
||||
fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) {
|
||||
fn collect_members(
|
||||
sem: &Semantics,
|
||||
unit: &Symbol,
|
||||
lines: &LineIndex,
|
||||
out: &mut Vec<(String, Decl)>,
|
||||
) {
|
||||
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
|
||||
return;
|
||||
};
|
||||
@@ -900,13 +1267,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
|
||||
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push((unit.name.clone(), Decl::of(member)));
|
||||
out.push((unit.name.clone(), Decl::member(member, lines)));
|
||||
// A class nested in a package (the dominant UVM shape) is not a unit,
|
||||
// but an external `cls::x` candidate looks its members up under the
|
||||
// *class's* name — register them there too. The scope tree is acyclic,
|
||||
// so this recursion terminates.
|
||||
if member.kind == SymbolKind::Class {
|
||||
collect_members(sem, member, out);
|
||||
collect_members(sem, member, lines, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -920,10 +1287,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
|
||||
/// the first file is parsed. Getting that ordering from here rather than
|
||||
/// re-deriving it is what keeps a watched build and a plain
|
||||
/// [`WorkspaceIndex::build`] the same index in the same order.
|
||||
pub fn index_order<'a>(
|
||||
files: impl IntoIterator<Item = (PathBuf, &'a str)>,
|
||||
) -> Vec<(PathBuf, &'a str)> {
|
||||
let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect();
|
||||
///
|
||||
/// Generic in what rides beside the path — a borrowed `&str` for a caller that
|
||||
/// holds the texts, an owned `String` for one that is handing them over — so a
|
||||
/// scan that owns its work list gets the same ordering from the same function
|
||||
/// rather than sorting for itself.
|
||||
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)> {
|
||||
let mut sources: Vec<(PathBuf, T)> = files.into_iter().collect();
|
||||
sources.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
// A path handed over twice is one file; the first copy wins.
|
||||
sources.dedup_by(|a, b| a.0 == b.0);
|
||||
@@ -1003,8 +1373,12 @@ impl IndexBuilder {
|
||||
pub struct IndexCounts {
|
||||
/// Files scanned, whether they parsed or not.
|
||||
pub files: usize,
|
||||
/// Module declarations indexed, duplicates counted separately.
|
||||
/// Module declarations indexed, duplicates counted separately. Interfaces
|
||||
/// are **not** in this number — they have their own, so a caller reporting
|
||||
/// "1 544 modules" still means 1 544 modules.
|
||||
pub modules: usize,
|
||||
/// Interface declarations indexed, duplicates counted separately.
|
||||
pub interfaces: usize,
|
||||
/// Package declarations indexed, duplicates counted separately.
|
||||
pub packages: usize,
|
||||
/// File-scope typedefs; a typedef inside a module or package is not one.
|
||||
@@ -1041,17 +1415,25 @@ fn parse_and_collect(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable) {
|
||||
|
||||
/// The file-scope kinds another file can name.
|
||||
fn is_unit(kind: SymbolKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
SymbolKind::Module | SymbolKind::Package | SymbolKind::Typedef | SymbolKind::Class
|
||||
)
|
||||
matches!(kind, SymbolKind::Package | SymbolKind::Typedef | SymbolKind::Class)
|
||||
|| kind.is_instantiable()
|
||||
}
|
||||
|
||||
/// What `unit::member` / `.member` may reach. A package or class exports
|
||||
/// everything declared at its top level (a package's classes included — that
|
||||
/// is what lets `import uvm_pkg::*` answer `uvm_object`); a module exports
|
||||
/// only what a connection list can name — its ports and its parameters — so
|
||||
/// an internal net is never reachable from another file.
|
||||
/// What `unit::member` / `.member` may reach.
|
||||
///
|
||||
/// A package or class exports everything declared at its top level (a
|
||||
/// package's classes included — that is what lets `import uvm_pkg::*` answer
|
||||
/// `uvm_object`). A **module** exports only what a connection list can name —
|
||||
/// its ports and its parameters — so an internal net is never reachable from
|
||||
/// another file.
|
||||
///
|
||||
/// An **interface** is the exception the 2026-09-01 round exists for: its
|
||||
/// signals *are* its surface. `virtual bus_if vif; vif.data` is how every DV
|
||||
/// testbench in the world reaches `data`, and `data` is an ordinary net or
|
||||
/// variable declared inside the interface, not a port of it. So an interface
|
||||
/// exports its nets, variables, ports, parameters, typedefs, methods, modports
|
||||
/// and clocking blocks. The module ruling is untouched: a module handle is an
|
||||
/// *instance*, whose internals no other file's connection list may name.
|
||||
fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool {
|
||||
match unit {
|
||||
SymbolKind::Package | SymbolKind::Class => matches!(
|
||||
@@ -1066,6 +1448,18 @@ fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool {
|
||||
| SymbolKind::Class
|
||||
),
|
||||
SymbolKind::Module => matches!(member, SymbolKind::Port | SymbolKind::Param),
|
||||
SymbolKind::Interface => matches!(
|
||||
member,
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::Typedef
|
||||
| SymbolKind::Function
|
||||
| SymbolKind::Task
|
||||
| SymbolKind::Modport
|
||||
| SymbolKind::Clocking
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -1138,17 +1532,20 @@ pub enum Definition<'a> {
|
||||
/// An [`Resolution::InheritedCandidate`] is not an external candidate and does
|
||||
/// not become one: its base class is the single-file layer's answer and stays
|
||||
/// the answer. But its paths are real — the imports the lexical walk collected
|
||||
/// and the use's own name — so they are tried, and an entry is recorded **only
|
||||
/// when one of them lands on a declaration**. A name the index cannot answer is
|
||||
/// left exactly as it was, absent from the overlay, which is what keeps
|
||||
/// "the overlay holds what the workspace was asked to finish" true.
|
||||
/// and the use's own name — so they are tried first, and when they say nothing
|
||||
/// the **base itself is chased** through the workspace's member tables and up
|
||||
/// its own `extends` chain ([`chase_inherited`], topo §2.9-9). An entry is
|
||||
/// recorded **only when one of the two lands on a declaration**. A name the
|
||||
/// index cannot answer is left exactly as it was, absent from the overlay,
|
||||
/// which is what keeps "the overlay holds what the workspace was asked to
|
||||
/// finish" true.
|
||||
pub fn resolve_external(sem: &Semantics, index: &WorkspaceIndex) -> ExternalResolutions {
|
||||
let mut targets = HashMap::new();
|
||||
for (i, reference) in sem.references().iter().enumerate() {
|
||||
let target = match &reference.resolution {
|
||||
Resolution::ExternalCandidate { paths } => follow_paths(index, &reference.name, paths),
|
||||
Resolution::InheritedCandidate { paths, .. } => {
|
||||
match follow_paths(index, &reference.name, paths) {
|
||||
Resolution::InheritedCandidate { base, paths } => {
|
||||
match resolve_fact(index, &reference.name, Some(base), paths) {
|
||||
ExternalTarget::StillUnresolved => continue,
|
||||
answered => answered,
|
||||
}
|
||||
@@ -1160,14 +1557,113 @@ pub fn resolve_external(sem: &Semantics, index: &WorkspaceIndex) -> ExternalReso
|
||||
ExternalResolutions { targets }
|
||||
}
|
||||
|
||||
/// One recorded use against the index: its paths first, in the order
|
||||
/// `analyze` wrote them, then — for an inherited-member miss — the base class
|
||||
/// it was recorded against, chased upward through the member tables.
|
||||
///
|
||||
/// The **one** function both layers ask, so the overlay (hover, definition)
|
||||
/// and the index's own reference postings (cross-file find-references, and the
|
||||
/// rename that fans out from them) cannot name different declarations for one
|
||||
/// use.
|
||||
fn resolve_fact(
|
||||
index: &WorkspaceIndex,
|
||||
name: &str,
|
||||
base: Option<&str>,
|
||||
paths: &[String],
|
||||
) -> ExternalTarget {
|
||||
match follow_paths(index, name, paths) {
|
||||
ExternalTarget::StillUnresolved => match base {
|
||||
Some(base) => target(member_chain(index, last_segment(base), name)),
|
||||
None => ExternalTarget::StillUnresolved,
|
||||
},
|
||||
answered => answered,
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` in `unit`'s member table, else in the member table of what `unit`
|
||||
/// extends, and so on upward — because **a class's member table is incomplete
|
||||
/// without its bases**, and every caller that asks a unit for a member wants
|
||||
/// the inherited ones too. A unit that extends nothing (every package, every
|
||||
/// module) is one map lookup, exactly as before.
|
||||
///
|
||||
/// Map reads only — [`WorkspaceIndex::member`] and
|
||||
/// [`WorkspaceIndex::base_of`], both `BTreeMap`s — so a hover pays a handful
|
||||
/// of comparisons and no file is read. The walk is bounded by the visited set
|
||||
/// as well as by the workspace: `class a extends b; class b extends a;`
|
||||
/// terminates, and so does a chain that meets itself further up.
|
||||
fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] {
|
||||
let mut current = unit;
|
||||
let mut visited: Vec<&str> = Vec::new();
|
||||
while !visited.contains(¤t) {
|
||||
visited.push(current);
|
||||
let found = index.member(current, name);
|
||||
if !found.is_empty() {
|
||||
return found;
|
||||
}
|
||||
// What the unit extends, else what it is an alias *of*: a file-scope
|
||||
// `typedef c1 my_t;` in one file is how another file's `my_t h;`
|
||||
// reaches `c1`'s members, and it is the same one-name hop.
|
||||
let Some(next) = index.base_of(current).or_else(|| aliased_unit(index, current)) else {
|
||||
break;
|
||||
};
|
||||
current = last_segment(next);
|
||||
}
|
||||
&[]
|
||||
}
|
||||
|
||||
/// The type a file-scope `typedef` names, when the workspace declares the name
|
||||
/// exactly once and as a typedef. Two declarations of the name are two
|
||||
/// answers, and this layer picks between candidates nowhere else either.
|
||||
fn aliased_unit<'i>(index: &'i WorkspaceIndex, unit: &str) -> Option<&'i str> {
|
||||
match index.units(unit) {
|
||||
[def] if def.kind == SymbolKind::Typedef => def.type_name.as_deref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The **declared type** of one member of one unit, as the next unit name to
|
||||
/// look in — the hop that walks a chain `pkt_t::hdr::addr` across files.
|
||||
///
|
||||
/// `None` whenever the hop cannot be taken honestly: no such member, several
|
||||
/// equally plausible ones, a member declared without a type this crate
|
||||
/// records, or a type name the **workspace** declares more than once — two
|
||||
/// declarations are two answers, and picking one is the guess round 1's
|
||||
/// `TypeHere` exists to refuse (a struct `hdr_t` in one file and an unrelated
|
||||
/// class `hdr_t` in another must not answer for each other). A class declared
|
||||
/// inside a package declares no file-scope unit at all — the dominant UVM
|
||||
/// shape — and is unaffected. The chain then answers nothing, which is what
|
||||
/// stops a guess.
|
||||
fn member_type(index: &WorkspaceIndex, unit: &str, member: &str) -> Option<String> {
|
||||
let [def] = member_chain(index, unit, member) else {
|
||||
return None;
|
||||
};
|
||||
let next = last_segment(def.type_name.as_deref()?);
|
||||
(index.units(next).len() < 2).then(|| next.to_string())
|
||||
}
|
||||
|
||||
/// What one table lookup means: nothing, one declaration, or several equally
|
||||
/// plausible ones.
|
||||
fn target(defs: &[Def]) -> ExternalTarget {
|
||||
match defs {
|
||||
[] => ExternalTarget::StillUnresolved,
|
||||
[def] => ExternalTarget::Resolved(def.clone()),
|
||||
defs => ExternalTarget::Ambiguous(defs.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly-qualified path — the name the member
|
||||
/// and inheritance tables are keyed by.
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
}
|
||||
|
||||
/// Try the recorded paths in the order `analyze` wrote them — which is the
|
||||
/// order the imports are written in — and take the first that has an answer.
|
||||
fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> ExternalTarget {
|
||||
for path in paths {
|
||||
match follow_one(index, name, path) {
|
||||
[] => continue,
|
||||
[def] => return ExternalTarget::Resolved(def.clone()),
|
||||
defs => return ExternalTarget::Ambiguous(defs.to_vec()),
|
||||
match target(follow_one(index, name, path)) {
|
||||
ExternalTarget::StillUnresolved => continue,
|
||||
answered => return answered,
|
||||
}
|
||||
}
|
||||
ExternalTarget::StillUnresolved
|
||||
@@ -1176,13 +1672,39 @@ fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> Externa
|
||||
/// One recorded path against the index. `p::*` and `p::x` both mean "the name
|
||||
/// this use spells, inside `p`". A bare path is the unit itself when the use
|
||||
/// spells the unit's name (an instantiated module, an imported package), and
|
||||
/// otherwise a member of it (the `.port` of a connection to that module).
|
||||
/// otherwise a member of it (the `.port` of a connection to that module, the
|
||||
/// member of a class-typed handle).
|
||||
///
|
||||
/// A path of **more than two** segments is a member chain: `pkt_t::hdr::addr`
|
||||
/// means "`addr` in the type of `hdr` in `pkt_t`", so every segment between
|
||||
/// the first and the last is one [`member_type`] hop before the final lookup.
|
||||
/// A two-segment path takes no hop at all and is exactly what it was.
|
||||
///
|
||||
/// Every member lookup goes through [`member_chain`], so a unit that extends
|
||||
/// another answers with its inherited members too — which is what makes
|
||||
/// `handle.member` and `this.member` reach a base class in a third file, and
|
||||
/// what keeps the overlay and the index's own reference postings (which run
|
||||
/// through this same function) from disagreeing about what a use names.
|
||||
fn follow_one<'i>(index: &'i WorkspaceIndex, name: &str, path: &str) -> &'i [Def] {
|
||||
match path.split_once("::") {
|
||||
Some((unit, _)) => index.member(unit, name),
|
||||
None if path == name => index.units(name),
|
||||
None => index.member(path, name),
|
||||
let mut segments: Vec<&str> = path.split("::").collect();
|
||||
let Some(first) = segments.first().copied() else {
|
||||
return &[];
|
||||
};
|
||||
if segments.len() < 2 {
|
||||
return if path == name { index.units(name) } else { member_chain(index, path, name) };
|
||||
}
|
||||
// The last segment is the use's own name, which `name` already carries
|
||||
// (and which a `p::*` import spells as a wildcard); the ones before it are
|
||||
// the hops.
|
||||
segments.pop();
|
||||
let mut unit = first.to_string();
|
||||
for segment in &segments[1..] {
|
||||
let Some(next) = member_type(index, &unit, segment) else {
|
||||
return &[];
|
||||
};
|
||||
unit = next;
|
||||
}
|
||||
member_chain(index, &unit, name)
|
||||
}
|
||||
|
||||
impl ExternalResolutions {
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Definition, Resolution, ScopeKind, Semantics, SymbolId, SymbolKind,
|
||||
WorkspaceIndex,
|
||||
analyze, resolve_external, Definition, ExternalTarget, Resolution, ScopeKind, Semantics,
|
||||
SymbolId, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
@@ -623,6 +623,40 @@ endclass
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins the opacity promise `docs/features/out-of-class-constraints/README.md`
|
||||
/// makes without a test of its own: an out-of-block `constraint C::name { ... }`
|
||||
/// is exactly as opaque as the in-class form above — same `ItemKind::Verbatim(_)`
|
||||
/// arm in `bind.rs`, reached by the same item walker, item position never
|
||||
/// entered into it.
|
||||
#[test]
|
||||
fn an_out_of_block_constraint_is_absent_but_nothing_crashes() {
|
||||
let src = "\
|
||||
class my_seq;
|
||||
rand int num_trans;
|
||||
extern constraint num_trans_c;
|
||||
endclass
|
||||
|
||||
constraint my_seq::num_trans_c {
|
||||
num_trans inside {[1:20]};
|
||||
}
|
||||
";
|
||||
let s = sem(src);
|
||||
// No symbol for the constraint name, in-class prototype or out-of-block
|
||||
// definition alike — both are `ItemKind::Verbatim(_)` leaves.
|
||||
assert!(s.symbols().iter().all(|sym| sym.name != "num_trans_c"));
|
||||
assert_eq!(
|
||||
s.symbols().iter().map(|sym| sym.name.as_str()).collect::<Vec<_>>(),
|
||||
vec!["my_seq", "num_trans"]
|
||||
);
|
||||
assert!(s.reference_at(nth(src, "num_trans inside", 0)).is_none());
|
||||
// Queries at every offset stay panic-free.
|
||||
for offset in 0..=src.len() as u32 {
|
||||
let _ = s.definition_of(offset);
|
||||
let _ = s.symbol_at(offset);
|
||||
let _ = s.reference_at(offset);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Workspace index
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -705,8 +739,15 @@ fn workspace_symbols_list_classes_and_their_members() {
|
||||
assert!(runs.iter().any(|h| h.name == "run" && h.container == Some("driver")));
|
||||
}
|
||||
|
||||
/// **Changed 2026-09-01 by class-member-access** (topo §2.9-9, filed by this
|
||||
/// feature and delivered there). The single-file answer is exactly what it
|
||||
/// was — this crate still never chases a base, in this file or out of it — but
|
||||
/// the *overlay* now does: `resolve_external` follows the recorded base
|
||||
/// through the workspace's member tables and up its own `extends` chain. The
|
||||
/// old name of this test was
|
||||
/// `inherited_candidates_are_not_the_workspace_overlays_business`.
|
||||
#[test]
|
||||
fn inherited_candidates_are_not_the_workspace_overlays_business() {
|
||||
fn inherited_candidates_are_chased_by_the_overlay_and_only_by_it() {
|
||||
let sources = [
|
||||
("base.svh", "class base;\n int held;\nendclass\n"),
|
||||
(
|
||||
@@ -717,19 +758,27 @@ fn inherited_candidates_are_not_the_workspace_overlays_business() {
|
||||
let ws = index(&sources);
|
||||
let file = parse_source(sources[1].1).expect("child parses");
|
||||
let s = analyze(&file, sources[1].1);
|
||||
// The miss on `held` is an inherited candidate — never chased, even
|
||||
// though the base is right there in the workspace (the documented
|
||||
// future round).
|
||||
// The single-file layer's answer is unchanged: the base, and the (empty)
|
||||
// import paths the lexical walk collected. `held = 1` is a value
|
||||
// position, so the type-position promotion gave it no path to sweep.
|
||||
let held = s.reference_at(nth(sources[1].1, "held = 1", 0)).expect("the use");
|
||||
assert_eq!(
|
||||
held.resolution,
|
||||
Resolution::InheritedCandidate { base: "base".into(), paths: Vec::new() }
|
||||
);
|
||||
// Two reasons it is absent from the overlay, and both hold: `held = 1` is
|
||||
// a value position, so the promotion never gave it a path to sweep; and
|
||||
// even with one, a class property is not a unit, so the sweep would find
|
||||
// nothing and record nothing.
|
||||
// The overlay chases `base` itself: `member("base", "held")` answers.
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let id = s.reference_id_at(nth(sources[1].1, "held = 1", 0)).expect("an id");
|
||||
let def = overlay.get(id).and_then(ExternalTarget::best).expect("the inherited property");
|
||||
assert_eq!(ws.path(def.file).map(|p| p.file_name().unwrap()), Some("base.svh".as_ref()));
|
||||
assert_eq!(def.kind, SymbolKind::Var);
|
||||
|
||||
// A base the workspace does not hold is still absent from the overlay:
|
||||
// the chase ends at the first name nothing declares, and records nothing.
|
||||
let orphan = "class child extends nowhere_c;\n function void f();\n held = 1;\n endfunction\nendclass\n";
|
||||
let file = parse_source(orphan).expect("child parses");
|
||||
let s = analyze(&file, orphan);
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let id = s.reference_id_at(nth(orphan, "held = 1", 0)).expect("an id");
|
||||
assert!(overlay.get(id).is_none(), "a name the workspace cannot answer is not in the overlay");
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
//! `interface`, `modport` and `clocking` as declarations and references: the
|
||||
//! kind an interface gets, the members another file may reach through a
|
||||
//! `virtual` handle, and the two constructs that only live inside an interface.
|
||||
//! The rules live in `docs/features/interface-semantics/README.md`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, Symbol,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helpers
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let file = parse_source(src).expect("fixture must parse");
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src)))
|
||||
}
|
||||
|
||||
/// Offset of the `n`th (0-based) occurrence of `needle`.
|
||||
fn nth(src: &str, needle: &str, n: usize) -> u32 {
|
||||
src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32
|
||||
}
|
||||
|
||||
/// Offset of the first occurrence of `needle`.
|
||||
fn at(src: &str, needle: &str) -> u32 {
|
||||
nth(src, needle, 0)
|
||||
}
|
||||
|
||||
/// Offset of the name written just after `prefix` — the way a cursor lands on
|
||||
/// the second half of `bus_if.mp` or on the tail of `vif.sig`.
|
||||
fn after(src: &str, prefix: &str) -> u32 {
|
||||
at(src, prefix) + prefix.len() as u32
|
||||
}
|
||||
|
||||
/// The resolution of the reference written at `offset`, or `None` when this
|
||||
/// crate recorded no reference there at all.
|
||||
fn resolution(s: &Semantics, offset: u32) -> Option<Resolution> {
|
||||
s.reference_at(offset).map(|r| r.resolution.clone())
|
||||
}
|
||||
|
||||
/// The declaration the in-file layer says the use at `offset` names.
|
||||
fn resolved(s: &Semantics, offset: u32) -> &Symbol {
|
||||
let id = s
|
||||
.reference_at(offset)
|
||||
.unwrap_or_else(|| panic!("no reference at {offset}"))
|
||||
.resolved()
|
||||
.unwrap_or_else(|| panic!("the reference at {offset} resolves to nothing"));
|
||||
s.symbol(id).expect("a resolved id names a symbol")
|
||||
}
|
||||
|
||||
fn symbol<'a>(s: &'a Semantics, name: &str) -> &'a Symbol {
|
||||
s.symbols()
|
||||
.iter()
|
||||
.find(|sym| sym.name == name)
|
||||
.unwrap_or_else(|| panic!("no symbol named {name}"))
|
||||
}
|
||||
|
||||
/// The workspace's answer for the use at `offset` in `src`.
|
||||
fn overlay_def(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option<Def> {
|
||||
let s = sem(src);
|
||||
let id = s.reference_id_at(offset)?;
|
||||
resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned()
|
||||
}
|
||||
|
||||
/// The text a workspace definition points at, read back out of the sources it
|
||||
/// was built from.
|
||||
fn slice<'a>(ws: &WorkspaceIndex, files: &[(&'a str, &'a str)], def: &Def) -> &'a str {
|
||||
let path = ws.path(def.file).expect("an indexed def names a file");
|
||||
let src = files
|
||||
.iter()
|
||||
.find(|(name, _)| Path::new(name) == path)
|
||||
.expect("the file is one of the sources")
|
||||
.1;
|
||||
&src[def.name_span.as_range()]
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the interface itself
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_interface_is_its_own_kind_and_a_program_is_not() {
|
||||
let src = "interface bus_if;\nendinterface\nmodule m;\nendmodule\nprogram p;\nendprogram\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(symbol(&s, "bus_if").kind, SymbolKind::Interface);
|
||||
assert_eq!(symbol(&s, "m").kind, SymbolKind::Module);
|
||||
assert_eq!(
|
||||
symbol(&s, "p").kind,
|
||||
SymbolKind::Module,
|
||||
"a program is a module body with another closing keyword; it gets no export rule of its own this round"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_instantiation_resolves_in_file_and_across_files() {
|
||||
let together = "interface bus_if;\nendinterface\nmodule top;\n bus_if u_bus ();\nendmodule\n";
|
||||
let s = sem(together);
|
||||
assert_eq!(resolved(&s, at(together, "bus_if u_bus")).kind, SymbolKind::Interface);
|
||||
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||||
("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let use_at = at(sources[1].1, "bus_if u_bus");
|
||||
assert_eq!(
|
||||
resolution(&sem(sources[1].1), use_at),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] })
|
||||
);
|
||||
let def = overlay_def(&ws, sources[1].1, use_at).expect("the unit table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Interface);
|
||||
assert_eq!(slice(&ws, &sources, &def), "bus_if");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_into_an_interface_instance_names_its_port() {
|
||||
let src = "interface bus_if (input logic clk);\nendinterface\nmodule top;\n logic c;\n bus_if u_bus (.clk(c));\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let port = resolved(&s, after(src, "(."));
|
||||
assert_eq!(port.name, "clk");
|
||||
assert_eq!(port.kind, SymbolKind::Port);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interfaces_stay_instantiable_units_beside_modules() {
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||||
("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let units: Vec<(&str, SymbolKind)> =
|
||||
ws.instantiable_units().map(|(name, def)| (name, def.kind)).collect();
|
||||
assert_eq!(units, [("bus_if", SymbolKind::Interface), ("top", SymbolKind::Module)]);
|
||||
|
||||
// The instantiation census is unchanged: an interface instance is an edge.
|
||||
assert_eq!(ws.instantiations_of("bus_if").len(), 1);
|
||||
|
||||
let counts = ws.counts();
|
||||
assert_eq!(counts.modules, 1, "an interface is not counted as a module");
|
||||
assert_eq!(counts.interfaces, 1);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// modports
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const IFACE: &str = "interface bus_if;\n logic a;\n logic b;\n logic c;\n task drive ();\n endtask\n clocking cb @(posedge a);\n input b;\n endclocking\n modport mp (input a, output b, inout c, import drive, clocking cb);\nendinterface\n";
|
||||
|
||||
#[test]
|
||||
fn a_modport_is_a_symbol_spanning_its_own_declaration() {
|
||||
let s = sem(IFACE);
|
||||
let mp = symbol(&s, "mp");
|
||||
assert_eq!(mp.kind, SymbolKind::Modport);
|
||||
assert_eq!(&IFACE[mp.name_span.as_range()], "mp");
|
||||
assert_eq!(
|
||||
&IFACE[mp.decl_span.as_range()],
|
||||
"mp (input a, output b, inout c, import drive, clocking cb)",
|
||||
"the declaration span is this modport's own, not the whole `modport ...;` statement"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_name_in_a_modport_port_list_is_a_reference_to_the_interfaces_own() {
|
||||
let s = sem(IFACE);
|
||||
for (prefix, name, kind) in [
|
||||
("modport mp (input ", "a", SymbolKind::Var),
|
||||
("output ", "b", SymbolKind::Var),
|
||||
("inout ", "c", SymbolKind::Var),
|
||||
("import ", "drive", SymbolKind::Task),
|
||||
(", clocking ", "cb", SymbolKind::Clocking),
|
||||
] {
|
||||
let target = resolved(&s, after(IFACE, prefix));
|
||||
assert_eq!(target.name, name, "{prefix}");
|
||||
assert_eq!(target.kind, kind, "{prefix}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modport_name_that_names_nothing_records_nothing() {
|
||||
// IEEE 1800 §25.5: a modport port names a member of *this* interface. A
|
||||
// name the interface does not declare must not be walked outward onto the
|
||||
// file-scope `other_if` that happens to share it — a wrong answer where
|
||||
// recording nothing is merely a missing one.
|
||||
let src = "interface other_if;\nendinterface\ninterface bus_if;\n modport mp (input other_if);\nendinterface\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(resolution(&s, after(src, "modport mp (input ")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modport_half_of_a_port_type_resolves_in_file() {
|
||||
let src = "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\nmodule sub (bus_if.mp bus);\nendmodule\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(resolved(&s, at(src, "bus_if.mp")).kind, SymbolKind::Interface);
|
||||
let mp = resolved(&s, after(src, "bus_if."));
|
||||
assert_eq!(mp.kind, SymbolKind::Modport);
|
||||
assert_eq!(mp.name, "mp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modport_half_of_a_port_type_resolves_across_files() {
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"),
|
||||
("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[1].1;
|
||||
let tail = after(src, "bus_if.");
|
||||
assert_eq!(
|
||||
resolution(&sem(src), tail),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::mp".to_string()] })
|
||||
);
|
||||
let def = overlay_def(&ws, src, tail).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
assert_eq!(slice(&ws, &sources, &def), "mp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_virtual_interface_handle_keeps_its_modport_reference_and_its_bare_type() {
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"),
|
||||
("env.sv", "class env;\n virtual bus_if.mp vif;\nendclass\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[1].1;
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
symbol(&s, "vif").type_name.as_deref(),
|
||||
Some("bus_if"),
|
||||
"a modport restricts direction, not membership: the handle's type is the interface"
|
||||
);
|
||||
let def = overlay_def(&ws, src, after(src, "bus_if.")).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
assert_eq!(slice(&ws, &sources, &def), "mp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modport_named_in_a_connection_resolves_through_the_instance() {
|
||||
let together = "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\nmodule sub (bus_if.mp bus);\nendmodule\nmodule top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n";
|
||||
let s = sem(together);
|
||||
let mp = resolved(&s, after(together, ".bus(b_if."));
|
||||
assert_eq!(mp.kind, SymbolKind::Modport);
|
||||
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"),
|
||||
("top.sv", "module top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[1].1;
|
||||
let def = overlay_def(&ws, src, after(src, ".bus(b_if.")).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_interfaces_with_the_same_modport_name_answer_for_themselves() {
|
||||
let a = "interface a_if;\n logic x;\n modport mp (input x);\nendinterface\n";
|
||||
let b = "interface b_if;\n logic y;\n modport mp (input y);\nendinterface\n";
|
||||
let sources = [
|
||||
("a_if.sv", a),
|
||||
("b_if.sv", b),
|
||||
("sub.sv", "module sub (a_if.mp p, b_if.mp q);\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[2].1;
|
||||
|
||||
for (prefix, want) in [("a_if.", "a_if.sv"), ("b_if.", "b_if.sv")] {
|
||||
let def = overlay_def(&ws, src, after(src, prefix)).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
let file = ws.path(def.file).and_then(|p| p.file_name()).unwrap().to_string_lossy();
|
||||
assert_eq!(file, want, "{prefix} must answer with its own interface's modport");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// clocking blocks
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const CLOCKED: &str = "interface bus_if;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\nendinterface\n";
|
||||
|
||||
#[test]
|
||||
fn a_named_clocking_block_is_a_symbol_typed_by_its_enclosing_unit() {
|
||||
let s = sem(CLOCKED);
|
||||
let cb = symbol(&s, "cb");
|
||||
assert_eq!(cb.kind, SymbolKind::Clocking);
|
||||
assert_eq!(
|
||||
cb.type_name.as_deref(),
|
||||
Some("bus_if"),
|
||||
"a clocking signal aliases the enclosing unit's own signal, so the block's type is that unit"
|
||||
);
|
||||
// The event and the signal list are both ordinary uses of the interface's
|
||||
// declarations.
|
||||
assert_eq!(resolved(&s, at(CLOCKED, "posedge clk") + 8).name, "clk");
|
||||
assert_eq!(resolved(&s, after(CLOCKED, " input ")).name, "data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_signal_is_reached_through_the_block_in_file_and_across_files() {
|
||||
let together = format!("{CLOCKED}class env;\n virtual bus_if vif;\n task go ();\n if (vif.cb.data) begin\n end\n endtask\nendclass\n");
|
||||
let s = sem(&together);
|
||||
let hit = resolved(&s, after(&together, "vif.cb."));
|
||||
assert_eq!(hit.name, "data");
|
||||
assert_eq!(hit.kind, SymbolKind::Var, "the honest answer is the signal's own declaration");
|
||||
|
||||
let env = "class env;\n virtual bus_if vif;\n task go ();\n if (vif.cb.data) begin\n end\n endtask\nendclass\n";
|
||||
let sources = [("bus_if.sv", CLOCKED), ("env.sv", env)];
|
||||
let ws = index(&sources);
|
||||
let tail = after(env, "vif.cb.");
|
||||
assert_eq!(
|
||||
resolution(&sem(env), tail),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::cb::data".to_string()] })
|
||||
);
|
||||
let def = overlay_def(&ws, env, tail).expect("the member chain answers");
|
||||
assert_eq!(slice(&ws, &sources, &def), "data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_block_is_a_chain_head_inside_its_own_interface() {
|
||||
let src = "interface bus_if;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\n initial d = cb.data;\nendinterface\n";
|
||||
let s = sem(src);
|
||||
let hit = resolved(&s, after(src, "cb."));
|
||||
assert_eq!(hit.name, "data");
|
||||
assert_eq!(hit.kind, SymbolKind::Var);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_anonymous_default_clocking_declares_nothing() {
|
||||
let src = "interface bus_if;\n logic clk;\n default clocking @(posedge clk);\n endclocking\nendinterface\n";
|
||||
let s = sem(src);
|
||||
assert!(
|
||||
s.symbols().iter().all(|sym| sym.kind != SymbolKind::Clocking),
|
||||
"an unnamed block binds no name, so there is nothing to declare"
|
||||
);
|
||||
assert_eq!(resolved(&s, at(src, "posedge clk") + 8).name, "clk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_less_default_clocking_names_an_existing_block() {
|
||||
let src = "interface bus_if;\n logic clk;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendinterface\n";
|
||||
let s = sem(src);
|
||||
let hit = resolved(&s, at(src, "default clocking cb") + 17);
|
||||
assert_eq!(hit.kind, SymbolKind::Clocking);
|
||||
assert_eq!(hit.name, "cb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_block_in_a_module_behaves_the_same_way() {
|
||||
let src = "module tb;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\n initial d = cb.data;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(symbol(&s, "cb").type_name.as_deref(), Some("tb"));
|
||||
assert_eq!(resolved(&s, after(src, "cb.")).name, "data");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what an interface exports
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const EXPORTER: &str = "interface bus_if;\n parameter int WIDTH = 8;\n wire net_sig;\n logic var_sig;\n task drive ();\n endtask\nendinterface\n";
|
||||
|
||||
#[test]
|
||||
fn an_interfaces_signals_are_reachable_through_a_virtual_handle_across_files() {
|
||||
let env = "class env;\n virtual bus_if vif;\n task go ();\n x = vif.net_sig;\n y = vif.var_sig;\n z = vif.WIDTH;\n vif.drive();\n endtask\nendclass\n";
|
||||
let sources = [("bus_if.sv", EXPORTER), ("env.sv", env)];
|
||||
let ws = index(&sources);
|
||||
|
||||
for (want, kind) in [
|
||||
("net_sig", SymbolKind::Net),
|
||||
("var_sig", SymbolKind::Var),
|
||||
("WIDTH", SymbolKind::Param),
|
||||
("drive", SymbolKind::Task),
|
||||
] {
|
||||
let offset = at(env, &format!("vif.{want}")) + 4;
|
||||
let def =
|
||||
overlay_def(&ws, env, offset).unwrap_or_else(|| panic!("vif.{want} is unanswered"));
|
||||
assert_eq!(slice(&ws, &sources, &def), want);
|
||||
assert_eq!(def.kind, kind, "vif.{want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_interface_does_not_declare_is_still_unanswered() {
|
||||
let env = "class env;\n virtual bus_if vif;\n task go ();\n x = vif.nope;\n endtask\nendclass\n";
|
||||
let ws = index(&[("bus_if.sv", EXPORTER), ("env.sv", env)]);
|
||||
assert_eq!(
|
||||
overlay_def(&ws, env, after(env, "vif.")),
|
||||
None,
|
||||
"a signal the interface does not declare has no honest answer"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modules_internals_are_still_not_exported() {
|
||||
// The module ruling (`docs/features/class-member-access/README.md`, round
|
||||
// 2) is untouched: an interface's signals are its surface, a module's are
|
||||
// not.
|
||||
let sub = "module sub (input logic p);\n logic internal;\nendmodule\n";
|
||||
let ws = index(&[("sub.sv", sub)]);
|
||||
let members: Vec<&str> = ws.members_of("sub").map(|(name, _)| name).collect();
|
||||
assert_eq!(members, ["p"]);
|
||||
|
||||
let iface = index(&[("bus_if.sv", EXPORTER)]);
|
||||
let members: Vec<&str> = iface.members_of("bus_if").map(|(name, _)| name).collect();
|
||||
assert_eq!(members, ["WIDTH", "drive", "net_sig", "var_sig"]);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the index's own equalities, over the new declarations
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_interface_survives_encode_and_decode_unchanged() {
|
||||
let facts = FileFacts::of(PathBuf::from("bus_if.sv"), IFACE);
|
||||
let line = facts.encode().expect("a plain path encodes");
|
||||
assert_eq!(FileFacts::decode(&line), Some(facts), "modport and clocking kinds round-trip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incrementally_indexing_an_interface_gives_the_index_a_build_would() {
|
||||
let files = [
|
||||
("bus_if.sv", IFACE),
|
||||
("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"),
|
||||
("top.sv", "module top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n"),
|
||||
];
|
||||
let whole = index(&files);
|
||||
|
||||
let mut incremental = index(&files[..1]);
|
||||
for (path, src) in &files[1..] {
|
||||
incremental.update_file(PathBuf::from(path), src);
|
||||
}
|
||||
assert_eq!(incremental.fingerprint(), whole.fingerprint());
|
||||
|
||||
let mut absorbed = index(&[]);
|
||||
absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]);
|
||||
assert_eq!(absorbed.fingerprint(), whole.fingerprint());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modport_and_a_clocking_block_are_exported_members() {
|
||||
let ws = index(&[("bus_if.sv", IFACE)]);
|
||||
let members: Vec<(&str, SymbolKind)> =
|
||||
ws.members_of("bus_if").map(|(name, defs)| (name, defs[0].kind)).collect();
|
||||
assert!(members.contains(&("mp", SymbolKind::Modport)), "{members:?}");
|
||||
assert!(members.contains(&("cb", SymbolKind::Clocking)), "{members:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// measurement
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// What this round costs the index over the real corpus: the store's size and
|
||||
/// what it is *made of*, group by group, so a byte delta can be attributed
|
||||
/// rather than guessed at.
|
||||
///
|
||||
/// `#[ignore]`d, asserting nothing — the house shape for a measurement probe
|
||||
/// (`crates/lucisv_server/src/perf.rs`), and it reads only public API so the
|
||||
/// same file can be dropped into a checkout of an older revision to produce
|
||||
/// the "before" column. Run with
|
||||
/// `cargo test -p vlog_semantic --release --test interfaces -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "measurement over corpus/, printed rather than asserted"]
|
||||
fn what_interface_semantics_cost_the_index() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !root.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
collect(&root, &mut files);
|
||||
files.sort();
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let (mut bytes, mut records) = (0usize, 0usize);
|
||||
// The record's own length-prefixed groups: units, members, references.
|
||||
let (mut units, mut members, mut refs) = (0usize, 0usize, 0usize);
|
||||
let (mut local, mut external) = (0usize, 0usize);
|
||||
let (mut paths, mut path_bytes) = (0usize, 0usize);
|
||||
for path in &files {
|
||||
let Ok(src) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let Some(line) = FileFacts::of(path.clone(), &src).encode() else {
|
||||
continue;
|
||||
};
|
||||
bytes += line.len() + 1;
|
||||
records += 1;
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let group = |tag: &str| -> usize {
|
||||
fields
|
||||
.iter()
|
||||
.position(|f| *f == tag)
|
||||
.and_then(|at| fields.get(at + 1))
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(0)
|
||||
};
|
||||
units += group("U");
|
||||
members += group("M");
|
||||
refs += group("R");
|
||||
local += fields.iter().filter(|f| **f == "l").count();
|
||||
external += fields.iter().filter(|f| **f == "e").count();
|
||||
// An external fact's bytes are dominated by the paths it carries, so
|
||||
// the path text is counted apart from everything else.
|
||||
let mut at = 0;
|
||||
while at < fields.len() {
|
||||
if fields[at] == "e" {
|
||||
let count: usize = fields.get(at + 3).and_then(|n| n.parse().ok()).unwrap_or(0);
|
||||
paths += count;
|
||||
for i in 0..count {
|
||||
path_bytes += fields.get(at + 4 + i).map_or(0, |f| f.len());
|
||||
}
|
||||
at += 4 + count + 2;
|
||||
} else {
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let elapsed = start.elapsed();
|
||||
println!("corpus: {records} records, {bytes} store bytes, {elapsed:?} to read them all");
|
||||
println!("corpus groups: {units} units, {members} members, {refs} references ({local} local, {external} external)");
|
||||
println!("corpus paths: {paths} recorded paths, {path_bytes} bytes of path text");
|
||||
}
|
||||
|
||||
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -596,8 +596,13 @@ endmodule
|
||||
assert!(dups[0].0 < dups[1].0, "declaration order, so the first match is the first written");
|
||||
}
|
||||
|
||||
/// A hierarchical name through an **instance** resolves both halves since
|
||||
/// 2026-09-01 (class-member-access round 2): the instance's declared type is
|
||||
/// the module it instantiates, so the tail is looked up in that module's
|
||||
/// scope. A head that is neither typed nor a unit still resolves alone, which
|
||||
/// is what this test pinned before and still pins in its second half.
|
||||
#[test]
|
||||
fn a_hierarchical_name_resolves_only_its_head() {
|
||||
fn a_hierarchical_name_through_an_instance_resolves_both_halves() {
|
||||
let src = "\
|
||||
module m;
|
||||
sub u ();
|
||||
@@ -612,7 +617,24 @@ endmodule
|
||||
let s = sem(src);
|
||||
let head = s.reference_at(nth(src, "u.inner_sig", 0)).expect("the head");
|
||||
assert_eq!(head.resolved(), Some(symbol_id(&s, "u")));
|
||||
// The tail is not recorded at all — see the README's non-goals.
|
||||
let tail = s.reference_at(nth(src, "u.inner_sig", 0) + 2).expect("the tail");
|
||||
assert_eq!(tail.resolved(), Some(symbol_id(&s, "inner_sig")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_name_off_an_untyped_head_resolves_only_its_head() {
|
||||
let src = "\
|
||||
module m;
|
||||
logic [3:0] u;
|
||||
assign x = u.inner_sig;
|
||||
wire x;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let head = s.reference_at(nth(src, "u.inner_sig", 0)).expect("the head");
|
||||
assert_eq!(head.resolved(), Some(symbol_id(&s, "u")));
|
||||
// The tail is not recorded at all — a built-in type names no declaration
|
||||
// to look a member up in.
|
||||
let tail = nth(src, "u.inner_sig", 0) + 2;
|
||||
assert!(s.reference_at(tail).is_none());
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
|
||||
Semantics, SymbolKind, WorkspaceIndex,
|
||||
Semantics, SymbolKind, Utf16Pos, WorkspaceIndex,
|
||||
};
|
||||
|
||||
/// Build an index from `(path, source)` literals, as a server would from disk.
|
||||
@@ -487,6 +487,7 @@ fn counts_report_what_was_indexed() {
|
||||
.counts();
|
||||
assert_eq!(counts.files, 2);
|
||||
assert_eq!(counts.modules, 1);
|
||||
assert_eq!(counts.interfaces, 0, "interfaces are counted apart from modules");
|
||||
assert_eq!(counts.packages, 1);
|
||||
assert_eq!(counts.typedefs, 1);
|
||||
assert_eq!(counts.members, 1);
|
||||
@@ -530,7 +531,7 @@ fn an_unqualified_type_miss_carries_its_own_name_to_the_unit_table() {
|
||||
let defs = external_defs(&sem, &ws, sources[1].1, "bus_if bus");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(slice(&ws, &sources, &defs[0]), "bus_if");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Module, "an interface is a Module symbol");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Interface, "an interface has its own kind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -602,7 +603,7 @@ fn a_direction_less_first_ansi_port_binds_its_interface_type_cross_file() {
|
||||
let defs = external_defs(&sem, &ws, src, needle);
|
||||
assert_eq!(defs.len(), 1, "{needle}: {defs:?}");
|
||||
assert_eq!(slice(&ws, &sources, &defs[0]), "bus_if");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Module, "an interface is a Module symbol");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Interface, "an interface has its own kind");
|
||||
}
|
||||
|
||||
// The port itself is still declared, and `clk` beside it too: the shared
|
||||
@@ -618,10 +619,13 @@ fn a_direction_less_first_ansi_port_binds_its_interface_type_cross_file() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_member_the_unit_table_cannot_hold_stays_exactly_what_it_was() {
|
||||
// The other half of the same shape: an ordinary member miss. The sweep is
|
||||
// a *unit* lookup, and a property or a method is not a unit, so nothing
|
||||
// answers and the reference keeps its base and no overlay entry.
|
||||
fn an_inherited_member_the_unit_table_cannot_hold_is_answered_by_the_base_chase() {
|
||||
// The other half of the same shape: an ordinary member miss. The *sweep*
|
||||
// is a unit lookup, and a property or a method is not a unit, so the
|
||||
// promotion this feature added answers nothing here — what answers, since
|
||||
// class-member-access (2026-09-01, topo §2.9-9), is the chase of the
|
||||
// recorded `base` through the member tables. The single-file resolution
|
||||
// is untouched either way.
|
||||
let sources = [
|
||||
("base.sv", "class base;\n int held;\nendclass\n"),
|
||||
(
|
||||
@@ -634,9 +638,20 @@ fn an_inherited_member_the_unit_table_cannot_hold_stays_exactly_what_it_was() {
|
||||
|
||||
assert!(matches!(
|
||||
resolution(&sem, sources[1].1, "held = 1"),
|
||||
Resolution::InheritedCandidate { .. }
|
||||
Resolution::InheritedCandidate { paths, .. } if paths.is_empty()
|
||||
));
|
||||
assert!(!in_overlay(&sem, &ws, sources[1].1, "held = 1"));
|
||||
// No path to sweep at all, so the answer cannot have come from the
|
||||
// promotion; it is `member("base", "held")`.
|
||||
let defs = external_defs(&sem, &ws, sources[1].1, "held = 1");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(slice(&ws, &sources, &defs[0]), "held");
|
||||
assert_eq!(defs[0].kind, SymbolKind::Var);
|
||||
|
||||
// With the base outside the workspace there is nothing to chase, and the
|
||||
// reference stays exactly what it was — absent from the overlay.
|
||||
let orphan = "class child extends nowhere_c;\n function void f();\n held = 1;\n endfunction\nendclass\n";
|
||||
let sem = semantics(orphan);
|
||||
assert!(!in_overlay(&sem, &ws, orphan, "held = 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -790,6 +805,37 @@ fn reference_postings_point_from_a_declaration_to_every_cross_file_use() {
|
||||
assert!(!ws.references_are_ambiguous(definition));
|
||||
}
|
||||
|
||||
/// `files_spelling` is the postings table asked the other question: not "who
|
||||
/// refers to this declaration" but "who would notice if this name started
|
||||
/// meaning something". The difference is a use that resolved to **nothing**,
|
||||
/// which no posting can be keyed by — and which is exactly what a rename onto
|
||||
/// that name would give a meaning.
|
||||
#[test]
|
||||
fn files_spelling_finds_the_uses_no_posting_can_be_keyed_by() {
|
||||
let sources = [
|
||||
("dangling.sv", "module strayer;\n import absent_pkg::*;\nendmodule\n"),
|
||||
("resolved.sv", "module holder;\n sub u0 ();\nendmodule\n"),
|
||||
("quiet.sv", "module quiet;\n wire absent_pkg;\n assign absent_pkg = 1'b0;\nendmodule\n"),
|
||||
("sub.sv", "module sub; endmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let named = |name: &str| -> Vec<&Path> {
|
||||
ws.files_spelling(name).filter_map(|file| ws.path(file)).collect()
|
||||
};
|
||||
|
||||
// Nothing declares `absent_pkg`, so it is in no posting at all …
|
||||
assert!(ws.units("absent_pkg").is_empty());
|
||||
// … but the file importing it is found, and the file that merely declares
|
||||
// a local wire of the same name is not: a local declaration resolves
|
||||
// inside its own file and the workspace was never asked about it.
|
||||
assert_eq!(named("absent_pkg"), vec![Path::new("dangling.sv")]);
|
||||
|
||||
// A use that *did* resolve is here too — a name that already means
|
||||
// something can equally start meaning something else.
|
||||
assert_eq!(named("sub"), vec![Path::new("resolved.sv")]);
|
||||
assert!(named("nobody_spells_this").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_one_file_rebuilds_reference_postings_without_reparsing_the_others() {
|
||||
let declaration = "module sub; endmodule\n";
|
||||
@@ -1103,6 +1149,122 @@ fn removing_a_file_gives_the_index_a_whole_build_would_have() {
|
||||
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_a_batch_gives_the_index_a_whole_build_would_have() {
|
||||
// The batch form the interleaved scan feeds
|
||||
// (`docs/features/scan-interleave/README.md`), against the same witness
|
||||
// every other incremental path is held to. Every shape at once: a file
|
||||
// replaced, two files added — one of which sorts *first*, so every id
|
||||
// moves — and one dropped.
|
||||
let held = [
|
||||
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||||
("gone.sv", "module gone;\nendmodule\n"),
|
||||
];
|
||||
let mut ws = index(&held);
|
||||
assert_eq!(ws.files().len(), 3, "premise");
|
||||
|
||||
let batch = [
|
||||
("a.sv", "module sub;\nendmodule\n"),
|
||||
("m.sv", "module m;\n sub u1 ();\n sub u2 ();\nendmodule\n"),
|
||||
("zz.sv", "class leaf extends base;\nendclass\n"),
|
||||
];
|
||||
ws.absorb(
|
||||
batch.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(),
|
||||
&[PathBuf::from("gone.sv")],
|
||||
);
|
||||
|
||||
let mut expected: Vec<(&str, &str)> = vec![("z.sv", held[1].1)];
|
||||
expected.extend(batch);
|
||||
assert_eq!(
|
||||
ws.fingerprint(),
|
||||
index(&expected).fingerprint(),
|
||||
"a batch folded in is the index a whole build over what is left would have"
|
||||
);
|
||||
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the added file took FileId(0)");
|
||||
assert!(ws.units("gone").is_empty(), "and the dropped one is gone");
|
||||
assert_eq!(ws.instantiations_of("sub").len(), 2, "the replaced file's new edges are in");
|
||||
assert_eq!(ws.subclasses_of("base").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index() {
|
||||
// What makes a *publish* free of consequence: the scan folds records in
|
||||
// whenever it happens to be asked a question, so how the same records are
|
||||
// grouped into batches must not reach the result.
|
||||
let records = |files: &[(&str, &str)]| -> Vec<FileFacts> {
|
||||
files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect()
|
||||
};
|
||||
let files = [
|
||||
("a.sv", "module sub;\nendmodule\n"),
|
||||
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||||
("dup.sv", "module m;\nendmodule\n"),
|
||||
];
|
||||
let mut whole = WorkspaceIndex::default();
|
||||
whole.absorb(records(&files), &[]);
|
||||
|
||||
let mut piecemeal = WorkspaceIndex::default();
|
||||
for one in &files {
|
||||
piecemeal.absorb(records(std::slice::from_ref(one)), &[]);
|
||||
}
|
||||
assert_eq!(whole.fingerprint(), piecemeal.fingerprint());
|
||||
assert_eq!(whole.fingerprint(), index(&files).fingerprint(), "and both are a whole build");
|
||||
assert_eq!(piecemeal.units("m").len(), 2, "the duplicate name is still disambiguated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records() {
|
||||
// QA attack (`docs/features/scan-interleave/README.md`, absorb attacks):
|
||||
// a duplicate path inside one batch. Not constructible through the scan
|
||||
// that actually feeds `absorb` — `Scan::work` is built from `index_order`,
|
||||
// which already dedupes by path — but `absorb` is a public entry point on
|
||||
// `WorkspaceIndex`, and its doc comment claims "what comes out is the
|
||||
// index a full build over the records it now holds would have produced."
|
||||
// `WorkspaceIndex::build` goes through `index_order`, which keeps the
|
||||
// *first* of a duplicate path (`Vec::dedup_by`'s contract). `absorb`'s own
|
||||
// loop walks `records` left to right and overwrites on a hit, keeping the
|
||||
// *last*. So handed the exact same two records for one path, the two
|
||||
// entry points disagree — the claimed equivalence does not hold for a
|
||||
// batch with a duplicate path. Filed as a finding, not fixed here: which
|
||||
// one should win is a design call, not a QA fix.
|
||||
let files = [
|
||||
("a.sv", "module first_shape;\nendmodule\n"),
|
||||
("a.sv", "package second_shape;\nendpackage\n"),
|
||||
];
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
|
||||
|
||||
let mut absorbed = WorkspaceIndex::default();
|
||||
absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]);
|
||||
|
||||
assert_eq!(absorbed.files().len(), 1, "one file survives either way");
|
||||
assert_ne!(
|
||||
built.fingerprint(),
|
||||
absorbed.fingerprint(),
|
||||
"build (first-wins) and absorb (last-wins) disagree on a duplicate path in one batch"
|
||||
);
|
||||
// Naming what absorb actually did, so a fix that changes this is a
|
||||
// deliberate, visible diff rather than a silent behavior change.
|
||||
assert_eq!(
|
||||
absorbed.fingerprint(),
|
||||
index(&[("a.sv", files[1].1)]).fingerprint(),
|
||||
"absorb kept the second (last) record for the duplicate path"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_nothing_changes_nothing() {
|
||||
// A publish with nothing staged and a finish with nothing left are both
|
||||
// this call, and neither may disturb an index that is already right.
|
||||
let files = [("a.sv", "module a;\nendmodule\n")];
|
||||
let mut ws = index(&files);
|
||||
let before = ws.fingerprint();
|
||||
ws.absorb(Vec::new(), &[]);
|
||||
assert_eq!(ws.fingerprint(), before);
|
||||
ws.absorb(Vec::new(), &[PathBuf::from("never_held.sv")]);
|
||||
assert_eq!(ws.fingerprint(), before, "dropping a file the index never held is harmless");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_file_moves_the_disambiguation_winner() {
|
||||
// The sharpest thing a removal can do to a *derived* answer: the file that
|
||||
@@ -1267,6 +1429,16 @@ endmodule
|
||||
let text = files[0].1;
|
||||
assert_eq!(&text[sites[0].site_span.as_range()], "sub");
|
||||
assert_eq!(&text[sites[0].owner.name_span.as_range()], "top");
|
||||
assert_eq!(
|
||||
sites[0].instances.iter().map(|instance| instance.name.as_str()).collect::<Vec<_>>(),
|
||||
["u1", "u2"],
|
||||
"the statement edge keeps each instance without becoming two call sites"
|
||||
);
|
||||
for instance in &sites[0].instances {
|
||||
assert_eq!(&text[instance.name_span.as_range()], instance.name);
|
||||
assert!(instance.span.start <= instance.name_span.start);
|
||||
assert!(instance.name_span.end <= instance.span.end);
|
||||
}
|
||||
assert!(sites[0].owner.span.start <= sites[0].owner.name_span.start);
|
||||
assert!(sites[0].owner.name_span.end <= sites[0].owner.span.end);
|
||||
}
|
||||
@@ -1552,8 +1724,259 @@ fn a_records_every_field_survives_the_round_trip() {
|
||||
// inheritance edges — so this is the whole record, not a summary of it.
|
||||
assert_eq!(back, facts);
|
||||
assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte");
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
builder.add_facts(back);
|
||||
let restored = builder.finish();
|
||||
let instances = &restored.instantiations_of("sub")[0].instances;
|
||||
assert_eq!(instances.len(), 1);
|
||||
assert_eq!(instances[0].name, "u_sub");
|
||||
assert_eq!(&EVERY_FIELD[instances[0].name_span.as_range()], "u_sub");
|
||||
assert_eq!(&EVERY_FIELD[instances[0].span.as_range()], "u_sub ()");
|
||||
}
|
||||
|
||||
/// What format 4 wrote for an instantiation: the statement ended immediately
|
||||
/// after its module-name span, before the per-instance count and records added
|
||||
/// in format 5. It must be dropped, not field-shifted into the following `S`
|
||||
/// tag.
|
||||
#[test]
|
||||
fn a_format_4_record_without_instance_occurrences_is_rejected() {
|
||||
let facts =
|
||||
FileFacts::of(PathBuf::from("/w/i.sv"), "module top; sub u1 (), u2 (); endmodule\n");
|
||||
let encoded = facts.encode().expect("encodes");
|
||||
let mut fields: Vec<&str> = encoded.split('\t').collect();
|
||||
let instances_at = fields.iter().position(|field| *field == "I").expect("I tag");
|
||||
assert_eq!(fields[instances_at + 1], "1", "one statement edge");
|
||||
// I,count,module, owner(name + two ranges), site range = ten fields. The
|
||||
// next field is the occurrence count added in format 5; each occurrence is
|
||||
// thirteen more — name, two byte ranges, two client ranges.
|
||||
let occurrence_count_at = instances_at + 10;
|
||||
assert_eq!(fields[occurrence_count_at], "2", "two individual instances");
|
||||
fields.drain(occurrence_count_at..occurrence_count_at + 1 + 2 * 13);
|
||||
let format_4 = fields.join("\t");
|
||||
assert!(FileFacts::decode(&format_4).is_none(), "format 4 decoded as format 5");
|
||||
}
|
||||
|
||||
/// Every indexed declaration carries the line it is written on, so a caller
|
||||
/// printing `file:line` never has to read the file
|
||||
/// (`docs/features/hover-line-index/README.md`). The awkward offsets are the
|
||||
/// point: line 1 has no newline before it, the last line has none after it,
|
||||
/// and both are where an off-by-one lives.
|
||||
#[test]
|
||||
fn every_declared_names_line_is_recorded_when_the_file_is_indexed() {
|
||||
// No trailing newline, so `last_t` really is on the file's last line.
|
||||
let src = "module first;\nendmodule\n\n// a comment\npackage p;\n localparam W = 8;\n\
|
||||
endpackage\ntypedef int last_t;";
|
||||
let index = index(&[("/w/m.sv", src)]);
|
||||
let line_of = |name: &str| index.units(name).first().expect(name).lines.name;
|
||||
assert_eq!(line_of("first"), 1, "a declaration on line 1");
|
||||
assert_eq!(line_of("p"), 5);
|
||||
assert_eq!(line_of("last_t"), 8, "the last line, with no newline after it");
|
||||
assert_eq!(index.member("p", "W").first().expect("W").lines.name, 6, "members too");
|
||||
|
||||
// The line really is the line the text says it is: every recorded line's
|
||||
// range, sliced out of the source, contains the name it was recorded for.
|
||||
for (name, line) in [("first", 1), ("p", 5), ("last_t", 8)] {
|
||||
let text = src.lines().nth(line as usize - 1).expect("that many lines");
|
||||
assert!(text.contains(name), "line {line} is {text:?}, which does not declare {name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `\r\n` file and multi-byte text before a declaration do not shift its
|
||||
/// line: lines are counted in newlines, not in bytes or in characters.
|
||||
#[test]
|
||||
fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() {
|
||||
let crlf = "// one\r\n// two\r\nmodule m;\r\nendmodule\r\n";
|
||||
assert_eq!(index(&[("/w/c.sv", crlf)]).units("m").first().expect("m").lines.name, 3);
|
||||
|
||||
// Three-byte characters and a four-byte emoji ahead of the declaration:
|
||||
// the byte offset of `m` is far past 3, its line is not.
|
||||
let wide = "// héllo ✓ 🎉\n// ünïcödé\nmodule m;\nendmodule\n";
|
||||
assert!(wide.find("module m").expect("a module") > 20, "premise: the bytes are wide");
|
||||
assert_eq!(index(&[("/w/w.sv", wide)]).units("m").first().expect("m").lines.name, 3);
|
||||
}
|
||||
|
||||
/// The extension `DeclLines` was shaped for, taken: a file-scope declaration
|
||||
/// now also carries the two ranges a *client* is pointed at, in the units a
|
||||
/// client counts in — 0-based lines and UTF-16 code units.
|
||||
#[test]
|
||||
fn a_file_scope_declaration_carries_its_client_ranges() {
|
||||
let src = "// \u{1F389}\nmodule top;\nendmodule\n";
|
||||
let index = index(&[("/w/t.sv", src)]);
|
||||
let positions = index.units("top").first().expect("top").lines.positions.expect("positions");
|
||||
assert_eq!(positions.name.start, Utf16Pos { line: 1, character: 7 });
|
||||
assert_eq!(positions.name.end, Utf16Pos { line: 1, character: 10 });
|
||||
assert_eq!(positions.decl.start, Utf16Pos { line: 1, character: 0 });
|
||||
assert_eq!(positions.decl.end, Utf16Pos { line: 2, character: 9 });
|
||||
}
|
||||
|
||||
/// A multi-byte character before a name shifts its UTF-16 column away from the
|
||||
/// byte column the spans are in — the whole reason the conversion is done here
|
||||
/// rather than guessed at later.
|
||||
#[test]
|
||||
fn client_ranges_count_utf16_units_not_bytes() {
|
||||
// `🎉` is four bytes and two UTF-16 units; `é` is two bytes and one.
|
||||
let src = "/*\u{1F389}\u{e9}*/ module top; endmodule\n";
|
||||
let index = index(&[("/w/t.sv", src)]);
|
||||
let def = index.units("top").first().expect("top");
|
||||
let positions = def.lines.positions.expect("positions");
|
||||
assert_eq!(def.name_span.start, src.find("top").expect("top") as u32, "the byte span");
|
||||
// `/*`, two units of `🎉`, one of `é`, `*/`, a space, then `module `.
|
||||
assert_eq!(positions.name.start, Utf16Pos { line: 0, character: 15 }, "the client column");
|
||||
assert_eq!(positions.decl.start, Utf16Pos { line: 0, character: 8 });
|
||||
}
|
||||
|
||||
/// Every instance occurrence carries the same pair, for the other half of what
|
||||
/// a design-hierarchy row points at.
|
||||
#[test]
|
||||
fn every_instance_occurrence_carries_its_client_ranges() {
|
||||
let src = "module top;\n sub u1 (), u2 ();\nendmodule\n";
|
||||
let index = index(&[("/w/t.sv", src)]);
|
||||
let edges = index.instantiations_of("sub");
|
||||
let instances = &edges[0].instances;
|
||||
assert_eq!(instances.len(), 2);
|
||||
assert_eq!(instances[0].name_positions.start, Utf16Pos { line: 1, character: 6 });
|
||||
assert_eq!(instances[0].name_positions.end, Utf16Pos { line: 1, character: 8 });
|
||||
assert_eq!(instances[0].positions.start, Utf16Pos { line: 1, character: 6 });
|
||||
assert_eq!(instances[1].name_positions.start, Utf16Pos { line: 1, character: 13 });
|
||||
}
|
||||
|
||||
/// A member does not carry them, deliberately: there are two orders of
|
||||
/// magnitude more members than units and no caller for theirs, so the record
|
||||
/// spends nothing on them (`DeclPositions`).
|
||||
#[test]
|
||||
fn a_member_carries_lines_but_no_client_ranges() {
|
||||
let src = "module m (\n input wire clk\n);\nendmodule\n";
|
||||
let index = index(&[("/w/m.sv", src)]);
|
||||
let port = index.member("m", "clk").first().expect("the port");
|
||||
assert_eq!(port.lines.name, 2, "a member still carries its line");
|
||||
assert_eq!(port.lines.positions, None);
|
||||
assert!(index.units("m").first().expect("m").lines.positions.is_some(), "the unit does");
|
||||
}
|
||||
|
||||
/// A non-ANSI port is named in the header and finished in the body, and the
|
||||
/// carrier holds a line for each — the extension the shape was chosen for:
|
||||
/// richer per-declaration position data is another field on `DeclLines`, not
|
||||
/// another table.
|
||||
#[test]
|
||||
fn a_split_ports_two_lines_ride_the_same_carrier() {
|
||||
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
|
||||
let split = index(&[("/w/s.sv", src)]);
|
||||
let def = split.member("m", "clk").first().expect("the port");
|
||||
assert!(def.detail_span.is_some(), "premise: this port is split");
|
||||
assert_eq!(def.lines.name, 2, "the header names it on line 2");
|
||||
assert_eq!(def.lines.detail, Some(4), "and the body finishes it on line 4");
|
||||
|
||||
// An ANSI port is complete where it is named, and says so in both fields.
|
||||
let ansi = index(&[("/w/a.sv", "module m (\n input wire clk\n);\nendmodule\n")]);
|
||||
let def = ansi.member("m", "clk").first().expect("the port");
|
||||
assert_eq!(def.detail_span, None);
|
||||
assert_eq!((def.lines.name, def.lines.detail), (2, None));
|
||||
}
|
||||
|
||||
/// The lines survive the record format, which is what makes them free on a
|
||||
/// cached scan rather than only on a parsed one.
|
||||
#[test]
|
||||
fn a_declarations_lines_survive_the_record_round_trip() {
|
||||
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
|
||||
let facts = FileFacts::of(PathBuf::from("/w/s.sv"), src);
|
||||
let line = facts.encode().expect("encodes");
|
||||
let back = FileFacts::decode(&line).expect("decodes");
|
||||
assert_eq!(back, facts, "every field, lines included");
|
||||
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
builder.add_facts(back);
|
||||
let restored = builder.finish();
|
||||
let def = restored.member("m", "clk").first().expect("the port");
|
||||
assert_eq!((def.lines.name, def.lines.detail), (2, Some(4)));
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): the single-decl fixture `index_cache`'s own format-bump
|
||||
/// test strips is not the only shape a genuine format-3 record could take —
|
||||
/// a file declaring *two* units is the shape where a field-shift attack would
|
||||
/// actually have somewhere plausible to land: if stripping the first decl's
|
||||
/// two line fields shifted every read two fields early, the fields it would
|
||||
/// then misread as `(name_line, detail_line)` are the *second* decl's own
|
||||
/// `name` and `kind` strings. Both are always non-numeric — a Verilog
|
||||
/// identifier cannot start with a digit and `kind_name` writes only letters —
|
||||
/// so `Reader::num` fails on them and `decode` returns `None` rather than
|
||||
/// quietly building a `Decl` out of someone else's fields. Proved directly
|
||||
/// here, generalizing `index_cache`'s stripper to more than one declaration,
|
||||
/// rather than only argued.
|
||||
#[test]
|
||||
fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
|
||||
let src = "module a; endmodule\nmodule b; endmodule\n";
|
||||
let facts = FileFacts::of(PathBuf::from("/w/two.sv"), src);
|
||||
let encoded = facts.encode().expect("encodes");
|
||||
let format_3 = strip_every_decls_line_fields(&encoded, 2, 0);
|
||||
assert_ne!(format_3, encoded, "premise: fields were actually removed");
|
||||
assert!(
|
||||
FileFacts::decode(&format_3).is_none(),
|
||||
"a two-unit format-3 record decoded as a format-4 one: {format_3}"
|
||||
);
|
||||
|
||||
// The mixed case: one unit with a member that has a real detail span (a
|
||||
// split port), so the decls being stripped are not even the same width
|
||||
// of *content* — only of field count, which is what the format promises.
|
||||
let split = "module m (\n clk\n);\n input wire clk;\nendmodule\n\
|
||||
module other; endmodule\n";
|
||||
let facts = FileFacts::of(PathBuf::from("/w/mixed.sv"), split);
|
||||
let encoded = facts.encode().expect("encodes");
|
||||
let format_3 = strip_every_decls_line_fields(&encoded, 2, 1);
|
||||
assert_ne!(format_3, encoded, "premise: fields were actually removed");
|
||||
assert!(
|
||||
FileFacts::decode(&format_3).is_none(),
|
||||
"a mixed unit+member format-3 record decoded as a format-4 one: {format_3}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The generalization of `index_cache`'s old-record stripper: turn a record
|
||||
/// this format wrote back into what `FACTS_FORMAT` 3 wrote for the same file —
|
||||
/// remove, from every one of `units` unit-decls and `members` member-decls, the
|
||||
/// client positions added in format 5, the `decl_span` added in format 5, the
|
||||
/// declared type name added in format 7, and the two trailing (`name_line`,
|
||||
/// `detail_line`) fields added in format 4.
|
||||
/// Assumes `D0` (no `` `define``s), which every fixture here satisfies, so the
|
||||
/// `U` tag's field index is fixed and decl positions can be computed directly
|
||||
/// rather than parsed.
|
||||
fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) -> String {
|
||||
let mut fields: Vec<&str> = encoded.split('\t').collect();
|
||||
let units_at = fields.iter().position(|f| *f == "U").expect("a U tag");
|
||||
assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count");
|
||||
// A member's decl = name, kind, name_span×2, decl_span×2, detail_span×2,
|
||||
// line×2, type_name — 11 fields. A unit's is that plus its two client
|
||||
// ranges, four numbers each — 19.
|
||||
let members_at = units_at + 2 + units * UNIT_DECL_FIELDS;
|
||||
assert_eq!(fields[members_at], "M", "premise: members tag follows the units");
|
||||
assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count");
|
||||
// A member entry is the owning unit's name (one text field) plus a decl.
|
||||
let member_decl_starts: Vec<usize> =
|
||||
(0..members).map(|m| members_at + 2 + m * (MEMBER_DECL_FIELDS + 1) + 1).collect();
|
||||
let unit_decl_starts: Vec<usize> =
|
||||
(0..units).map(|u| units_at + 2 + u * UNIT_DECL_FIELDS).collect();
|
||||
// Highest index first, so removing one strip does not move the others, and
|
||||
// within one decl highest-first for the same reason.
|
||||
let mut starts: Vec<(usize, bool)> = unit_decl_starts
|
||||
.into_iter()
|
||||
.map(|start| (start, true))
|
||||
.chain(member_decl_starts.into_iter().map(|start| (start, false)))
|
||||
.collect();
|
||||
starts.sort_unstable_by_key(|start| std::cmp::Reverse(start.0));
|
||||
for (start, is_unit) in starts {
|
||||
if is_unit {
|
||||
fields.drain(start + MEMBER_DECL_FIELDS..start + UNIT_DECL_FIELDS);
|
||||
}
|
||||
fields.drain(start + 10..start + 11);
|
||||
fields.drain(start + 8..start + 10);
|
||||
fields.drain(start + 4..start + 6);
|
||||
}
|
||||
fields.join("\t")
|
||||
}
|
||||
|
||||
/// Fields one member declaration occupies in a record this format writes.
|
||||
const MEMBER_DECL_FIELDS: usize = 11;
|
||||
/// The same for a unit, which also carries its two client ranges.
|
||||
const UNIT_DECL_FIELDS: usize = MEMBER_DECL_FIELDS + 8;
|
||||
|
||||
#[test]
|
||||
fn an_index_built_from_records_is_the_index_the_parse_would_have_given() {
|
||||
// The claim the cache rests on: facts through the record format and back
|
||||
@@ -1668,7 +2091,9 @@ fn a_degenerate_file_still_makes_a_record() {
|
||||
/// `lucisv_server::state::Document::new` builds it — one lex, the tree from a
|
||||
/// clone of that token stream, the define table off the same tokens, and the
|
||||
/// same all-or-nothing lex-failure branch.
|
||||
fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics) {
|
||||
fn as_a_server_analyzes(
|
||||
src: &str,
|
||||
) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics, vlog_parser::LineIndex) {
|
||||
let (tokens, tree) = match tokenize(src) {
|
||||
Ok(tokens) => {
|
||||
let (tree, _) = parse_tolerant(tokens.clone(), src);
|
||||
@@ -1678,7 +2103,7 @@ fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable
|
||||
};
|
||||
let defines = collect_defines(&tokens);
|
||||
let sem = analyze(&tree, src);
|
||||
(tree, defines, sem)
|
||||
(tree, defines, sem, vlog_parser::LineIndex::new(src))
|
||||
}
|
||||
|
||||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||||
@@ -1720,9 +2145,9 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
];
|
||||
for src in crafted {
|
||||
let path = PathBuf::from("/w/x.sv");
|
||||
let (tree, defines, sem) = as_a_server_analyzes(src);
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
|
||||
let from_text = FileFacts::of(path.clone(), src);
|
||||
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem);
|
||||
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, src, &lines);
|
||||
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
|
||||
assert_eq!(
|
||||
from_analysis.encode(),
|
||||
@@ -1750,9 +2175,10 @@ fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
|
||||
let Ok(src) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let (tree, defines, sem) = as_a_server_analyzes(&src);
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(&src);
|
||||
let from_text = FileFacts::of(path.clone(), &src);
|
||||
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem);
|
||||
let from_analysis =
|
||||
FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &src, &lines);
|
||||
assert_eq!(
|
||||
from_analysis.encode(),
|
||||
from_text.encode(),
|
||||
@@ -1799,8 +2225,15 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
// Deliberately not path order: the reuse must not smuggle an ordering in.
|
||||
for (path, src) in files.iter().rev() {
|
||||
let (tree, defines, sem) = as_a_server_analyzes(src);
|
||||
builder.add_facts(FileFacts::from_analysis(PathBuf::from(*path), &tree, &defines, &sem));
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
|
||||
builder.add_facts(FileFacts::from_analysis(
|
||||
PathBuf::from(*path),
|
||||
&tree,
|
||||
&defines,
|
||||
&sem,
|
||||
src,
|
||||
&lines,
|
||||
));
|
||||
}
|
||||
let from_analyses = builder.finish();
|
||||
assert_eq!(from_analyses.fingerprint(), from_text.fingerprint());
|
||||
@@ -1809,12 +2242,14 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from
|
||||
// index `update_file` would have left.
|
||||
let mut updated = from_text.clone();
|
||||
let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n";
|
||||
let (tree, defines, sem) = as_a_server_analyzes(changed);
|
||||
let (tree, defines, sem, lines) = as_a_server_analyzes(changed);
|
||||
updated.update_facts(FileFacts::from_analysis(
|
||||
PathBuf::from("/w/pkg.sv"),
|
||||
&tree,
|
||||
&defines,
|
||||
&sem,
|
||||
changed,
|
||||
&lines,
|
||||
));
|
||||
let mut parsed = from_text.clone();
|
||||
parsed.update_file(PathBuf::from("/w/pkg.sv"), changed);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
|
||||
|
||||
What lucisv 0.21.0 does not yet handle, ranked by severity, from two
|
||||
independent sweeps crossed against each other:
|
||||
|
||||
- **Empirical probe** — 71 minimal-but-realistic files (44 RTL, 27 DV)
|
||||
covering the Verilog-2005 / SV-2017 features an RTL or DV engineer
|
||||
writes, each run through `--check`, `--stdout`, a second `--stdout`
|
||||
(idempotency) and a comment/layout eyeball; plus 13 headless LSP
|
||||
hover/definition spot checks. Probe files, harness and logs:
|
||||
the session scratchpad `survey/` (re-runnable). Snapshot binaries were
|
||||
used so concurrent dev rebuilds could not skew results.
|
||||
- **Documentation inventory** — every non-goal, deferral, verbatim
|
||||
capture, non-resolution rule, parse-error string and open handshake
|
||||
across `TODO.md`, `docs/topo.md` §2.9, `syntax_coverage.md` and all
|
||||
108 feature READMEs.
|
||||
|
||||
**Headline:** across every file that parsed, `format(format(x)) ==
|
||||
format(x)` held with zero exceptions and no comment was moved or lost.
|
||||
The gaps are (1) grammar holes, (2) regions the parser captures as opaque
|
||||
verbatim text — they *format* but nothing inside is navigable, renamable
|
||||
or lintable — and (3) semantic blind spots where the LSP answers nothing
|
||||
or, worse, the wrong thing.
|
||||
|
||||
Severity scale: **Critical** = wrong answer or a correctness risk on
|
||||
common code · **High** = common construct with no formatting or no
|
||||
navigation · **Medium** = less common construct, or partial behavior ·
|
||||
**Low** = rare construct or deliberate non-goal worth revisiting only on
|
||||
request.
|
||||
|
||||
---
|
||||
|
||||
## Critical
|
||||
|
||||
| # | Gap | Evidence | Why it ranks here |
|
||||
|---|---|---|---|
|
||||
| C1 | **Rename/references do not see inside verbatim regions** — constraint blocks, covergroups, `property`/`sequence` bodies, concurrent-assertion expressions, `randomize() with {…}`. | Documented: classes, assertions, dv-statements READMEs; vlog-semantic non-goals. | A DV rename of `user_id` rewrites every declaration and use the binder knows and **silently leaves `constraint c { user_id < 5; }` untouched** — output that does not compile. Same for a coverpoint on the renamed field. This is the one gap that turns a refactor into a correctness problem, and constraints/covergroups are in every UVM sequence item and coverage class. Fix path: parse constraint bodies (an expression grammar plus `inside`/`dist`/`->`/`soft`/`solve … before`/`foreach`/`if-else`) and covergroup bodies as real nodes; SVA property expressions can stay opaque longer but must at least yield *identifier occurrences* so rename can warn or refuse. |
|
||||
| C2 | **Modport port resolves to the wrong symbol.** Hover on `.m(b_if.mp)` answers with the instantiated *module*, definition jumps to the module, not the modport. | Probe: LSP check "modport port, used". Documented root: interfaces indexed as `Module`, modport names unbound (topo §2.9-7). | A wrong answer is worse than none. Needs `SymbolKind::Interface` + modport symbols; unlocks C3/H2 too. |
|
||||
|
||||
## High
|
||||
|
||||
| # | Gap | Evidence | Why |
|
||||
|---|---|---|---|
|
||||
| H1 | **Struct field access `s.field` — hover null, definition empty.** | Probe: struct field LSP check. Documented: vlog-semantic rule 4 ("nothing ever looks up into it"), topo §2.9-13. | `typedef struct packed {…} bus_t;` is the standard way RTL carries buses; every `.field` use is dark to hover/definition/references. Needs struct members as symbols (named typedefs and the anonymous form) plus the `type_name` link the §15 round-1 work introduces — the natural §15 round 2. |
|
||||
| H2 | **Virtual-interface signal access `vif.sig` — hover null.** | Probe: `vif.sig_a` LSP check. | The DV daily driver. Same mechanism as H1 once interfaces export their signals (C2's `SymbolKind::Interface`) and `virtual my_if vif` carries `type_name`. |
|
||||
| H3 | **Escaped identifiers are unformattable.** `wire \my-signal ;` → `verification failed: … output has identifier "\my-signal;"`. | Probe: two RTL files, both refused. | The formatter drops the mandatory terminating space, verify.rs catches it (invariant 1 holds), and the whole file is refused. Netlists and synthesis/tool-generated RTL are full of escaped names, so those files cannot be formatted at all. Small formatter fix (emit the space), attack tests owed. |
|
||||
| H4 | **Include-fragment files (`*.svh` class-body pieces) do not parse at all.** | The 6 remaining opentitan sweep failures (clocking-wave README §"11 left"); `cip_base_vseq__tl_errors.svh`, `riscv_custom_instr_enum.sv` etc. | UVM codebases split classes across `` `include``d fragments routinely; a fragment file gets no formatting, no diagnostics, no navigation — the LSP is simply off in it. A "fragment mode" (tolerant top-level fallback to a class-item / module-item / enum-member list when the file's top level fails) is bounded work and does not require preprocessing. |
|
||||
| H5 | **`` `define`` go-to-definition returns nothing** while hover shows the body. | Probe: macro LSP check. | Inconsistent and cheap: the define table already knows the site. |
|
||||
| H6 | **Class member chains `a.b.c` and instance heads `u.port`** through the index. | TODO §15 round 2 (filed); vlog-semantic rule 8. | Follows directly from §15 round 1 (needs `Def::type_name`, FACTS_FORMAT bump). `cfg.vif.clk` and `item.hdr.addr` are the common DV shapes; `u_sub.port` is the common RTL one. |
|
||||
|
||||
## Medium
|
||||
|
||||
| # | Gap | Evidence | Why |
|
||||
|---|---|---|---|
|
||||
| M1 | `specify … endspecify` / `specparam` and UDP `primitive … endprimitive` — hard parse errors. | Probe (3 files); README "still open". Corpus count 0, opentitan 0. | Absent from hand-written RTL, present in every std-cell / IO / memory simulation model a project vendors. Exclude patterns cover most; parsing (opaque-verbatim capture is enough) would stop the errors. |
|
||||
| M2 | `checker … endchecker` — parse error on the checker's port list; `checker` not even a keyword. | Probe; corpus has **13** files with it. | Formal-verification collateral; 13 corpus hits says it is real. |
|
||||
| M3 | `interface class` + `implements` — parse error. | Probe; interfaces/type-hierarchy READMEs. | UVM-style DV uses it occasionally; also blocks type-hierarchy's `implements` edges. |
|
||||
| M4 | Macro call with a space before `(` — `` `uvm_field_int (x, y) `` — clean parse error at item position. | macro-items/lexer-cleanup READMEs; measured 11 opentitan files. | A UVM spelling people actually type. Deliberately deferred because the lexer fix could break expression position; needs a careful round. |
|
||||
| M5 | Directives inside a list *element* or between an instance name and its `(`. | directives-in-instances README; measured 13 files. | The `.a(` ⏎ `` `ifdef `` ⏎ … ⏎ `)` shape in real port maps. |
|
||||
| M6 | Indexed hierarchical `bind` target (`bind top.gen[0].u_core …`). | bind README non-goals. | Binding SVA into generate arrays is common in formal setups. |
|
||||
| M7 | Semantic lints (`unused-signal`, `undriven-net`, `multiply-driven`) ship **off by default**. | linter-core / semantic-lints READMEs; blocked on topo §2.9-6 (workspace-wide "does any file mention this name"). | These are the lints RTL engineers want most; the index now has reference postings and `files_spelling`, so §2.9-6 is closer than when filed. |
|
||||
| M8 | Lint rules do not descend into verbatim regions; clocking blocks routed to `opaque_spans`. | assertions / clocking-wave READMEs. | Same root as C1; resolves with it. |
|
||||
| M9 | Statement-level format fences (inside `always`, case items, port lists) and fences inside class bodies (topo §2.9-3). | format-fences / classes READMEs. | Users protect hand-aligned tables inside procedural blocks; DV users protect them in classes. |
|
||||
| M10 | Error recovery does not reach headers and lists (port lists, parameter lists, for-headers) — a half-typed port list yields a garbage tree. | error-recovery README (QA-confirmed). | Editing experience: diagnostics cascade while typing a header. |
|
||||
| M11 | Anonymous aggregate members (`enum {A,B} x;`) not symbols (topo §2.9-13); cast type `state_t'(0)` records no reference. | overlay-promotion README; probe: enum *typedef'd* members do work. | Partial: named enums navigate, anonymous ones do not. |
|
||||
| M12 | No `lint` key in `lucisv.toml` (topo §2.9-4); no `--rules-doc`. | four READMEs. | Config surface, not language — but it gates per-project rule selection. |
|
||||
| M13 | Modport method prototypes (`import task drive(int x);`), `const` task/function arguments, unnamed DPI formals. | interfaces / dpi-export READMEs. | Real interface-class idioms; each a small grammar arm. |
|
||||
|
||||
## Low
|
||||
|
||||
| # | Gap | Evidence |
|
||||
|---|---|---|
|
||||
| L1 | `expect (@(posedge clk) prop);` — parsed as a call, not a keyword. | Probe. |
|
||||
| L2 | Tagged unions (`union tagged`, `tagged Valid`, `case … matches`). | Probe. |
|
||||
| L3 | `randsequence` production bodies. | Probe; classes README ("building for a user that does not exist" — corpus 0). |
|
||||
| L4 | `alias` statement. | Probe. |
|
||||
| L5 | `config … endconfig`, `library`. | Probe. |
|
||||
| L6 | `->>` non-blocking event trigger; stream `with [range]`; cast bases other than a name/system call; drive strength on a net declaration; net delay written after the type; `let` at statement position; `#(min:typ:max)` clocking skew. | expressions-2 / interfaces / dv-statements READMEs, TODO §11 skips. |
|
||||
| L7 | `` `ifdef `` conditions never evaluated (both arms listed); no macro expansion; stringification passes through. | TODO §7 non-goal — by design, like Verible. |
|
||||
| L8 | Execute-command spelling of the instantiation skeleton for clients without `inlineCompletion` (topo §2.9-19). | inline-instantiation README. |
|
||||
| L9 | `codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved. | TODO §10 deferred. |
|
||||
| L10 | Cosmetic: an enum body one-lined when short; `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` column (they are plain macro statements — no block for the formatter to see). | Probe observations. |
|
||||
|
||||
---
|
||||
|
||||
## What passed (so nobody re-probes it)
|
||||
|
||||
RTL: `always_ff`/`always_comb`/`always_latch`; `unique`/`unique0`/`priority`; `casez`/`casex`/`inside`; packed/unpacked struct/union/enum + typedefs; multi-dim packed arrays; `'{…}` patterns with default/index keys; streaming and replication; `+:`/`-:`; interfaces with modports, parameterized interface instantiation, interface ports; generate if/case/for with named blocks; `defparam`; `parameter type`; `$clog2`; gate primitives with strengths and delays; `wand`/`wor`/`tri1`/`supply0`; `@*`/`@(*)`; net/procedural/assign delays; `timeunit`/`` `timescale``; `` `define`` with args, `` `ifdef``/`` `elsif``/`` `else``, `` `include``, `` `default_nettype``; attributes; `import`/`export`; `let` (item); `bind`; `$unit`; every literal form; `++`/`+=`/`do while`/`foreach`/`repeat`/`forever`; `fork`/`join_any`/`join_none`, named events, `wait`, `wait fork`, `disable fork`; `void'()`; `static`/`automatic`; DPI import/export; `q[$]`.
|
||||
|
||||
DV: parameterized classes and `extends #()`; `virtual`/`pure virtual`/`extern` + out-of-class bodies; `static`/`local`/`protected`/`const`; `typedef class`; `this`/`super`/`new`; `rand`/`randc`; constraints with `inside`/`dist`/`->`/`if-else`/`soft`/`solve … before`/`foreach`/`unique`; `randomize() with`; `std::randomize`; queues/dynamic/associative arrays and their methods; `.sum`/`.find with`; virtual interfaces + clocking blocks; `program`, `mailbox`, `semaphore`, `process`; covergroups with `bins`/`cross`/`iff`/`sample()`; `property`/`sequence` with arguments; `assert`/`cover`/`assume property` with `|->`/`|=>`/`##[1:$]`/`throughout`/`$rose`/`$past`/`disable iff`; immediate assertions; `$cast`/`$sformatf`/`int'()`; string and enum methods; `$bits`/`$size`/`$typename`; UVM macro blocks incl. multi-line `` `uvm_info``; macro-as-statement; `case … inside` with `?`.
|
||||
|
||||
LSP: hover + definition for package-imported parameters, enum members, class parameters, function arguments, genvars, hierarchical instance ports (`u_sub.port_q`), `let` names.
|
||||
|
||||
## Recommended order
|
||||
|
||||
1. **§15 round 1** (in flight) → **H6 chains** as its round 2 — the same machinery, and it unlocks H1/H2 once the member tables exist.
|
||||
2. **C2 + H2**: `SymbolKind::Interface`, modport symbols, interface member export — fixes a wrong answer and the DV daily driver together.
|
||||
3. **H1**: struct members as symbols (with §2.9-13's anonymous forms).
|
||||
4. **H3**: the escaped-identifier space — a one-line formatter fix with attack tests; ship it in any adjacent round.
|
||||
5. **C1**: constraint and covergroup bodies as real nodes — the biggest single DV win and the one correctness risk; SVA expressions can follow.
|
||||
6. **H4**: fragment mode for `.svh` pieces.
|
||||
7. **M1–M3** grammar arms (specify/UDP/checker/interface class) as one "vendor and formal collateral" round, verbatim capture acceptable.
|
||||
8. **M7** semantic lints on by default via §2.9-6.
|
||||
|
||||
Two stale READMEs found by the inventory, to fix on the next docs pass:
|
||||
`docs/features/interfaces/README.md` still lists `program` and the
|
||||
clocking `= expression` as unsupported (delivered in §11 round 2);
|
||||
`docs/features/dv-statements/README.md` lists `foreach (a[, j])` as not
|
||||
done (delivered by testbench-mopup); `docs/features/assertions/README.md`
|
||||
says `interface` is still a parse error.
|
||||
@@ -36,11 +36,16 @@ write the port *second* to have anything to test.
|
||||
string; `bus_if.mp` follows the same rule, so no consumer needed a new
|
||||
field. The one place the two halves matter is `vlog_semantic`, which binds
|
||||
the interface half (below).
|
||||
- **A modport is not a symbol.** `ItemKind::Modport` is a leaf in
|
||||
`vlog_semantic` (it declares nothing into a scope), so the modport half of
|
||||
the type name is left unbound rather than recorded as a name that could
|
||||
never resolve. The day modports become symbols, the tail is where to bind
|
||||
them.
|
||||
- ~~**A modport is not a symbol.**~~ **Delivered 2026-09-01** by
|
||||
`docs/features/interface-semantics/README.md`: a modport is a
|
||||
`SymbolKind::Modport` declared in its interface's scope, and the tail of the
|
||||
glued type name is bound where this said it would be — in
|
||||
`bind_data_type`, as `Target::TypeMember { unit }`, resolved through the
|
||||
interface's own scope in-file and as the path `bus_if::mp` across files.
|
||||
Until then it read: *`ItemKind::Modport` is a leaf in `vlog_semantic` (it
|
||||
declares nothing into a scope), so the modport half of the type name is left
|
||||
unbound rather than recorded as a name that could never resolve. The day
|
||||
modports become symbols, the tail is where to bind them.*
|
||||
- **`module m (interface bus);`** — the *generic* interface port, whose type
|
||||
is the `interface` keyword itself — is a separate production and still does
|
||||
not parse. It is neither one of the three shapes filed nor reachable from
|
||||
@@ -105,10 +110,15 @@ its name, so it reports `iface_bus.mst` as the type with no change either.
|
||||
itself. It is a different production, none of the three filed shapes
|
||||
needs it, and it wants a `DataType` that can say "any interface", which
|
||||
is a modelling question this round should not answer in passing.
|
||||
- [ ] **Not done, deliberately: `virtual bus_if.mp v;`** — a modport-qualified
|
||||
virtual interface in a *declaration* (§25.9). Reaching it means teaching
|
||||
`parse_opt_data_type` about the dot, which changes how an identifier is
|
||||
read in every position; it needs its own round and its own attack tests.
|
||||
- [x] ~~**Not done, deliberately: `virtual bus_if.mp v;`**~~ — delivered by
|
||||
the testbench-mopup round (2026-08-29): `at_modport_port` — this
|
||||
feature's own gate — is reused at the two `virtual` positions, so the
|
||||
dot is read only where a modport can legally follow, exactly the
|
||||
narrow reading this item said a broad `parse_opt_data_type` change
|
||||
would violate. The pinning test here was amended in the same round
|
||||
(`the_two_shapes_left_open_by_ansi_first_port_still_refuse` still
|
||||
pins what genuinely remains open). See
|
||||
`docs/features/testbench-mopup/README.md`.
|
||||
- [ ] **Not done, pre-existing: `module m (a[3], b);`** — a non-ANSI port with
|
||||
a bit-select. It failed before this round and fails identically after
|
||||
(pinned by `a_broken_header_still_reports_its_own_token`), and it is not
|
||||
@@ -148,9 +158,10 @@ its name, so it reports `iface_bus.mst` as the type with no change either.
|
||||
- **`vlog_semantic` binds the interface, not the glued string.** Left alone,
|
||||
`bind_data_type` would have recorded a use of the name `bus_if.mp`, which
|
||||
resolves nowhere and never could. It now takes the half before the dot. The
|
||||
modport half is dropped rather than bound because this crate declares no
|
||||
symbol for a modport (`ItemKind::Modport` is a leaf, `bind.rs:364`) — a
|
||||
reference to a name nothing can declare is worse than no reference.
|
||||
modport half was dropped rather than bound because this crate declared no
|
||||
symbol for a modport — a reference to a name nothing can declare is worse
|
||||
than no reference. **Since 2026-09-01 it does declare one**, and both halves
|
||||
are bound (`docs/features/interface-semantics/README.md`).
|
||||
- **`type_def::type_span` needed the mirror of that.** The server matches a
|
||||
declaration site's type name against the references the binder left in the
|
||||
same window; with the site saying `bus_if.mp` and the reference saying
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -41,7 +41,13 @@ the deviations are stated where they happen.
|
||||
lucisv cannot see into a base class it does not model, so the full lexical
|
||||
chain is searched first and inheritance is the fallback. An in-file name
|
||||
therefore always wins over a hypothetical inherited one.
|
||||
4. **Inheritance is never chased — not even in-file.** `extends Base` itself
|
||||
4. **Inheritance is never chased — not even in-file.**
|
||||
*(Amended 2026-09-01 by class-member-access: an `extends` chain **this
|
||||
file declares** is now walked, so a `this.x` or a `handle.x` naming a base
|
||||
class's property in the same file resolves outright; a chain that leaves
|
||||
the file still stops here, exactly as below, and the workspace overlay
|
||||
chases it from there. Everything else in this rule stands.)*
|
||||
`extends Base` itself
|
||||
is resolved as a reference (rule 5). But a member use that misses the
|
||||
whole lexical chain, written inside a class whose nearest
|
||||
extends-carrying enclosing class says `extends Base`, becomes
|
||||
@@ -134,9 +140,11 @@ the deviations are stated where they happen.
|
||||
answers even though the class is not a file-scope unit.
|
||||
- `IndexCounts` gains a `classes` field (additive; all existing fields
|
||||
unchanged).
|
||||
- `resolve_external` does **not** chase `InheritedCandidate` — that is the
|
||||
documented future round, and the variant exists precisely so the index
|
||||
can do it without re-deriving anything.
|
||||
- ~~`resolve_external` does **not** chase `InheritedCandidate`~~ — **it does
|
||||
since 2026-09-01** (class-member-access), through the reverse edge
|
||||
`WorkspaceIndex::base_of` built from this same inheritance census. The
|
||||
variant existed precisely so the index could do it without re-deriving
|
||||
anything, and that is what happened: no `FileFacts` field was added.
|
||||
|
||||
## scan.rs status
|
||||
|
||||
@@ -213,10 +221,11 @@ variant does not compile without them; each is one arm, no logic):
|
||||
- `crates/lucisv_server/src/symbols.rs` — `SymbolKind::Class => "class"` in
|
||||
`kind_label`, `SymbolKind::Class => LspKind::CLASS` in `lsp_kind`.
|
||||
|
||||
**Requested of a future round (not done here):** chasing
|
||||
`InheritedCandidate` — in-file via `Semantics`, cross-file via the
|
||||
workspace member table (`member(base_tail, name)` is already the right
|
||||
lookup); and hover text for "class c extends base".
|
||||
**Requested of a future round:** ~~chasing `InheritedCandidate` — in-file via
|
||||
`Semantics`, cross-file via the workspace member table (`member(base_tail,
|
||||
name)` is already the right lookup)~~ — **delivered 2026-09-01 by
|
||||
class-member-access**, and by exactly that lookup. Still open: hover text for
|
||||
"class c extends base".
|
||||
|
||||
## Corpus acceptance
|
||||
|
||||
@@ -298,8 +307,18 @@ absent sources (`sail_ibexspec`, `SB_SPRAM256KA`, `PLLE2_ADV`, `uvm_pkg`).
|
||||
report prints the classes count, no existing assertion weakened or
|
||||
removed
|
||||
- [x] TODO.md §6 annotation; classes README handshake annotated delivered
|
||||
- [ ] Future round: chase `InheritedCandidate` (in-file + workspace);
|
||||
hover "extends base"
|
||||
- [x] ~~Future round: chase `InheritedCandidate` (in-file + workspace)~~ —
|
||||
**delivered 2026-09-01 by class-member-access** (topo §2.9-9):
|
||||
`resolve.rs` walks the `extends` chain as far as this file declares it
|
||||
(`member_in_chain`, feeding `this.x` and the new `head.member` tail),
|
||||
and `workspace.rs` walks it across files (`member_chain` inside
|
||||
`follow_one`, plus `resolve_external`'s chase of a bare `base`). Rule 4
|
||||
below is amended there: the *single-file* layer still never chases a
|
||||
base out of this file, and `base` still stays on the resolution — what
|
||||
changed is that an in-file base is now resolved outright, and the
|
||||
overlay finishes the rest. See
|
||||
`docs/features/class-member-access/README.md`.
|
||||
- [ ] Future round: hover "extends base"
|
||||
- [ ] Still blocked on parser handshake item 2: delete `scan.rs`
|
||||
|
||||
## Work log
|
||||
|
||||
@@ -0,0 +1,831 @@
|
||||
# clocking-wave
|
||||
|
||||
## Goal
|
||||
|
||||
Round 2 of the testbench-syntax wave: close every remaining bucket of the
|
||||
OpenTitan sweep that is a *grammar* gap rather than a preprocessing one, in one
|
||||
round. Six shapes — clocking-block signal bindings (`output tms = _tms;`), the
|
||||
standing `default disable iff`, an `iff` gate on an event-control term, a bare
|
||||
event control naming an indexed hierarchical path, a gate's drive strength, and
|
||||
`program … endprogram` — plus one engineering measurement: the chain-length
|
||||
limit, which real generated register files had outgrown. The sweep goes
|
||||
**43 → 11 failures**, and the eleven that remain are the two OUT rows the brief
|
||||
named (macro fragments that need preprocessing, and vendor files that are not
|
||||
SystemVerilog).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Clocking blocks are already modelled, not verbatim.** The brief expected
|
||||
the house verbatim-capture precedent to apply here (`constraint`,
|
||||
`covergroup`, concurrent assertions). It does not: `ClockingDecl` /
|
||||
`ClockingItem` have been real AST since the `interfaces` feature, with a
|
||||
printer arm, span coverage and a linter guard. Converting a working modelled
|
||||
construct into opaque bytes to close a one-field gap would have *lost*
|
||||
information, so the fix is the one field the grammar was missing. See the
|
||||
work log for the deviation.
|
||||
- **The 14-file "clocking" bucket is two shapes, not one.** Reading all
|
||||
fourteen sites showed seven failing on a clocking item's `= expression` and
|
||||
seven on `default disable iff` — which is not a clocking construct at all
|
||||
(IEEE 1800 §16.12, assertion control). The bucket label was a guess from the
|
||||
error text (`unsupported construct starting with keyword 'default'`); every
|
||||
site was read before a line was written.
|
||||
- **A clocking block stays opaque to the semantic layer.** `analyze` treats
|
||||
`ItemKind::Clocking` as a leaf and the linter takes the whole clocking item's
|
||||
span out through `opaque_spans`. The `= expression` a binding adds sits
|
||||
*inside* that span, so it neither declares, reads nor drives anything as far
|
||||
as the lints are concerned. That is deliberate — a clocking block's signals
|
||||
are driven and sampled by whatever testbench drives the block, which lucisv
|
||||
does not see — and it is pinned by a lint case rather than left implicit.
|
||||
- **`default disable iff` belongs in the verbatim bucket.** It holds
|
||||
`expression_or_dist` (a `dist { … }` set is legal there) and it exists to
|
||||
govern the concurrent assertions in its scope, which are already verbatim. A
|
||||
modelled node would have been half of a grammar lucisv deliberately does not
|
||||
model. It is the round's only new capture, and it ships with attack pairs.
|
||||
- **A `program` block is a module.** IEEE 1800 §24.3's `program_declaration` is
|
||||
the module header over the module body list with a different closer, so it
|
||||
reuses `Module` the way `interface` already does. The stricter *legality*
|
||||
rules a program has (no `always`, only interface instantiations) are a
|
||||
checker's business; lucisv is not a legality checker.
|
||||
- **Chain links, not source terms.** `MAX_CHAIN_LENGTH` counts AST layers on a
|
||||
path. A generated `|` chain of *N* registers costs *N* links for the
|
||||
operators plus whatever its deepest operand adds, so the number measured
|
||||
below is the budget, not the register count.
|
||||
- **Trailing commas are not SystemVerilog.** `named_parameter_assignment` has
|
||||
no empty alternative, so `#(.A(1), .B(2),)` is invalid input that some
|
||||
simulators tolerate. Skipped deliberately; see Status.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:** nothing new.
|
||||
|
||||
**Promised to `vlog_formatter` / `vlog_semantic` / `vlog_linter` — AST changes
|
||||
this round makes.** Every one is additive except the two marked *changed*,
|
||||
which are source-incompatible and were fixed up at each site:
|
||||
|
||||
| node | change | consumers touched |
|
||||
|---|---|---|
|
||||
| `ClockingItemKind::Signals` | *changed*: `names: Vec<Name>` → `signals: Vec<ClockingSignal>` | `format.rs::clocking_item`, `vlog_parser/tests/spans.rs`; `vlog_linter/src/signals.rs` matches `{ .. }` and is unaffected |
|
||||
| `ClockingSignal` | new: `{ name: Name, value: Option<Expr> }` | as above |
|
||||
| `SensItem::iff` | new: `Option<Expr>` | `format.rs::sens_list`, `vlog_semantic/src/bind.rs::bind_timing` |
|
||||
| `GateInstantiation::strength` | new: `Option<DriveStrength>` | `format.rs::gate_instantiation` |
|
||||
| `DriveStrength::second` | *changed*: `String` → `Option<String>` | `format.rs` (one new helper, `drive_strength`) |
|
||||
| `Module::end_kw()` | now answers `endprogram` for `kw == "program"` | every `Module` consumer, transparently |
|
||||
|
||||
**Promised to `vlog_semantic`:** an `iff` gate on an event-control term is
|
||||
bound as an ordinary read (`bind_timing`). A clocking block — bindings included
|
||||
— stays a leaf, and `ItemKind::Verbatim` (which `default disable iff` now also
|
||||
produces at module scope) keeps its existing "mentions nothing" contract.
|
||||
|
||||
**Promised to `vlog_linter`:** unchanged for the verbatim capture —
|
||||
`ItemKind::Verbatim` already routes to `opaque_spans`, so it inherits the right
|
||||
behaviour by doing nothing, the property
|
||||
`docs/features/directive-split/README.md` calls "not item scope, does not
|
||||
count" as the default.
|
||||
|
||||
**Widened for `vlog_linter`, deliberately: a `program` is a module to every
|
||||
rule.** Because `program` reuses `ItemKind::Module`, every generic
|
||||
`ItemKind::Module(_)` match now picks it up for free (QA, 2026-08-29) — so
|
||||
`vlog_linter::visit::items` descends into program bodies and `module-filename`
|
||||
holds a one-program file to the same name-matches-file convention as a module
|
||||
or an interface. That is the intended consequence of "a program is a module",
|
||||
not an accident: a program block is a compilation unit with a name, a header
|
||||
and a body, and every one of these rules is about exactly that. It is the same
|
||||
widening `interface` already made, and it is now pinned by two cases in
|
||||
`module_name_style.lint` so it cannot be reversed silently. **Filed, not fixed
|
||||
here:** `rules/module_name_style.rs` hardcodes the word "module" in its
|
||||
violation message regardless of `Module::kw`, so a badly-named program is
|
||||
reported as ``module `FooBar` is not lower_snake_case``. That inaccuracy is
|
||||
pre-existing — it has said the same thing about `interface` since before this
|
||||
round — and correcting it changes a message shared with `interface` and its own
|
||||
tests, which is outside this round's file set. One-line fix for whoever owns
|
||||
that rule next; the cases above pin today's behaviour either way.
|
||||
|
||||
**Requirement met, from `docs/features/recursion-limit/README.md`:** the bare
|
||||
event control's segment loop wraps what it has already built
|
||||
(`Box::new(previous)` per `.name` / `[expr]`), so it charges `link()` and
|
||||
restores the count it started from, the way `parse_postfix` does. It did *not*
|
||||
charge before this round — a pre-existing hole in the same shape that README's
|
||||
Handshakes warns about, closed here and pinned by a test.
|
||||
|
||||
**Changed for every consumer: `PARSE_STACK_SIZE` is now 32 MiB** (was 16). The
|
||||
rule is unchanged — any thread that can reach a parse is spawned with the
|
||||
constant — but the number moved, because `MAX_CHAIN_LENGTH` moved with it. See
|
||||
the recursion-limit README's round 4 for the measurement.
|
||||
|
||||
## The chain limit — measured, not guessed
|
||||
|
||||
`MAX_CHAIN_LENGTH = 256` rejected seven real files. The question is not "is 256
|
||||
too small" but "how long is the longest chain real code actually contains", and
|
||||
then "what does that cost on the stack".
|
||||
|
||||
**What is needed.** A high-water-mark probe (a scratchpad copy of the
|
||||
workspace, `links` recorded per file, limit raised out of the way; never built
|
||||
inside the repo) over all **3,943** OpenTitan files:
|
||||
|
||||
| file | links needed |
|
||||
|---|---|
|
||||
| `top_earlgrey/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` | **567** |
|
||||
| `top_englishbreakfast/…/pinmux_reg_top.sv` | 519 |
|
||||
| `top_darjeeling/…/pinmux_reg_top.sv` | 502 |
|
||||
| `top_darjeeling/…/alert_handler_reg_top.sv` | 397 |
|
||||
| `top_earlgrey/…/alert_handler_reg_top.sv` | 353 |
|
||||
| `rv_dm/rtl/rv_dm_mem_reg_top.sv` | 280 |
|
||||
| `top_darjeeling/…/rv_core_ibex_cfg_reg_top.sv` | 266 |
|
||||
|
||||
Distribution over the whole tree: 3,932 files under 128, four in 129–256, five
|
||||
in 257–512, two over 512. The shape is one `|` chain per generated register
|
||||
file — `(addr_hit[N] & (|(PERMIT[N] & ~reg_be))) | …` — so the number tracks
|
||||
the register count and grows with the design.
|
||||
|
||||
**What it costs.** Minimum surviving thread stack for the whole
|
||||
`format_source` pipeline, bisected one trial per subprocess (house method, same
|
||||
probe style as the recursion-limit rounds), rustc 1.97.1:
|
||||
|
||||
| shape | debug | release |
|
||||
|---|---|---|
|
||||
| nested `case` at the depth limit — the old global worst case | 5 959 KiB | 775 KiB |
|
||||
| `+` chain, 2048 terms | 567 KiB | 183 KiB |
|
||||
| the real `or_chain` shape, 2048 terms | 567 KiB | 183 KiB |
|
||||
| postfix chain (`a.b…`), 640 links | 5 911 KiB | 375 KiB |
|
||||
| postfix chain, 768 | 7 079 KiB | 455 KiB |
|
||||
| postfix chain, **1024** | **9 430 KiB** | 615 KiB |
|
||||
| postfix chain, 1280 | 11 798 KiB | 775 KiB |
|
||||
| 28 nested `case` **+** a 1024-link postfix chain inside | **9 894 KiB** | 727 KiB |
|
||||
| 64 nested `case` (trips depth) + a 1024-link chain inside | 5 959 KiB | 775 KiB |
|
||||
|
||||
Per link: (11 798 − 5 911) / 640 = **9.20 KiB debug**, 0.63 KiB release. The
|
||||
binary-operator chains that actually appear in the generated files are ~40×
|
||||
cheaper than that (the formatter's `binary_chain` flattens the left spine); the
|
||||
*postfix* chain is the worst case the limit has to be safe for, and it is what
|
||||
the numbers above are chosen from.
|
||||
|
||||
**The choice: 1024, and `PARSE_STACK_SIZE` 32 MiB.**
|
||||
|
||||
- 1024 is 1.8× the largest chain the real tree contains, on a number that grows
|
||||
with design size. 640 would have cleared today's files by 13 %, which is a
|
||||
fit, not a margin — and this limit has now been outgrown once.
|
||||
- At 1024 the debug worst case moves from 5 959 KiB (nesting) to **9 894 KiB**
|
||||
(a maximal chain inside nesting). So, for the first time, *the chain budget
|
||||
sets the global peak* — the "chains do not move the worst case" line in the
|
||||
recursion-limit README stops being true and is corrected there.
|
||||
- 16 MiB against 9.9 MiB is 1.65×, below the 2.7× the stack round settled on
|
||||
for a failure mode that is an abort rather than a diagnostic. 32 MiB is
|
||||
**3.3×**, and a thread stack costs address space rather than resident memory.
|
||||
- The two peaks still compose additively rather than multiplicatively, and the
|
||||
measurement shows why: 64 nested `case` *with* a 1024-link chain inside
|
||||
bisects to exactly the same byte as without it (5 959 KiB), because tripping
|
||||
the depth limit peaks in the parser and the chain peaks in the formatter.
|
||||
|
||||
The invariant becomes **64 + 1024 = 1088 layers**.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] **Clocking signal bindings** — `ClockingItemKind::Signals` carries
|
||||
`Vec<ClockingSignal>`; one new parse function, one printer arm. 7 files.
|
||||
- [x] **`default disable iff expr;`** — verbatim item, one dispatch arm, one
|
||||
scanner. 7 files (4 of them behind a second blocker, below).
|
||||
- [x] **A macro as a concurrent assertion's action statement** — not in the
|
||||
brief, but the next blocker on 4 of the 7 `default disable iff` files and
|
||||
on 2 more. `skip_action_stmt` ends the statement at a macro invocation
|
||||
when — and only when — nothing that could continue a statement follows
|
||||
it (`Parser::at_statement_tail`). **This is the one change with a
|
||||
whole-tree output effect; see the work log.** *Reworked after QA:* the
|
||||
first shipping shape decided from the macro *starting* a statement,
|
||||
which regressed four idioms where the macro is a name the statement goes
|
||||
on to use.
|
||||
- [x] **`iff` on an event-control term** — `SensItem::iff`, IEEE 1800 §9.4.2.
|
||||
5 files. LRM scope checked: `iff` gates one *event expression term*, so
|
||||
the parenthesized list is the only place it can appear — the bare
|
||||
`@name` form is a `hierarchical_event_identifier` with no `iff`
|
||||
alternative, and `wait`/`wait_order` take an expression, not an event
|
||||
expression. Both `,` and `or` separators still work around it.
|
||||
- [x] **Bare event control over an indexed path** — `.name` and `[expr]`
|
||||
segments, chain-budget charged. 3 files.
|
||||
- [x] **A gate's drive strength** — `GateInstantiation::strength`,
|
||||
`DriveStrength::second: Option<String>`; the mop-up's documented skip.
|
||||
1 file.
|
||||
- [x] **`program … endprogram`** — one dispatch arm reusing `parse_module`,
|
||||
one `end_kw` arm, `endprogram` added to `SYNC_CLOSERS` and `program` to
|
||||
`SYNC_OPENERS`. 3 files.
|
||||
- [x] **Chain limit 256 → 1024, `PARSE_STACK_SIZE` 16 → 32 MiB**, measured
|
||||
above; the recursion-limit README's invariant, tables and Status updated.
|
||||
7 files.
|
||||
- [x] OpenTitan sweep **43 → 11**, set difference: **0 newly failing**.
|
||||
- [x] Whole-tree superset check over all 3,943 files: exactly **one**
|
||||
previously-passing file's output moves, and it moves because 55 lines
|
||||
that used to be swallowed into an opaque verbatim blob are now parsed —
|
||||
see the work log.
|
||||
- [x] Corpus gate byte-identical: 813/820, and all **860** corpus files hash
|
||||
identically to trunk's output.
|
||||
- [x] `verify.rs` untouched; attack pairs for the one new capture.
|
||||
- [x] 12 parser unit tests (negatives and a tolerant regression included), 7
|
||||
`verification.rs` tests (1 re-indent + **6 attack pairs**), 3 new
|
||||
`spans.rs` `SOURCES` entries, 12 formatter cases in a new
|
||||
`clocking_wave.cases`, 3 lint cases pinning the opacity, 1 new
|
||||
`deep_nesting` test at the combined worst case. Workspace total
|
||||
2 425 → **2 625**.
|
||||
- [x] **QA rework (2026-08-29):** the macro-action decision moved onto what
|
||||
*follows* the call; QA's three `#[ignore]`d pins un-ignored and passing,
|
||||
plus the fourth shape and both sides of the decision. Tests now
|
||||
2 425 → **2 633**; the `program`-as-`Module` lint widening documented in
|
||||
Handshakes and pinned by two `module_name_style.lint` cases.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
|
||||
**Skipped, deliberately, with reasons:**
|
||||
|
||||
- [ ] **`hw/dv/sv/jtag_agent/jtag_if.sv`** — its clocking blocker *is* fixed;
|
||||
a second, independent, **pre-existing** blocker sits behind it. The file
|
||||
opens with two rival interface headers in an `` `ifdef ``/`` `else ``
|
||||
region (lines 6–12). Both are bracket-balanced complete headers, so
|
||||
`at_split_conditional` — which requires the arm to have left a bracket
|
||||
open — does not fire, and the parser nests the second header inside the
|
||||
first and runs out of `endinterface`s. Reproduced on trunk grammar
|
||||
alone (`` `ifdef G / module i #(…)(); / `else / module i #(…)(); /
|
||||
`endif / wire w; / endmodule ``), so it is not a regression of this
|
||||
round. Closing it means teaching `directive-split` about rival
|
||||
*declaration heads that are complete*, which is a design change to the
|
||||
safety-sensitive recovery, not a bucket fix. **Handshake request to a
|
||||
future `directive-split` round.**
|
||||
- [ ] **`SimDTM.sv`** — `wire [31:0] #0.1 x = y;`: a net delay written *after*
|
||||
the type, which is where IEEE 1800 A.2.1.3 puts it. lucisv parses a net
|
||||
delay only *before* the type, and `DataDecl` has one `delay` field with
|
||||
one print position — so accepting the other spelling and printing it back
|
||||
where it was written needs a positional field, or the safety net rightly
|
||||
refuses the reordered token stream. Two AST changes for one vendor file
|
||||
in `tb/unused/`. Bounded follow-up whenever a second file wants it.
|
||||
- [ ] **`kmac_reduced_tb.sv`** — a trailing comma in a *named* parameter
|
||||
override list (`.EntropyWidth(EntropyWidth),\n)`). Not legal
|
||||
SystemVerilog: `list_of_parameter_assignments` has no empty alternative
|
||||
(the empty-element allowance is for *ordered* port connections only).
|
||||
lucisv rejects invalid input on purpose, and nothing else in the tree
|
||||
writes it.
|
||||
- [ ] **`edn_env_cfg.sv`, `compare_helper.sv`** — a `for` loop standing where a
|
||||
class item goes, inside `` `uvm_object_utils_begin/end ``; and
|
||||
`assign x = `X_EACH_CSR 1;` where the macro expands to a run of
|
||||
`a == b &&`. Both are macro fragments: they are only grammatical after
|
||||
expansion. OUT per the brief.
|
||||
|
||||
**Out of scope, unchanged (the 11 remaining sweep failures):**
|
||||
|
||||
| file | why |
|
||||
|---|---|
|
||||
| `cip_base_vseq__tl_errors.svh` | `include fragment — a class body with no class |
|
||||
| `keccak_2share_fpv.sv`, `spi_device_scoreboard.sv` | case-arm macros |
|
||||
| `riscv_custom_instr_enum.sv` | `include fragment — enum members with no enum |
|
||||
| `riscv_instr_cover_group.sv` | covergroup fragment behind a macro |
|
||||
| `edn_env_cfg.sv`, `compare_helper.sv` | macro fragments (above) |
|
||||
| `riscv_core_setting.tpl.sv` | a Mako template, not SystemVerilog |
|
||||
| `SimDTM.sv`, `kmac_reduced_tb.sv`, `jtag_if.sv` | the three skips above |
|
||||
|
||||
**Recommended exclude patterns** rather than grammar work, for the files that
|
||||
are not SystemVerilog at all: `**/*.tpl.sv` (Mako templates),
|
||||
`**/vendor/google_riscv-dv/**` and `**/pulp_riscv_dbg/tb/unused/**`. Two of the
|
||||
eleven fall under these; the rest are real SystemVerilog that needs a
|
||||
preprocessor.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-29 — dev (round 2, the clocking wave)
|
||||
|
||||
**Method, and the hard rule.** Every sweep against
|
||||
`/Users/guoliangchen/repo/opentitan` used `--check` or `--stdout` only, with
|
||||
`git -C … status --porcelain` after every one; the checkout's single legitimate
|
||||
modification (`hw/ip/aes/dv/tb/tb.sv`) was the only thing it ever reported, on
|
||||
all five sweeps and both hash passes. Every bucket was read at its real
|
||||
`file:line` before a line was written — which is what caught the bucket
|
||||
mis-label below.
|
||||
|
||||
**Baseline: 43 failures over 3,943 files at trunk `5ad0772`** (the brief said
|
||||
44; the difference is the brief's own count, not a moved file). Recorded
|
||||
per-file with its message so every later claim is a set operation.
|
||||
|
||||
**The bucket table was wrong in one place, and reading the sites is what
|
||||
found it.** All seven "unsupported construct starting with keyword `default`"
|
||||
failures are `default disable iff <expr>;` — assertion control (§16.12), not a
|
||||
clocking construct. `default clocking @(posedge clk); endclocking` already
|
||||
parsed on trunk; I checked before assuming. So the 14-file bucket is 7 + 7.
|
||||
|
||||
**Deviation from the brief: no verbatim capture for clocking.** The brief asked
|
||||
for `clocking … endclocking` captured byte-exact as a leaf, on the house
|
||||
precedent. Clocking is already a modelled node with a printer, spans and a
|
||||
linter guard, and the seven failures are one missing production —
|
||||
`clocking_decl_assign`, §14.4's optional `= expression` on a signal. Replacing
|
||||
a working model with opaque bytes to fix a one-field gap would lose the
|
||||
structure the LSP and the linter already use, so the fix is the field. The
|
||||
brief's *opacity* requirement still applies and is honoured where it actually
|
||||
lives: `analyze` keeps `ItemKind::Clocking` a leaf and the linter takes the
|
||||
clocking item's whole span — the new binding expression included — out through
|
||||
`opaque_spans`, now pinned by a lint case instead of being implicit.
|
||||
|
||||
**The one new verbatim capture, and its attack pairs.** `default disable iff`
|
||||
scans to its own `;`, skipping bracketed runs whole so a `;` inside a
|
||||
`dist { … }` set does not end it early, then copies the bytes by span exactly
|
||||
as `parse_concurrent_assertion` does. `verify.rs` was **not touched** and **no
|
||||
normalization was added or widened**; the six attack pairs in
|
||||
`tests/verification.rs` are the ones the *existing* forgiveness (indentation,
|
||||
line breaks, comment re-indentation) could plausibly have masked — a flipped
|
||||
polarity, a dropped operand, a dropped comment, a dropped item, a re-joined
|
||||
multi-line condition, a changed `dist` weight — each asserted rejected.
|
||||
|
||||
**The macro action block: a bucket the brief did not have, and the round's only
|
||||
output move.** Fixing `default disable iff` moved four of its seven files onto
|
||||
a *new* first error, and two clocking files (`jtag_if`, `kmac_app_if`) onto one
|
||||
too. All six were the same shape: `assert property (p) else `ASSERT_ERROR(A)`
|
||||
with no `;`. `skip_action_stmt` scanned for a `;` and, not finding one, ran
|
||||
through whatever followed. So `skip_action_stmt` now ends the statement at a
|
||||
macro invocation — but **only one that starts a statement**, tracked with an
|
||||
`at_stmt_start` flag reset after an `else` continues one, because a macro
|
||||
standing mid-expression (`x = `VAL + 1;`) is an operand and the `;` still
|
||||
terminates. Both readings have a test.
|
||||
|
||||
That fix is what moves `hw/ip/prim/rtl/prim_sync_reqack.sv`, the **only** one
|
||||
of 3,943 files whose output changed. Before it, the `else `ASSERT_ERROR(…)` at
|
||||
line 364 ran the scan through the `` `endif ``, through
|
||||
`if (EnRstChks) begin : gen_assert_en_rst_chks`, and out at that block's `end`
|
||||
— so ~55 lines of ordinary generate-block code were absorbed into the
|
||||
assertion's opaque bytes and printed back unformatted. Now they are parsed and
|
||||
laid out. Verified: the new output is a fixed point, and a whitespace-insensitive
|
||||
token comparison against the source shows only line joins. This is a
|
||||
correctness improvement, not a regression, and it is the reason the round's
|
||||
superset check reports one move rather than zero.
|
||||
|
||||
**`iff`, and the LRM scope the brief asked about.** §9.4.2's
|
||||
`event_expression ::= [edge_identifier] expression [iff expression]` gates one
|
||||
*term*, and terms only exist inside `@( … )`. The paren-less form is
|
||||
`@ hierarchical_event_identifier`, which has no `iff` alternative; `wait` takes
|
||||
an expression, not an event expression. So one field on `SensItem` and one
|
||||
parse line covers every position, and `iff` being a keyword means
|
||||
`parse_expr` already stops in front of it. The formatter prints the gate before
|
||||
the separator so it stays attached to its own term.
|
||||
|
||||
**The bare event control, and a pre-existing chain hole.** The `@name` path
|
||||
grew `[expr]` segments beside the `.name` ones it already had (§A.9.3's
|
||||
`hierarchical_identifier` is exactly names with optional bit-selects), which is
|
||||
what the three rstmgr copies need. Taking both greedily is safe because no
|
||||
statement begins with `.` or `[`. Lifting the loop into
|
||||
`parse_bare_event_name` also closed a hole: the *existing* `.name` loop boxed
|
||||
one layer per iteration without charging `link()`, which is precisely the shape
|
||||
`docs/features/recursion-limit/README.md` makes a standing requirement. It now
|
||||
charges, and the caller restores the count it started from the way
|
||||
`parse_postfix` does.
|
||||
|
||||
**The gate strength, at the amortized cost the mop-up predicted.**
|
||||
`DriveStrength::second` becomes `Option<String>` (one new formatter helper,
|
||||
`drive_strength`, so `assign` and gates share one spelling) and
|
||||
`GateInstantiation` gains `strength`. The `(` still only opens a strength when
|
||||
a strength *keyword* follows it, so `buf b1 ((a & b), c);` is untouched — a
|
||||
case in the table pins that.
|
||||
|
||||
**`program`, not in the brief's table.** Three files, and it is IEEE 1800
|
||||
§24.3's "module header, module body, different closer". One dispatch arm
|
||||
reusing `parse_module`, one `Module::end_kw` arm, and the two sync lists.
|
||||
Taking it brings the sweep to exactly the brief's ~11 target.
|
||||
|
||||
**The chain limit, measured in three stages** (all in a scratchpad copy;
|
||||
nothing built inside the repo, and the probes' `unsafe` static and
|
||||
million-link limit never leave it): what the files need (567, whole-tree
|
||||
distribution), what a link costs (9.20 KiB debug per postfix link, bisected
|
||||
across four lengths so the slope is measured and not assumed), and what the
|
||||
combined worst case is (9 894 KiB at 1024). Full tables and the choice above.
|
||||
The one thing worth flagging is that the previous rounds' "chains do not move
|
||||
the worst case" no longer holds at this budget — it did at 256, where a
|
||||
maximal chain cost 2.4 MiB against nesting's 5.9 — so `PARSE_STACK_SIZE` is now
|
||||
measured against the chain, and moved to 32 MiB to keep the 2.7×-or-better
|
||||
margin the stack round argued for. `MAX_NESTING_DEPTH` is untouched: nothing
|
||||
about this round changes which nesting a file may use.
|
||||
|
||||
**Deliberately not done: making the chain non-recursive in the AST.** The
|
||||
brief allows that consideration only if the needed limit were absurd (>10k).
|
||||
567 is not; it is a limit that was set for a smaller tree.
|
||||
|
||||
**Verification, in this order.** Sweep 43 → 19 → 14 → 11, `git status` clean
|
||||
after each. Set difference over the failing file names: **0 newly failing**.
|
||||
Whole-tree superset: `--stdout` hashed for all 3,943 files under trunk's binary
|
||||
(built in a temporary detached worktree, removed afterwards) and under this
|
||||
one — 0 newly failing, 32 newly passing, 1 moved (analysed above). Corpus: all
|
||||
860 files hash identically to trunk, and the gate reports 813/820 unchanged.
|
||||
|
||||
**Files touched.** `crates/vlog_parser/src/ast.rs`,
|
||||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_parser/tests/spans.rs`,
|
||||
`crates/vlog_formatter/src/format.rs`,
|
||||
`crates/vlog_formatter/tests/cases/clocking_wave.cases` (new),
|
||||
`crates/vlog_formatter/tests/verification.rs`,
|
||||
`crates/vlog_formatter/tests/deep_nesting.rs`,
|
||||
`crates/vlog_semantic/src/bind.rs`,
|
||||
`crates/vlog_linter/tests/cases/unused_signal.lint`,
|
||||
`docs/features/recursion-limit/README.md`, `TODO.md`, this README.
|
||||
`crates/vlog_formatter/src/verify.rs` is **not** among them.
|
||||
|
||||
### 2026-08-29 (later) — dev, QA-driven rework
|
||||
|
||||
**QA's finding is correct, and the fix was the wrong shape rather than a
|
||||
missing guard.** The first version asked *"does a macro start this
|
||||
statement?"* — a question about the token before, when the information needed
|
||||
is entirely in the tokens after. A macro's expansion is a piece of text: it can
|
||||
be a whole statement (`` `ASSERT_ERROR(A) ``) or a signal name the statement
|
||||
goes on to assign to, read or increment (`` `SIG = 1'b1; ``, `` `CNT <= `CNT +
|
||||
1; ``, `` `MSG(x) + 1; ``, `` `CNT++; ``). The macro itself cannot tell those
|
||||
apart; the next token can. So the decision moved:
|
||||
|
||||
```rust
|
||||
let call = self.parse_macro_call()?;
|
||||
if call.semi || !self.at_statement_tail() { … return/chain … }
|
||||
// The macro was a name, not a statement. Scan on.
|
||||
```
|
||||
|
||||
`at_statement_tail` is one line — *the cursor is a `Symbol`* — because every
|
||||
way a statement continues past a name is spelled with one (`=`, `<=`, `+`,
|
||||
`++`, `.`, `[`, `::`), while everything that can stand after a complete action
|
||||
is a keyword, an identifier, another macro, a directive or EOF. Its doc comment
|
||||
records the asymmetry that makes the one-liner safe: guessing "continues" when
|
||||
the statement was in fact complete only falls back to the brute-force scan that
|
||||
ran before this case existed, i.e. to trunk; guessing "complete" when it was
|
||||
not is the regression, and non-symbols cannot continue an expression.
|
||||
|
||||
**Why not QA's literal suggestion** ("fall through to the ordinary scan
|
||||
whenever `;`/`else` does not follow"): that is the *old* over-scan for the case
|
||||
this round exists to fix — `` else `ASSERT_ERROR(A) `` has neither, and falling
|
||||
through is exactly what swallowed 55 lines of `prim_sync_reqack.sv`. The
|
||||
predicate is the missing third answer between "ends" and "scan on".
|
||||
|
||||
**Verified both directions against the real trunk binary**, not just the suite.
|
||||
All four QA shapes now produce **byte-identical** output to `5ad0772`
|
||||
(`--stdout`, diffed per shape). The six OpenTitan files this case unblocked
|
||||
still parse, `prim_sync_reqack.sv` still moves exactly as documented, and the
|
||||
sweep and whole-tree superset re-ran with the same numbers.
|
||||
|
||||
**Tests.** QA's three `#[ignore]`d pins are now active and green (their
|
||||
`#[ignore]` attributes removed and the "not fixed here" comment above them
|
||||
replaced with what the fix does). Added
|
||||
`a_macro_postfix_increment_is_not_the_whole_action_statement` (QA's fourth
|
||||
shape) and `a_macro_action_still_ends_where_no_statement_tail_follows`, which
|
||||
walks the four token kinds that can stand after a complete macro action — a
|
||||
keyword, a label identifier, another macro, a directive — so the *other* side
|
||||
of the decision is pinned too, not just the regression side. One more
|
||||
`clocking_wave.cases` entry round-trips all four shapes through the formatter.
|
||||
|
||||
**QA's LOW note folded in.** The `program`-as-`ItemKind::Module` lint widening
|
||||
is documented in Handshakes as deliberate, with the `module-name-style` message
|
||||
wording filed rather than fixed (pre-existing for `interface`, shared rule,
|
||||
outside this round's file set), and pinned by two new cases in
|
||||
`module_name_style.lint`.
|
||||
|
||||
**Files touched by the rework:** `crates/vlog_parser/src/parser.rs`,
|
||||
`crates/vlog_formatter/tests/cases/clocking_wave.cases`,
|
||||
`crates/vlog_linter/tests/cases/module_name_style.lint`, this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-29 — QA agent (round 2 verification)
|
||||
|
||||
**Verdict: REWORK (medium-high severity, one finding), everything else
|
||||
confirmed.** One real bug in the round's own charter-flagged risk area
|
||||
(the `skip_action_stmt` macro heuristic); every other claim in the work
|
||||
log reproduced exactly, including the chain-limit margin math with a
|
||||
sabotage check that genuinely aborts.
|
||||
|
||||
**Method.** Read CLAUDE.md, the work log above (all three premise
|
||||
corrections, all three skips), `docs/features/recursion-limit/README.md`
|
||||
round 4, and the dev brief. Built the round-2 tree and a detached
|
||||
`5ad0772` worktree, both `--release`, so every comparison below is
|
||||
binary-vs-binary, not test-suite-vs-claim. Every OpenTitan sweep used
|
||||
`--check`/`--stdout` only; `git -C .../opentitan status --porcelain`
|
||||
after every pass showed only `hw/ip/aes/dv/tb/tb.sv`, never anything else.
|
||||
|
||||
**BLOCKING — `skip_action_stmt`'s macro-at-statement-start check ends the
|
||||
scan too early when the macro is an operand or an lvalue, not a whole
|
||||
statement** (`crates/vlog_parser/src/parser.rs`, the `at_stmt_start` branch
|
||||
added this round, ~line 2021). The check assumes any macro token standing
|
||||
first in an action is *the entire action*, terminated by its own `;` or by
|
||||
chaining another one via `else`. That assumption is false whenever the
|
||||
macro's expansion is only the first sub-token of a larger statement — it
|
||||
stands for a signal name, not a full statement — and this happens for
|
||||
completely ordinary RTL/testbench idioms:
|
||||
|
||||
```
|
||||
A_A: assert property (a) else `SOME_SIGNAL = 1'b1; // macro as an lvalue
|
||||
A_A: assert property (a) else `MSG(x) + 1; // macro as an operand (the charter's own example)
|
||||
A_A: assert property (a) else `CNT <= `CNT + 1; // macro standing for a counter register
|
||||
A_A: assert property (a) else `CNT++;
|
||||
```
|
||||
|
||||
In each case `parse_macro_call` fails to eat a `;` (the next token is `=`,
|
||||
`+`, `<=`, `++`), `eat_kw("else")` then also fails, and the function
|
||||
returns `Ok(())` immediately — leaving the rest of the statement
|
||||
(`= 1'b1;`, `+ 1;`, …) on the token stream to be misread as the start of a
|
||||
new module item, which is a parse error (`expected item (found "=")`,
|
||||
etc.). **Confirmed on the real debug binary, both directions:**
|
||||
|
||||
```
|
||||
$ ./target/debug/lucisv --stdout a1_macro_lvalue.sv # round 2
|
||||
error: ...: parse error: 2:46: expected item (found "=")
|
||||
$ git stash && cargo build -p lucisv && ./target/debug/lucisv --stdout a1_macro_lvalue.sv # trunk 5ad0772
|
||||
module m;
|
||||
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
|
||||
assign y = 1;
|
||||
endmodule
|
||||
```
|
||||
|
||||
All four shapes above parse cleanly on trunk (no macro special-case at all
|
||||
— the old brute-force scan just runs to the real `;`) and fail to parse on
|
||||
round 2. This is exactly the charter's sin #1 ("an action scan that ends
|
||||
too early") and exactly the shape the charter's own example
|
||||
(`` `MSG(x) + 1; ``) named as worth checking. It does **not** corrupt
|
||||
output — invariant #1 holds, because the failure is an outright parse
|
||||
error, not a silently-wrong reformat — but it is a genuine, reproducible
|
||||
regression in *acceptance*: files with this pattern that parsed
|
||||
successfully on trunk now fail to format at all. It happens not to appear
|
||||
anywhere in the swept 3,943-file OpenTitan tree or the 860-file corpus
|
||||
today (both reproduced clean below), which is why the round's own
|
||||
sweep/superset checks did not catch it — but that is a statement about
|
||||
today's two trees, not about the fix's correctness.
|
||||
|
||||
The macro-terminates-the-action case the round actually needed
|
||||
(`` else `ASSERT_ERROR(A_A) `` with nothing after it, or chained with
|
||||
`else`) is real and correctly fixed; the bug is only in how the code tells
|
||||
that case apart from "a macro starts a larger statement". A plausible fix:
|
||||
before committing to the short return, check that `;` or `else` *actually*
|
||||
follows the macro (which the code already does, via `eat_sym`/`eat_kw`);
|
||||
on failure it currently just returns anyway. It needs to instead fall back
|
||||
to the ordinary token-by-token scan from wherever the macro call left the
|
||||
cursor, the same way it would have if the macro check didn't exist. Left
|
||||
to the dev — this changes control flow in a checked capture, not a
|
||||
one-line fix.
|
||||
|
||||
**Permanent regression tests added**, `crates/vlog_parser/src/parser.rs`
|
||||
(`mod tests`), marked `#[ignore]` (not left red — see below) with the
|
||||
finding quoted in the doc comment:
|
||||
`a_macro_used_as_an_lvalue_is_not_the_whole_action_statement`,
|
||||
`a_macro_used_as_an_operand_before_an_operator_is_not_the_whole_action_statement`,
|
||||
`a_macro_counter_increment_is_not_the_whole_action_statement`. Verified
|
||||
each one currently **fails** when run explicitly
|
||||
(`cargo test -p vlog_parser -- --ignored <name>`, 3 failed / 0 passed),
|
||||
confirming they pin the real bug rather than being vacuous; un-ignore once
|
||||
fixed. Also added three passing tests for edges that *did* hold up (below).
|
||||
|
||||
**Everything else in the charter, confirmed:**
|
||||
|
||||
1. **`default disable iff` bracket scan — solid.** Attacked with the real
|
||||
binary: a `;` inside a string (`x == "a;b"`), a `;` inside a block
|
||||
comment (`/* ; */`), two `default disable iff` items back to back, and
|
||||
EOF before the terminating `;`. All four behave correctly (string/
|
||||
comment cases parse through unaffected because the lexer already
|
||||
tokenizes strings whole and comments as trivia, not because the scanner
|
||||
does anything special; two-in-a-row capture separately; EOF is a clean
|
||||
`expected \`;\`` error, not a swallowed rest-of-file). Added as permanent
|
||||
tests: `a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_string`,
|
||||
`a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_comment`,
|
||||
`two_default_disable_iffs_in_a_row_are_captured_separately`. The six
|
||||
`verification.rs` attack pairs are legitimate: `verify.rs` was not
|
||||
touched, and none of the six rely on a normalization the capture
|
||||
introduced — they exercise the *pre-existing* generic net (byte-exact
|
||||
comparison outside `Directive`/`Attribute`/backtick-`Ident` tokens,
|
||||
line-trim only for comments) against a new *source* of `RawText`, which
|
||||
is the correct, minimal thing to test per CLAUDE.md rule 4 (no
|
||||
normalization was added, so there is nothing new to attack beyond
|
||||
proving the generic net still sees every token inside this capture —
|
||||
which the six pairs do).
|
||||
|
||||
2. **Chain math — reproduced, and the margin is real, not overstated.**
|
||||
`cargo test -p vlog_formatter --test deep_nesting`: 5/5 pass, including
|
||||
`a_maximal_chain_inside_deep_nesting_formats` (the 9.9 MiB combined
|
||||
worst case) at the shipped `PARSE_STACK_SIZE = 32 MiB`. **Sabotage
|
||||
check, as the charter asked**: set `MAX_CHAIN_LENGTH = 4096` with the
|
||||
stack left at 32 MiB, rebuilt — `a_maximal_chain_inside_deep_nesting_formats`
|
||||
(spelled generically off the constant) now dies with a genuine
|
||||
`SIGABRT` / "stack overflow" (not a graceful test failure), confirming
|
||||
the chosen 1024 actually needs the 32 MiB and the margin claim is not
|
||||
inflated. Reverted immediately; `cargo test -p vlog_formatter --test
|
||||
deep_nesting` back to 5/5 green.
|
||||
`pinmux_reg_top.sv` (567 links, the file that started the round) parses
|
||||
with the release binary — `--check` reports "would reformat", not a
|
||||
parse error.
|
||||
|
||||
3. **New-field audit.** `ClockingSignal.value`: only consumed in
|
||||
`format.rs::clocking_item` and matched by `signals.rs:366`'s
|
||||
`ClockingItemKind::Signals { .. }` wildcard (correctly opaque — pinned
|
||||
by the three new `unused_signal.lint` cases, which I re-ran directly and
|
||||
confirm: the clocking-bound signal, the `default disable iff` name, and
|
||||
the `iff`-gated `enable` behave exactly as documented — opaque, opaque,
|
||||
read respectively). `SensItem::iff` is bound as an ordinary read in
|
||||
`bind.rs:1084-1090` (`bind_expr`), matching the lint case. `DriveStrength
|
||||
::second`/`GateInstantiation::strength`: the one non-test consumer,
|
||||
`format.rs::gate_instantiation`/`drive_strength`, handles `None`
|
||||
correctly (prints the single-strength form). **`program`-as-`Module`
|
||||
wildcard side effect (not a bug, but undocumented):** because `program`
|
||||
reuses `ItemKind::Module`, every generic `ItemKind::Module(_)` match
|
||||
picks it up for free — including `vlog_linter::visit::items` (so every
|
||||
lint rule now descends into program bodies) and
|
||||
`rules/module_filename.rs` (a one-program file is now held to the same
|
||||
"file name matches the construct's name" convention as a module or
|
||||
interface). Both are reasonable, consistent with the "a program is a
|
||||
module" design decision, and neither is exercised by a program-specific
|
||||
linter test in this round. `rules/module_name_style.rs` hardcodes the
|
||||
word "module" in its violation message regardless of `.kw` — a
|
||||
pre-existing cosmetic inaccuracy for `interface` from before this round
|
||||
(not introduced here), now also reachable for `program`. Low severity,
|
||||
not blocking; worth a one-line doc/message fix and a program lint case
|
||||
whenever this area is touched again.
|
||||
|
||||
4. **Reproduce, all exact:**
|
||||
- Sweep: **43 → 11** (trunk / round 2 release binaries, `--check` over
|
||||
all 3,943 real `.sv`/`.svh` files, 32 excluded symlinks). Set
|
||||
difference (round-2-fail minus trunk-fail): **empty** — zero newly
|
||||
failing. The 11 match the README's table exactly (the 3 skips +
|
||||
the 8 OUT files), by name.
|
||||
- Whole-tree superset: hashed `--stdout` output over the 3,900
|
||||
trunk-passing files under both binaries — **exactly 1** moves,
|
||||
`hw/ip/prim/rtl/prim_sync_reqack.sv`. Diffed it: the moved lines are
|
||||
precisely the ~55-line generate block the old scan used to swallow
|
||||
into the assertion's opaque bytes (re-indented from 2-space to
|
||||
4-space now that it is a real nested `if`/`always_ff`, `else if(` →
|
||||
`else if (`, nothing else). Re-formatted the round-2 output a second
|
||||
time: byte-identical — idempotent.
|
||||
- Corpus: `scripts/corpus_gate.sh` → `813/820` passing, gate exits 0.
|
||||
All **860** `.sv`/`.v`/`.svh`/`.vh` corpus files hash identical
|
||||
between trunk and round 2.
|
||||
- The three skips: `kmac_reduced_tb.sv` and `SimDTM.sv` fail with
|
||||
byte-identical messages on both binaries. `jtag_if.sv`'s message
|
||||
*does* change (trunk: `51:17 expected \`;\` (found "=")` — the
|
||||
clocking blocker; round 2: `163:1 expected \`endinterface\` (found
|
||||
"<eof>")` — the rival-`ifdef`-headers blocker) — this is the
|
||||
documented, correct behavior, not a violation: the first blocker is
|
||||
genuinely fixed, and the second is independent and pre-existing.
|
||||
Verified pre-existence directly: fed the work log's own minimal
|
||||
repro (`` `ifdef G / module i #(...)() / `else / module i #(...)()
|
||||
/ `endif / wire w; / endmodule ``) to **both** binaries — identical
|
||||
`8:1 expected \`endmodule\` (found "<eof>")` on trunk and round 2, so
|
||||
the second blocker is provably not something this round introduced.
|
||||
|
||||
5. **Gates.** `cargo fmt --check`: clean. `cargo clippy --all-targets`:
|
||||
silent. `cargo test --workspace`: green (0 failed) both before and
|
||||
after my additions; my 3 new active tests pass, my 3 `#[ignore]`d
|
||||
regression tests are excluded from the default run so the gate stays
|
||||
green while still pinning the bug for whoever reworks it.
|
||||
|
||||
**Files touched by this QA pass:** `crates/vlog_parser/src/parser.rs`
|
||||
(6 new tests only — 3 active, 3 `#[ignore]`d), this README's QA log.
|
||||
Nothing else in the tree was modified; the `MAX_CHAIN_LENGTH` sabotage
|
||||
edit was reverted before any test run that could persist it, and confirmed
|
||||
reverted (`git diff 5ad0772 --stat` unchanged from the dev's own file
|
||||
list). No commits made.
|
||||
|
||||
### 2026-08-29 (later) — QA agent, rework verification
|
||||
|
||||
**Verdict: SHIP.** The rework fixes the blocking finding correctly and the
|
||||
fix shape (deciding by what *follows* the macro, not by what precedes it)
|
||||
is the right one — my own suggested "fall through whenever `;`/`else`
|
||||
doesn't follow" would have reintroduced the exact over-scan
|
||||
`prim_sync_reqack.sv` needed fixed, and the dev's writeup says so
|
||||
explicitly. Two new informational findings surfaced while attacking the
|
||||
asymmetry claim, neither blocking; everything else reproduces.
|
||||
|
||||
**Charter 1 — attacking the asymmetry claim ("wrongly continues ⇒
|
||||
trunk-identical").** Confirmed the mechanism first: no lexer changes this
|
||||
round (`ast.rs`/`parser.rs`/tests only in the diff), `BLOCK_OPENERS`/
|
||||
`BLOCK_CLOSERS` byte-identical to trunk, and the fallback loop body after
|
||||
the new macro branch is textually unchanged from trunk's
|
||||
`skip_action_stmt`. So *when the predicate is correct*, the fallback walks
|
||||
the identical token stream through identical code from the identical
|
||||
cursor position trunk would reach — the claim holds by construction, not
|
||||
just by observation. Tested it anyway, real binary, both directions, per
|
||||
shape:
|
||||
|
||||
| shape | round 2 vs trunk |
|
||||
|---|---|
|
||||
| `;` immediately following the macro, written on the **next source line** | byte-identical (`eat_sym` is whitespace/line-blind, so `call.semi` is `true` here regardless of the line break — the charter's premised "call.semi false" doesn't arise for a directly-adjacent `;`) |
|
||||
| macro call's close paren followed by `::` (`` `GET_TYPE(x)::CONST = 1; ``) | byte-identical — `::` is a `Symbol`, correctly reads "continues," falls through, matches trunk |
|
||||
| macro-only action immediately followed by `{p, q} = c;` | byte-identical — `{` is a `Symbol`, "continues," and trunk's own brute scan already swallowed the same statement (this is the *pre-existing* over-swallow class, not a new one) |
|
||||
| macro-only action immediately followed by `#5 x <= 1;` | byte-identical, same reasoning |
|
||||
|
||||
**Two informational findings, not blocking, from pushing on the *other*
|
||||
side of the same question — cases where the predicate correctly says
|
||||
"complete" and *that* is what moves output away from trunk:**
|
||||
|
||||
- `` else `ASSERT_ERROR(A_A) `` directly followed by `(* foo *) wire w;`:
|
||||
`(* ... *)` lexes as `TokenKind::Attribute`, not `Symbol`, so
|
||||
`at_statement_tail` correctly says "complete." Trunk's un-special-cased
|
||||
scan swallowed the attribute *and* the declaration into the assertion's
|
||||
opaque bytes (same class as `prim_sync_reqack.sv`), so it printed
|
||||
`(* foo *) wire w;` on one line, byte-for-byte as written. Round 2
|
||||
correctly cuts the action off before the attribute, so `wire w;` is
|
||||
reparsed as its own item and the formatter's ordinary
|
||||
attribute-before-item rule puts `(* foo *)` on its own line — a second,
|
||||
undocumented, correct output-moving case of exactly the same species as
|
||||
the one the work log calls out. It does not show up in either swept
|
||||
corpus today (both re-verified below at zero newly-failing / exactly one
|
||||
move), so the round's specific count is accurate for the trees it was
|
||||
measured against — but the "exactly one move" framing describes today's
|
||||
corpora, not a ceiling on how many files this class of shape could ever
|
||||
move. Worth a one-line note in the Handshakes section next time this
|
||||
area is touched; not a defect.
|
||||
- `` else `ASSERT_ERROR(A_A) `` directly followed by `B_LBL: assign x =
|
||||
1;` (a labelled *procedural continuous assignment*, IEEE 1800 §10.6):
|
||||
round 2 correctly separates the two statements (the label is an
|
||||
`Ident`, not a `Symbol`), but the parser has no support for `assign` as
|
||||
a *statement* inside a procedural block at all — confirmed pre-existing
|
||||
and identical on trunk with the construct in isolation, no macro
|
||||
involved (`initial begin assign x = 1; end` errors identically,
|
||||
byte-for-byte same message and column, on both binaries). On trunk the
|
||||
gap was invisible because the whole labelled statement was swallowed as
|
||||
opaque verbatim bytes next to the macro; round 2's correct boundary
|
||||
detection now *reaches* the gap and reports a clean parse error instead
|
||||
of silently accepting unparsed text. This does not corrupt anything
|
||||
(invariant #1 holds — a clean error, not partial output) and the shape
|
||||
does not occur in either swept tree, so it is not a regression against
|
||||
either corpus today. It is a real (if obscure) residual: any future file
|
||||
combining a bare-macro assertion action with a procedural `assign`
|
||||
statement immediately after it would newly report an error rather than
|
||||
silently mis-swallow. Filing rather than fixing — supporting procedural
|
||||
`assign`/`deassign` as statements is unrelated grammar work, out of this
|
||||
round's scope.
|
||||
|
||||
**Charter 2 — attacking `at_statement_tail`'s `Symbol` test from the other
|
||||
side.** Both named traps checked directly with the real binary: a `;` on
|
||||
the line after the macro (covered in the table above — resolves via
|
||||
`call.semi`, not via the predicate, so the "symbol ⇒ continues" path never
|
||||
even gets exercised for this shape) and `::` after the macro's close paren
|
||||
(covered above — correctly "continues," matches trunk). No case found
|
||||
where the `Symbol` test itself picks the wrong side for a real construct.
|
||||
|
||||
**Charter 3 — pins, then sabotage.** `cargo test -p vlog_parser --lib`
|
||||
filtered to the seven relevant tests (my four un-ignored pins, the dev's
|
||||
new `a_macro_action_still_ends_where_no_statement_tail_follows`, and the
|
||||
two originals `a_macro_may_be_a_concurrent_assertions_whole_action_statement`
|
||||
/ `a_macro_inside_an_action_statement_is_an_operand_not_a_terminator`):
|
||||
7/7 green, none `#[ignore]`d anymore. Inverted `at_statement_tail`
|
||||
(`==` → `!=`) and reran the same seven: **6 of 7 failed** — all four of my
|
||||
"continues" pins, the dev's new "complete" pin, and the original
|
||||
whole-action test all broke; only the pre-existing mid-expression test
|
||||
survived (it never reaches the predicate — the macro isn't at
|
||||
`at_stmt_start` there). This is a stronger result than a single-direction
|
||||
check: inverting the boolean breaks tests on *both* sides of the decision,
|
||||
so the suite is not merely pinned to one branch. Reverted; reran clean
|
||||
(7/7).
|
||||
|
||||
**Charter 4 — spot-re-verification, all against fresh binaries (release,
|
||||
rebuilt from the reworked source; a fresh detached `5ad0772` worktree for
|
||||
trunk, removed after use).** `--check`/`--stdout` only throughout;
|
||||
`git -C .../opentitan status --porcelain` after every sweep showed only
|
||||
`hw/ip/aes/dv/tb/tb.sv`, on every pass below.
|
||||
- Sweep: **43 → 11**, identical to the pre-rework run — diffed the two
|
||||
11-line failure lists directly, byte-identical set. Zero newly-failing
|
||||
against trunk's 43, reconfirmed by `comm`.
|
||||
- The four attack-pair table shapes above are the dev's own claim,
|
||||
independently reproduced: byte-identical `--stdout` output between
|
||||
trunk and round 2 for all four, diffed directly rather than taken on
|
||||
the work log's word.
|
||||
- Whole-tree superset: re-hashed all 3,900 trunk-passing files —
|
||||
**exactly 1** moves (`prim_sync_reqack.sv`), same file as before the
|
||||
rework.
|
||||
- The six previously-blocked files individually re-checked: `adc_ctrl_
|
||||
fsm_sva_if.sv`, `kmac_app_if.sv`, `prim_sync_reqack.sv` all "would
|
||||
reformat" (no error); `jtag_if.sv` still fails at its documented,
|
||||
independent second blocker (`163:1 expected endinterface`), unchanged
|
||||
from the pre-rework check.
|
||||
- Corpus: `scripts/corpus_gate.sh` → `813/820`, gate exits 0. All 860
|
||||
`.sv`/`.v`/`.svh`/`.vh` corpus files hash identical to trunk.
|
||||
|
||||
**Charter 5 — gates.** `cargo fmt --check`: clean. `cargo clippy
|
||||
--all-targets`: silent. `cargo test --workspace`: **2633 passed, 0
|
||||
failed, 36 ignored** — up from my pre-rework count of 2628/0/39, consistent
|
||||
with my three `#[ignore]`d pins now being active and green (+3 passed, -3
|
||||
ignored) plus the dev's new `#[test]` additions; the `.cases`/`.lint`
|
||||
additions are new cases inside existing fixture-driver tests, not new
|
||||
`#[test]` functions, so they don't add to the raw count directly but are
|
||||
covered by `cargo test -p vlog_formatter --test fixtures` (2/2) and
|
||||
`cargo test -p vlog_linter --test lint_cases` (14/14), both green. The
|
||||
number that matters — **0 failed** — is unambiguous either way.
|
||||
|
||||
**Files touched by this pass:** none in the tracked tree (the
|
||||
`at_statement_tail` sabotage was reverted immediately after the two test
|
||||
runs that bracket it, confirmed by `git diff 5ad0772 --stat` matching the
|
||||
dev's rework file list exactly); this README's QA log only. No commits
|
||||
made.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead.** Reviewed across dev, QA REWORK (a real
|
||||
regression in four macro-action shapes trunk parses — latent on both
|
||||
swept corpora, found only by crafted idiom), the rework, and QA's SHIP
|
||||
on re-verification; gates re-run by the lead. Three things distinguish
|
||||
this round. First, it corrected its own brief twice by reading real
|
||||
sites — the 14-file "clocking" bucket was two seven-file families, and
|
||||
clocking itself was already modelled, needing one production rather
|
||||
than the capture the brief presumed. Second, the chain-limit change is
|
||||
what a limit change should be: measured need (567), measured per-link
|
||||
cost, a stack resized to restore the house margin, a sabotage probe
|
||||
proving the margin real, one of the feature's own published claims
|
||||
("chains do not move the worst case") retired on the numbers, and a
|
||||
pre-existing uncharged loop closed in passing. Third, the rework's
|
||||
predicate decides on the token after the macro with the failure
|
||||
direction argued and then attacked: QA verified "wrongly continues
|
||||
degrades to trunk-identical" by construction against the diff, not by
|
||||
trust. The dev's rejection of QA's literal fix suggestion, with
|
||||
reasons, is the loop working as peers rather than as a pipeline. The
|
||||
two informational finds (the attribute-after-action instance of the
|
||||
explained output-move class; a pre-existing procedural-assign gap now
|
||||
surfacing as a clean error) are filed. Accepted; committed by the
|
||||
lead. OpenTitan sweep: 151 at the wave's start, 11 now — the remainder
|
||||
being macro fragments awaiting a preprocessing decision, vendor
|
||||
non-SV recommended for exclusion, and three written-up skips.
|
||||
@@ -81,20 +81,52 @@ workspace index, from the same file list, and are replaced with it.
|
||||
- **Consumes `vlog_parser`**: `tokenize` for the word harvest, `KEYWORDS` for
|
||||
the keyword tier, `defines::DefineKind` to keep `` `undef`` entries out of the
|
||||
macro table.
|
||||
- **Consumes `vlog_refactor`** exactly as M4 did — `module_names`,
|
||||
`module_definition`, `instantiation_plan`, `render_with` — through the
|
||||
unchanged `module_tier`. Nothing in `vlog_refactor` was touched.
|
||||
- **Consumes `vlog_refactor`** — `instantiation_plan`, `render_with` —
|
||||
through the planning half (`plan_for`), which since 2026-08-30 serves only
|
||||
`inline.rs`'s ghost; `module_tier` itself reads no files. The
|
||||
`module_definition` consumption ended with round 2 of inline-instantiation:
|
||||
the file is chosen by `completion::nearest_definition` (most shared leading
|
||||
path components with the asking buffer, then shallowest, then
|
||||
lexicographic), which never refuses on multiplicity the way
|
||||
`module_definition` deliberately does. Nothing in `vlog_refactor` was
|
||||
touched, then or since.
|
||||
- **Stopped consuming `vlog_refactor::module_names` (2026-08-28).** That
|
||||
function is `WorkspaceIndex::workspace_symbols("")` filtered to modules, and
|
||||
`workspace_symbols` builds and sorts a record per declaration in the whole
|
||||
workspace — 43 140 of them in opentitan, on *every keystroke*.
|
||||
`Candidates::modules` is the same list, built once beside the index and
|
||||
filtered per request, and
|
||||
`candidates::tests::the_module_table_answers_exactly_what_module_names_answers`
|
||||
asserts the two agree — set *and* order — at eleven queries.
|
||||
`vlog_refactor::module_names` is unchanged and still has its own callers;
|
||||
only tier 0 stopped asking it. **Note for whoever changes it**: the two are
|
||||
now pinned against each other by that test, so a change to `module_names`'s
|
||||
match rule or ordering breaks the build rather than silently diverging.
|
||||
- **Reads `WorkspaceIndex::units`'s `Def::name_span` directly (2026-08-28)**,
|
||||
to anchor the header slice (`module_header`). Treated as advisory, never as
|
||||
truth: the byte range is checked against the text actually read, and a
|
||||
mismatch — a file edited on disk since the last scan — declines the slice
|
||||
and parses the whole file, exactly as before.
|
||||
- **Duplicated deliberately, not shared**: `vlog_refactor::ports::visible_in`
|
||||
answers "is this *one* name visible here" and is `pub(crate)` to that crate;
|
||||
`completion::visible_symbols` answers "what is visible here". They share the
|
||||
innermost-scope idea and nothing else, and lifting one to fit both would have
|
||||
meant widening another crate's API for a second caller that wants a different
|
||||
answer. Recorded so the lead can overrule it cheaply.
|
||||
- **Promises `lucisv_server`'s own callers**: `completions` never panics, always
|
||||
returns items whose `textEdit` replaces exactly the typed word (plus the
|
||||
backtick, in the macro case), and never returns a module item whose text
|
||||
differs from what M4 returned — the M4 tests assert the skeleton byte for
|
||||
byte and still pass.
|
||||
- **Promises `lucisv_server`'s own callers**: `completions` never panics, and
|
||||
always returns items whose `textEdit` replaces exactly the typed word (plus
|
||||
the backtick, in the macro case).
|
||||
- ~~"never returns a module item whose text differs from what M4 returned"~~ —
|
||||
**superseded 2026-08-30** by the owner's two-level ruling. A tier-0 item now
|
||||
inserts the module's **name**; the instantiation is ghost text served by
|
||||
`inline.rs`, planned once, for the one module the user has spelled out. The
|
||||
byte-for-byte skeleton pins moved with it. See
|
||||
`docs/features/inline-instantiation/README.md`.
|
||||
- **Provides `at_instantiation_site` (new, 2026-08-30, `pub(crate)`)** — tier
|
||||
0's own position gate, lifted out of `completions` so `inline.rs` asks the
|
||||
identical question rather than growing a second answer to it. `plan_for` and
|
||||
`snippet_hole` became `pub(crate)` for the same caller; `module_header`
|
||||
already was. Nothing about what any of the three computes changed.
|
||||
- **`editors/vscode` needs no change.** No new setting, no new capability: the
|
||||
completion provider was already advertised, and `snippetSupport` is read the
|
||||
same way.
|
||||
@@ -106,15 +138,19 @@ alphabetically within a tier.
|
||||
|
||||
| Tier | What | `CompletionItemKind` | Where it comes from |
|
||||
|---|---|---|---|
|
||||
| `0` | Module instantiation skeletons | `MODULE` | M4, unchanged — module-item position only |
|
||||
| `0` | Module **names** (instantiation candidates) | `MODULE` | `Candidates::modules`, module-item position only |
|
||||
| `1` | Declarations the scope chain at the cursor binds | the declaration's own kind | this file's `Semantics` |
|
||||
| `2` | Packages, package members, typedefs, classes, modules, `` `define`` names | the declaration's own kind, `CONSTANT` for a macro | `WorkspaceIndex`, tabled at build time |
|
||||
| `3` | Every reserved word | `KEYWORD` | `vlog_parser::KEYWORDS` |
|
||||
| `4` | Every identifier used anywhere in the project | `TEXT` | token harvest, tabled at build time |
|
||||
|
||||
Tier 0 is first because at module-item position a fifteen-line skeleton is what
|
||||
the user is reaching for, and it is the only tier that is *position*-gated at
|
||||
all: M4's gate (nothing but whitespace before the word on its line, plus
|
||||
Tier 0 is first because at module-item position a module name is what the user
|
||||
is reaching for — and, since 2026-08-30, a *name* is all it inserts: the
|
||||
instantiation follows as ghost text once the name is spelled exactly and a
|
||||
space typed after it (`docs/features/inline-instantiation/README.md`). For a
|
||||
module declared in more than one file, the item's detail names the copy the
|
||||
ghost will read (`nearest_definition`'s pick for this buffer). It is still the only tier
|
||||
that is *position*-gated at all: M4's gate (nothing but whitespace before the word on its line, plus
|
||||
`pairs::analyze`'s scope chain) is unchanged and still declines inside a
|
||||
procedural block, a function, a class, a connection list and an expression.
|
||||
Every other tier ignores position entirely — a name is a name wherever it is
|
||||
@@ -130,6 +166,39 @@ Dedup is by label, first tier wins. A name that is both a local declaration and
|
||||
a word used elsewhere in the project is offered once, in tier 1, with its real
|
||||
kind and its declaration line as detail.
|
||||
|
||||
### Amendment, 2026-08-30 — how a tier *matches*
|
||||
|
||||
Tier ordering, `sortText`, dedup, the caps and the position gates are all
|
||||
unchanged. What changed is the comparison three of the tiers make, and only
|
||||
from the third typed character up:
|
||||
|
||||
| Tier | Matched by, ≥3 characters typed | Was |
|
||||
|---|---|---|
|
||||
| `0` module names | substring | substring — unchanged |
|
||||
| `1` declarations in scope | **subsequence** | prefix |
|
||||
| `2` index names | **subsequence** | prefix |
|
||||
| `2` `` `define`` names | prefix — unchanged | prefix |
|
||||
| `3` templates | prefix — unchanged | prefix |
|
||||
| `4` keywords | prefix — unchanged | prefix |
|
||||
| `5` project words | **subsequence** | prefix |
|
||||
| the backtick response | prefix — unchanged | prefix |
|
||||
|
||||
**Below three characters every tier matches exactly as it did before**, item
|
||||
for item. The one thing that had to change there is `isIncomplete`: a 1- or
|
||||
2-character response now always sets it, because VS Code re-asks the server
|
||||
only when the last answer said so, and a complete 2-character answer would
|
||||
swallow the third keystroke — the one that turns subsequence matching on.
|
||||
|
||||
Within a tier the fuzzy hits are ordered prefix-first, then by a boundary /
|
||||
contiguity / gap score, then by name; that order is the order of the `items`
|
||||
array, and decides which items survive the cap. `sortText` is still
|
||||
`<tier digit><name>` and still means the tier order and nothing else.
|
||||
|
||||
Rules, scoring, the `isIncomplete` argument and the measurements are in
|
||||
`docs/features/fuzzy-completion/README.md`. The prefix API this file describes
|
||||
(`Candidates::units`/`words`/`macros`/`modules`/`has_module`) is untouched and
|
||||
still answers exactly what it answered.
|
||||
|
||||
## The backtick ruling
|
||||
|
||||
`` `define`` names are the one candidate whose spelling depends on where the
|
||||
@@ -217,9 +286,89 @@ sorted case-insensitively, so a match is a `partition_point` and then a
|
||||
`take_while` over one contiguous run. Nothing allocates a lowercase copy —
|
||||
`lower_cmp` compares byte iterators.
|
||||
|
||||
The one request that is *not* microseconds is a module-item position, which
|
||||
still parses up to 64 defining files. That is M4's cost, unchanged and
|
||||
separately capped.
|
||||
The one request that was *not* microseconds was a module-item position, which
|
||||
parsed up to 64 defining files. Two rounds took that apart: the header slice
|
||||
below (2026-08-28) and, finally, the two-level split (2026-08-30) that stopped
|
||||
the popup planning anything at all. Tier 0 is now a scan of a table like every
|
||||
other tier.
|
||||
|
||||
### The module tier, 2026-08-28
|
||||
|
||||
That last paragraph was the whole bill. `performance.md` §6d measured
|
||||
completion at **34–66 ms per keystroke** against opentitan, worst at 0–4 typed
|
||||
characters, and typing an eleven-character identifier at **201 ms** of blocked
|
||||
single-threaded loop. The probe
|
||||
(`perf::completing_one_keystroke_at_a_time`) runs the same request with the
|
||||
cursor at module-item position and inside an expression, where tier 0 is gated
|
||||
off:
|
||||
|
||||
| generated corpus, 4 000 files | at an item | in an expression |
|
||||
|---|---:|---:|
|
||||
| empty prefix, before | 53.2 ms | 0.19 ms |
|
||||
| empty prefix, after | **3.17 ms** | 0.19 ms |
|
||||
|
||||
Every other tier put together is 0.19 ms and always was. Two changes, neither
|
||||
of which may alter an item:
|
||||
|
||||
1. **`module_header` — parse the header, not the file.** A plan reads a
|
||||
module's parameter list and port list and nothing else, and both are in the
|
||||
header; the body was being parsed to reach them. The slice is the file's
|
||||
text up to the `;` that ends the header, **kept byte for byte** so every
|
||||
span the plan reads still points where it did, with an `endmodule` written
|
||||
in place of the body. It is anchored on the index's `Def::name_span`
|
||||
(checked against the text, so a file edited under the index declines rather
|
||||
than slices at a stale offset) and the end is found by lexing a bounded
|
||||
window and walking a **whitelist**: `static`/`automatic`, `import …;`,
|
||||
`#(…)`, `(…)`, `;`. Anything else answers "no slice" and the whole file is
|
||||
parsed exactly as before — `module aes import aes_pkg::*; #(…) (…);` writes
|
||||
three semicolons and only the last ends the header, which is why this is a
|
||||
whitelist and not a search for the first `;`.
|
||||
2. **`Candidates::modules` — table the module names.** See Handshakes.
|
||||
|
||||
Two guards keep the answer identical, and both are load-bearing rather than
|
||||
decoration:
|
||||
|
||||
- **A non-ANSI port list writes its directions in the module *body***
|
||||
(`module m (a); input wire [7:0] a;`), which is the part the slice drops. A
|
||||
plan whose ports have neither a direction nor a type is the signature of
|
||||
that, and `plan_for` re-plans from the whole file when it sees one.
|
||||
`a_non_ansi_port_list_is_planned_from_the_whole_file` asserts both halves —
|
||||
that the header alone really does lose them, and that the guard really does
|
||||
get them back.
|
||||
- **A slice that fails to plan is re-planned whole**, so the list can only
|
||||
ever lose an item where it would have lost it anyway.
|
||||
|
||||
`the_header_slice_plans_exactly_what_the_whole_file_plans` is the argument, not
|
||||
the prose: fifteen header shapes — imports, two imports, no ports, an empty
|
||||
port list, non-ANSI with and without body declarations, a comment inside the
|
||||
header, a lifetime qualifier, a directive between the name and the port list, a
|
||||
directive *inside* the port list, an escaped module and port name, a second
|
||||
module before and after the one being planned, and a header wider than the
|
||||
first window rung — each planned both ways and compared field by field.
|
||||
|
||||
`HEADER_WINDOWS` is a ladder because the lex is the whole cost of the slice and
|
||||
it is linear in what it is handed. The rungs are measured, not guessed: over
|
||||
opentitan's 344 RTL modules 59% of headers end inside 256 bytes and 90% inside
|
||||
2 KB, and the largest is 6.6 KB — so a top rung of 16 KB, because a rung that
|
||||
is too small is not a wrong answer but a 2–4 ms whole-file parse. The full
|
||||
before/after, including the four `aes_control*` modules that found this, is in
|
||||
`docs/perf/README.md`, *Before / after — round 7*.
|
||||
|
||||
Against the real checkout, over the wire: **63–66 ms → 13.1–15.0 ms** at the
|
||||
empty prefix, and typing `aes_reg_top` **200.9 ms → 64.5 ms**. What was left
|
||||
was 64 real header parses, and the two ways down from there — memoizing the
|
||||
plan, or `completionItem/resolve` — both changed something that round was not
|
||||
allowed to change.
|
||||
|
||||
### The module tier, 2026-08-30
|
||||
|
||||
The owner took the third way: **stop planning on the popup path entirely.**
|
||||
Tier 0 answers with module *names*, and the instantiation is offered as ghost
|
||||
text once the user has typed a name exactly — one plan, for one module, at the
|
||||
moment they have said which one they mean. The 64 remaining header parses are
|
||||
gone with it, and `module_header`/`plan_for` live on unchanged as the ghost's
|
||||
planner. See `docs/features/inline-instantiation/README.md`; the numbers on
|
||||
opentitan are QA's to record there.
|
||||
|
||||
## Version 0.3.0
|
||||
|
||||
@@ -269,9 +418,47 @@ incidental; they exercise the parser, not the version.
|
||||
- [x] Version 0.3.0 across the workspace, the extension and the docs
|
||||
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`,
|
||||
`cargo test --workspace` all clean; `smoke.js` OK
|
||||
- [x] **Performance wave, Lane B (2026-08-28):** completion 34–66 ms per
|
||||
keystroke → 13–15 ms worst case on opentitan and 3.2 ms on the
|
||||
same-sized generated corpus, with the items pinned identical. Tier 0
|
||||
parses the header instead of the whole declaring file
|
||||
(`module_header` / `plan_for`), and the module-name list is a table
|
||||
built with the index (`Candidates::modules`) instead of a
|
||||
whole-symbol-table sort per keystroke.
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-08-28 (dev, performance wave Lane B)** — the module tier.
|
||||
|
||||
Profiled first, as the brief asked, with an `#[ignore]`d house probe rather
|
||||
than a guess: `perf::completing_one_keystroke_at_a_time` measures the whole
|
||||
request at nine prefixes with tier 0 on and off. The answer was that
|
||||
**everything except tier 0 costs 0.19 ms at every prefix**, so
|
||||
`performance.md`'s hypothesis — "scanning/filtering the candidate set, and
|
||||
the broader the prefix the more of the 3 976-file symbol table is walked" —
|
||||
was half right: the symbol-table walk was real but it was
|
||||
`vlog_refactor::module_names`'s, inside tier 0, not the word or index tiers'.
|
||||
|
||||
What changed is in *The module tier, 2026-08-28* above, with the identity
|
||||
argument and the fifteen-shape test that carries it. Two decisions worth
|
||||
naming:
|
||||
|
||||
- **No cache.** The obvious fix is to memoize the plan per module. It was not
|
||||
taken: `Candidates` is rebuilt at `didSave`, and tier 0 reads
|
||||
`ws.text_of`, which sees an *unsaved* buffer — so a cache there would go
|
||||
stale exactly where `another_open_buffer_overlays_disk_once_the_index_is_rebuilt`
|
||||
says it must not. Slicing needed no new invalidation rule at all, and it
|
||||
makes the cold request fast rather than only the repeat.
|
||||
- **The whitelist is a whitelist.** `header_end` refuses every shape it does
|
||||
not recognise instead of scanning for the first `;`. `module aes import
|
||||
aes_pkg::*; #(…) (…);` is the case that makes the difference, and it is
|
||||
what most of opentitan's `aes*` modules are written as: a first-`;` scan
|
||||
would have silently reported them as having no ports.
|
||||
|
||||
Deviations from the brief: none on this item. The measurement is on
|
||||
`docs/perf/README.md` rather than here, because that is where this
|
||||
repository keeps before/after numbers; this section keeps the argument.
|
||||
|
||||
- **2026-08-24 (dev)** — implemented.
|
||||
|
||||
**Keyword list.** `vlog_parser/src/token.rs`'s `is_keyword` was a 181-arm
|
||||
@@ -637,8 +824,128 @@ unambiguous" (typo/missing assertion) territory; all three are judgment
|
||||
calls for the dev/lead. No commits, no edits to `TODO.md` or the umbrella
|
||||
`docs/features/refactor/README.md`.
|
||||
|
||||
### 2026-08-28 — QA agent (performance wave Lane B: the module tier)
|
||||
|
||||
Verdict: **the fix holds. No corruption found, one pre-existing parser gap
|
||||
surfaced (filed below, not fixed here — out of this feature's touched
|
||||
files).**
|
||||
|
||||
**What I attacked.** The whitelist walk in `header_end`, the guard in
|
||||
`plan_for`, and `Candidates::modules`'s parity with
|
||||
`vlog_refactor::module_names`, per the adversarial list in the round brief:
|
||||
header-slice mis-slicing, stale-span handling, and the module-table's set
|
||||
*and* order against hostile queries.
|
||||
|
||||
**Header-slice attacks — all safe, one gap in the dev's own test found and
|
||||
fixed.** Extended `SHAPES` in `completion.rs` (in
|
||||
`the_header_slice_plans_exactly_what_the_whole_file_plans`) with: a single
|
||||
`import a::*, b::*;` declaration (comma-chained packages, one statement —
|
||||
`skip_to_semicolon` must not stop at the first `::`), a parameter default
|
||||
whose string literal contains a literal `;` and `)` (`"a;b)c"`), CRLF line
|
||||
endings through the whole header, a genuine attribute instance right after
|
||||
the module name, and one inside the port list on a single port. All five
|
||||
plan identically sliced vs. whole-file; the two attribute shapes exposed
|
||||
something worth recording (next paragraph). Added
|
||||
`the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously`
|
||||
(`completion.rs`) asserting the first three actually invoke the slice path
|
||||
(`module_header(..).is_some()`) rather than passing the comparison
|
||||
vacuously by both sides falling back to the whole file — a real risk with
|
||||
this style of pinned-equality test, since a shape the whitelist declines
|
||||
passes the assertion for free.
|
||||
|
||||
**Finding (LOW, not a regression this round introduced) — `completion.rs`,
|
||||
`module_header`, and transitively `vlog_semantic`/`vlog_parser`: a module
|
||||
with an attribute instance (`(* ... *)`) anywhere near its header is not
|
||||
indexed as a `Module` unit at all.** `WorkspaceIndex::units("attributed")`
|
||||
and `..("port_attributed")` both come back empty for
|
||||
`module attributed (* some_attr *) #(...) (...);` and
|
||||
`module port_attributed (input logic clk, (* keep *) output logic q);`.
|
||||
`module_header` correctly declines at its very first line (`let [def] =
|
||||
index.units(module)...else { return None }`, `completion.rs:99-103`) —
|
||||
this is the documented whole-file fallback working exactly as designed,
|
||||
not a slicing bug — but it means completion's module tier, which sources
|
||||
its candidate names from the same index, never offers such a module as a
|
||||
completion candidate in the first place, attribute-based header or not.
|
||||
This predates 2026-08-28 (the index-level gap is not something tier 0's
|
||||
change touches), so it is filed rather than fixed: out of Lane B's stated
|
||||
files (`vlog_semantic`/`vlog_parser` are not touched-file scope for this
|
||||
round). Reproduction: `cargo test -p lucisv_server -- completion::tests::
|
||||
a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`, a new
|
||||
permanent regression pinning the current (gap) behavior so a future fix to
|
||||
the indexer is *noticed* here rather than silently changing what
|
||||
`module_header` sees.
|
||||
This also means the dev's own `noisy` shape's doc comment ("a comment and
|
||||
an attribute inside the header") was inaccurate — it has two comments and
|
||||
no attribute; I did not edit that comment since fixing it is a one-line
|
||||
call for the dev, and the actual behavior is now separately pinned above.
|
||||
|
||||
**Stale-span attack**: `a_stale_index_span_declines_to_slice_rather_than_
|
||||
slicing_the_wrong_bytes` (dev's own test) re-verified by hand — re-ran with
|
||||
`cargo test -p lucisv_server -- completion::tests::a_stale_index_span` in
|
||||
isolation, passes. No addition needed; the test already does the right
|
||||
thing (name-span-vs-text mismatch declines).
|
||||
|
||||
**`Candidates::modules` parity**: `contains_ignore_case` (`candidates.rs`)
|
||||
and `contains_ignore_ascii_case` (`vlog_semantic::workspace`) are
|
||||
byte-identical implementations, and both `Candidates::modules` and
|
||||
`vlog_refactor::module_names` ultimately filter the same
|
||||
`workspace_symbols`-sorted, `container.is_none() && kind == Module` slice
|
||||
with the same predicate — so parity is structural, not incidental, and
|
||||
holds for any name content (case-different names, escaped identifiers,
|
||||
duplicate names across files) without needing per-shape tests. Traced by
|
||||
hand rather than by adding more cases to the dev's own
|
||||
`the_module_table_answers_exactly_what_module_names_answers` (which
|
||||
already covers duplicates-across-files and query-case-differences); no
|
||||
counter-example found.
|
||||
|
||||
**Numbers reproduced** (release build, this machine, M1 Max):
|
||||
- `perf::completing_one_keystroke_at_a_time`: empty prefix at item position
|
||||
**3.28 ms** (dev's claim: 3.17 ms — within machine noise), expression
|
||||
position 190 µs unchanged. Whole-file plan 2.68 ms vs. header-alone
|
||||
16.3 µs for one skeleton off the 1214-line generated file — matches the
|
||||
claimed order of magnitude.
|
||||
- `LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test
|
||||
--release -p lucisv_server perf::completing_over_a_real_project`: empty
|
||||
prefix **11.6 ms** (dev's claim against the real wire protocol: 13.1–15.0
|
||||
ms; this is the in-process `completions()` call without LSP round-trip
|
||||
overhead, so a bit faster is expected, same order of magnitude). Zero
|
||||
modules fell back to whole-file parsing across every prefix tested
|
||||
(`parsed whole: []`), confirming the slice fires in practice on real RTL,
|
||||
not just in the synthetic corpus.
|
||||
- Live end-to-end confirmation against the real opentitan checkout with
|
||||
this worktree's release binary (`node`-free, via a copy of the
|
||||
scratchpad's `lspclient.py`/`bench.py` pointed at
|
||||
`target/release/lucisv-server`): completion itself was not re-measured
|
||||
over the wire (out of scope to re-run the whole battery), but see the
|
||||
references-nav QA log below for the documentHighlight leg of the same
|
||||
session, which used the identical harness.
|
||||
|
||||
**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test
|
||||
--workspace` (1261 passed, up from 1259 with my additions), `node
|
||||
editors/vscode/smoke.js target/release/lucisv-server` — all clean, run
|
||||
against the worktree with my additional tests included.
|
||||
|
||||
No fixes applied beyond the two new permanent regression tests (attack
|
||||
shapes actually slicing; the attribute-indexing gap pinned). No commits.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead, performance-wave Lane B.** Reviewed after QA's
|
||||
SHIP; gates re-run on the worktree (fmt clean, clippy silent, 2495
|
||||
workspace tests green). The header-slice design is right because of
|
||||
what it refuses: a whitelist walk that re-plans from the whole file on
|
||||
anything it does not positively recognize — including the non-ANSI
|
||||
signature — is the honest shape, and QA's seven added attack shapes
|
||||
plus the field-by-field plan-equality pin make the "items byte
|
||||
identical" claim tested rather than asserted. The stale-span decline
|
||||
and the Candidates::modules order-and-set parity are correctly pinned.
|
||||
QA's LOW (attribute-instance modules not indexed as units — a
|
||||
pre-existing parser/semantic gap the guard already declines safely) is
|
||||
accepted as filed with its regression pin; it belongs to a parser
|
||||
round, not this one. The residual opentitan cost is real header
|
||||
parses, with the plan-cache and completionItem/resolve options filed
|
||||
where the numbers are. Accepted.
|
||||
|
||||
**2026-08-24 — lead.** Reviewed after QA's ship verdict — the first
|
||||
milestone through with no rework round; gates run independently (1262
|
||||
tests, 0 failures, clippy silent). The keyword-table refactor was verified
|
||||
|
||||
@@ -197,7 +197,7 @@ nothing, and the same is true of a buffer that does not lex.
|
||||
|
||||
| Tier | What |
|
||||
|---|---|
|
||||
| `0` | module instantiation skeletons (M4) |
|
||||
| `0` | module names (the instantiation follows as ghost text) |
|
||||
| `1` | declarations the scope chain binds |
|
||||
| `2` | what the project declares |
|
||||
| `3` | **templates** |
|
||||
@@ -291,17 +291,21 @@ as it is… the client will not apply any kind of adjustments". The vendored
|
||||
*that* into the `KeepWhitespace` rule that clears `adjustWhitespace`.
|
||||
|
||||
So `completion.rs` sends `insertTextMode: asIs` (the `KEEP_MY_INDENTATION`
|
||||
constant) on the two item builders that write more than one line: the template
|
||||
tier and the module-instantiation skeleton. Single-line items neither need it
|
||||
nor are harmed by it, so they do not send it. It is the right answer for the
|
||||
plain-text spelling as well — that text is absolutely positioned too — which
|
||||
is why this path did **not** switch to relative indentation the way ghost text
|
||||
had to. An inline completion has no `insertTextMode` field at all; see
|
||||
constant) on every item builder that writes more than one line. Single-line
|
||||
items neither need it nor are harmed by it, so they do not send it. It is the
|
||||
right answer for the plain-text spelling as well — that text is absolutely
|
||||
positioned too — which is why this path did **not** switch to relative
|
||||
indentation the way ghost text had to. An inline completion has no
|
||||
`insertTextMode` field at all; see
|
||||
`docs/features/inline-templates/README.md`'s *The indentation contract*.
|
||||
|
||||
Pinned by `tests/e2e.rs` (`insertTextMode == 1` on both the template item and
|
||||
the module skeleton), over the wire, beside the `newText` each already
|
||||
asserted.
|
||||
**Amended 2026-08-30:** that used to be *two* builders, the template tier and
|
||||
the module-instantiation skeleton. The module item is a plain word now — the
|
||||
instantiation moved to ghost text
|
||||
(`docs/features/inline-instantiation/README.md`) — so the template tier is the
|
||||
only multi-line item left, and the module item sends no `insertTextMode` at
|
||||
all. Pinned by `tests/e2e.rs`: `insertTextMode == 1` on the template item, and
|
||||
absent on the module item.
|
||||
|
||||
## Reconciliation with the static VS Code snippets
|
||||
|
||||
|
||||
@@ -0,0 +1,608 @@
|
||||
# directive-in-statements
|
||||
|
||||
## Goal
|
||||
|
||||
Stop refusing files where a `` `ifdef ``/`` `else ``/`` `endif `` region opens
|
||||
**part-way through a construct** — splitting an assign's right-hand side, an
|
||||
expression inside a bracketed list, a call's argument list, an instantiation's
|
||||
parameter value, or a function's port list. This is bucket 7 of
|
||||
`syntax_coverage.md` plus its bucket-13 sibling: 7 files across the OpenTitan
|
||||
sweep, and the specific files are the point — **both chips' top-level
|
||||
synthesizable RTL** (`chip_earlgrey_asic.sv`, `chip_earlgrey_cw340.sv`), **both
|
||||
chips' DV probe interfaces** (`top_{earlgrey,darjeeling}/dv/env/chip_if.sv`,
|
||||
anchor B), and **both chips' DUT top testbenches**
|
||||
(`top_{earlgrey,darjeeling}/dv/tb/tb.sv`), plus `jtag_dtm_reg_block.sv`.
|
||||
|
||||
Such a region is not a tree, for the same reason `directive-split`'s already
|
||||
was not: there is no AST that holds "either this expression or that one", and
|
||||
no layout to apply to something that only becomes a construct after the
|
||||
preprocessor has chosen an arm. So it joins the **verbatim** bucket — the exact
|
||||
source bytes, re-indented on the first line only — reached by a *recovery*
|
||||
after a real parse failure rather than by a grammar rule. This is the sequel
|
||||
`syntax_coverage.md`'s own implementation note recommends: "the existing
|
||||
`ItemKind::Verbatim` pattern extends naturally to capture from the failed
|
||||
statement/instantiation through the shared terminator, exactly as
|
||||
`directive-split` already does for item-level declarations."
|
||||
|
||||
## Assumptions
|
||||
|
||||
### The gap, stated as a mirror image
|
||||
|
||||
`directive-split` (2026-08-26) recovers when the failure lands on the directive
|
||||
that **closes** a region opened *before* the construct started, with a bracket
|
||||
the arm left open. This round is the other half: the failure lands on the
|
||||
`` `ifdef `` that **opens** a region *inside* the construct.
|
||||
|
||||
```verilog
|
||||
// closing shape (directive-split, 2026-08-26) -- the item IS an arm
|
||||
`ifdef DSIM
|
||||
privileged_reg_t implemented_csr[] = { <- fails at the `else below
|
||||
`else
|
||||
const privileged_reg_t implemented_csr[] = {
|
||||
`endif
|
||||
MVENDORID
|
||||
};
|
||||
|
||||
// opening shape (this round) -- the item CONTAINS the region
|
||||
assign aes_ctrl_rnd_ctr =
|
||||
`ifdef GATE_LEVEL <- fails right here
|
||||
`AES_HIER.u_aes_cipher_control.mr_rnd_ctr[3:0];
|
||||
`else
|
||||
`AES_HIER.u_aes_cipher_control.rnd_ctr;
|
||||
`endif
|
||||
```
|
||||
|
||||
None of the three existing directive features fire on the second shape, and
|
||||
`syntax_coverage.md`'s Anchor B deep-dive says why: `directives-in-lists` /
|
||||
`directives-in-instances` sit at the element boundaries of four *bracketed
|
||||
lists* (port lists, parameter lists, enum members, instantiation
|
||||
`#()`/connection lists) — an assign's RHS is a single expression, not a list;
|
||||
`directive-split` needs a bracket already open at a *closing* directive; and
|
||||
directive pass-through otherwise exists only at item- and statement-list
|
||||
boundaries. An expression parse has no "this might be a pass-through directive"
|
||||
branch at all, so it fails immediately, before any bracket is opened and before
|
||||
`directive-split`'s trigger is ever evaluated.
|
||||
|
||||
### The opening trigger is two conditions, checked in `at_opening_split`
|
||||
|
||||
1. **The cursor stands on an `` `ifdef `` / `` `ifndef ``.** Every other
|
||||
directive mid-expression is still an ordinary parse error — `` `include ``,
|
||||
a bare `` `endif ``, a macro call. This is what keeps the net narrow: the
|
||||
recovery is about conditional *regions*, not about directives in general.
|
||||
2. **The construct is one unterminated run reaching that directive**: it has
|
||||
consumed at least one token (a directive standing where an item or a
|
||||
statement *begins* is an ordinary pass-through directive, unchanged), and
|
||||
there is no `;` at bracket depth zero between its first token and the
|
||||
cursor.
|
||||
|
||||
Condition 2 is the load-bearing one and it replaces `directive-split`'s
|
||||
"a bracket is open" test, which cannot be reused here — at `chip_if.sv:1192`
|
||||
nothing is open yet, the failure is three tokens into the item. What it buys is
|
||||
that a failure which **propagated up** from somewhere deeper cannot capture the
|
||||
construct that happens to enclose it: by the time an error inside a module body
|
||||
reaches `parse_item_inner`, many `;` at depth zero have gone by, so the module
|
||||
is refused as a candidate. Without it, one bad expression would turn an entire
|
||||
`module` into opaque bytes on a guess.
|
||||
|
||||
### The extent follows the first arm, and ends on one of two terminators
|
||||
|
||||
`scan_opening_split_extent` walks from the construct's first token, tracking
|
||||
brackets and conditional nesting, and — like `scan_split_extent` — on a
|
||||
`` `else ``/`` `elsif `` it **skips the alternative arms whole** (reusing
|
||||
`skip_conditional_arms`), because the arms are rival spellings of one thing and
|
||||
counting all of their brackets would demand as many closers as there are arms.
|
||||
|
||||
Where it stops depends on which side of the region the construct's terminator
|
||||
was written on, and **both spellings are in the corpus**:
|
||||
|
||||
| shape | corpus evidence | ends at |
|
||||
|---|---|---|
|
||||
| each arm carries the construct's own `;` | `chip_if.sv:1189` | the `` `endif `` closing the region |
|
||||
| the region is balanced *inside* the construct | `chip_earlgrey_asic.sv:621`, `jtag_dtm_reg_block.sv:173` | the `;` after it |
|
||||
|
||||
`terminated_in_arm` is what tells them apart: a `;` met at bracket depth zero
|
||||
while a region is still open means the tail lives inside the arms. Getting this
|
||||
wrong in the first direction swallows the next item (there is no `;` after
|
||||
`chip_if.sv`'s `` `endif ``); getting it wrong in the second truncates the
|
||||
construct.
|
||||
|
||||
**Every exit leaves conditional nesting back at zero.** A captured block is
|
||||
therefore conditional-balanced by construction, which is why this recovery —
|
||||
unlike `directive-split`'s — needs no `open_conds` adjustment at all. Pinned by
|
||||
`an_opening_split_leaves_item_scope_nesting_alone`.
|
||||
|
||||
### A head that opens a body does not end at its first `;`
|
||||
|
||||
The first draft assumed, as `directive-split` documents it does, that "the
|
||||
construct's terminator is a `;`". `jtag_dtm_reg_block.sv:273` is the
|
||||
counterexample — a split `function new(` **header**:
|
||||
|
||||
```verilog
|
||||
function new(string name = "",
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
int unsigned n_bits = 50,
|
||||
`else
|
||||
int unsigned n_bits = 41,
|
||||
`endif
|
||||
int has_coverage = UVM_NO_COVERAGE);
|
||||
super.new(name, n_bits, has_coverage);
|
||||
endfunction : new
|
||||
```
|
||||
|
||||
That `;` closes a *header*. Stopping there captured the header, left the body
|
||||
behind as items, and the file failed on `super` three lines later — a worse
|
||||
diagnostic than the one it replaced. So `construct_end` reads the construct's
|
||||
head and answers one of three things:
|
||||
|
||||
- `Semi` — the default, and what every identifier-headed construct gets
|
||||
(instantiation, call statement, assignment) along with every declaration
|
||||
keyword. Unchanged from `directive-split`'s assumption.
|
||||
- `Keyword("endfunction")` / `Keyword("endtask")` — the two body-opening heads
|
||||
the corpus needs. The block runs to the closing keyword and takes the
|
||||
`: label` it may carry (`past_end_label`), because a label left outside would
|
||||
be parsed as an item.
|
||||
- `Unknown` — every other body-opening keyword (`BODY_KEYWORDS`: `module`,
|
||||
`class`, `case`, `begin`, `for`, `always`, …). **Refused outright**, because
|
||||
capturing at a `;` would produce exactly the truncated head above and nothing
|
||||
in the corpus asks for these.
|
||||
|
||||
`TF_QUALIFIERS` (`virtual`, `static`, `automatic`, `local`, `protected`) are
|
||||
skipped in front of `function`/`task`. `extern` and `pure` are deliberately
|
||||
**not** in that list: those spell a prototype, which really does end at its `;`,
|
||||
so they fall through to `Semi`, which is correct for them.
|
||||
|
||||
### `take_list_directives` must not harvest an outer region's seam
|
||||
|
||||
The two `tb.sv` files (bucket 13) fail for a related but distinct reason, and
|
||||
they need no new recovery at all — `directive-split`'s existing one already
|
||||
fits, it just never got to see the failure:
|
||||
|
||||
```verilog
|
||||
`ifdef DISABLE_ROM_INTEGRITY_CHECK
|
||||
chip_earlgrey_asic #( .SecRomCtrlDisableScrambling(1'b1) ) dut (
|
||||
`else
|
||||
chip_earlgrey_asic dut (
|
||||
`endif
|
||||
.POR_N(...), ...
|
||||
);
|
||||
```
|
||||
|
||||
The parser accepts the first arm's head, opens the shared connection list, and
|
||||
inside it meets the `` `else ``. `take_list_directives` harvested *any*
|
||||
directive found inside a list's brackets as conditioning list elements, so it
|
||||
took the `` `else ``, then read `chip_earlgrey_asic` (the second arm's module
|
||||
name) as a positional connection — which succeeds, as a bare identifier — and
|
||||
failed two tokens later at `dut`, three lines from the actual seam.
|
||||
|
||||
`at_outer_arm_split` stops that: a `` `else ``/`` `elsif ``/`` `endif `` that
|
||||
**this list did not open** (counted over the list's own harvested directives),
|
||||
while a region opened at **item** scope is still live (`open_conds > 0`, the
|
||||
same "a region is live" guard `at_split_conditional` makes), is not conditioning
|
||||
elements — it is the seam. The harvest breaks, the item fails standing on the
|
||||
directive, and `at_split_conditional`'s four conditions all hold: the whole
|
||||
instantiation becomes one verbatim block.
|
||||
|
||||
Both halves of the guard matter. Without `open_conds > 0` an ordinary
|
||||
list-internal region would be refused; without the "did not open it" count the
|
||||
`` `endif `` of a legitimately list-internal region would be. Pinned from both
|
||||
sides by `an_ifdef_that_splits_an_instantiation_head_is_still_the_closing_shape`
|
||||
and `a_list_internal_region_is_still_harvested_as_list_elements`, and by the
|
||||
`.cases` control entry.
|
||||
|
||||
### The statement level runs first, and only the opening shape
|
||||
|
||||
The recovery is wired into **both** `parse_item_inner` and `parse_stmt_inner`.
|
||||
The statement one is what keeps `jtag_dtm_reg_block.sv:173`'s capture at the
|
||||
`abits.configure(...)` statement instead of at the enclosing `class`: an error
|
||||
raised inside a function body propagates outward, and the innermost frame that
|
||||
recognizes the shape must claim it first. (Condition 2 above would refuse the
|
||||
enclosing item anyway — the belt to this braces — but the useful capture is the
|
||||
narrow one.)
|
||||
|
||||
Statements get **only** the opening shape. The closing shape is item-scope by
|
||||
construction: `Parser::open_conds` counts the `` `ifdef ``s consumed *as items*,
|
||||
per `directive-split`'s rule, so `mark.conds` inside a body would be answering a
|
||||
question about a different scope. No corpus file asks for it.
|
||||
|
||||
### What is deliberately still refused
|
||||
|
||||
- Any non-conditional directive mid-expression.
|
||||
- A stray `` `else ``/`` `endif `` with nothing open.
|
||||
- An unterminated region, or a construct with no terminator before EOF.
|
||||
- Brackets that do not balance across the chosen arm.
|
||||
- A plain syntax error that merely sits near a directive.
|
||||
- Any body-opening head other than `function`/`task`.
|
||||
|
||||
All seven pinned by `the_opening_split_refuses_everything_it_does_not_model`
|
||||
and re-run against the release binary on standalone files.
|
||||
|
||||
### One deliberate widening, and it supersedes a test
|
||||
|
||||
`parser.rs`'s `a_directive_inside_a_connection_is_still_a_parse_error` pinned
|
||||
that a conditional region written *inside* a connection's parens is refused —
|
||||
"out of scope by design". That premise is exactly what this round changes:
|
||||
`chip_earlgrey_asic.sv:621` writes one inside a parameter value's
|
||||
concatenation, which is the same shape. The test is renamed
|
||||
`a_directive_inside_a_connection_is_captured_or_refused_by_kind` and now pins
|
||||
both halves — the conditional region is captured verbatim, any other directive
|
||||
there is still an ordinary parse error. This is the only pre-existing test whose
|
||||
expectation changed, and the only shape whose accept/refuse verdict moved
|
||||
outside the seven target files (measured: see the Work log's sweep diff).
|
||||
|
||||
### A currently-passing file cannot be affected
|
||||
|
||||
Both recoveries are reached only from an `Err` arm, and a file that formats
|
||||
today produces no such `Err`. The one exception is `at_outer_arm_split`, which
|
||||
runs on the **success** path — so it was measured rather than argued: the
|
||||
820-file corpus gate produces byte-identical per-file results before and after,
|
||||
and the 3,943-file OpenTitan sweep's pass set is a strict superset with no file
|
||||
moving out.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Consumed
|
||||
|
||||
- `Parser::verbatim_since(start, col)` — slices `source[span]` into a `RawText`
|
||||
and drops the comment copies falling inside the span. Used unchanged.
|
||||
- `Fmt::raw_text(raw)` / `Fmt::raw_lines(text, col)` — the verbatim printer.
|
||||
Used unchanged; no formatter source file was touched by this round.
|
||||
- `Parser::skip_conditional_arms` — `directive-split`'s arm skipper, reused by
|
||||
the opening-shape scan with the same meaning.
|
||||
- `Parser::open_conds` — read (never written) by `at_outer_arm_split`, which is
|
||||
its third reader. `directive-split`'s rule that only `note_item_conditional`
|
||||
and `split_conditional_item` may *write* it is preserved: this round adds no
|
||||
writer, because an opening-split block is conditional-balanced.
|
||||
- `ItemKind::Verbatim(RawText)` gained a **sixth** producer and
|
||||
`StmtKind::Verbatim(RawText)` a **second** (after the concurrent assertions).
|
||||
No signature changed, so no exhaustive match anywhere needed a new arm —
|
||||
`format.rs`, `bind.rs`, `visit.rs`, `spans.rs` and the linter are untouched.
|
||||
**No new AST variant, no new AST field.**
|
||||
|
||||
### Promised / changed for others
|
||||
|
||||
- **`crates/vlog_formatter/src/verify.rs` is untouched.** No normalization was
|
||||
added and no forgiveness widened. Verbatim bytes need none: a captured block
|
||||
is re-lexed as ordinary tokens on both sides, so every token inside it must
|
||||
still match, and all seven newly-passing OpenTitan files go through the
|
||||
runtime safety net (`lucisv --check`, which verifies) plus a two-pass
|
||||
idempotency check.
|
||||
- **Request to whoever next owns `crates/vlog_formatter/tests/verification.rs`:**
|
||||
`directive-split` shipped ten invariant-#4 attack tests there even though it
|
||||
too left `verify.rs` alone, on the grounds that a verbatim capture is
|
||||
forgiveness-*adjacent*. The equivalent tests for this round were **not**
|
||||
added, because `verification.rs` is Lane B's file this wave and a silent edit
|
||||
would break the merge contract. The seven refusal shapes are pinned in
|
||||
`parser.rs` instead (`the_opening_split_refuses_everything_it_does_not_model`)
|
||||
and were re-run against the release binary. Adding the (input, corrupted
|
||||
output) pairs to `verification.rs` after the merge is a QA-sized task and is
|
||||
recommended.
|
||||
- **New private parser surface only.** Two consts (`BODY_KEYWORDS`,
|
||||
`TF_QUALIFIERS`), one enum plus its reader (`ConstructEnd`,
|
||||
`construct_end`), two free functions (`directive_word_of` — extracted from
|
||||
the existing `directive_word` so a harvested `RawText` can be classified —
|
||||
and `take_since`), and seven `Parser` methods (`take_gap`,
|
||||
`at_outer_arm_split`, `at_opening_split`, `scan_opening_split_extent`,
|
||||
`past_end_label`, `capture_split`, `split_conditional_stmt`). Nothing is
|
||||
`pub`. `split_conditional_item`'s body was split so `capture_split` is shared
|
||||
by both shapes; its behaviour on the closing shape is unchanged.
|
||||
- **Delivered: `formatter-bug-fixes` round 2's `take_before_open` request.**
|
||||
See that README's Handshakes section, marked DELIVERED, and the work log
|
||||
below. `Parser::take_before_open` and the empty-call `CallComments::dangling`
|
||||
harvest now take only the comments written in the gap that ends at the
|
||||
bracket (`Parser::take_gap`), instead of draining the whole pending queue.
|
||||
|
||||
### Requests to other clusters
|
||||
|
||||
- **`directives-in-lists`**: a function/task port list
|
||||
(`Parser::parse_tf_ports`) still has no directive harvest, because `TfArg`
|
||||
lists carry no `Vec<ListDirective>` and adding one is an AST change with
|
||||
printer arms. `jtag_dtm_reg_block.sv:273` is therefore *captured verbatim*
|
||||
rather than formatted. Teaching that list the existing harvest would be
|
||||
strictly better output for the same file, and belongs to whoever owns the
|
||||
`directives-in-lists` surface plus `format.rs`.
|
||||
- **`StmtKind::Return` has no comment slot**, so `return // c` ⏎ `g();` still
|
||||
refuses (see the formatter-bug-fixes note). Not a directive matter; recorded
|
||||
because this round's parser change is what isolates it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Baseline recorded: OpenTitan sweep 107 failures at `17633d2`, corpus gate
|
||||
813/820, both re-run from a pristine scratchpad build of `HEAD`.
|
||||
- [x] Parser: `at_opening_split` (the trigger), `scan_opening_split_extent`
|
||||
(the extent), `past_end_label`, `construct_end` + `BODY_KEYWORDS` +
|
||||
`TF_QUALIFIERS`.
|
||||
- [x] Parser: `capture_split` extracted so both shapes share the rewind/walk.
|
||||
- [x] Parser: `at_outer_arm_split`, the `take_list_directives` guard, and the
|
||||
`directive_word_of` refactor it needs.
|
||||
- [x] Parser: statement-level recovery in `parse_stmt_inner`
|
||||
(`split_conditional_stmt`), opening shape only.
|
||||
- [x] Handshake (item 2): `take_before_open` + empty-call `dangling` narrowed
|
||||
to `take_gap`.
|
||||
- [x] 10 new parser tests, including the 7-shape refusal test and the two
|
||||
comment-ownership tests; one superseded test rewritten to pin both halves
|
||||
(`vlog_parser` lib suite 224 → 234).
|
||||
- [x] 7 cases in `crates/vlog_formatter/tests/cases/directive_in_statements.cases`
|
||||
(the harness asserts idempotency on every one).
|
||||
- [x] All 7 target OpenTitan files parse and format strict-clean; two-pass
|
||||
idempotency and unchanged on-disk md5 confirmed for each.
|
||||
- [x] Sweep 107 → 100, pass set a strict superset, no message changed on any
|
||||
still-failing file.
|
||||
- [x] Corpus gate byte-identical to baseline (813/820).
|
||||
- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test --workspace`
|
||||
clean.
|
||||
- [ ] **Not done, deliberately:** directive harvesting in function/task port
|
||||
lists (needs an AST field — see Requests); body-opening heads other than
|
||||
`function`/`task`; any canonical *layout* for the inside of a captured
|
||||
region — it stays byte-for-byte; the invariant-#4 attack pairs in
|
||||
`verification.rs` (Lane B's file — see Promised/changed).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-29 — dev
|
||||
|
||||
**Setup.** Worktree branched at `34b766c`, fast-forwarded to `master`
|
||||
(`17633d2`, Lane A merged) before any edit, so the round builds on the freed
|
||||
`parser.rs`. All measurement against the real checkout at
|
||||
`/Users/guoliangchen/repo/opentitan` (HEAD `0098135`), read-only — every probe
|
||||
uses `--check`/`--stdout` with `--no-cache`, and each target file's md5 was
|
||||
compared before and after.
|
||||
|
||||
**Baseline** (pristine `git archive HEAD` build in the scratchpad, so before and
|
||||
after are the same corpus and the same commands): OpenTitan sweep **107**
|
||||
failures over 3,943 files; corpus gate
|
||||
`{"passing":813,"total":820,"pct":99.1,...}`.
|
||||
|
||||
**Item 1 — the design choice.** Verbatim capture, reached by two recoveries
|
||||
that share one extent-capture step, rather than new grammar. Justified against
|
||||
the three existing directive features' contracts in Assumptions above; the
|
||||
short version is that the arms of a split region are rival spellings of one
|
||||
construct, there is no tree that holds "either this or that", and the four
|
||||
existing pass-through sites are all list-element boundaries that an expression
|
||||
does not have. No AST variant and no AST field was added, so `format.rs`,
|
||||
`bind.rs`, `spans.rs`, `visit.rs` and the linter are untouched — which is also
|
||||
what kept this round inside its file-ownership list while Lane B held the
|
||||
formatter.
|
||||
|
||||
Three things were learned by building it, each recorded above as an assumption:
|
||||
|
||||
1. The corpus writes the construct's terminator on **both** sides of the region
|
||||
(`chip_if.sv` inside the arms, `chip_earlgrey_asic.sv` after them), so one
|
||||
terminator rule is not enough — hence `terminated_in_arm`.
|
||||
2. `directive-split`'s "the terminator is a `;`" assumption is **false for a
|
||||
function header**. The first build of this round captured
|
||||
`jtag_dtm_reg_block.sv`'s `function new(...)` header and orphaned its body,
|
||||
moving the file's error from line 173 to line 280. `construct_end` is the
|
||||
answer, and it refuses by default for every body-opening head it does not
|
||||
model.
|
||||
3. The two `tb.sv` files needed **no new recovery** — only that
|
||||
`take_list_directives` stop hiding the seam from the recovery that already
|
||||
existed. That is the smallest change in the round and the one that fixes the
|
||||
two highest-value files.
|
||||
|
||||
**Item 1 — result.** All 7 target files clean:
|
||||
|
||||
| file | before | after |
|
||||
|---|---|---|
|
||||
| `hw/top_earlgrey/dv/env/chip_if.sv` | `1192:1: expected expression` | formats |
|
||||
| `hw/top_darjeeling/dv/env/chip_if.sv` | `894:1: expected expression` | formats |
|
||||
| `hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv` | `621:1: expected expression` | formats |
|
||||
| `hw/top_earlgrey/rtl/autogen/chip_earlgrey_cw340.sv` | `502:1: expected expression` | formats |
|
||||
| `hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv` | `173:1: expected expression` | formats |
|
||||
| `hw/top_earlgrey/dv/tb/tb.sv` | `114:22: expected \`)\` (found "dut")` | formats |
|
||||
| `hw/top_darjeeling/dv/tb/tb.sv` | `105:24: expected \`)\` (found "dut")` | formats |
|
||||
|
||||
Whole-sweep **107 → 100**. `comm -13` over the sorted failure lists is empty
|
||||
(nothing regressed); `comm -23` is exactly those seven files; and no file that
|
||||
still fails changed its message. Each of the seven was formatted twice through
|
||||
`--stdout` and the passes compared byte-for-byte — **idempotent** — with the
|
||||
checkout's md5 unchanged. Corpus gate re-run with both binaries against the
|
||||
same pinned corpus: **813/820 both times, and `diff` over the two per-file
|
||||
result tables is empty**, not merely the same total.
|
||||
|
||||
**Item 2 — the handshake.** Implemented as specified —
|
||||
`take_before_open` keeps only comments with `span.start >= self.last_end()` —
|
||||
and then found by bisection that it was not sufficient on its own: with
|
||||
`before_open` fixed, the pinned shape's comment was swallowed one line later by
|
||||
`CallComments::dangling`, the empty-`()` harvest, which drains the queue the
|
||||
same way. Both now go through one narrow helper, `Parser::take_gap()`. The
|
||||
"or better, justified" clause of the brief covers the second site; it is the
|
||||
same defect at the same struct, and without it the handshake does not deliver.
|
||||
|
||||
Verified by composing this lane's `parser.rs` with Lane B's worktree in a
|
||||
scratchpad copy — their files were read, never written — and running their whole
|
||||
workspace suite: everything stays green **except**
|
||||
`a_comment_before_a_call_in_a_condition_is_still_refused`, which flips from pass
|
||||
to fail, i.e. the shape now formats:
|
||||
|
||||
```
|
||||
if (
|
||||
// why
|
||||
!en() || b
|
||||
) begin
|
||||
```
|
||||
|
||||
and the real `hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` — the 12th and last
|
||||
bucket-2 file, which Lane B could not fix from inside `vlog_formatter` — formats
|
||||
cleanly end to end. Lane B's `expect_divergence` attack pairs all still pass;
|
||||
`verify.rs` is untouched by either lane. Marked DELIVERED in
|
||||
`docs/features/formatter-bug-fixes/README.md`.
|
||||
|
||||
**Deviations from the brief, all flagged:**
|
||||
|
||||
1. **No formatter `.cases` entry proves the keymgr line-1254 shape in *this*
|
||||
worktree**, because half the fix is Lane B's: `Fmt::header_parens` (their
|
||||
round 2) is what gives a comment written after `if (` a home. At `17633d2`
|
||||
that shape is refused with or without this round's parser change — confirmed
|
||||
against the pristine baseline binary — so a case asserting it here would
|
||||
fail. The parser side is pinned instead by two new parser tests
|
||||
(`a_comment_after_an_opening_bracket_is_not_stolen_by_an_inner_call`, which
|
||||
asserts both call comment slots are empty and the comment reaches the body's
|
||||
leading comments where `header_parens` collects it, and
|
||||
`a_comment_actually_written_before_a_bracket_is_still_taken` for the other
|
||||
side), and end to end by the composed run above. **The `.cases` entry belongs
|
||||
to the merged tree** and is the natural first QA task after the merge.
|
||||
2. **Only one pinned refusal test exists**, not two. Lane B's README names one
|
||||
(`a_comment_before_a_call_in_a_condition_is_still_refused`) and describes
|
||||
`return // c` ⏎ `g();` as a second *symptom*, which is not pinned as a test.
|
||||
That symptom is **not** fixed by this round and is refused identically before
|
||||
and after: it needs a comment slot on `StmtKind::Return`. Recorded as a
|
||||
request above.
|
||||
3. **One pre-existing parser test's expectation changed**
|
||||
(`a_directive_inside_a_connection_is_still_a_parse_error`), because the
|
||||
behaviour it pinned is the behaviour this round adds. Rewritten to pin both
|
||||
halves rather than deleted; rationale in Assumptions.
|
||||
4. **`docs/features/formatter-bug-fixes/README.md` was edited** — the
|
||||
Handshake-status edit the brief sanctions. This worktree holds the *trunk*
|
||||
copy of that file, which does not yet contain Lane B's round-2 Handshakes
|
||||
text, so the new `### Round 2's take_before_open request — DELIVERED`
|
||||
subsection sits where Lane B also appends. **A merge conflict there is
|
||||
expected and the resolution is to keep both blocks.**
|
||||
|
||||
**Gates.** `cargo fmt --all --check` clean, `cargo clippy --all-targets` clean
|
||||
(no new warnings, no `#[allow]` added), `cargo test --workspace` green, corpus
|
||||
gate exactly at baseline. No `git commit`, no `git push`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-29 — QA
|
||||
|
||||
**Verdict: SHIP.** No corruption, no capture-extent bug, no comment
|
||||
relocation found across the adversarial charter. All claimed numbers
|
||||
reproduced exactly. `vlog_parser` lib suite: 234 → 238 (4 new QA regression
|
||||
tests added, all passing; see below).
|
||||
|
||||
**Gates**, all re-run from a fresh build in this worktree:
|
||||
- `cargo fmt --all --check`: clean.
|
||||
- `cargo clippy --all-targets`: clean, no new warnings.
|
||||
- `cargo test --workspace --no-fail-fast`: green, every crate, 0 failures.
|
||||
|
||||
**Reproduction of the round's numbers**, against a pristine `17633d2` binary
|
||||
built in a separate `git worktree` (never touching this lane's tree) for
|
||||
every "before" comparison:
|
||||
- OpenTitan sweep (`/Users/guoliangchen/repo/opentitan`, HEAD `0098135`,
|
||||
read-only, `--no-cache --check`, both binaries against the identical
|
||||
3,943-file list): baseline **107**, round **100**. `comm -13` (round-only
|
||||
failures, i.e. regressions) is **empty**. `comm -23` (fixed) is **exactly**
|
||||
the 7 named files. Joined the two failure tables on filename and diffed
|
||||
the messages for every file failing in both: **zero** changed.
|
||||
- The 7 target files: each formats (`--check` exit 0 or 1, never 2), each
|
||||
two-pass idempotent (`--stdout` output fed back in produces byte-identical
|
||||
output), and each file's on-disk md5 confirmed unchanged before/after.
|
||||
- Corpus gate (`scripts/score.sh` against the real 820-file `corpus/`, not
|
||||
reachable by name from inside a worktree — BSD `find` on this machine
|
||||
does not descend into a directory given to it as a symlink without `-L`,
|
||||
which `score.sh` doesn't pass, so the corpus has to be referenced by its
|
||||
real path rather than a `corpus` symlink dropped in the worktree root):
|
||||
baseline `{"passing":813,"total":820,...}`, round identical, and
|
||||
`diff` over the two `-o details.tsv` per-file tables is **empty** —
|
||||
not just the same count, the same outcome for every one of the 820 files.
|
||||
- Composed-tree claim (Lane B's worktree,
|
||||
`.claude/worktrees/agent-a8ee7330b649bc150` @ `d3deacf`, read-only —
|
||||
rsynced to a scratch copy, Lane B's files untouched, only this lane's
|
||||
`parser.rs` overlaid on top): `cargo test --workspace --no-fail-fast`
|
||||
is green except exactly
|
||||
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
|
||||
which flips from pass to fail because the shape it pins now *formats* —
|
||||
matching the dev's report precisely, one flip and no other change. Built
|
||||
the composed release binary and confirmed
|
||||
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` formats end-to-end and is
|
||||
two-pass idempotent.
|
||||
|
||||
**Adversarial testing** (the charter's three named sins: a capture that eats
|
||||
too much, a refusal that became corruption, a comment that moved homes).
|
||||
Built two probe harnesses — a temporary `vlog_parser` integration test
|
||||
(deleted after use, not part of the final diff) dumping parsed-tree
|
||||
summaries, and a set of standalone `.sv` files run through both the round
|
||||
and baseline release binaries with `--stdout`/`--check`/idempotency:
|
||||
|
||||
- Nested `` `ifdef `` (with its own `` `elsif ``/`` `else ``) fully inside an
|
||||
opening split's first arm, itself inside an outer already-open region:
|
||||
captures the right byte range, `open_conds` lands back at exactly the
|
||||
outer count, next item survives. No prior test combined all three levels
|
||||
at once.
|
||||
- A 4-arm `` `elsif `` chain in an opening split: captured through the final
|
||||
`` `endif ``, not an intermediate arm.
|
||||
- A block comment whose text contains the literal string `` `endif ``
|
||||
inside the region: does not fool the extent scan (comments are never
|
||||
`TokenKind::Directive`, so this was never actually at risk, but it is now
|
||||
pinned).
|
||||
- A string literal containing the literal text `` `endif `` as data, and a
|
||||
string literal containing a bare `;`: neither confuses the bracket/`;`
|
||||
scan, since both are lexed as single opaque tokens.
|
||||
- `` `define ``/`` `include `` written inside the captured region: swept as
|
||||
ordinary opaque directive tokens, included verbatim, no special handling
|
||||
needed or present.
|
||||
- The split construct as the last item of its `module`/`class` (no sibling
|
||||
item follows): extent scan stops at its own terminator, never wanders
|
||||
into `endmodule`/`endclass`.
|
||||
- Two independent opening splits back-to-back in the same module: each
|
||||
captured as its own `Verbatim` item; the first's capture does not bleed
|
||||
into the second's region.
|
||||
- Mismatched bracket nesting *across* arms (deliberately malformed,
|
||||
adversarial input, not valid SV): the scanner follows only the first arm
|
||||
as documented, produces a verbatim capture, formats and reparses clean —
|
||||
no corruption, matching the documented "follow the first arm, skip the
|
||||
rest whole" policy.
|
||||
- Comment-ownership sweep for the `take_gap` handshake: comments in empty
|
||||
call parens (both before and after), nested calls each with their own
|
||||
comment, a comment between `!` and its callee, a bare macro call with a
|
||||
comment inside its parens, a `$display` system-call comment, and a
|
||||
three-comment instantiation connection list (before/between/trailing) —
|
||||
diffed byte-for-byte between the baseline and round binaries. **All six
|
||||
are identical**, including the still-refused `!en()`/`return` shapes
|
||||
(refused by both, same diagnostic), confirming `take_gap` changed nothing
|
||||
for any comment site outside the one it was built to fix.
|
||||
|
||||
One false alarm, recorded for the record: an ad hoc probe
|
||||
(`` `ifdef ``/`` `else ``/`` `endif `` conditioning a bare positional call
|
||||
argument with no comma, i.e. `f(` `` `ifdef A `` `1` `` `else `` `2`
|
||||
`` `endif `` `);`) initially looked like a diagnostic-quality regression —
|
||||
the round's error landed three lines away from the baseline's. Root cause
|
||||
was the probe file itself, not the parser: it placed a bare `x = 1;`
|
||||
directly as a *module item* (only legal inside a procedural block), an
|
||||
unrelated pre-existing syntax error that the baseline never reached because
|
||||
it failed earlier. Corrected to `initial begin ... end`, the shape formats
|
||||
cleanly and idempotently on both sides — not a finding.
|
||||
|
||||
**Tests added** (`crates/vlog_parser/src/parser.rs`, `#[cfg(test)] mod
|
||||
tests`, appended after the round's own directive-in-statements block; lib
|
||||
suite 234 → 238, all green):
|
||||
`a_nested_ifdef_with_its_own_elsif_survives_inside_an_opening_split_under_an_outer_region`,
|
||||
`an_elsif_chain_in_an_opening_split_is_captured_through_the_final_endif`,
|
||||
`a_block_comment_naming_endif_does_not_fool_the_extent_scan`,
|
||||
`an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword`.
|
||||
None of these were failing before they were added correctly (the first one
|
||||
initially failed on a test-construction mistake — a trailing `` `endif ``
|
||||
that closed the "still open" outer region I meant to leave open, and a
|
||||
wrong item index once the outer `` `ifdef `` became a sibling file item —
|
||||
both fixed in the test, not the parser); they exist to guard the
|
||||
adversarial coverage above against a future regression, since none of it
|
||||
was pinned by the round's own 10 tests.
|
||||
|
||||
**Not independently re-verified**: the `verify.rs`/invariant-#4 attack-test
|
||||
request the dev's Handshakes section files against `verification.rs`
|
||||
(Lane B's file this wave) — correctly left undone here too, per the
|
||||
merge-contract rule (`crates/vlog_formatter/tests/verification.rs` is
|
||||
outside this lane's file-ownership list). Recommended as the first QA task
|
||||
after the merge, as both this round's and Lane B's READMEs already say.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead.** Reviewed after QA's zero-finding SHIP; gates
|
||||
re-run on the worktree. The round's craft shows in what it refused to
|
||||
do: construct_end's Unknown → refuse arm turns "I don't understand
|
||||
this head" into a clean error instead of a guess (the jtag
|
||||
first-build bug caught by the dev's own testing is exactly why that
|
||||
arm exists), and the tb.sv fix being three lines in
|
||||
take_list_directives rather than a new recovery is the
|
||||
smallest-change discipline paying out on the highest-value files.
|
||||
Item 2's bisection — the specified fix necessary but not sufficient,
|
||||
the second drain found and unified behind take_gap — is why
|
||||
"implement exactly that, or better, justified" is written into every
|
||||
such handoff. The composed-tree verification against Lane B's
|
||||
worktree was the right way to prove a cross-lane delivery without a
|
||||
cross-lane edit, and QA reproduced it independently. Deviations all
|
||||
accepted; the two post-merge items (keymgr .cases entry, the
|
||||
standing-template attack pairs in verification.rs) are the lead's and
|
||||
are done in the merge commit's follow-up. Accepted; merged by the
|
||||
lead. OpenTitan sweep: 151 at the wave's start, 100 after this round.
|
||||
@@ -104,7 +104,21 @@ change. No `initializationOptions` fallback is needed, and none was added.
|
||||
`extractSettingsInformation(['lucisv'])` calls
|
||||
`workspace.getConfiguration(undefined).get('lucisv')`, which returns the whole
|
||||
section with every key at its effective value — so the server sees
|
||||
`serverPath` and `rainbowBeginEnd` in the payload too, and ignores them.
|
||||
`serverPath`, `rainbowBeginEnd` and `verbose` in the payload too, and ignores
|
||||
all three.
|
||||
|
||||
**Two settings in the section are deliberately not wire settings**, and the
|
||||
list is worth keeping short:
|
||||
|
||||
- `lucisv.serverPath` decides *which binary* the extension spawns, so it can
|
||||
only be read before there is a server to tell.
|
||||
- `lucisv.verbose` (2026-08-29) decides *how* it is spawned — it becomes the
|
||||
`--verbose` argument, and a process argument cannot be changed by a
|
||||
notification. Hence the one thing no other setting here does: changing it
|
||||
restarts the language server. It is a startup decision, not an opinion the
|
||||
server can adopt mid-session, and giving it a second spelling as a wire
|
||||
setting would mean two ways to say one thing that could disagree. See
|
||||
`docs/features/verbose-timing/README.md`.
|
||||
|
||||
Other editors: anything that can send `workspace/didChangeConfiguration` with
|
||||
that `settings` shape works. Neovim's `vim.lsp.config` sends its `settings`
|
||||
|
||||
@@ -145,6 +145,16 @@ invariant #4 is not in play. The formatter is not involved in this path at all.
|
||||
have disagreed with the first in the corner cases nobody tests.
|
||||
- **`IncludeGraph::incdirs()`** — a read-only accessor, so a candidate
|
||||
spelling can be a suffix under a real include path rather than a guess.
|
||||
- **`IncludeGraph::includers()`** (added 2026-08-28) — a read-only accessor
|
||||
over the edge table's keys, which is what lets the sweep read the files
|
||||
that write a resolving `` `include`` instead of every file in scope. The
|
||||
property it stands on is `resolve`'s agreement with the `found` the edges
|
||||
were built from; it is written out under "The sweep reads the includers,
|
||||
not the workspace", and a change to either half must re-read it.
|
||||
**Scope note for the lead:** `includes.rs` is outside the Lane A file
|
||||
list this round was scoped to. The accessor is four lines, purely
|
||||
additive, and there is no second way to ask the graph this question
|
||||
without a second copy of the include scan — flagged rather than smuggled.
|
||||
- **`includes::normalize` is now `pub`** (it was private). A renamed path and
|
||||
a resolved include are compared, and they must be folded the same way; a
|
||||
fourth private copy of that loop is the one thing that guarantees they
|
||||
@@ -212,6 +222,47 @@ probe (`cargo test --release -p lucisv_server --bin lucisv-server
|
||||
file_ops::tests::perf -- --ignored --nocapture`), the same shape as
|
||||
`includes.rs`'s: it prints and asserts nothing but the corpus's presence.
|
||||
|
||||
### The sweep reads the includers, not the workspace (2026-08-28)
|
||||
|
||||
The prefilter above still cost a *read* of every file to run. On OpenTitan
|
||||
(3 976 files) that is 249 ms of `sources()` per gesture, and the server
|
||||
advertises `willRename` with a `**` folder filter, so **renaming any folder in
|
||||
the explorer paid it**.
|
||||
|
||||
The include graph already holds the answer. `IncludeGraph`'s edge table is
|
||||
built as `scan(text).filter_map(|include| self.found(Some(path), include))`
|
||||
over every in-scope file, and `resolve` is exactly `found` followed by the
|
||||
index's own spelling of the result — so `resolve` answers `Some` for an
|
||||
include if and only if `found` did. Therefore:
|
||||
|
||||
> **A file with no entry in the edge table writes no `` `include`` this
|
||||
> workspace can resolve, so every iteration of `will_rename`'s inner loop over
|
||||
> it hits `let Some(old) = graph.resolve(…) else { continue }`.** It can
|
||||
> produce neither an edit nor a warning, and reading it is reading the
|
||||
> workspace to answer "nothing".
|
||||
|
||||
`Workspace::include_sources` is that set — `IncludeGraph::includers()` — plus
|
||||
every **open buffer**, because the graph is rebuilt on save and an `` `include``
|
||||
typed and not yet saved is in the buffer and in no edge
|
||||
(`an_unsaved_include_is_still_rewritten`). The one-directional property is
|
||||
asserted directly over a hostile tree rather than argued
|
||||
(`nothing_skipped_has_an_include_to_rewrite`: every in-scope file the sweep
|
||||
skips is checked to have no resolving include, and the tree is asserted to
|
||||
actually exercise the skip).
|
||||
|
||||
Measured, `--release`:
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| synthetic 506 files, 1 of them including anything | reading the scope **16.1 ms** | reading the includers **18.9 µs**; whole answer **35.4 µs** |
|
||||
| OpenTitan, 3 976 files, 331 of them includers | `sources()` **249 ms** | whole answer **14.1 ms** |
|
||||
|
||||
Same staleness premise the rename family adopted the same day
|
||||
(`docs/features/refactor-rename/README.md`): the graph is the server's
|
||||
authority on who includes what, a file changed on disk with nothing telling
|
||||
this server is a file the sweep does not read, and open buffers are the
|
||||
exemption.
|
||||
|
||||
The notifications cost one `reindex()` each, which is the cost a save has.
|
||||
|
||||
## Status / TODO
|
||||
@@ -230,6 +281,10 @@ The notifications cost one `reindex()` each, which is the cost a save has.
|
||||
is still one search order and one path folding.
|
||||
- [x] `watch::watched` made public, so the notifications and the watcher share
|
||||
one scope test.
|
||||
- [x] The sweep reads the include graph's includers plus the open buffers
|
||||
rather than `sources()` (2026-08-28): `IncludeGraph::includers`,
|
||||
`Workspace::include_sources`, the one-directional property asserted over
|
||||
a hostile tree, and a before/after probe.
|
||||
- [x] Tests: 24 in `file_ops.rs`, 7 in `server.rs` (dispatch, warning volume,
|
||||
reindex, watcher-double, unopened file, `null`), 1 in `main.rs` (the
|
||||
capability on the wire), 1 e2e session (real binary, edit decoded,
|
||||
@@ -327,6 +382,45 @@ target/debug/lucisv-server` → OK, 9 messages, unchanged from `bf17ddd`
|
||||
JSON and adds no message). Perf measured as above. No new dependency, no
|
||||
version bump, no other crate touched.
|
||||
|
||||
**2026-08-28 — dev agent (performance wave, Lane A).** The sweep stops reading
|
||||
the workspace. `performance.md` §6e flagged `file_ops.rs:120`'s `ws.sources()`
|
||||
as the same shape as the rename family's, unmeasured; it is 249 ms of file
|
||||
reading per gesture on OpenTitan, and the server advertises `willRename` with
|
||||
a `**` folder filter, so **renaming any folder in the explorer paid it** to
|
||||
learn that 3 645 of 3 976 files write no `` `include`` that resolves.
|
||||
|
||||
The include graph already holds that fact. `IncludeGraph::includers()` — four
|
||||
lines, the edge table's keys — is the new accessor, `Workspace::include_sources`
|
||||
is the set (includers plus every open buffer, because the graph is rebuilt on
|
||||
save and an unsaved `` `include`` is in neither `raw` nor `edges`), and
|
||||
`will_rename`'s loop is otherwise untouched. The argument is one sentence long
|
||||
and is written up under "The sweep reads the includers, not the workspace":
|
||||
`resolve` is `found` plus a re-spelling, and `raw` is built from `found`, so a
|
||||
file with no edge has no include `resolve` answers — every iteration of the
|
||||
inner loop over it hits its first `continue`.
|
||||
|
||||
Rather than argue that by inspection alone it is asserted over a hostile tree:
|
||||
`nothing_skipped_has_an_include_to_rewrite` walks every in-scope file the sweep
|
||||
skips and checks each of its `` `include``s resolves to nothing, and asserts
|
||||
the tree exercises the skip at all. Two behaviour tests beside it —
|
||||
`the_narrowed_sweep_reads_the_includers_and_answers_the_same` (24 files, 1
|
||||
includer, 2 with dangling includes) and `an_unsaved_include_is_still_rewritten`.
|
||||
|
||||
Measured, `--release`: synthetic 506 files, reading the scope **16.1 ms** →
|
||||
reading the includers **18.9 µs**, whole answer **35.4 µs**
|
||||
(`perf::a_will_rename_before_and_after`). OpenTitan, 3 976 files with 331
|
||||
includers: `sources()` **249 ms** → whole answer **14.1 ms** (throwaway probe
|
||||
against the local checkout, deleted; no test depends on it).
|
||||
|
||||
**One scope deviation, flagged not smuggled:** `includes.rs` is outside the
|
||||
file list this lane was scoped to, and the accessor was added there anyway.
|
||||
The alternative was a second copy of the include scan inside `state.rs`, which
|
||||
is the one thing this module's Handshakes section already says must not
|
||||
happen. Recorded in Handshakes above and in the round's report.
|
||||
|
||||
Gates: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` clean,
|
||||
`cargo test --workspace` green, `node editors/vscode/smoke.js` OK.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent, file operations (TODO.md §9c)
|
||||
@@ -514,8 +608,86 @@ nested-batch ordering is a documentation/robustness suggestion for the dev,
|
||||
not a blocker — no corruption path exists even in that shape, thanks to the
|
||||
safety net doing its job independently of what `Moves` models.
|
||||
|
||||
**2026-08-28 — QA agent (performance wave, Lane A).** Verified the round that
|
||||
moves `will_rename`'s sweep off `ws.sources()` onto
|
||||
`Workspace::include_sources()` (the include graph's `includers()`, plus open
|
||||
buffers). Worked alongside the rename-family QA pass in the same worktree;
|
||||
see `docs/features/refactor-rename/README.md`'s QA log for the shared gate
|
||||
run.
|
||||
|
||||
### Gates
|
||||
|
||||
`cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace` (0
|
||||
failures workspace-wide) and `node editors/vscode/smoke.js` all pass — see the
|
||||
refactor-rename QA entry for the exact run, which covered this round's diff
|
||||
in the same pass. `file_ops::tests::perf::one_rename_sweeps_the_whole_corpus_in_milliseconds`
|
||||
and `includes::tests::perf::building_the_graph_over_the_whole_corpus_is_milliseconds`
|
||||
fail in this worktree because `corpus/` is not checked out here; confirmed
|
||||
pre-existing (unchanged by this diff, present at `HEAD` before it) and
|
||||
unrelated.
|
||||
|
||||
### Attacks
|
||||
|
||||
The safety-net argument this narrowing rests on ("a file with no entry in the
|
||||
edge table writes no `` `include`` this workspace can resolve") is
|
||||
mechanical and did not need attacking on its own terms — `nothing_skipped_
|
||||
has_an_include_to_rewrite` already asserts it directly over whatever tree a
|
||||
test builds. What was worth attacking is whether `includers()` narrows in
|
||||
**every** file that matters, not just the ones the dev's own tree happened to
|
||||
build:
|
||||
|
||||
- **An include chain, `a.svh -> b.svh`, with a third file `c.sv -> a.svh`
|
||||
never spelling `b.svh` at all.** Renaming `b.svh` must narrow to `a.svh`
|
||||
(its direct includer) and rewrite only it; `c.sv` must not be mistaken for a
|
||||
candidate even though it transitively depends on the moved file through
|
||||
`a.svh`. Added `an_include_chain_narrows_to_the_direct_includer_of_the_moved_file`
|
||||
— passes: `will_rename` only ever rewrites a *direct* include of the moved
|
||||
file, which is exactly what `includers()` (a flat key set, not a
|
||||
reachability walk) bounds.
|
||||
- **A case-mismatched include spelling** — `` `include "DEFS.svh"`` written
|
||||
against a real `defs.svh` on disk, which macOS's default case-insensitive
|
||||
filesystem (confirmed case-insensitive on this machine) resolves silently.
|
||||
`IncludeGraph::found`/`found_as_if` key `raw` by the **includer's own path**,
|
||||
not the target's spelling, so the case mismatch does not stop the includer
|
||||
from landing in `includers()`. Added
|
||||
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites` — passes,
|
||||
narrows in and rewrites correctly.
|
||||
- **Unsaved includer, and the property test's own coverage** — re-read
|
||||
`an_unsaved_include_is_still_rewritten` and
|
||||
`nothing_skipped_has_an_include_to_rewrite`; both hold and both are
|
||||
exercised (`assert!(skipped > 0, ...)` in the property test actually forces
|
||||
the tree to have skippable files, so the property is not vacuously true).
|
||||
|
||||
No divergence found: every file `will_rename` would have read under the old
|
||||
`ws.sources()` sweep and actually needed (an includer of something that
|
||||
resolves) is still read under `include_sources()`, and no file that used to
|
||||
be read-and-skipped is now silently mis-included either. The `includes.rs`
|
||||
scope deviation the dev flagged (a four-line, purely additive accessor,
|
||||
outside Lane A's stated file list) is accepted as argued — the only
|
||||
alternative was a second copy of the include scan, which the feature's own
|
||||
Handshakes section already forbids.
|
||||
|
||||
### Summary
|
||||
|
||||
| Claim | Verdict |
|
||||
|---|---|
|
||||
| Gates | **Pass** |
|
||||
| `includers()` narrows in every file that can produce an edit or a warning | **Holds** under an include-chain attack and a case-mismatched-spelling attack, beyond the dev's own tree |
|
||||
| Scope deviation (`includes.rs::includers`) | Accepted, correctly flagged, minimal |
|
||||
|
||||
**Verdict: ship.** No findings against this round's diff. (The rename family's
|
||||
own residue finding, which needs the lead's ruling, is filed in
|
||||
`docs/features/refactor-rename/README.md` and does not touch this feature.)
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead, performance-wave Lane A (willRenameFiles).** The
|
||||
includers() narrowing is the same discipline as the rename fan-out
|
||||
applied to the include graph, QA's chain/case-spelling/unsaved attacks
|
||||
all pinned, and the property test ("nothing skipped has an include to
|
||||
rewrite") is the right shape of guarantee. Accepted; merged by the
|
||||
lead.
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
|
||||
@@ -22,6 +22,25 @@ per notification.
|
||||
filelist, are whole rebuilds exactly as before. `watch::one_scope_file` is
|
||||
the test. See `docs/features/incremental-index/README.md`.
|
||||
|
||||
- **Amended (index-scope, 2026-08-28): this feature now carries a little more
|
||||
weight than it did, and the difference is named here rather than left to be
|
||||
found.** A scope-widening `didOpen` used to run a whole rescan, which re-read
|
||||
every in-scope file and so *incidentally* caught anything that had changed on
|
||||
disk behind the server's back. Since that round it indexes only the folders it
|
||||
added. For a client that advertised
|
||||
`workspace.didChangeWatchedFiles.dynamicRegistration` — VS Code and Neovim
|
||||
both do — nothing is lost: the registered glob covers create, change and
|
||||
delete of every source file in the workspace, which is the mechanism, and the
|
||||
widen never was. For a client that did not, the **save-only model this README
|
||||
already documents is slightly narrower**: an external change in a folder
|
||||
already in scope now waits for the next whole rescan (a save of a file the
|
||||
index does not hold, a settings change, a folder change, a rename/delete
|
||||
notification) instead of possibly being caught by the next jump. That is the
|
||||
same class of window, not a new one — a save has taken the one-file
|
||||
incremental path since 2026-08-27, so such a session already had no reliable
|
||||
whole-tree re-read. Written up in full in
|
||||
`docs/features/index-scope/README.md`.
|
||||
|
||||
- **Registration is the only way in.** The protocol has no static
|
||||
`didChangeWatchedFiles` server capability — a server that wants file events
|
||||
must ask for them with `client/registerCapability`, and only a client that
|
||||
|
||||
@@ -24,6 +24,21 @@ The five:
|
||||
5. `always @( /* c */ * )` loses the comment: `parse_sens_list` discarded
|
||||
comments written inside the parens of an implicit sensitivity list.
|
||||
|
||||
**Round 2 (2026-08-29, Lane B of the testbench-syntax wave).** The same
|
||||
feature, extended to `syntax_coverage.md`'s bucket 2: the 12 real OpenTitan
|
||||
files that parse with zero errors but whose *formatted output* the safety net
|
||||
refused. Three more bugs, all in `format.rs`'s layout, none needing a
|
||||
`verify.rs` change:
|
||||
|
||||
6. A line comment trailing the then-branch's `end` swallowed the `else` that
|
||||
followed it (`end // addr_phase_write` + `else if (...) begin` came back as
|
||||
one comment). 4 of the 12 files.
|
||||
7. A comment written inside a statement header's parentheses (`if (// why` ⏎
|
||||
`cond)`, `while (`, `repeat (`, `wait (`, `case (`) printed *after* the
|
||||
`)`, moving it across a token. 7 of the 12 files.
|
||||
8. `default;` — the case-item colon IEEE 1800 §12.5 makes optional — came
|
||||
back as `default:`, inventing a token the source never wrote. 1 file.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The four `#SKIP` expected outputs are the spec. None of them was changed.
|
||||
@@ -66,6 +81,46 @@ The five:
|
||||
enclosing group in this printer. The hug only applies when the value already
|
||||
contains a forced break, so no case without comments changed.
|
||||
|
||||
### Round 2 (2026-08-29)
|
||||
|
||||
- **`verify.rs` was not touched at all this round** (`git diff` on it is
|
||||
empty), and no normalization was added or broadened. Every fix is a layout
|
||||
change in `format.rs`; the safety net's judgement of all three shapes is
|
||||
unchanged, and four crafted (input, corrupted output) pairs assert it still
|
||||
rejects exactly the corruptions these bugs used to produce.
|
||||
- **The parser's trivia attachment is taken as given.** Nothing between a
|
||||
statement header's `(` and `)` owns trivia, so a comment written there is
|
||||
queued and lands on the next node that takes meta — the body statement, or
|
||||
a `case`'s first item. The formatter takes it back by *span* rather than
|
||||
asking the parser to change: a leading comment of the body that starts
|
||||
before the header's `)` was written inside the parentheses. This is Lane B's
|
||||
file-set constraint made into a design point, and it is exact, because a
|
||||
comment's byte span says unambiguously which side of the `)` it was on.
|
||||
- **The `)` is found in the source, not in the AST**, by skipping whitespace
|
||||
and comments forward from the end of the condition expression
|
||||
(`skip_trivia`). Only trivia can stand there for `if`/`while`/`repeat`/
|
||||
`wait`/`case`. If anything else turns up, the header prints its plain
|
||||
parentheses and takes nothing, so an unrecognized shape behaves exactly as
|
||||
it did before.
|
||||
- **A cuddled `else` is a layout decision, not a token.** `end` keeps `else`
|
||||
on its line unless the then-branch's own trailing comments end in a line
|
||||
comment, which would swallow it. A block comment still cuddles
|
||||
(`end /* why */ else`).
|
||||
- `for`, `foreach` and `do ... while` are **not** covered: the first two do
|
||||
not end their header in a single condition expression, and a `do`-`while`
|
||||
has no body after its parentheses to take the comment back from. All three
|
||||
still refuse cleanly and are pinned as refusals by a test.
|
||||
- A comment written *before* a header's `(` (`if /* c */ (a)`) is also not
|
||||
covered — the formatter has no offset for the `(`, so such a comment is
|
||||
treated as if it were inside and the file is still refused, exactly as it
|
||||
was before. No corpus use.
|
||||
- **`default;` is read from the source too.** `CaseItem` records no `colon`
|
||||
flag (the parser does `let _ = self.eat_sym(":")`), so `default_has_colon`
|
||||
looks at the byte after the keyword. With a null body the `;` hugs the
|
||||
keyword — `default;`, not `default ;` — while `default: ;` keeps both the
|
||||
colon and the space it already had. Generate-case `default` reads the same
|
||||
way.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser::token::Comment` gained a position** (the handshake request
|
||||
@@ -102,6 +157,80 @@ The five:
|
||||
and the top-level `README.md` (another agent's scope) are untouched;
|
||||
`cargo fmt` was run and left those files byte-identical.
|
||||
|
||||
### Round 2 (2026-08-29)
|
||||
|
||||
- **Nothing was changed outside `crates/vlog_formatter`.** Round 2 consumes
|
||||
the AST exactly as it stands: `Comment.span`, `Expr.span`, `CaseItem.span`
|
||||
and `Meta.leading`'s source order are the only new load-bearing surfaces,
|
||||
and all four already existed. `git diff` on `crates/vlog_parser` and
|
||||
`crates/vlog_semantic` is empty.
|
||||
- **Open handshake request to whoever owns `vlog_parser/src/parser.rs`
|
||||
(Lane A's file this wave).** `Parser::take_before_open` (`parser.rs:757`)
|
||||
calls `take_dangling()`, which drains the *whole* pending-comment queue —
|
||||
`pending_trailing`, `pending_leading` and the bracket token's own leading
|
||||
comments — rather than only the comments actually written in front of the
|
||||
bracket. So a comment written just after a statement header's `(` is
|
||||
swallowed by the first call inside the condition and printed between that
|
||||
call's callee and its own `(`:
|
||||
|
||||
```systemverilog
|
||||
if (// If keymgr is not enabled in the current LC
|
||||
!cfg.keymgr_vif.get_keymgr_en() || ...
|
||||
```
|
||||
|
||||
comes back as `!cfg.keymgr_vif.get_keymgr_en // If keymgr ...` ⏎ `() ||`.
|
||||
`header_parens` cannot take it back — it never reaches the body's leading
|
||||
comments — and the formatter cannot hoist it out past the `!` without a
|
||||
cutoff threaded through every `expr` call, which is far more machinery than
|
||||
the parser fix. **Requested fix**: in `take_before_open`, keep only the
|
||||
comments whose `span.start >= self.last_end()`, i.e. those written in the
|
||||
gap that ends at the bracket, and leave the rest queued. `last_end()`
|
||||
already exists (`parser.rs:611`). This is the last of the 12 bucket-2 files
|
||||
(`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv`); the shape is pinned as a
|
||||
clean refusal by
|
||||
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
|
||||
which is the test that should flip to a `.cases` entry when the parser fix
|
||||
lands.
|
||||
- **Format-cache discipline** (`topo.md` §2.3): this round changes formatter
|
||||
*output* for the shapes above, so the workspace version must be bumped at
|
||||
release or a stale `.lucisv_cache` will skip files that would now format
|
||||
differently. Flagged for the lead; no version was bumped here.
|
||||
|
||||
### Round 2's `take_before_open` request — **DELIVERED** (2026-08-29)
|
||||
|
||||
Filed by round 2 against whoever owns `crates/vlog_parser/src/parser.rs`;
|
||||
answered by the `directive-in-statements` round (see
|
||||
`docs/features/directive-in-statements/README.md`). The requested change and
|
||||
one more site it needed:
|
||||
|
||||
- `Parser::take_before_open` no longer calls `take_dangling()`. It takes only
|
||||
the comments whose `span.start >= self.last_end()` — the gap that ends at
|
||||
the bracket — through a new narrow sibling, `Parser::take_gap()`. Exactly
|
||||
the fix round 2 specified.
|
||||
- **That alone was not enough.** `CallComments::dangling` (the inside of an
|
||||
*empty* `()`, `parser.rs`'s postfix-call arm) drained the whole queue too,
|
||||
so with `before_open` fixed the comment was swallowed one line later —
|
||||
which is why the pinned shape's condition starts `!en()` and not `!en(x)`.
|
||||
It now uses `take_gap()` as well. Both sites are `CallComments`; nothing
|
||||
else changed.
|
||||
|
||||
Verified by composing this lane's parser with round 2's worktree in a
|
||||
scratchpad copy (round 2's files read-only, never edited): the whole workspace
|
||||
suite stays green except
|
||||
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
|
||||
which flips from pass to fail — i.e. the shape now formats — and the real
|
||||
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` formats cleanly, closing the 12th
|
||||
and last bucket-2 file. That test should become a `.cases` entry at merge, as
|
||||
round 2 predicted. Round 2's `expect_divergence` attack pairs all still pass:
|
||||
`verify.rs` is untouched by either lane.
|
||||
|
||||
Still open, and **not** this handshake: `return // c` ⏎ `g();`, round 2's
|
||||
"second, independent symptom". The parser no longer misplaces that comment
|
||||
into the call, but nothing owns a comment written between `return` and its
|
||||
expression, so it drifts and the safety net still refuses the file — refused
|
||||
before this round and refused after, byte-identical either way. It needs a
|
||||
comment slot on `StmtKind::Return`, which is an AST change with printer arms.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Bug 3 — closing block labels preserved (`end`, all `join` kinds,
|
||||
@@ -131,6 +260,34 @@ The five:
|
||||
The "re-enable the four `#SKIP` cases" item lives in the case-tables
|
||||
README's TODO and is now satisfied.
|
||||
|
||||
### Round 2 (2026-08-29)
|
||||
|
||||
- [x] Bug 6 — a line comment trailing `end` no longer swallows the `else`
|
||||
that follows it; a block comment still cuddles.
|
||||
- [x] Bug 7 — a comment written inside an `if`/`while`/`repeat`/`wait`/`case`
|
||||
header's parentheses is printed inside them, on the correct side of the
|
||||
condition.
|
||||
- [x] Bug 8 — `default;` keeps IEEE 1800 §12.5's optional colon off, and
|
||||
`default: ;` keeps it on.
|
||||
- [x] 11 of the 12 bucket-2 OpenTitan files format cleanly and are
|
||||
idempotent; the whole checkout is unchanged on disk. Before/after in
|
||||
the work log.
|
||||
- [x] 11 new `.cases` entries (10 in `comments.cases`, 1 in
|
||||
`statements.cases`) — each one asserts the output *and* that
|
||||
re-formatting it is a fixed point, which is what the harness does.
|
||||
- [x] 4 masked-corruption rejection pairs + an explicit
|
||||
comments-never-dropped assertion in `verification.rs`, plus 4 pinned
|
||||
refusals for the shapes deliberately left uncovered.
|
||||
- [x] `cargo fmt --check` clean, `cargo clippy --all-targets` silent,
|
||||
`cargo test --workspace` green, pinned corpus 813/820 (baseline 813,
|
||||
zero verification errors).
|
||||
- [ ] Not fixed, needs a change in `vlog_parser` (see Handshakes): a comment
|
||||
after `if (` when the condition starts with a call —
|
||||
`keymgr_scoreboard.sv`, the 12th file.
|
||||
- [ ] Not fixed, no corpus evidence, pinned as refusals: a comment inside a
|
||||
`for`/`foreach` header or a `do ... while (...)`; a comment written
|
||||
between a header keyword and its `(`.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-18 — dev agent
|
||||
@@ -239,6 +396,109 @@ an indented banner comment) formats cleanly, and `lucisv` on its own output is
|
||||
byte-identical. Every bug's original repro from the two feature READMEs was
|
||||
re-run through the built CLI and now exits 0.
|
||||
|
||||
### 2026-08-29 — dev agent (Lane B, testbench-syntax wave)
|
||||
|
||||
**Scope.** `syntax_coverage.md`'s bucket 2: the 12 OpenTitan files that parse
|
||||
with zero errors but whose formatted output the safety net refused. Measured
|
||||
first, against the real checkout at `/Users/guoliangchen/repo/opentitan`
|
||||
(`--no-cache --check` over all 3,943 `.sv`/`.svh`): **151 failures, 12 of them
|
||||
`verification failed:`** — reproducing the sweep exactly. The 12 are three
|
||||
shapes, not one:
|
||||
|
||||
| # | shape | files |
|
||||
|---|---|---|
|
||||
| 6 | `end // c` ⏎ `else …` — the trailing line comment swallows the `else` | 4 |
|
||||
| 7 | a comment inside a statement header's `(...)` prints after the `)` | 7 |
|
||||
| 8 | `default;` comes back as `default:` | 1 |
|
||||
|
||||
**Bug 6 — `end // c` then `else`.** `if_stmt` cuddled `else` onto the `end`
|
||||
line whenever the then-branch was a block. `stmt_as_body` has already printed
|
||||
the block's trailing comments by then, so ` else if (b) begin` landed *inside*
|
||||
a line comment's text and `verify.rs` saw one comment reading
|
||||
`// addr_phase_write else if (addr_phase_read) begin`. The whole fix is one
|
||||
extra condition on `then_is_block`: a free `trailing_ends_line(&then.meta)`
|
||||
that asks whether the last thing `trailing` prints is a `//` comment. A block
|
||||
comment still cuddles, which is what the source wanted anyway.
|
||||
|
||||
**Bug 7 — comments inside a header's parentheses.** The header's `(` and `)`
|
||||
are printed by `parens()` and belong to no node, so the parser has nowhere to
|
||||
put a comment written between them: it stays in the pending queue and lands on
|
||||
the next node that calls `take_meta` — the body statement (`if`, `while`,
|
||||
`repeat`, `wait`) or the first case item (`case`). Printed there, the comment
|
||||
sits after a `)` it was written before.
|
||||
|
||||
Fixed entirely on the formatter side, by span. `header_parens(cond, body_meta)`
|
||||
finds the closing `)` with `skip_trivia` (forward from `cond.span.end`; only
|
||||
whitespace and comments can stand there), takes every leading comment of the
|
||||
body that starts before it, splits them at `cond.span.start` into before/after
|
||||
buckets, and hands them to `paren_comments` — which is the existing
|
||||
`ExprKind::Paren { before, after }` layout, factored out and now shared by both
|
||||
callers rather than duplicated. It returns how many comments it consumed;
|
||||
`stmt_as_body_from` / `leading_from` / `case_body` skip exactly that many.
|
||||
`leading`, `stmt_as_body` and `case_body`'s old signature are all preserved as
|
||||
`skip = 0` wrappers, so the twelve other `stmt_as_body` call sites are
|
||||
untouched. When the source is not the expected shape (no `)` where one was
|
||||
expected, or nothing to take) the function returns the plain `parens(cond)` and
|
||||
takes nothing, so every input that formatted before formats identically.
|
||||
|
||||
`for`, `foreach` and `do ... while` were deliberately left out: the first two
|
||||
do not end their header in one condition expression and the third has no body
|
||||
after its parens. Confirmed they still refuse cleanly and pinned that with a
|
||||
test, so a later round sees them change rather than appear.
|
||||
|
||||
**Bug 8 — `default;`.** `parse_case_body` does `let _ = self.eat_sym(":")`, so
|
||||
the AST does not record whether the source wrote the colon, and `case_labels`
|
||||
printed `default:` unconditionally — inventing a token. Since `CaseItem.span`
|
||||
starts at the `default` keyword, `default_has_colon` reads the byte after it
|
||||
(through the same `skip_trivia`) and prints what was written. With a null body
|
||||
the `;` hugs the keyword, because `stmt_as_body` would otherwise lay the `;`
|
||||
out as a body and produce `default ;`. `default: ;` is unchanged.
|
||||
|
||||
**`verify.rs` is untouched** — `git diff` on it is empty. Per `topo.md` §2.1's
|
||||
standing template I added the rejection tests anyway: four crafted (input,
|
||||
corrupted output) pairs asserting the net still refuses the comment merged into
|
||||
`else if`, the comment moved across the `)`, `default;` → `default: ;` and its
|
||||
mirror `default: ;` → `default;`.
|
||||
|
||||
**Before / after on the real OpenTitan checkout** (3,943 files, `--no-cache
|
||||
--check`, nothing ever written — `git status` in the corpus shows only the
|
||||
pre-existing `hw/ip/aes/dv/tb/tb.sv` modification `syntax_coverage.md` already
|
||||
records):
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| total failures (exit 2) | 151 | 140 |
|
||||
| `verification failed:` | 12 | **1** |
|
||||
| `parse error:` / `lex error:` | 139 | 139 |
|
||||
| crashes | 0 | 0 |
|
||||
|
||||
All 11 fixed files were additionally formatted twice through `--stdout` and the
|
||||
two passes compared byte-for-byte: **idempotent**, and every checkout file's
|
||||
`md5` is unchanged. Pinned 820-file corpus: **813 passing** (baseline 813),
|
||||
zero verification errors, zero crashes — no regression.
|
||||
|
||||
**The 12th file, and why it is not mine to fix.**
|
||||
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` had *two* bucket-2 bugs; fixing the
|
||||
first (the `end // addr_phase_write` / `else if` merge at line 643) uncovered a
|
||||
second at line 1254 that is not a formatter layout bug at all. The comment
|
||||
there is written after `if (` and the condition starts with a call, so
|
||||
`Parser::take_before_open` — which drains the whole pending queue — hands it to
|
||||
`CallComments::before_open`, and the formatter faithfully prints it between the
|
||||
callee and its `(`. `header_parens` never sees it. Hoisting it back out of the
|
||||
expression past the `!` would need a suppression cutoff threaded through every
|
||||
`expr` call; the parser fix is one span check. Filed as an open handshake
|
||||
(above) with the exact patch, out of Lane B's file set, and pinned as a clean
|
||||
refusal by a test. Also confirmed the same parser bug bites
|
||||
`return // c` ⏎ `g();`, which is a second, independent symptom.
|
||||
|
||||
**Deviation from the brief**: 11 of 12 files, not 12, for the reason above.
|
||||
Nothing was worked around and no corruption ships — the 12th file is still
|
||||
refused and left byte-identical, which is the correct behavior until the parser
|
||||
lands its fix.
|
||||
|
||||
**Format-cache note for the lead**: formatter output changed, so the workspace
|
||||
version must be bumped at release (`topo.md` §2.3). Not bumped here.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
@@ -485,8 +745,187 @@ compliance (no unwrap/expect/panic in library paths, no new deps, no
|
||||
un-explained `#[allow]`, TODO.md/README.md/`lucisv` untouched) all confirmed
|
||||
by direct inspection, not just by trusting the work log's claims.
|
||||
|
||||
### 2026-08-29 — QA agent (Lane B, testbench-syntax wave)
|
||||
|
||||
**Scope**: round 2 only — the three bucket-2 fixes (bug 6 `end // c` + `else`,
|
||||
bug 7 `header_parens`, bug 8 `default;`) — with the adversarial charter aimed
|
||||
squarely at a dropped/merged comment, an invented/moved token, or a fix that
|
||||
only works on the corpus shapes. Built a `--no-cache --stdout`/`--check`
|
||||
attack harness (pass1 → pass2 byte comparison for idempotency) and ran ~30
|
||||
hand-crafted `.sv` files beyond the committed cases, then reproduced every
|
||||
number in the work log independently against the real checkouts.
|
||||
|
||||
**Tool chain** (workspace root, after adding the two regression tests below):
|
||||
`cargo fmt --check` clean; `cargo clippy --all-targets` silent, no new
|
||||
`#[allow]`; `cargo test --workspace` green — `vlog_formatter`'s
|
||||
`verification.rs` at 119/119 (118 + 1 new), `cases.rs` 1/1 (672 total cases
|
||||
across all `.cases` files, `grep -c '#SKIP'` zero everywhere). Confirmed
|
||||
`git diff --stat` on `crates/vlog_parser`, `crates/vlog_semantic`,
|
||||
`crates/vlog_formatter/src/verify.rs` is empty — the "verify.rs untouched"
|
||||
claim holds.
|
||||
|
||||
**Shape-A attacks (`end // c` / `else`)** — 5 crafted files: nested three-deep
|
||||
if-else-if chain with every `end` individually commented (correct, stable);
|
||||
the comment text containing the literal word "else" (correct, not
|
||||
mistaken for structure); a CRLF-terminated file with the same shape
|
||||
(correct); a pure block comment before `else` (still cuddles, as designed).
|
||||
**One real gap found** (below) with a mixed block+line trailing comment.
|
||||
|
||||
**Shape-B attacks (`header_parens`)** — 9 crafted files hitting the source
|
||||
scan directly: a `)` inside a string literal in the condition
|
||||
(`s == ")"`), a `)` inside a nested paren sub-expression, a `)` spelled
|
||||
inside a block comment (`/* looks like ) but is not */`), comments on both
|
||||
sides of the `cond.span.start` split simultaneously, a condition that is
|
||||
itself a `Paren` (double parens), `case`/`while`/`repeat`/`wait` each with
|
||||
both-sided comments, and a case with two commented items after the header to
|
||||
attack the skip-count plumbing. **All format correctly, keep every comment
|
||||
in its original stream position, and are idempotent — no corruption, no
|
||||
double-print, no drop.** Also re-confirmed the two documented refusal
|
||||
boundaries directly (not just via `cargo test`): a comment before the
|
||||
statement keyword's `(` (`if /* c */ (a)`) refuses cleanly (`token stream
|
||||
diverges ... input has comment ... output has symbol "("`), and a comment
|
||||
before a call in the condition refuses cleanly, matching the Handshakes
|
||||
description exactly.
|
||||
|
||||
**Shape-C attacks (`default`)** — 9 crafted files: `default ;` (extra space)
|
||||
normalizes to `default;`; `default: ;` unchanged; `default begin end` /
|
||||
`default: begin end` both correct with the colon exactly as written;
|
||||
`default y = 9;` (no colon, non-null body — a shape not explicitly named in
|
||||
the work log but legal per the same IEEE grammar) correctly keeps the colon
|
||||
off; two `default`s in one `case` (illegal but tolerated) round-trips both
|
||||
correctly; `default /* c */: y = 9;` (comment between keyword and colon)
|
||||
refuses cleanly rather than dropping or moving the comment. **One
|
||||
non-blocking style nit found** (below): a trailing comment on `default;`
|
||||
breaks the hug. `default;` inside a `generate case` without `begin`/`end`
|
||||
hits a **pre-existing parser error** ("expected item"), confirmed unrelated
|
||||
— `default begin : gd end` in the same position parses and formats fine, so
|
||||
this is generate-case's existing null-body restriction, not a regression
|
||||
from this round.
|
||||
|
||||
**Refusal-pin sabotage check**: confirmed by inspection that `StmtKind::For`
|
||||
and `StmtKind::DoWhile` were not touched by the diff at all (no
|
||||
`header_parens` call added), so their pinned refusal test is exercising the
|
||||
same pre-existing, unmodified comment-position divergence check from round
|
||||
1 — not a vacuous pass against dead code.
|
||||
|
||||
**Masked-corruption template**: all four crafted pairs genuinely attack the
|
||||
paths this round changed (else-swallow, comment-across-`)`, colon invented,
|
||||
colon dropped) rather than generic corruptions; re-ran them independently
|
||||
via `cargo test -p vlog_formatter the_bucket_two_corruptions_are_still_rejected`.
|
||||
|
||||
**Numbers reproduced independently**, all against the live checkouts, all
|
||||
read-only (`--check`/`--stdout` only):
|
||||
- OpenTitan (`/Users/guoliangchen/repo/opentitan` @ `0098135264`, the same
|
||||
pre-existing `hw/ip/aes/dv/tb/tb.sv` local edit `syntax_coverage.md`
|
||||
records, nothing else dirty): `lucisv --no-cache --check .` →
|
||||
**exactly 1** `verification failed:` (`hw/ip/keymgr/dv/env/
|
||||
keymgr_scoreboard.sv:1254`, byte-identical message to the Handshakes
|
||||
quote). Total failure count differs slightly from the work log's 140
|
||||
(146 here) — attributable to `.gitignore`/vendor-tree walk differences
|
||||
between sweeps, not to this round; the load-bearing number (verification
|
||||
failures) matches exactly.
|
||||
- Grepped the whole checkout for the three trigger shapes independently of
|
||||
the work log's file list (`end\s*//.*\n\s*else`, `(if|while|repeat|wait|
|
||||
case)\s*\(\s*//`, `^\s*default\s*;`) and got **exactly 12** candidate
|
||||
files. Ran each through format+idempotency: **10 format cleanly and are
|
||||
pass1==pass2 idempotent**, `keymgr_scoreboard.sv` is the documented
|
||||
refusal, and one grep hit (`spi_device_scoreboard.sv`) fails on an
|
||||
unrelated pre-existing macro-expansion parse error
|
||||
(`` `CREATE_TPM_CASE_STMT ``) before the formatter ever reaches the
|
||||
bucket-2 shape — confirms "11 of 12" exactly, with the 12th grep hit
|
||||
being a false positive from the search pattern, not a second bug.
|
||||
- Corpus gate: fetched `tools/corpus_fetch.sh`'s four pinned repos (820
|
||||
files: 131 + 613 + 35 + 41, matches exactly) and ran `scripts/score.sh`:
|
||||
`{"passing":813,"total":820,...}` — the exact baseline, zero
|
||||
`verification failed:` entries in `.score-results.tsv` (the 7 failures
|
||||
are all pre-existing parse/lex errors, none in the `other` bucket is a
|
||||
verification error).
|
||||
|
||||
**Findings**
|
||||
|
||||
*Should-fix*: none. No hard-invariant violation found in either crafted
|
||||
attacks or the real checkouts.
|
||||
|
||||
*Nit / informational* (both non-blocking — the safety net holds in both
|
||||
cases; regression tests added for both):
|
||||
|
||||
1. **`trailing_ends_line` (`format.rs`, the `Some(tr)` arm) checks whether
|
||||
the *merged* trailing text starts with `//`, not whether it ends in a
|
||||
line comment.** `Meta.trailing` merges several trailing comments into one
|
||||
string (see `ast.rs:92-96`); a line comment must physically be last in
|
||||
any such merge (nothing can follow `//` on the same source line), so the
|
||||
correct test is "does the merge end in one", not "does it start with
|
||||
one". For `end /* a */ // b` the merged text is `"/* a */ // b"`, which
|
||||
does not start with `//`, so `trailing_ends_line` returns `false` and
|
||||
`then_is_block` stays `true` — the `else` still tries to cuddle, exactly
|
||||
reproducing the bug this round fixes, on the one merge shape the fix's
|
||||
condition doesn't cover. **Not a corruption**: `verify.rs` catches it on
|
||||
reparse (the output's one merged comment doesn't match the input's two)
|
||||
and the file is refused, byte-identical, same as it was before this
|
||||
round (this exact shape always cuddled unconditionally pre-fix too, so
|
||||
it is not a regression — it is the fix's coverage boundary, undocumented
|
||||
until now). Pinned as a refusal, not fixed — narrowing `is_line_comment`
|
||||
into a "starts vs. ends" split is a real design decision (the merge
|
||||
already lost the individual comments' boundaries) that belongs to
|
||||
whoever next touches this heuristic, not a QA-scope patch. Regression
|
||||
test: `crates/vlog_formatter/tests/verification.rs::
|
||||
a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`.
|
||||
2. **A trailing comment on a colon-less `default;` breaks the hug and
|
||||
inserts a space**: `default; // fallback` formats to `default ; //
|
||||
fallback`. Root cause: `case_item`'s shortcut requires `is_bare(&item.
|
||||
stmt.meta)`, and a comment trailing the null statement lands in `item.
|
||||
stmt.meta.trailing`, which is not bare, so the shortcut is skipped and
|
||||
the general `case_labels` + `stmt_as_body` path inserts its usual
|
||||
`Doc::Line` between the label and the body. **Not a correctness issue**:
|
||||
the comment is kept verbatim in its original stream position, `verify.rs`
|
||||
accepts it (whitespace is not part of the token stream), and it is
|
||||
idempotent. It does contradict the round's stated design point
|
||||
("`default;`, not `default ;`") for this one sub-case. Pinned with an
|
||||
exact-output case rather than fixed, since teaching the shortcut to also
|
||||
fire with a bare-except-trailing-comment statement (and then print that
|
||||
comment itself) is a small but real behavior change outside a
|
||||
verify-and-report QA pass. Regression case:
|
||||
`crates/vlog_formatter/tests/cases/statements.cases`, "a trailing
|
||||
comment on a colon-less `default;` keeps the comment and the missing
|
||||
colon".
|
||||
|
||||
**Regression tests added this pass** (2 files, both green):
|
||||
- `crates/vlog_formatter/tests/verification.rs`:
|
||||
`a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`
|
||||
(finding 1 above, pins the safe refusal).
|
||||
- `crates/vlog_formatter/tests/cases/statements.cases`: one new case (finding
|
||||
2 above, pins the current — correct but slightly odd — output).
|
||||
|
||||
**Overall verdict**: **SHIP.** Both bucket-2 fixes claimed (11/12 files,
|
||||
verification failures 12→1) are reproduced exactly against the live
|
||||
OpenTitan checkout and the pinned 813/820 corpus, `verify.rs` is
|
||||
byte-for-byte untouched, and every crafted adversarial input across all
|
||||
three shapes either formats correctly with every comment preserved in place
|
||||
and idempotently, or is safely refused with the file left untouched — never
|
||||
corrupted. The two findings are both informational nits with permanent
|
||||
regression tests now guarding them; neither is a hard-invariant violation
|
||||
and neither blocks merge.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead, round 2 (bucket-2 round-trip bugs).** Reviewed
|
||||
after QA's SHIP; gates re-run on the worktree (fmt clean, formatter
|
||||
suite green). Three shapes, three root causes, all fixed where the bug
|
||||
lived — format.rs — with verify.rs, the parser and the semantics
|
||||
provably untouched, and the standing template honored: rejection tests
|
||||
added anyway, four of them attacking the fixed paths specifically.
|
||||
The dev's best decision was the one it did NOT make: the twelfth file
|
||||
is a parser bug (take_before_open draining the pending-comment queue),
|
||||
and it was filed as a specified Handshake instead of a cross-lane
|
||||
edit — the directive round is delivering it. QA's two informational
|
||||
pins are accepted as filed: the block-plus-line trailing-comment
|
||||
boundary stays a clean refusal (the safety net's job, done), and the
|
||||
`default ; // comment` stray space is a style wrinkle, not a token
|
||||
change. 11 of 12 files independently confirmed on the real checkout,
|
||||
corpus exactly at baseline. Formatter output changed, so the release
|
||||
bumps the workspace version per the format-cache rule — flagged and
|
||||
carried. Accepted; merged by the lead.
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes
|
||||
needed.**
|
||||
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
# fuzzy-completion
|
||||
|
||||
## Goal
|
||||
|
||||
Make identifier completion answer the name the user is *reaching* for rather
|
||||
than only the one they have spelled the front of: typing `clkenq` should offer
|
||||
`clk_osc_en_q`. The letters have to be present and in order — a subsequence
|
||||
match — and nothing more is promised.
|
||||
|
||||
The failure this fixes was entirely server-side. VS Code's suggest widget has
|
||||
always fuzzy-ranked whatever list it holds, but lucisv narrowed by prefix with
|
||||
a binary search into a sorted table, so `clkenq` returned *nothing* and
|
||||
`clk_osc_en_q` never reached the client to be ranked. The policy, ruled by the
|
||||
owner, is **VS Code's own**: prefix matching below three typed characters,
|
||||
subsequence matching from three up. Matching the client is the point — a server
|
||||
that went fuzzy at one character would answer a question the widget then
|
||||
filtered the answer to, and one that never went fuzzy is the bug.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The typed word is ASCII.** `completion::is_ident_char` accepts
|
||||
`[A-Za-z0-9_$]` and nothing else, which is what lets `candidates::fold` be
|
||||
`byte | 0x20` instead of a branch, and what makes a non-ASCII byte in a
|
||||
*name* unable to collide with any query byte.
|
||||
- **A subsequence match is monotone in the query.** If a name holds `clke` in
|
||||
order it holds `clk` in order. This is what makes a complete (not
|
||||
`isIncomplete`) answer at three characters safe: everything the fourth
|
||||
keystroke could match is already in the list the client holds, and VS Code's
|
||||
own filter is a subsequence filter too. It is also why the 1–2-character
|
||||
answers must be marked incomplete — there the hit set *grows* at the third
|
||||
keystroke, which is the one transition the rule does not cover.
|
||||
- **The client re-ranks.** VS Code scores every item it holds with its own
|
||||
matcher and orders the widget by that; `sortText` breaks its ties and the
|
||||
order of the `items` array is not consulted at all. So the server's score
|
||||
decides exactly two things: **which** items survive the cap, and the order a
|
||||
client that does *not* re-rank would show. It is not trying to reproduce VS
|
||||
Code's scorer and does not need to.
|
||||
- **`sortText` is still `<tier digit><name>`.** Unchanged, deliberately: it is
|
||||
the tier ordering, and a client that sorts purely on it gets tiers in order
|
||||
and alphabetical names inside each, exactly as before. The fuzzy ranking
|
||||
lives in the array order instead.
|
||||
- **A one-character fuzzy query is not worth answering.** It matches most of a
|
||||
workspace, which is a list nobody reads, and the character mask is one bit
|
||||
wide so it prunes nothing. The three-character floor fences it off.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`candidates.rs` → `completion.rs`** (new): `Query`, `Score`, `rank_cmp`,
|
||||
`Candidates::words_fuzzy`, `Candidates::units_fuzzy`. `Query::new` folds and
|
||||
masks the typed characters once per request; `Query::score` matches one name.
|
||||
The `cap` argument to the two table scans is the caller's `LIMIT`, and a full
|
||||
return means the table held more — **the caller owes the response an
|
||||
`isIncomplete`**, which `completion.rs` pays.
|
||||
- **The prefix API is untouched.** `Candidates::words`, `units`, `macros`,
|
||||
`modules` and `has_module` answer exactly what they answered, so every other
|
||||
caller is unaffected. `words()` still returns `&[String]`, which is what
|
||||
`state.rs`'s and `perf.rs`'s equality checks compare.
|
||||
- **`inline.rs` is deliberately not a consumer.** The ghost instantiation
|
||||
probes `Candidates::has_module`, which is an **exact, case-sensitive** binary
|
||||
search, and it stays that way: it decides whether to plan a real
|
||||
instantiation of a real module, and `Fifo` is not `fifo` to any Verilog tool.
|
||||
Fuzzy matching must never leak into the instantiation trigger — a ghost
|
||||
offering `clk_osc_en_q ...(...)` because the user typed `clkenq ` would be
|
||||
the same class of mistake as a formatter changing code.
|
||||
- **No new setting.** This is VS Code-default behaviour, so `settings.rs` and
|
||||
`editors/vscode/package.json` are untouched. A `lucisv.completion.fuzzy`
|
||||
toggle (or a configurable floor) is a plausible future request; it is not
|
||||
this round's.
|
||||
- **`vlog_semantic`, `vlog_parser`, `vlog_refactor` unchanged.** Nothing new is
|
||||
asked of any of them.
|
||||
|
||||
## The rules, in one place
|
||||
|
||||
**Which tiers match how**, at three or more typed characters:
|
||||
|
||||
| Tier | Matched by | Changed? |
|
||||
|---|---|---|
|
||||
| 0 module names | substring | no |
|
||||
| 1 declarations in scope | **subsequence** | yes |
|
||||
| 2 index names (packages, members, typedefs, classes, modules) | **subsequence** | yes |
|
||||
| 2 `` `define`` names | prefix | no |
|
||||
| 3 templates | prefix | no |
|
||||
| 4 keywords | prefix | no |
|
||||
| 5 project words | **subsequence** | yes |
|
||||
| the backtick-only response (`` `WI| ``) | prefix | no |
|
||||
|
||||
Below three characters **every** tier matches exactly as it did before this
|
||||
round, byte for byte, and the response says `isIncomplete`.
|
||||
|
||||
### What did not go fuzzy, and why
|
||||
|
||||
- **Keywords.** 181 short words a user knows the spelling of; a subsequence
|
||||
match over them is noise, not help. `alws` offering `always` is not worth
|
||||
`nd` offering `endmodule`, `and`, `bind`, `unique`, ….
|
||||
- **Templates.** Reached by a `prefix` field that is itself a keyword.
|
||||
- **`` `define`` names.** The brief named the macro tier as unchanged and it is
|
||||
taken literally, in both places a macro name is offered — after a backtick
|
||||
(`` `WI| ``, the macro-only response) and bare (`` `ifdef WI| ``). The
|
||||
backtick case is the load-bearing one: it is a small, closed vocabulary the
|
||||
user is spelling deliberately. **The bare case is a defensible one-line
|
||||
change the lead may want**: a `localparam WIDTH_MAX` is reachable from
|
||||
`WIDTHMAX` and a `` `define WIDTH_MAX `` beside it is not, which a user could
|
||||
reasonably file. Left as the brief wrote it rather than decided here.
|
||||
- **The module tier**, which matches a *substring* — its own semantics, wider
|
||||
than a prefix and narrower than a subsequence, and tier 0's whole ranking
|
||||
argument rests on it.
|
||||
|
||||
### Scoring
|
||||
|
||||
One scorer, `Query::score`, in `candidates.rs`. Three linear passes, the shape
|
||||
fzf's first algorithm uses: a forward greedy walk that says whether the name
|
||||
matches at all and where the match must end; a backward walk that slides the
|
||||
start as late as it can without losing the match; a third pass that scores the
|
||||
tightened window.
|
||||
|
||||
The tightening is load-bearing, not polish. Without it `clk` takes the `c` of
|
||||
`osc_clk_en` and then reaches four characters for the `l`, scoring that name
|
||||
*below* `xclkx` — when the run it should have found starts at an underscore
|
||||
three characters on. It costs about a tenth of a table scan.
|
||||
|
||||
The points:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `BOUNDARY` +6 | the character landed at the start of a part of the name: position 0, after `_` or `$`, a letter/digit transition, or the capital of a `camelCase` part |
|
||||
| `CONTIGUOUS` +8 | it directly follows the previous matched character |
|
||||
| `GAP` −3 each | per character skipped between two matched ones |
|
||||
| `LEAD` −1 each, floored at −12 | per character skipped before the first matched one |
|
||||
|
||||
`CONTIGUOUS + |GAP| > BOUNDARY` is the one inequality that had to hold: `clk`
|
||||
must reach `clk_osc_en_q` ahead of `c_l_k_scatter`, where every letter is at a
|
||||
boundary and none is contiguous. 8 + 3 > 6, nearly twice over.
|
||||
|
||||
**Prefix matches outrank every fuzzy match**, as the first sort key rather than
|
||||
as a consequence. The points very nearly give it for free — a non-prefix match
|
||||
always pays `LEAD` at least once and cannot beat an unbroken run from the start
|
||||
— but "very nearly" is not something a ranking should rest on: a name whose
|
||||
case changes mid-word can earn a `BOUNDARY` that a prefix match of the same
|
||||
query cannot, and `x_aB` would then outrank `abc` for `ab`. So `Score` carries
|
||||
the flag and sorts on it first.
|
||||
|
||||
Ties break on the name (`word_cmp`, case-insensitive then exact), which is a
|
||||
real tie-break and not decoration: every prefix match of the same query usually
|
||||
scores identically, and without it the answer would depend on whatever order
|
||||
the table happened to be in.
|
||||
|
||||
### The `isIncomplete` trap
|
||||
|
||||
This is the correctness heart of the round and it is not about matching at all.
|
||||
|
||||
VS Code asks the server again on the next keystroke **only** when the last
|
||||
response said `isIncomplete: true`. Otherwise it filters the list it already
|
||||
holds, client-side, for the rest of the word. A complete two-character prefix
|
||||
response would therefore swallow the third keystroke — the one that turns fuzzy
|
||||
on — and fuzzy would never fire in a real editor no matter how correct the
|
||||
matching was.
|
||||
|
||||
The rule, in `completions`:
|
||||
|
||||
- a response for a **1- or 2-character** word (or an empty one) is
|
||||
`isIncomplete: true`, whatever the cap did;
|
||||
- a response from **three characters up** is incomplete when it was truncated —
|
||||
by the response cap (`LIMIT`), by the module tier's own cap, or by either
|
||||
fuzzy table scan returning its full `cap` — and complete otherwise.
|
||||
|
||||
Complete is safe above the floor because appending a character can only shrink
|
||||
the hit set (see *Assumptions*), so the list the client holds already contains
|
||||
every answer to the longer query.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Per-entry 32-bit character mask for the `words` and `units` tables
|
||||
- [x] Masks maintained by every mutation path — `build`, `update_file` /
|
||||
`update_words`, `absorb`, `remove_file` — through two single writers
|
||||
(`take_index_tables`, `remask_words`), pinned by a test that re-derives
|
||||
them from scratch after each
|
||||
- [x] `Query` / `Score` / `rank_cmp`, `words_fuzzy`, `units_fuzzy`
|
||||
- [x] Scope, index and word tiers match by subsequence at ≥3 characters
|
||||
- [x] Keyword, template, macro, backtick and module tiers unchanged
|
||||
- [x] Prefix hits first, then score, then name; cross-tier dedup preserved
|
||||
- [x] `isIncomplete` for every 1–2-character response, and for truncation
|
||||
above the floor
|
||||
- [x] `textEdit` still replaces exactly the typed word; no `filterText`
|
||||
- [x] Top-K under the existing `LIMIT`, selected linearly rather than sorted
|
||||
- [x] Tests: mask/table sync through all four paths; fuzzy membership against
|
||||
brute-force subsequence over a seeded 20 000-word table;
|
||||
case-insensitivity; out-of-order letters; the cap keeps the *best*;
|
||||
prefilter-prunes guard; `clkenq → clk_osc_en_q`; 2-char prefix-only;
|
||||
1–2-char golden; prefix-beats-scatter; boundary-beats-buried; dedup;
|
||||
`textEdit` range; e2e over the wire including the 2→3 transition
|
||||
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets --workspace`,
|
||||
`cargo test --workspace`, `smoke.js`
|
||||
- [ ] **For the lead**: bare `` `define`` names in tier 2 — fuzzy or not (see
|
||||
*What did not go fuzzy*)
|
||||
- [ ] **For the lead**: the wide-query cost below, and whether the follow-up
|
||||
levers are worth a round
|
||||
|
||||
## Performance
|
||||
|
||||
Measured on the real opentitan checkout (3 976 indexed files, 43 263 index
|
||||
names, 100 022 project words), release build, aarch64-apple-darwin, through
|
||||
`perf::completing_over_a_real_project` — the whole `completions()` call, at
|
||||
module-item position.
|
||||
|
||||
| typed | before | after | added |
|
||||
|---|---:|---:|---:|
|
||||
| *(empty)* | 275 µs | 320 µs | — (prefix path) |
|
||||
| `a` | 254 µs | 254 µs | — (prefix path) |
|
||||
| `ae` | 309 µs | 313 µs | — (prefix path) |
|
||||
| `aes` | 283 µs | **1.08 ms** | +0.80 ms |
|
||||
| `aes_` | 279 µs | 968 µs | +0.69 ms |
|
||||
| `prim_` | 224 µs | 990 µs | +0.77 ms |
|
||||
| `clk` | 285 µs | 800 µs | +0.52 ms |
|
||||
| `aes_reg` | 27 µs | 543 µs | +0.52 ms |
|
||||
| `zzzz` | 18 µs | 154 µs | +0.14 ms |
|
||||
|
||||
The 1- and 2-character rows are the point of the floor: they are the same
|
||||
binary search they always were.
|
||||
|
||||
The two table scans on their own, same tree:
|
||||
|
||||
| query | mask-only | survive mask | match | `words_fuzzy` | `units_fuzzy` |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| `clkenq` | 16 µs | 422 | 70 | **54 µs** | 21 µs |
|
||||
| `clk` | 16 µs | 5 793 | 3 072 | 300 µs | 159 µs |
|
||||
| `prim_` | 16 µs | 8 783 | 1 531 | 429 µs | 196 µs |
|
||||
| `aes` | 16 µs | 39 362 | 20 822 | 1.86 ms | 838 µs |
|
||||
|
||||
`clkenq` — the query the round is named after — is the *cheap* case, at 0.05 ms
|
||||
for the word table, which matches the lead's sizing benchmark (0.07 ms over a
|
||||
139 800-word list). The mask does its whole job there: it rejects 99.6% of the
|
||||
table with one `&` per entry, at 16 µs for the whole pass.
|
||||
|
||||
The expensive shape is three *common* letters — `aes` was the dev's example,
|
||||
and QA found `ena` costs more still (2.95–4.05 ms answered-in on the real
|
||||
corpus; enable-signal letters are even commoner than `a`/`e`/`s`). Neither is
|
||||
*the* worst case, only the worst tried; the class is "a 3-char query of very
|
||||
common letters", where the mask leaves tens of thousands of names and half
|
||||
genuinely match — there is nothing to prune, and the scan is the answer
|
||||
(lead wording correction after QA's finding, 2026-08-30). Two things bound it:
|
||||
`select_nth_unstable_by` instead of a full sort (0.8 ms of the 2.6 ms it used
|
||||
to be), and the tiers filling in order, so a wide query fills the response from
|
||||
tier 2 and the word tier's `items.full()` guard skips its scan entirely. The
|
||||
two are anti-correlated by construction: a query wide enough to be slow is a
|
||||
query that fills the cap early.
|
||||
|
||||
**Above the ≤0.5 ms bar the round was sized against, on the widest queries.**
|
||||
Recorded rather than smoothed over. Two levers were considered and not taken:
|
||||
|
||||
1. **Skip the fuzzy scan when the prefix run alone fills the cap.** Sound —
|
||||
every prefix match outranks every fuzzy one, so if there are ≥ `LIMIT` of
|
||||
them nothing the scan finds can be shown. It is a binary search away. It
|
||||
does not help `aes` (480 prefix hits, just under the 512 cap) and it helps
|
||||
`clk` (710) completely, so it is a real but partial win for a second code
|
||||
path and a subtle argument. Filed, not taken.
|
||||
2. **Two-stage scoring** — the cheap forward-only score for the whole table,
|
||||
the tightened one for the few hundred that survive the cut. Implemented and
|
||||
measured at ~7%, then reverted: two scorers and a "the cut is made on the
|
||||
cheaper number" caveat is not what 7% buys.
|
||||
|
||||
Build-side cost of the masks is one `char_mask` per table entry — 30 bytes of
|
||||
byte-ORs on this corpus's average name — paid inside loops that already touch
|
||||
every entry (`merge_words`'s merge, `index_tables`'s collect). Not separately
|
||||
measurable against the index build beside it; the corpus test's
|
||||
`index+tables built in …` line is unchanged at ~370 ms for the 860-file corpus.
|
||||
|
||||
The permanent guards are
|
||||
`completion::tests::a_keystroke_over_the_whole_corpus_stays_in_budget`, which
|
||||
now measures a **fuzzy** request beside the two prefix ones (10.7 µs over the
|
||||
860-file corpus's 16 750 words), and
|
||||
`candidates::tests::the_character_mask_prunes_the_table_before_the_subsequence_scan`,
|
||||
which asserts the prefilter leaves under 5% of a seeded 20 000-word table for a
|
||||
`clkenq`-shaped query — a clock-free assertion, so it means the same thing on a
|
||||
loaded machine.
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-08-30 (dev)** — implemented.
|
||||
|
||||
**`candidates.rs`.** Two parallel mask vectors, `unit_masks` and
|
||||
`word_masks`, each written in exactly one place: `take_index_tables` (which
|
||||
also collapsed the four mutation paths' repeated
|
||||
`(self.units, self.modules) = index_tables(index); self.macros =
|
||||
macros_of(index);` into one call) and `remask_words`. Deriving the masks
|
||||
from the table they belong to, in one writer each, is what makes desync
|
||||
unrepresentable rather than merely tested — though it is tested too, after
|
||||
each of the four paths, by re-deriving from scratch.
|
||||
|
||||
`remask_words` re-derives the *whole* word-mask vector rather than patching
|
||||
it alongside `merge_words`'s merge. That is deliberate: it is one pass over
|
||||
a table the merge loop is already walking with a `HashSet` lookup per word,
|
||||
it reads nothing but `self.words`, and it only runs when the table actually
|
||||
moved (`merge_words` returns early otherwise). Patching in lockstep would
|
||||
have been faster by a hair and desyncable by a typo.
|
||||
|
||||
`Query`, `Score`, `rank_cmp`, `at_boundary`, `char_bit`, `char_mask`,
|
||||
`fold`, `keep_best`, and the two scans. Rules and numbers above.
|
||||
|
||||
**`completion.rs`.** `FUZZY_MIN = 3` and one `Query` per request, passed to
|
||||
the three tiers that changed as `Option<&Query>` — `None` *is* the policy
|
||||
decision, made once in `completions` and read as "below the floor" by each
|
||||
tier. `word_tier`'s buffer-word scan came out as `buffer_words` so both
|
||||
branches share it.
|
||||
|
||||
**Decisions worth flagging to the lead:**
|
||||
|
||||
1. **"Byte-for-byte below three characters" is true of the *items*, not of
|
||||
`isIncomplete`.** The brief asks for both that and "responses for a
|
||||
1-2-char word are `isIncomplete: true`", and they cannot both hold — a
|
||||
2-character response used to be complete. The flag is the one thing that
|
||||
had to change, because without it the third keystroke never arrives.
|
||||
Pinned both ways: `the_short_answers_are_what_they_always_were` for the
|
||||
items, `a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives`
|
||||
for the flag.
|
||||
2. **`` `define`` names stayed on prefix**, in both the backtick response and
|
||||
the bare tier-2 offering. The brief lists "macro tiers" among the
|
||||
unchanged and the index/project tier among the changed, and tier 2 holds
|
||||
both — the literal reading was taken. The bare case is arguable; it is
|
||||
filed above rather than decided here.
|
||||
3. **The scorer tightens.** A plain greedy walk is what the brief's
|
||||
"subsequence, scored" implies and it ranks `osc_clk_en` below `xclkx` for
|
||||
`clk`, which is wrong enough to be worth a second and third linear pass.
|
||||
Measured at about a tenth of a table scan.
|
||||
4. **`fold` is `| 0x20`, not `to_ascii_lowercase`.** A branch per byte, run
|
||||
over every byte of every name a scan reaches, was worth removing; the
|
||||
safety argument (it is exact over the identifier alphabet, and non-ASCII
|
||||
bytes cannot collide with an ASCII query) is in the function's doc.
|
||||
5. **Top-K by `select_nth_unstable_by`, not by sorting.** A wide query
|
||||
matches tens of thousands of names and shows five hundred.
|
||||
6. **Two-stage scoring implemented, measured, reverted** — see *Performance*.
|
||||
7. **The wide-query cost is over the round's ≤0.5 ms bar** and is reported
|
||||
rather than hidden. Numbers and the two untaken levers above.
|
||||
|
||||
**Also touched, inside owned files**: `the_prefix_filters_server_side` still
|
||||
uses a 3-character query (`aaa`) and still passes, because nothing in its
|
||||
fixture matches `aaa` by subsequence without also matching it by prefix — it
|
||||
is now a weaker pin than its name suggests, and the real prefix/fuzzy split
|
||||
is pinned by `two_characters_match_by_prefix_and_nothing_else` and
|
||||
`the_short_answers_are_what_they_always_were`. Left alone rather than
|
||||
rewritten, so the M5-era assertion stays where the lead last read it.
|
||||
|
||||
**Suite**: `lucisv_server` 1 407 → **1 429** (1 360 unit + 66 e2e + 3
|
||||
grammar), 22 added; whole workspace **2 691 passed, 0 failed, 36 ignored**.
|
||||
`cargo fmt --all -- --check` clean, `cargo clippy --all-targets --workspace`
|
||||
zero warnings, `node editors/vscode/smoke.js target/debug/lucisv-server` →
|
||||
`smoke: OK`.
|
||||
|
||||
## QA log
|
||||
|
||||
- **2026-08-30 (QA)** — verified. **Verdict: SHIP.**
|
||||
|
||||
**Scope.** `git diff --stat` touches exactly the five files the brief
|
||||
names, plus the new feature README — nothing else.
|
||||
`git diff -- crates/lucisv_server/src/inline.rs` is empty (confirmed by
|
||||
running the diff directly, not by trusting the work log), and its own test
|
||||
module still passes inside the full-workspace run below. No
|
||||
`unwrap`/`expect`/`panic!` was added outside `#[cfg(test)]` (checked by
|
||||
grepping only the `+` lines of both diffs).
|
||||
|
||||
**Gates.**
|
||||
- `cargo fmt --all -- --check` — clean.
|
||||
- `cargo clippy --all-targets --workspace` (forced recompile with `touch`
|
||||
first, so this isn't a cache hit) — zero warnings.
|
||||
- `cargo test --workspace` — **2691 passed, 0 failed, 36 ignored**, matching
|
||||
the expected count exactly (no drift). `lucisv_server` unit tests:
|
||||
1360 passed / 34 ignored; `e2e.rs`: 66 passed / 2 ignored.
|
||||
- `cargo build -p lucisv_server` (debug) and `--release` — both clean.
|
||||
- `node --check editors/vscode/smoke.js` — clean; `node smoke.js` against
|
||||
both the debug and release binaries — `smoke: OK` both times.
|
||||
|
||||
**Attacking the matcher.** Wrote ten adversarial `#[test]` fns directly in
|
||||
`candidates.rs`'s test module (mixed-case table entries reached by a
|
||||
lowercase query; `$`/digit/`_` in the query at ≥3 chars; a literal non-ASCII
|
||||
multibyte byte sequence in a table entry, confirmed no panic; ranking
|
||||
determinism across repeated calls with the same query; the `aes`-style
|
||||
commonest-letters trio; a query containing a literal `_`; a 3-char query
|
||||
that is itself a keyword spelling (`end`); `absorb` overwriting an
|
||||
already-present path; `remove_file` followed by re-`absorb`ing the same
|
||||
path). **All ten passed** — ran them (`cargo test -p lucisv_server
|
||||
candidates::tests::qa_`, 10/10 ok), then reverted the file to the dev's
|
||||
exact diff (verified byte-identical via `git diff | diff -`) since they
|
||||
found nothing to fix. No corruption of the ranking, no panic, no mask/table
|
||||
desync under any of the attacked mutation sequences.
|
||||
|
||||
Also ran the existing property test
|
||||
(`a_fuzzy_scan_finds_exactly_what_brute_force_subsequence_finds`, 20k-word
|
||||
table, 9 queries including a case variant and an out-of-order-adjacent one)
|
||||
and `letters_out_of_order_never_match` (`qneklc`, `kclenq`, `clkqne`,
|
||||
`clkenqq`) — both green, and both are real assertions, not tautologies:
|
||||
confirmed by reading them rather than just running them.
|
||||
|
||||
**isIncomplete / the 2→3 transition.** Unit and e2e coverage both pin the
|
||||
trap correctly: 0/1/2-char responses always `isIncomplete: true`; a
|
||||
3+-char response is `isIncomplete` only when a tier's cap or the fuzzy
|
||||
scan's own `cap` truncated it. Re-verified live over the wire (below).
|
||||
|
||||
**Opentitan measurement (read-only).** `git -C /Users/guoliangchen/repo/opentitan
|
||||
status --porcelain` before and after every session: **exactly the three
|
||||
pre-existing owner-modified files** (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/{top_darjeeling,top_earlgrey}/ip/ast/rtl/ast.sv|`), untouched by
|
||||
anything QA did — confirmed both before starting and after every server
|
||||
session, including the one that opened a real file's buffer.
|
||||
|
||||
The real signal: `clk_osc_en_q` is not in `ast.sv` itself, but it *is*
|
||||
declared as a real local variable in
|
||||
`hw/top_earlgrey/ip/ast/rtl/gfr_clk_mux2.sv` (grepped first, as instructed).
|
||||
Drove a real `--verbose` release-server LSP session at the opentitan root
|
||||
(custom hand-rolled Node LSP-framing harness, since no such script existed
|
||||
in the repo — modeled on `editors/vscode/smoke.js`'s framing). Initial
|
||||
scan (`$/progress`, title "Indexing Verilog workspace") really did cover
|
||||
the whole tree: `widen finished: 3977 files (3 skipped, 3976 from cache)
|
||||
in ~1.5s` — in the right ballpark scaled from the 860-file corpus's
|
||||
~370 ms baseline (4.6× the files, well under 4.6× the time), not
|
||||
measurably worse from mask maintenance.
|
||||
|
||||
- `clkenq` from a scratch buffer elsewhere in the workspace → finds
|
||||
`clk_osc_en_q` via the project-word tier. **Confirmed.**
|
||||
- `clkenq` typed *inside* `gfr_clk_mux2.sv`'s own real buffer (opened with
|
||||
its actual on-disk text, one line appended after `endmodule`) → also
|
||||
finds `clk_osc_en_q`, correctly still via the word tier (`sortText`
|
||||
`5clk_osc_en_q`) rather than the scope tier, because the probe line was
|
||||
appended after the module's closing `endmodule` and so is outside its
|
||||
scope — an artifact of the probe's placement, not a bug; the scope-tier
|
||||
fuzzy path is separately and directly pinned by
|
||||
`completion.rs`'s own `a_declaration_in_scope_is_reached_by_subsequence`
|
||||
unit test, which does put the probe inside the module.
|
||||
- The 2→3 transition, live: `ce` → `isIncomplete: true`; `cen` also comes
|
||||
back `isIncomplete: true` on the real corpus — correctly, since the huge
|
||||
real word table means even a 3-char subsequence query legitimately hits
|
||||
the 512-item cap and must say so (the small unit-test fixture where
|
||||
`cen` is *complete* has only three declared names in scope; both are the
|
||||
same rule, applied to different-sized tables).
|
||||
- `textEdit`/no-`filterText` behavior reconfirmed over the wire via the
|
||||
e2e test (`cargo test`) rather than re-driven by hand, since it is
|
||||
already an exact-byte-range assertion there.
|
||||
|
||||
**Latency table** (client wall-clock **and** the server's own
|
||||
`timing: textDocument/completion answered in … ms` line, which is the
|
||||
fairer comparison to the dev's in-process numbers since it also pays JSON
|
||||
request/response marshalling the dev's isolated `Candidates` benchmark
|
||||
never did — expect these to run higher than the dev's table for that
|
||||
reason alone, on **every** query including the pre-existing prefix path):
|
||||
|
||||
| typed | items | isIncomplete | server "answered in" (2–3 warm reps) | dev's isolated number |
|
||||
|---|---:|---|---:|---:|
|
||||
| `a` | 512 | true | 0.9–2.0 ms | 254 µs (unchanged path) |
|
||||
| `ae` | 483 | true | ~1.9 ms | 313 µs |
|
||||
| `c` / `cl` | 512 | true | 0.9–2.2 ms | n/a |
|
||||
| `clk` | 512 | true | 1.5–2.9 ms | 800 µs |
|
||||
| `prim_` | 512 | true | 2.5–2.8 ms | 990 µs |
|
||||
| `aes` | 512 | true | **1.7–2.2 ms** | **1.08 ms (dev's stated worst case)** |
|
||||
| `clkenq` | 71 | **false** | 0.4–0.5 ms | matches — the cheap case |
|
||||
| `the` | 512 | true | 2.3–2.6 ms | (not in dev's table) |
|
||||
| `q_e` | 512 | true | 2.5–2.8 ms | (not in dev's table) |
|
||||
| `for` | 512 | true | 1.2–1.3 ms | (not in dev's table) |
|
||||
| `int` | 512 | true | 1.5 ms | (not in dev's table) |
|
||||
| **`ena`** | 512 | true | **2.95–4.05 ms** | **not tested by dev** |
|
||||
| `eni` | 512 | true | 2.76–2.85 ms | (not in dev's table) |
|
||||
|
||||
Every number here is per-request wall/server cost, not an "added" delta —
|
||||
the dev's table subtracts a same-shaped before number this harness has no
|
||||
clean way to reproduce (no pre-fuzzy binary was kept), so treat the
|
||||
right-hand column as "does the shape match", per the assignment.
|
||||
|
||||
**Finding (informational, not blocking): `ena` is a worse pathological
|
||||
query than `aes` on the real corpus, not a better-or-equal one.**
|
||||
Reproduced 3× in a dedicated repeat-measurement harness, isolated from
|
||||
other queries in the same session, using only the server's own `timing:`
|
||||
line: `aes` 1.72–2.18 ms, **`ena` 2.95–4.05 ms**, `eni` 2.76–2.85 ms,
|
||||
`clk` 1.48–1.54 ms. `ena` is a real, common RTL fragment (enable-signal
|
||||
naming), not a contrived string, and it costs roughly 1.4–2× what `aes`
|
||||
does on this corpus while `aes` is the query the feature README singles
|
||||
out as *the* worst case in its *Performance* section. It does not change
|
||||
the verdict — it is the same architecture (mask survivors scanned
|
||||
linearly), the same order of magnitude the lead already accepted
|
||||
(single-digit milliseconds, not tens), and well within Lead ruling #1's
|
||||
"~1.1 ms server-side absolute" framing even at its own worst rep (4.05 ms
|
||||
wall includes IPC; 4.05 ms is the *outlier* first rep, later reps settle
|
||||
at ~3.0 ms). But the *Performance* section's claim that `aes` is the
|
||||
worst case a wide query can produce is not shown to be true — it is
|
||||
merely the worst case the dev happened to try. Recommend the lead either
|
||||
(a) accept this as within the already-approved envelope and note `ena` as
|
||||
a second data point rather than re-open the sizing question, or (b) ask
|
||||
for the "widest query" framing in *Performance* to be softened from "the
|
||||
worst case is three common letters (`aes`)" to "one example of a wide
|
||||
query" so a future reader does not treat `aes` as a proven upper bound.
|
||||
|
||||
**No correctness, safety, or scope findings.** No corruption risk: every
|
||||
fuzzy path is additive (widens which candidates surface, never rewrites
|
||||
what a candidate's inserted text is), `verify.rs` is untouched, and
|
||||
`inline.rs`'s exact-match ghost trigger is provably untouched by both the
|
||||
diff and its own tests. Idempotency is not implicated — completion is not
|
||||
a formatting transform.
|
||||
|
||||
**TODO.md §13** — ticked with the numbers above; see the diff.
|
||||
|
||||
## Review
|
||||
|
||||
*(reserved for the lead.)*
|
||||
|
||||
**2026-08-30 — lead.** Approved and committed.
|
||||
|
||||
- Read the diff's core in full: the mask tables and their two-writer
|
||||
discipline (`take_index_tables` collapsing the four mutation paths'
|
||||
boilerplate is a genuine simplification, not just the mask's plumbing), the
|
||||
three-pass greedy-tighten scorer (the `osc_clk_en`-below-`xclkx` example
|
||||
justifies the tightening concretely), `keep_best`'s bounded selection, and
|
||||
the tier changes. The `isIncomplete` handling is the round's correctness
|
||||
heart and its argument is airtight in both directions: forced incomplete
|
||||
below the floor because the 3rd keystroke must reach the server, ordinary
|
||||
truncation semantics above it because a subsequence hit set only shrinks as
|
||||
characters are appended.
|
||||
- The dev's deviations all stand: items-not-flag reading of "byte-for-byte
|
||||
below 3" (the two demands genuinely conflict and the flag had to move),
|
||||
prefix-first as an explicit sort key, `|0x20` fold with its exactness
|
||||
argument, bounded top-K, and the reverted two-stage scorer (7% wasn't worth
|
||||
a second scorer).
|
||||
- **Performance ruling (owner bar was ≤0.5 ms added):** the widest
|
||||
common-letter 3-char queries exceed it — `aes` +0.8 ms isolated, and QA's
|
||||
`ena` at 2.95–4.05 ms answered-in is the better data point. Accepted: the
|
||||
criterion is the absolute answer time, and ~1–4 ms server-side on the
|
||||
pathological class keeps the popup imperceptible; `clkenq`-class queries —
|
||||
the ones the feature exists for — cost +0.05 ms. The README's "worst case"
|
||||
wording corrected to say the class, not the sample (QA's finding).
|
||||
- Macro/`define` names stay prefix-only in both spellings this round — the
|
||||
conservative reading; the bare-tier one-liner is noted as a future choice,
|
||||
not an oversight.
|
||||
- QA's ten adversarial matcher tests all passed and were correctly reverted
|
||||
(diff byte-identical); the live opentitan run confirmed `clkenq` →
|
||||
`clk_osc_en_q` from a real buffer (`gfr_clk_mux2.sv`) and the 2→3
|
||||
transition over the wire; the opentitan checkout carries exactly the three
|
||||
pre-existing owner edits, untouched.
|
||||
- Gates re-run by the lead before commit: fmt clean, clippy zero warnings,
|
||||
full suite green, smoke OK. `docs/topo.md` updated (fuzzy-completion
|
||||
handshake row, matrix, header). Ships as 0.20.0.
|
||||
@@ -64,6 +64,10 @@ entirely whenever it could be the wrong line.
|
||||
bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is
|
||||
discarded. This round's own promise held while it was this round's to
|
||||
make; the index is text-free either way (a span is not text).
|
||||
**Superseded again 2026-08-28 by `docs/features/hover-line-index/README.md`**,
|
||||
which adds `Def::lines` (each declaration's line number) and bumps
|
||||
`FACTS_FORMAT` 3 → 4. Same reading: a line number is not text either, and
|
||||
it is what makes this feature's heading free.
|
||||
- The heading line `**label** — declared in `file:line`` is unchanged, so a
|
||||
client (or a test) reading only that half sees exactly what it saw before.
|
||||
|
||||
@@ -131,6 +135,10 @@ The character cap counts `char`s and cuts on a boundary.
|
||||
tie-break pinned by test.
|
||||
- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior
|
||||
`\r` into the fence; QA finding 2 closed.
|
||||
- [x] **2026-08-28** (`docs/features/hover-line-index/README.md`): the disk
|
||||
path's heading costs no read at all (`Def::lines`) and its snippet's
|
||||
read is shared across hovers, so the second hover into a closed file is
|
||||
free. `disk_view` is gone, subsumed by `Workspace::file_view`.
|
||||
|
||||
## Work log
|
||||
|
||||
@@ -230,6 +238,32 @@ with less work. Numbers in `docs/perf/README.md`.
|
||||
- Cost: four bytes per symbol. Measured saving on the lookup alone:
|
||||
8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`).
|
||||
|
||||
### 2026-08-28 — dev (the heading stops reading the file at all)
|
||||
|
||||
Round `hover-line-index` — full argument, measurements and tests in
|
||||
`docs/features/hover-line-index/README.md`. What changed *here*:
|
||||
|
||||
- **The `External` arm's disk branch no longer reads anything for the
|
||||
heading.** `Def` now carries `lines: DeclLines`, recorded when the file was
|
||||
indexed, so `**port** — declared in `sub.sv:2`` is a field lookup. The live
|
||||
branch is untouched and still asks the open buffer's own line index, because
|
||||
that buffer may hold unsaved edits the index has not seen — the same reason
|
||||
`declaration_snippet` matches a `Def` to a live symbol logically.
|
||||
- **`disk_view` was deleted.** Its job — one read per file per hover — is now
|
||||
`Workspace::file_view`'s, which does it once per file per *generation of that
|
||||
file*, so the next hover into the same file reads nothing. The four points
|
||||
that drop a held view are listed in that round's Handshakes.
|
||||
- **`spells_exactly` and both caps are untouched**, and a stale held view can
|
||||
only ever make a snippet vanish. Every existing test in this file passed
|
||||
unmodified.
|
||||
- **One corner moved deliberately**: a closed file that cannot be *read* now
|
||||
still gets its line in the heading (`sub.sv:2` rather than a bare `sub.sv`),
|
||||
because the line no longer depends on the read. Pinned by
|
||||
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read`.
|
||||
- Measured: a hover into a 12 MB closed file, 6.2 ms → **0.95 µs** on the
|
||||
second hover; the 31.7 MB probe above, 17.0 ms → **4.4 µs** on the second.
|
||||
The first touch is unchanged, because the snippet genuinely wants the text.
|
||||
|
||||
### 2026-08-28 — dev (CRLF, closing QA finding 2)
|
||||
|
||||
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
# hover-line-index
|
||||
|
||||
## Goal
|
||||
|
||||
The owner's report (2026-08-28): hovering a module instantiation is slow, and
|
||||
hovering one of its ports — to see the port's own declaration — is slow on the
|
||||
**first** try. Both land on the same code: a hover whose target is declared in
|
||||
a *closed* file read that whole file and built a whole `LineIndex` over it, for
|
||||
two things at once — the heading's `file:line`, and the fenced snippet of the
|
||||
declaration. On a netlist-adjacent file that read is milliseconds, and nothing
|
||||
was kept, so the *next* hover into the same file paid it again. The owner's
|
||||
design, which this round implements: put each declared name's **line number**
|
||||
into the index itself, where it costs a `u32` per declaration and is computed
|
||||
once when the file is scanned. The heading then costs no file access at all,
|
||||
and only the snippet still wants text — served from a small bounded cache of
|
||||
closed files' text in `Workspace`, so the first touch pays one read and no
|
||||
touch after it pays anything.
|
||||
|
||||
The shape of what that buys, measured below: a hover into a 12 MB closed file
|
||||
goes **6.2 ms → 0.9 µs on the second hover** and stays 6.2 ms on the first;
|
||||
the steady-state cross-file hover on a 10 000-line file goes **157 µs →
|
||||
13 µs**. The round also *measured the other suspect* and did not fix it — see
|
||||
Handshakes.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A line is a fact about the same snapshot the span is.** `Def::name_span`
|
||||
and `Def::lines.name` are read off one text in one pass, so a heading and a
|
||||
snippet can never name different generations of a file. Where the file has
|
||||
changed on disk with nothing telling the server, both are stale together,
|
||||
which is strictly better than the previous shape — a stale *offset* looked
|
||||
up in *fresh* text, whose line was arbitrary.
|
||||
- **Lines are 1-based, and are exactly what `LineIndex::line_col` reports.**
|
||||
That is what `locate::line_number` returned before, so the same headings come
|
||||
out.
|
||||
- **`FileFacts::from_analysis`'s caller has a line index already.** It is a
|
||||
server holding an open buffer's finished `Document`, which carries one. So
|
||||
the extra parameter costs the caller nothing, and `FileFacts::of` builds its
|
||||
own — one pass over the source's newlines, about 1 % of the parse it sits
|
||||
beside (`docs/perf/README.md`: `LineIndex::new` 115 µs against
|
||||
`parse_tolerant` 14.3 ms at 10 000 lines).
|
||||
- **The view cache is a cache and never a correctness input.** Every entry can
|
||||
be dropped at any moment with no change to any answer; a *stale* entry can
|
||||
only ever make a snippet disappear, never make it wrong, because
|
||||
`hover::spells_exactly` still checks the text at the span against the hovered
|
||||
name before anything is shown. That guard is unchanged and is still the last
|
||||
line of defence.
|
||||
- **Only closed files are cached.** `Workspace::file_view` returns `None` for a
|
||||
path an open buffer speaks for: that buffer's `Document` already holds its
|
||||
text and line index, and a second copy here would be a second opinion.
|
||||
- **The index is still text-free.** A line number is not text, exactly as a
|
||||
span is not text (`docs/features/workspace-index/README.md`'s promise, and
|
||||
the same reading `port-detail-spans` took for `detail_span`).
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `vlog_semantic` — `DeclLines`, and the carrier's extension story
|
||||
|
||||
```rust
|
||||
/// Where a declaration sits in its file, counted in lines.
|
||||
pub struct DeclLines {
|
||||
pub name: u32, // 1-based line of the declared name
|
||||
pub detail: Option<u32>, // 1-based line the detail span starts on
|
||||
}
|
||||
|
||||
pub struct Def {
|
||||
pub file: FileId,
|
||||
pub name_span: TextRange,
|
||||
pub kind: SymbolKind,
|
||||
pub detail_span: Option<TextRange>,
|
||||
pub lines: DeclLines, // new
|
||||
}
|
||||
|
||||
// One added parameter, because a record now carries lines:
|
||||
impl FileFacts {
|
||||
pub fn from_analysis(path, tree, defines, sem, lines: &LineIndex) -> FileFacts;
|
||||
}
|
||||
pub const FACTS_FORMAT: u32 = 4; // was 3
|
||||
```
|
||||
|
||||
**The carrier is one value per declaration, and it extends by gaining a
|
||||
field.** That is the owner's explicit ask ("keep the implementation flexible so
|
||||
we might even cache the port location") answered structurally rather than
|
||||
promised:
|
||||
|
||||
- **Ports already ride it.** A module's ports and parameters are indexed as
|
||||
*members*, and a member is a `Decl` exactly as a unit is — so
|
||||
`index.member("sub", "addr").lines.name` is that port's line, recorded in the
|
||||
same pass, with no extra table, no extra pass and no extra decision about
|
||||
"small projects". The owner's optional second step was already paid for by
|
||||
the first.
|
||||
- **A split port's two lines ride it too.** A non-ANSI port is named in the
|
||||
header and finished in the body (`detail_span`,
|
||||
`docs/features/port-detail-spans/README.md`), and `DeclLines::detail` is that
|
||||
body's line — the second position datum, already present, in the same value.
|
||||
- **A third one is a field.** A column, a rendered preview, an end line: add it
|
||||
to `DeclLines`, write it in `Writer::decl`, read it in `Reader::decl`, bump
|
||||
`FACTS_FORMAT`. Nothing else moves, because nothing else knows how many
|
||||
fields a `DeclLines` has. **Taken, 2026-08-29**, and it went exactly that
|
||||
way: `docs/features/vscode-hierarchy-sidebar/README.md` added
|
||||
`positions: Option<DeclPositions>` — the declared name's and the whole
|
||||
declaration's ranges in the units a client counts in — for `FACTS_FORMAT`
|
||||
4 → 5, so a design-hierarchy snapshot needs no file text at all. The one
|
||||
amendment that round made to the story above: those positions ride
|
||||
**file-scope declarations only**, because members outnumber units by two
|
||||
orders of magnitude and the record's `U` and `M` groups are separate, so
|
||||
the absence costs a member nothing. A member still carries its lines. A *parallel table* keyed by declaration was the
|
||||
alternative and was rejected: it would have to be kept in step with `Decl`
|
||||
through every merge, every incremental update and every record round-trip,
|
||||
and there is no second consumer to justify the indirection
|
||||
(`CLAUDE.md`, "Simplicity first").
|
||||
|
||||
### `vlog_semantic` — `FACTS_FORMAT` 3 → 4, justified
|
||||
|
||||
A record's per-declaration group grew two fields. The rule written at the
|
||||
constant is that **any** change to what a record holds bumps the format, and
|
||||
the reason it is a whole-store discard rather than a migration is
|
||||
`docs/features/index-persistence/README.md`'s: a reader that guessed at an
|
||||
older layout would read last month's field order as this month's. Concretely,
|
||||
a format-3 record read as a format-4 one would shift every field after the
|
||||
first declaration by two — which is why the format field in the store's header
|
||||
catches it first, and why `decode` rejects it even if something served it past
|
||||
the header (both pinned, see Tests). The cost is one re-parse of the workspace
|
||||
on the first scan after upgrading; the corpus measurement below says that is
|
||||
about 175 ms.
|
||||
|
||||
### `vlog_semantic` — fingerprint
|
||||
|
||||
`WorkspaceIndex::fingerprint`'s `sym` line now carries `line=` and `detail=`.
|
||||
That is what makes the house witness — incremental index == fresh build —
|
||||
cover the new field rather than ignore it; every existing equivalence test
|
||||
(`update_file`, `update_facts`, `add_facts` from records, the corpus sweep)
|
||||
now compares lines as well as spans, and all of them stayed green unmodified.
|
||||
|
||||
### `lucisv_server::state` — the closed-file view cache
|
||||
|
||||
```rust
|
||||
pub struct FileView { pub path: PathBuf, pub text: String, pub lines: LineIndex }
|
||||
impl Workspace {
|
||||
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>>;
|
||||
}
|
||||
```
|
||||
|
||||
Bounded by **four entries** and **8 MiB of text**, newest first, oldest
|
||||
evicted. Two bounds because they answer two questions: how many files one
|
||||
answer can name (a card names one or two; a references list walks a handful
|
||||
before moving on), and how much memory a netlist-shaped file may cost. The
|
||||
newest entry is kept whatever it weighs — one file can exceed the whole byte
|
||||
budget on its own, and a cache that refused to hold it would be useless for
|
||||
exactly the file it exists for — so a huge file simply evicts everything else.
|
||||
|
||||
**Every invalidation point, in full.** A view is dropped when:
|
||||
|
||||
| event | what is dropped | why |
|
||||
|---|---|---|
|
||||
| `set_document(uri, text)` — `didOpen`, `didChange`, a text-carrying `didSave` | that path's view | the buffer becomes the authority, and the held disk copy may predate the edits it carries |
|
||||
| `close_document(uri)` | that path's view | disk is the authority again, and the view predates every save that buffer made |
|
||||
| `update_one(path)` | that path's view | re-indexing one file *is* the claim its bytes moved |
|
||||
| `rebuild_index_with(..)` | **all** views | a rescan says nothing about which file moved |
|
||||
|
||||
Those four are every path in the server that can change what a file holds:
|
||||
`server.rs` reaches the first two directly from the sync notifications, and the
|
||||
last two through `reindex_one` / `reindex`, which is where a save, a watched
|
||||
file change, a client file operation and a settings change all land.
|
||||
|
||||
What survives all four is a file changed on disk with nothing telling this
|
||||
server — and there the *index* is stale by the same event, which is precisely
|
||||
what `spells_exactly` exists for.
|
||||
|
||||
### `lucisv_server::locate` — the sweep
|
||||
|
||||
`locate::line_number` and `locate::location` were the only two functions that
|
||||
read a whole file to answer a position question, and `line_number`'s only
|
||||
callers were `hover.rs`'s two. Both now take an open buffer's own line index
|
||||
when there is one and the shared view otherwise; neither reads a file directly
|
||||
any more. `location`'s open-buffer arm also stops cloning the whole buffer text
|
||||
(`text_of` returns a `String`) on the way to a range. Mechanical, no behaviour
|
||||
change: `location` is what `textDocument/definition`, references, the lens and
|
||||
the hierarchies build their `Location`s from, and a references list over one
|
||||
file now reads that file once instead of once per site.
|
||||
|
||||
An indexed declaration's line no longer goes through `line_number` at all —
|
||||
`Def::lines` is the answer. What is left for it is the spans the index records
|
||||
no line for, which today is a `` `define``'s (the macro hover card's
|
||||
`defined in file:line`). Those ride the shared view, so a second macro hover
|
||||
into one file is free; giving `Define` its own line would mean a field in
|
||||
`vlog_parser`'s `Define` and is filed rather than done — it buys the first
|
||||
touch of one card and costs a second crate a field.
|
||||
|
||||
### Suspect 2 — **reported, not fixed here; DELIVERED 2026-08-28** by `docs/features/scan-interleave/README.md`
|
||||
|
||||
The brief named a second suspect and asked for it to be measured and filed
|
||||
rather than redesigned. It is real, and on the owner's own complaint it is by
|
||||
far the larger of the two:
|
||||
|
||||
`Server::new` runs the whole startup scan **before** `run()`'s message loop
|
||||
takes its first message. `main.rs` answers `initialize` (through
|
||||
`initialize_finish`, which also consumes `initialized`) and only then builds
|
||||
the `Server` — so everything a client sends the instant the handshake is done
|
||||
sits in the OS pipe until the scan is over. Measured over a 200-file, 1 000-
|
||||
line-each workspace with a filelist (so the startup scan really indexes it):
|
||||
|
||||
| the first hover of a session | cold store | warm store |
|
||||
|---|---:|---:|
|
||||
| issued the moment `initialized` was sent | **780 ms** | **287 ms** |
|
||||
| the same hover once the scan is done | 64 µs | 61 µs |
|
||||
|
||||
Four orders of magnitude, and this round does not touch it: fixing it means
|
||||
answering requests during the scan (or scanning on another thread), which is a
|
||||
change to request scheduling and to what an answer *means* while the index is
|
||||
half-built. `docs/features/index-persistence`'s store already takes it from
|
||||
780 ms to 287 ms; the rest is the read, the completion word table's lex and
|
||||
the include scan, which that feature's README already names as uncached.
|
||||
**Request to whoever owns the message loop next:** this is where "the first
|
||||
hover is really slow" mostly lives, and the probe that measures it is
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`.
|
||||
|
||||
**DELIVERED, 2026-08-28.** `docs/features/scan-interleave/README.md` took the
|
||||
scan apart into per-file steps and drains the message queue between them, so a
|
||||
startup scan long enough to be worth it answers requests while it runs. The
|
||||
same probe, flipped and renamed
|
||||
(`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`), now
|
||||
reports **15.5 ms cold / 12.8 ms warm** where the table above says 780 / 287 —
|
||||
and the scan's own total moved by under a percent. The request is closed; what
|
||||
that round did *not* do (the files are still read eagerly, a rescan still makes
|
||||
requests wait) is filed in its own Status/TODO with numbers.
|
||||
|
||||
## Measured
|
||||
|
||||
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
|
||||
`--release`, `#[ignore]`d probes, `--test-threads=1`, means where the numbers
|
||||
are small enough to need one. Every figure below was taken on 2026-08-28,
|
||||
before and after, in the same session.
|
||||
|
||||
### Suspect 1 — the per-hover read
|
||||
|
||||
| what | before | after |
|
||||
|---|---:|---:|
|
||||
| hover on an **instantiation** into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms |
|
||||
| — the same hover again | 5.75 ms | **0.95 µs** |
|
||||
| hover on a **port** into the same file, first touch | 5.85 ms | 5.92 ms |
|
||||
| — the same hover again | 5.71 ms | **0.99 µs** |
|
||||
| hover into a 31.7 MB closed file, first touch (QA's own probe) | 17.0 ms | 16.8 ms |
|
||||
| — the same hover again | 17.0 ms | **4.4 µs** |
|
||||
| cross-file hover, 1 000-line target, mean of 20 | 39.8 µs | **4.7 µs** |
|
||||
| cross-file hover, 10 000-line target, mean of 20 | 157 µs | **12.9 µs** |
|
||||
| — one read + `LineIndex` of that file, for comparison | 149 µs | 158 µs |
|
||||
|
||||
Read the table as two claims. **The first touch is unchanged**, and it should
|
||||
be: the snippet genuinely wants that file's text, and reading it is what the
|
||||
6.2 ms is. **Every touch after it is free**, which is the shape the owner's
|
||||
"slow on the FIRST try" report describes — and the heading half is free even
|
||||
on the first touch, which is why a card with no snippet (an unreadable file, a
|
||||
guard miss) now costs nothing at all.
|
||||
|
||||
### The price paid for it
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| whole 860-file corpus scan, no cache | 338 ms | 343 ms |
|
||||
| — cold, filling the store | 372 ms | 374 ms |
|
||||
| — warm, every file from the store | 197 ms | 200 ms |
|
||||
| the store, 860 files | 2 312 802 B | 2 380 790 B |
|
||||
|
||||
The scan times are inside their own run-to-run noise: the added work is one
|
||||
`LineIndex::new` per parsed file, which the flush breakdown puts at under 1 %
|
||||
of that file's parse. The store grows **68 KB over 860 files — 2.9 %**, which
|
||||
is the two decimal numbers per declaration over roughly 13 000 declarations,
|
||||
and is the owner's "a few KB for 20 000 modules" measured on real source.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Measure both suspects before touching anything; both recorded above.
|
||||
- [x] `DeclLines` on `Decl` and on `Def`, computed in `facts_from_analysis`
|
||||
from the file's own `LineIndex`.
|
||||
- [x] `FileFacts::from_analysis` takes the line index; `FileFacts::of` builds
|
||||
one.
|
||||
- [x] Record codec: two fields per declaration, `FACTS_FORMAT` 3 → 4, with the
|
||||
justification above.
|
||||
- [x] `WorkspaceIndex::fingerprint` carries the lines, so incremental == fresh
|
||||
covers them.
|
||||
- [x] `Workspace::file_view` — bounded, LRU, four named invalidation points.
|
||||
- [x] `hover.rs`: heading from `Def::lines`, snippet from the shared view; the
|
||||
per-request `disk_view` memo is gone, subsumed.
|
||||
- [x] `locate.rs` swept onto the buffer's index / the shared view.
|
||||
- [x] Tests (11 new, listed in the work log) and two new `#[ignore]`d probes.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- [ ] **Not done, deliberately: `` `define``s get no indexed line.** A
|
||||
`Define` is `vlog_parser`'s, and giving it a line means a field in
|
||||
another crate's public type plus its own record fields, to save the
|
||||
*first* macro hover into one file and nothing after it. The shared view
|
||||
already covers the repeat.
|
||||
- [ ] **Not done, deliberately: the other `text_of` callers are untouched.**
|
||||
`rename`, `ports`, `hierarchy`, `type_hierarchy`, `completion`,
|
||||
`signature`, `inlay` and `nav` read whole files because they want whole
|
||||
files, not a line — the sweep was for the position-only readers. Routing
|
||||
them through the view cache would mean `text_of` handing out an `Rc`
|
||||
instead of a `String`, which is a different change with a different
|
||||
argument.
|
||||
- [x] **Reported, not fixed *here*: the first request of a session waits out
|
||||
the startup scan.** Numbers and the filed request are in Handshakes;
|
||||
**delivered 2026-08-28** by `docs/features/scan-interleave/README.md`
|
||||
(780 ms → 15.5 ms cold, 287 ms → 12.8 ms warm).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-28 — dev
|
||||
|
||||
**Measured first, both suspects, before a line of the fix was written.** Two
|
||||
new probes were needed and are part of the round:
|
||||
`perf::hovering_into_a_big_closed_file_first_touch_and_repeat` (an
|
||||
instantiation and a port, into a 12 MB file, first touch and repeat separately
|
||||
— the existing probes all reported means, which hide exactly the first/repeat
|
||||
split the owner's report is about) and
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` (over the wire,
|
||||
against the real binary, two whole sessions so the persistent store is cold in
|
||||
one and warm in the other). The second answered the brief's question about
|
||||
suspect 2 with a number four orders of magnitude larger than suspect 1's, which
|
||||
is worth saying plainly even though this round could not act on it.
|
||||
|
||||
**The carrier: a struct, not a bare `u32`.** `DeclLines { name, detail }`
|
||||
rather than `line: u32` on `Decl`, because the *second* datum already exists —
|
||||
a split port's body line — and because the owner asked for room for more. The
|
||||
alternative shapes were both worse: a bare `u32` would have needed a second
|
||||
field the day `detail` was wanted (and `detail` was wanted on day one), and a
|
||||
parallel table keyed by declaration would have to be kept in step with `Decl`
|
||||
through the merge, the incremental update and the record round-trip, for no
|
||||
consumer that exists. `Option<u32>` for `detail` rather than a `0` sentinel in
|
||||
the *type*, even though the *record* writes `0` for `None`: the record's
|
||||
sentinel is a framing decision (the stream stays flat, exactly as
|
||||
`detail_span`'s `0 0` already does) and the type's is an API decision, and
|
||||
those two should not be forced to be the same thing.
|
||||
|
||||
**`from_analysis` grew a parameter rather than growing a `&str`.** It could
|
||||
have taken `src: &str` and built its own index, but its one real caller —
|
||||
`Document::facts` — already holds a `LineIndex` over exactly that text, and
|
||||
handing it over is both cheaper and more honest about what the function needs.
|
||||
The test helper `as_a_server_analyzes` grew a fourth return value for the same
|
||||
reason.
|
||||
|
||||
**`FACTS_FORMAT` 3 → 4, not 2 → 3 as the brief said.** The brief was written
|
||||
against a tree where `port-detail-spans` had not yet been counted; the constant
|
||||
was already at 3 when this round started. Same rule, next number.
|
||||
|
||||
**The heading now comes from the index on the disk path, and that is a small
|
||||
behaviour change in one corner.** Before, a closed file that could not be read
|
||||
produced a bare `` `sub.sv` `` heading with no line; now it produces
|
||||
`` `sub.sv:2` ``, because the line no longer depends on the file being
|
||||
readable. That is more information and not less, it is the line the index
|
||||
recorded from the text it indexed, and it is pinned by
|
||||
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` — which
|
||||
deletes the file and requires the heading to survive. Every other card is
|
||||
byte-identical: the full suite passed unmodified before a single new test was
|
||||
added, including the stale-span, guard, CRLF, cap and ambiguity tests.
|
||||
|
||||
**The live path was deliberately left alone.** An open buffer's heading still
|
||||
comes from that buffer's own line index and *not* from `Def::lines`, because
|
||||
the buffer may hold unsaved edits the index has not seen — the same reason
|
||||
`declaration_snippet` matches a `Def` to a live symbol logically instead of
|
||||
reading at the indexed span (`docs/features/hover-declarations/README.md`).
|
||||
Zero I/O either way, so there is nothing to win by unifying them and a
|
||||
correctness property to lose.
|
||||
|
||||
**`disk_view` is gone, subsumed.** Its whole job — one read per file per hover
|
||||
— is now the view cache's, which does the same thing per *session* instead of
|
||||
per request. The per-request memo would have been a second cache in front of
|
||||
the first.
|
||||
|
||||
**Files touched.** `crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`,
|
||||
`crates/vlog_semantic/tests/workspace.rs`,
|
||||
`crates/lucisv_server/src/{state.rs,locate.rs,hover.rs,index_cache.rs,perf.rs}`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, this README,
|
||||
`docs/features/{hover-declarations,workspace-index,index-persistence}/README.md`,
|
||||
`docs/perf/README.md`, `TODO.md`. No new dependency, no `unsafe`, no
|
||||
`#[allow]`, no version bump, no commits.
|
||||
|
||||
**Tests added.**
|
||||
|
||||
| test | where | pins |
|
||||
|---|---|---|
|
||||
| `every_declared_names_line_is_recorded_when_the_file_is_indexed` | `vlog_semantic/tests/workspace.rs` | line 1, a middle line, the last line with no trailing newline, and a member's line — each checked against the source line's own text |
|
||||
| `crlf_and_multibyte_text_do_not_shift_a_declarations_line` | same | `\r\n` line endings, and three- and four-byte characters ahead of the declaration |
|
||||
| `a_split_ports_two_lines_ride_the_same_carrier` | same | the extension story: a non-ANSI port's header line *and* body line, and an ANSI port's `None` |
|
||||
| `a_declarations_lines_survive_the_record_round_trip` | same | encode → decode → equal, and through `IndexBuilder` to a `Def` |
|
||||
| `a_store_from_any_previous_facts_format_is_dropped_not_misread` | `lucisv_server/src/index_cache.rs` | **rewritten**: every format `1..FACTS_FORMAT` is discarded by the header, *and* a genuine format-3 record (today's minus the two line fields) fails `decode` even served past the header. Was pinned at the literal `2` and would have gone on testing 2 forever |
|
||||
| `a_closed_files_text_is_read_once_and_then_reused` | `lucisv_server/src/state.rs` | the cache exists: the file is rewritten behind the server's back and the second view is the first |
|
||||
| `a_file_an_open_buffer_speaks_for_has_no_view_of_its_own` | same | closed files only |
|
||||
| `every_way_a_files_text_can_move_drops_its_view` | same | all four invalidation points, each by the same warm-change-event-check experiment |
|
||||
| `the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text` | same | both bounds, LRU order, and that a file over the whole byte budget is still cached and evicts the rest |
|
||||
| `a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` | `lucisv_server/src/hover.rs` | the round's central claim: the file is deleted and the heading still names its line, snippet correctly dropped |
|
||||
| `a_second_hover_into_one_closed_file_reads_nothing` | same | the snippet's read is shared: the file is rewritten and the second card is the first |
|
||||
|
||||
Two `#[ignore]`d probes added (`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`,
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`); one existing probe
|
||||
(`hovering_into_a_large_closed_file_reads_it_once`) grew a second timing so it
|
||||
reports the repeat beside the first touch.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` silent. `cargo test --workspace` green, 0 failed. The counts, by
|
||||
binary: `lucisv_server`'s unit tests **1 210 passed / 24 ignored** (+6 passing,
|
||||
+1 `#[ignore]`d probe), its `e2e` suite **56 passed / 2 ignored** (+1
|
||||
`#[ignore]`d probe), `vlog_semantic`'s `workspace` suite **66 passed** (+4).
|
||||
One test was renamed rather than added
|
||||
(`a_store_from_the_previous_facts_format_is_dropped_not_misread` →
|
||||
`a_store_from_any_previous_facts_format_is_dropped_not_misread`), so nothing
|
||||
was quietly dropped.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-28 — QA
|
||||
|
||||
Verdict: **SHIP.** No correctness bug found in the round's own code — every
|
||||
finding below is a test-coverage gap, closed in this pass with permanent
|
||||
regression tests. All seven charter items checked; details follow.
|
||||
|
||||
**1. Heading staleness — reproduced, and the documented window holds.**
|
||||
Constructed the exact attack: index `sub.sv` from its original text, then
|
||||
rewrite it on disk (`addr` moved from line 2 to line 6, and the byte offset
|
||||
the index still holds for it now lands inside a comment) with no `didSave`, no
|
||||
watcher event and no `update_one`/`rebuild_index` call — before any hover has
|
||||
ever read the file, so the view cache is empty and the read the snippet does
|
||||
is genuinely against the *new* bytes. Result: the heading still shows
|
||||
`sub.sv:2` (the index's last-scanned line, not the file's true current one),
|
||||
and the snippet is dropped by `spells_exactly` rather than showing whatever
|
||||
now sits at that byte range — no wrong line and no wrong snippet, matching the
|
||||
README's Assumptions ("both are stale together") exactly. Pinned:
|
||||
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`
|
||||
(`crates/lucisv_server/src/hover.rs`). The docs (this README's Assumptions
|
||||
section, and `Workspace::file_view`'s doc comment at
|
||||
`crates/lucisv_server/src/state.rs:1043`) already state this honestly — no
|
||||
doc fix needed.
|
||||
|
||||
**2. `DeclLines` correctness — dev's tests already cover the awkward
|
||||
offsets** (line 1, the last line with no trailing newline, CRLF, multi-byte
|
||||
text ahead of the declaration, a split port's two lines, an ANSI port's
|
||||
`None`) and check each recorded line against the source line's own text, not
|
||||
just against a hand-computed expectation. No drift found; ran unmodified.
|
||||
|
||||
**3. View-cache attacks — three untested-but-correct paths, now covered.**
|
||||
The cache's own logic (`trim_views`, `cached_view`,
|
||||
`crates/lucisv_server/src/state.rs:349` and `:1061`) was already right by
|
||||
inspection and by trace, but three of the charter's named attacks had no
|
||||
regression test, meaning a future refactor could break any of them silently:
|
||||
- *Recency, not insertion order.* `cached_view`'s `rotate_right` had no test
|
||||
at all. Added
|
||||
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`:
|
||||
fills the cache, re-touches the oldest entry, adds a fifth file, and
|
||||
requires the just-touched file to survive while the untouched one is what
|
||||
falls off instead.
|
||||
- *`update_one` selectivity.* Every existing invalidation test warms one
|
||||
file's view at a time, so a hypothetical `update_one` that widened to
|
||||
`views.clear()` would still pass all of them. Added
|
||||
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`.
|
||||
- *A second oversized file.* The existing bound test caches exactly one
|
||||
file over the byte budget; it never tries a second one. Added
|
||||
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`,
|
||||
confirming the cache stays at one entry (the newest) rather than
|
||||
accumulating unbounded huge files.
|
||||
All three pass against the round's code unmodified — genuine coverage gaps,
|
||||
not bugs.
|
||||
|
||||
**4. Format bump — the single-decl test's premise checked, and generalized.**
|
||||
`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread`
|
||||
genuinely constructs a format-3 record (verified by hand: `strip_the_line_
|
||||
fields` removes exactly the two trailing fields of the one declaration `M`
|
||||
has, and the record that results is what format 3 actually wrote — not merely
|
||||
a v3 header over v4 bytes). That fixture has only one declaration, so it could
|
||||
not have caught a field-shift that landed on a *second* declaration's fields
|
||||
rather than on a tag literal. Added
|
||||
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_
|
||||
rejected_not_misread`, generalizing the stripper to N declarations (both units
|
||||
and members) and covering a two-unit file and a mixed unit+split-port-member
|
||||
file. Both decode to `None`, confirming the structural reason this is safe in
|
||||
general: a field-shift by exactly one declaration's two line-fields always
|
||||
lands either on a tag literal (`"M"`, `"I"`, …) or on the next declaration's
|
||||
`name`/`kind` string fields, and a Verilog identifier can never parse as
|
||||
`u32`, so `Reader::num` fails and `decode` returns `None` rather than building
|
||||
a `Decl` out of someone else's fields. No misread constructed; the
|
||||
"guilty until proven innocent" bar is met.
|
||||
|
||||
**5. Equivalence — confirmed, not just claimed.** `cargo test --workspace`
|
||||
green with 0 failures both before and after this pass's additions (dev's
|
||||
counts: `lucisv_server` 1210 passed/24 ignored, `vlog_semantic` `workspace` 66
|
||||
passed — both unmodified by this pass except for the new tests below). Read
|
||||
the `hover.rs` and `locate.rs` diffs directly: the live-buffer branch is
|
||||
untouched, `location()`'s open-buffer arm is a straight substitution
|
||||
(`doc.positions()` for the old `Positions::new(&text, &index)` built from a
|
||||
clone of the same text), and the disk branch is the only place behavior can
|
||||
differ — which is exactly the one documented corner (an unreadable closed
|
||||
file now shows its indexed line). No other behavior change found.
|
||||
|
||||
**6. Numbers reproduced**, `--release`, this machine, this session:
|
||||
- `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`: first
|
||||
touch 5.75 ms (instantiation) / 5.65 ms (port), repeat 1.35 µs / 1.89 µs —
|
||||
same order as the README's 6.23 ms / 0.95 µs and 5.92 ms / 0.99 µs; run-
|
||||
to-run noise, not drift.
|
||||
- `state::tests::qa_perf_cold_warm_and_half_warm_scans` (860-file corpus):
|
||||
store size **2 380 790 bytes** — an exact match to the README's "after"
|
||||
figure, confirming the +68 KB / 2.9 % growth claim against the real
|
||||
corpus rather than trusting the doc's arithmetic. Scan times (325 / 350 /
|
||||
186 ms) were in the same band as the README's (343 / 374 / 200 ms);
|
||||
machine noise, no regression.
|
||||
- `e2e::a_hover_issued_during_the_initial_scan_waits_for_it`: 748.7 ms cold
|
||||
/ 274.0 ms warm for the first hover issued the moment `initialized` is
|
||||
sent, vs. 26.3 µs / 40.2 µs once the scan is done — the same four-orders-
|
||||
of-magnitude gap the README reports (780 / 287 ms vs. 64 / 61 µs). The
|
||||
test genuinely exercises the wait (it asserts the answer resolves
|
||||
correctly across files, and the two timings are taken across the real
|
||||
wire protocol against the shipped binary) — the Handshake in this
|
||||
README's "Suspect 2" section is accurate and not overstated.
|
||||
|
||||
**7. Full gates**, run after adding the tests above:
|
||||
- `cargo fmt --all -- --check`: clean (after formatting the new tests —
|
||||
two blocks needed `cargo fmt`'s wrapping, applied).
|
||||
- `cargo clippy --all-targets --workspace`: clean, no warnings.
|
||||
- `cargo test --workspace`: green. `lucisv_server` unit tests **1214
|
||||
passed** (dev's 1210 + this pass's 4), `vlog_semantic` `workspace` suite
|
||||
**67 passed** (dev's 66 + this pass's 1). 0 failed anywhere in the
|
||||
workspace, including doctests.
|
||||
- `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**Tests added this pass** (5, all permanent regressions, all green):
|
||||
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`,
|
||||
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`,
|
||||
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`,
|
||||
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`
|
||||
(all `crates/lucisv_server/src/`), and
|
||||
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_rejected_not_misread`
|
||||
(`crates/vlog_semantic/tests/workspace.rs`).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
|
||||
independently (fmt clean, clippy silent, 2440 workspace tests green).
|
||||
This round is the owner's design implemented at the right altitude:
|
||||
`DeclLines` as a field on the carrier the index already had — not a
|
||||
parallel table — so ports got their lines for free through the member
|
||||
entries and the extension story is "add a field, bump the format",
|
||||
exactly the flexibility the owner asked for. The +68 KB store growth
|
||||
on the 860-file corpus scales to the owner's 20 000-module thought
|
||||
experiment at the few-tens-of-KB order they predicted. The `FileView`
|
||||
cache is honest about its one unwatchable staleness case and leans on
|
||||
`spells_exactly` correctly (a stale view omits, never lies); QA's
|
||||
staleness repro pins the heading/snippet pair going stale *together*.
|
||||
The dev's rewrite of the format-discard test from a pinned literal to
|
||||
all-previous-formats is the kind of fix that outlives the round.
|
||||
Suspect 2 — the first request of a session waiting 287–780 ms behind
|
||||
the startup scan — is confirmed genuine by dev and QA independently
|
||||
and is the dominant remainder of the owner's "slow on first try";
|
||||
correctly filed as a Handshake, next round's work. Accepted; committed
|
||||
by the lead.
|
||||
@@ -216,7 +216,33 @@ impl WorkspaceIndex {
|
||||
- Since indexed navigation (2026-08-27), the private facts also carry compact
|
||||
local/external reference records used to rebuild declaration-to-occurrence
|
||||
postings. That encoding change bumped `FACTS_FORMAT` from 1 to 2; no cache
|
||||
migration is attempted or needed.
|
||||
migration is attempted or needed. **2 → 3** (2026-08-28,
|
||||
`docs/features/port-detail-spans/README.md`): each declaration gained its
|
||||
`detail_span`. **3 → 4** (2026-08-28,
|
||||
`docs/features/hover-line-index/README.md`): each declaration gained its two
|
||||
*line numbers*, which is what lets a server print `file:line` for an indexed
|
||||
declaration without reading that file. **4 → 5** (2026-08-29,
|
||||
`docs/features/vscode-hierarchy-sidebar/README.md`): one bump for three
|
||||
additions — each declaration's `decl_span`; a per-instance
|
||||
`InstanceOccurrence` list on every instantiation edge (the edge itself is
|
||||
still one per *statement*, so no census moved); and **client positions**,
|
||||
0-based lines and UTF-16 columns, on every file-scope declaration and every
|
||||
instance occurrence, which is what lets the design-hierarchy snapshot answer
|
||||
with no file read at all. Members deliberately get none: the `U` and `M`
|
||||
groups of a record are separate, so "units carry positions, members do not"
|
||||
costs a member no field, not even a presence flag — and members outnumber
|
||||
units by two orders of magnitude. Same rule each time, same
|
||||
consequence: the store is discarded whole on the first scan after the
|
||||
upgrade and rewritten — measured at about 175 ms over the 860-file corpus,
|
||||
once. `a_store_from_any_previous_facts_format_is_dropped_not_misread`
|
||||
checks **every** format this build is not, rather than the one literal
|
||||
number it was pinned at, so each bump inherits the test; its
|
||||
belt-and-braces half (a genuine previous-format record served past the
|
||||
header) is re-derived at each bump — `as_a_format_4_record` at format 5.
|
||||
The store grew 68 KB (2.9 %) for the lines at format 4, and a further
|
||||
212 KB (8.9 %) over the 860-file corpus for all of format 5 — of which the
|
||||
client positions are 1.7 %, measured separately on the same corpus and again
|
||||
on opentitan (1.9 % of a 24.7 MB store).
|
||||
- `record_path` is public separately because a store keyed by path reads that
|
||||
field out of every record it holds and decodes only the ones it is asked
|
||||
for.
|
||||
@@ -350,7 +376,16 @@ name span `19..20`), no members, one instantiation edge (of `sub`, owned by
|
||||
`m` whose name is at `19..20` and whose declaration runs `12..41`, with the
|
||||
site's own name span `22..25`), no subclasses, and one external reference fact
|
||||
(`e`, name `sub`, one resolution path also named `sub`, occurrence `22..25`),
|
||||
then the checksum. The record is what lies between the hash field and the
|
||||
then the checksum. **The example is written at `FACTS_FORMAT` 2 and is kept
|
||||
for its shape, not its field count**: since then every declaration also
|
||||
carries its detail span (`0 0` when there is none, format 3), its two line
|
||||
numbers (format 4), its `decl_span` and — for a file-scope declaration only —
|
||||
its two client ranges of four numbers each (format 5); and an instantiation
|
||||
edge carries a length-prefixed list of its individual instances, each a name,
|
||||
two byte ranges and two client ranges. So a real record today is considerably
|
||||
wider per declaration than the one above. The framing — one line, tab-separated,
|
||||
length-prefixed lists, checksum last — is what the example is for and is
|
||||
unchanged. The record is what lies between the hash field and the
|
||||
checksum; both hashes above are illustrative.
|
||||
|
||||
**Any change to what a record holds or how it is written bumps
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -74,7 +74,18 @@ are answerable without a debugger. All three settings ride both settings doors
|
||||
here because it is the one non-obvious reach of the setting.
|
||||
- **The denominator is the work list after `exclude` and after the cap.** It
|
||||
is `vlog_semantic::index_order`'s length, known before the first parse, so
|
||||
the bar counts towards a number the scan will actually reach.
|
||||
the bar counts towards a number the scan will actually reach. **Amended
|
||||
(index-scope, 2026-08-28): a scope widen's work list is the files it is
|
||||
actually indexing** — the folders it added, plus the open buffers it refreshes
|
||||
— so a jump into a 25-file folder of a 4 000-file project says `1/25`, not
|
||||
`1/3979`. That is the same rule, not an exception to it: the denominator has
|
||||
always been "what this scan will do", and a widen simply does less. The bar's
|
||||
**end message is unchanged** and still names the whole index
|
||||
(`"N files indexed"`), because the bar names the scan and the message names
|
||||
what the workspace now holds. No test in this feature moved; the fixtures
|
||||
here are small enough that a widen's work list is the whole scope, and the
|
||||
new denominator has its own test in `state.rs`
|
||||
(`a_widen_bar_counts_the_new_files_and_not_the_whole_scope`).
|
||||
- **The percentage only counts up, and the last file always reports.** See the
|
||||
throttle below; `the_report_schedule_never_floods_and_never_stops_short`
|
||||
checks both properties across nine workspace sizes.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -198,6 +198,27 @@ contract*.
|
||||
|
||||
**Promised**
|
||||
|
||||
- **Amended 2026-08-30 — this module now serves two ghosts.**
|
||||
`inline_completions` routes on the shape of the text before the cursor: an
|
||||
identifier followed by exactly one space goes to the module-instantiation
|
||||
ghost (`docs/features/inline-instantiation/README.md`), and the token ending
|
||||
*at* the cursor goes to the trigger table below. **The cursor contract for
|
||||
the triggers here is unchanged** — a template still fires only when its own
|
||||
last token ends exactly at the cursor, and `begin |` still offers nothing
|
||||
(`whitespace_between_the_keyword_and_the_cursor_never_triggers`). The two
|
||||
routes cannot contend for a keystroke: a space is not a token, so nothing
|
||||
ends at the cursor when one has just been typed, and no trigger's last token
|
||||
is an `Ident`. Each carries its own setting — `lucisv.inlineTemplates` gates
|
||||
only the triggers here. What used to be `triggered`'s prologue (the `Eof`
|
||||
skip and the "ends exactly at the cursor" rule) is now `last_token`, shared
|
||||
by both — the instantiation route asks it about the byte *before* the space
|
||||
— so the 2026-08-25 true-EOF fix protects the instantiation ghost too. The
|
||||
wire shape, the empty range at the cursor and the relative indentation are
|
||||
unchanged and are what the new path inherits.
|
||||
- **Round 2, 2026-08-30 (owner ruling):** the instantiation route used to
|
||||
fire on the identifier ending at the cursor, exactly as a trigger does. It
|
||||
now needs the space, so an identifier ending at the cursor reaches
|
||||
*neither* ghost. Nothing in the trigger table changed for it.
|
||||
- `textDocument/inlineCompletion` (LSP 3.18, proposed in `lsp-types`),
|
||||
advertised as `inlineCompletionProvider: true`. The result is
|
||||
`{"items": [ { "insertText": {"kind": "snippet", "value": … },
|
||||
@@ -217,7 +238,9 @@ contract*.
|
||||
- **Request to `completion.rs` (made and applied, 2026-08-25):** the popup's
|
||||
multi-line items now send `insertTextMode: asIs`. See the QA/Review note in
|
||||
the work log — the change is one field on two item builders and is
|
||||
documented in `completion-templates`' README.
|
||||
documented in `completion-templates`' README. *(2026-08-30: one of those two
|
||||
builders, the module skeleton, no longer exists — the module item is a plain
|
||||
word. The template item still sends the field.)*
|
||||
- Root `Cargo.toml`: `lsp-types` gains `features = ["proposed"]`. That
|
||||
feature also adds `offset_encoding` fields to `ClientCapabilities`,
|
||||
`InitializeResult` and `TextDocumentClientCapabilities` — all
|
||||
|
||||
@@ -0,0 +1,633 @@
|
||||
# interface-semantics
|
||||
|
||||
## Goal
|
||||
|
||||
An `interface` was a `SymbolKind::Module`, so hover called it a "module"; a
|
||||
`modport` and a `clocking` block declared nothing, so the signal names written
|
||||
inside them were not references at all; and `is_exported(Module, ·)` passed
|
||||
ports and parameters only, so `vif.sig` through a `virtual bus_if vif` handle
|
||||
resolved inside the declaring file and never across one. This round gives an
|
||||
interface its **own kind**, gives a modport and a named clocking block their
|
||||
own **symbols**, binds every name written inside either as a reference to the
|
||||
interface's own declaration, binds the **modport half** of a glued
|
||||
`bus_if.mp` type name, and widens the export rule so an interface's *signals*
|
||||
— which are its surface, where a module's are not — reach another file.
|
||||
Hover, definition, references, documentHighlight, rename, completion, the
|
||||
outline, the design hierarchy and the call hierarchy all follow, because all
|
||||
of them read the two layers this round widens.
|
||||
|
||||
It delivers `docs/coverage_gaps.md` C2 (the wrong "module" label on an
|
||||
interface, and the `b_if.mp` that answered nothing) and H2 (`vif.sig` across
|
||||
files), and `docs/topo.md` §2.9-7.
|
||||
|
||||
The governing rule is round 1's, unchanged: **a link that cannot be resolved
|
||||
honestly records nothing; a wrong answer is the only forbidden outcome.** Two
|
||||
of the three new targets can record nothing, and do.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`program … endprogram` stays a `Module`.** It shares the module's header
|
||||
and body grammar and the parser gives it the same node; unlike an interface
|
||||
it has no export rule of its own to write, and nothing in the corpus (0 of
|
||||
860) declares one. Giving it a kind would be a label change with no
|
||||
behaviour behind it. `SymbolKind::Interface` is spelled off `Module::kw ==
|
||||
"interface"` and nothing else.
|
||||
- **`ScopeKind::Module` still covers all three.** A scope's kind governs
|
||||
*lookup rules*, and a module body, an interface body and a program body bind
|
||||
names identically: declaration order, imports consulted, file scope outside.
|
||||
What differs is which members another file may reach, and that is a property
|
||||
of the **declaration** (`SymbolKind`), which is where the export rule reads
|
||||
it. No `ScopeKind::Interface` was added; adding one would have meant a second
|
||||
spelling of the same rule in every place that matches on scope kind.
|
||||
- **A modport port names a member of its own interface and nothing else**
|
||||
(IEEE 1800-2017 §25.5). So those names are looked up in exactly the scope
|
||||
they are written in and never outward. This is the correctness assumption,
|
||||
not a convenience: an ordinary lexical walk out of `modport mp (input
|
||||
other_if)` would land on a file-scope `other_if` — a wrong answer, where
|
||||
recording nothing is merely a missing one.
|
||||
- **A clocking signal aliases the same-named signal of the enclosing unit**
|
||||
(§14.4), so answering with that signal's own declaration is honest. That is
|
||||
what `SymbolKind::Clocking`'s `type_name = <enclosing unit>` encodes: it
|
||||
makes `vif.cb.data` hop cb → interface → `data` through round 2's existing
|
||||
chase, with no new machinery on either layer.
|
||||
- **A clocking item written `output tms = expr;` declares a name of the
|
||||
block's own**, not a use of an enclosing `tms`, so only the value is bound.
|
||||
(The parser does not accept that spelling today — `docs/features/interfaces`
|
||||
records 0 corpus uses — but the AST models it and the binder answers it.)
|
||||
- **A modport restricts direction, not membership.** A `virtual bus_if.mp vif`
|
||||
handle keeps `type_name = bus_if`, so `vif.<anything the interface declares>`
|
||||
resolves. Answering the superset is honest — the modport's direction list is
|
||||
a legality question this crate does not model anywhere — and answering the
|
||||
subset would have made `vif.sig` stop working for every DV testbench that
|
||||
writes a modport-qualified handle.
|
||||
- **An interface exports its signals; a module still does not.** The round-2
|
||||
module ruling (`docs/features/class-member-access/README.md`: ports and
|
||||
parameters only, because a module handle is an *instance* whose internals no
|
||||
other file's connection list may name) is untouched, and its pin
|
||||
(`member_access.rs`, `a_modules_internals_are_still_not_exported` here)
|
||||
stays. An interface handle is not an instance handle: `virtual bus_if vif;
|
||||
vif.data` is the way every DV testbench in the world reaches `data`, and
|
||||
`data` is an ordinary net declared inside the interface.
|
||||
- **The semantic-token legend is unchanged.** `tokens.rs::token_types()` is a
|
||||
wire contract — the index into that array is what the protocol carries — so
|
||||
adding an `interface` token type would renumber every highlight a live
|
||||
client already holds. An interface and a modport keep the `class` highlight a
|
||||
module has always had; a clocking block takes the `variable` one a block
|
||||
label takes. If the extension ever registers an `interface` token type, the
|
||||
arm to change is `tokens.rs::symbol_type`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed:
|
||||
|
||||
- `vlog_parser::ast::Module::kw` — the one thing that tells an interface from a
|
||||
module (`docs/features/interfaces/README.md`'s own handshake).
|
||||
- `ItemKind::Modport(Vec<ModportDecl>)` and `ItemKind::Clocking(ClockingDecl)`,
|
||||
and the spans on `ModportDecl::name_span`/`span`, `ModportPort::names`,
|
||||
`ClockingDecl::name` and `ClockingSignal::name`. Every name this round binds
|
||||
came with a real span; nothing new was asked of the parser.
|
||||
- Round 1/2's chase machinery unchanged: `resolve::type_here`, `link_type`,
|
||||
`member_in_chain`, and the workspace's `follow_one` / `member_chain` /
|
||||
`member_type`. The clocking hop and the modport tail are both expressed as
|
||||
existing path shapes (`bus_if::cb::data`, `bus_if::mp`), so neither layer
|
||||
grew a special case.
|
||||
|
||||
Promised / changed for others:
|
||||
|
||||
- **`SymbolKind` has three new variants**: `Interface`, `Modport`, `Clocking`.
|
||||
Every exhaustive match over it must gain an arm; the four in the workspace
|
||||
did (`lucisv_server::symbols::kind_label`, `symbols::lsp_kind`,
|
||||
`tokens::symbol_type`, `completion::completion_kind`).
|
||||
- **`SymbolKind::is_instantiable()`** is the new spelling of "a thing an
|
||||
instantiation may name" — `Module | Interface`. Every filter that used to
|
||||
compare `kind == Module` for that meaning now asks this and answers what it
|
||||
always did. The sites are listed in the work log.
|
||||
- **`WorkspaceIndex::instantiable_units()`** is `units_of(Module)` widened to
|
||||
both kinds, for the design hierarchy and anything else that roots at units
|
||||
you can instantiate. `units_of(kind)` itself is unchanged.
|
||||
- **`IndexCounts` has a new field, `interfaces`**, and `modules` no longer
|
||||
counts interfaces — so a caller printing "N modules" still means N modules.
|
||||
- **`FACTS_FORMAT` 7 → 8.** Three new kind names, plus a wider census (an
|
||||
interface's members, a modport, a clocking block, and every name inside
|
||||
either). A store written by an older build is discarded whole.
|
||||
- **`vlog_refactor`**: a rename that lands on the `mp` of `bus_if.mp` now has
|
||||
a symbol to rename, so it renames the modport and every type-position use of
|
||||
it instead of refusing. The test that pinned the refusal —
|
||||
`vlog_refactor/tests/rename.rs::renaming_the_modport_half_of_a_port_type_is_refused`
|
||||
— therefore fails **by design**, with the correct edit set. It is left
|
||||
untouched here: `vlog_refactor`'s tests are not this lane's to edit, and
|
||||
TODO.md §16 reserves the call for the lead at merge.
|
||||
|
||||
Requests to other owners (not done here):
|
||||
|
||||
- **editors/**: if the VS Code extension ever wants a distinct colour for an
|
||||
interface, the semantic-token legend needs an `interface` type appended
|
||||
(appended, never inserted — the indices are the wire contract) and
|
||||
`tokens.rs::symbol_type` one changed arm.
|
||||
- **`vlog_parser`**: a `DataType` still carries no span, so the modport half of
|
||||
`bus_if.mp` is located by deriving from the interface half's range and
|
||||
verifying it twice (a literal `.` must follow, and the bytes after it must
|
||||
spell the modport). That works on every corpus spelling, but the standing
|
||||
request from `docs/features/vlog-semantic/README.md` (item 2: give
|
||||
`DataType` a span) would delete `Binder::modport_tail` outright.
|
||||
- **explicit modport ports and modport method prototypes** (`.name(expr)`,
|
||||
`import task drive(int x);`) are still parse errors
|
||||
(`docs/features/interfaces/README.md`); nothing here needs them and the
|
||||
corpus has none.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `SymbolKind::Interface`, declared by `bind_module` off `kw ==
|
||||
"interface"`; `program` stays `Module`, with a test saying so
|
||||
- [x] Every Module-exact match that meant "instantiable unit" widened through
|
||||
`SymbolKind::is_instantiable()`; every exhaustive match given its arms
|
||||
- [x] Export rule for interfaces: `Net | Var | Port | Param | Typedef |
|
||||
Function | Task | Modport | Clocking`; the module ruling untouched
|
||||
- [x] `SymbolKind::Modport`, declared from `ModportDecl::name_span`; every
|
||||
name in the port list a reference to the interface's own declaration
|
||||
- [x] The modport half of `bus_if.mp` / `virtual bus_if.mp` bound as a member
|
||||
of the type — in-file through the interface's scope, cross-file as
|
||||
`bus_if::mp`
|
||||
- [x] `SymbolKind::Clocking` for a named block, typed by its enclosing unit;
|
||||
the event and every signal name bound; `default clocking cb;` a
|
||||
reference; an anonymous `default clocking` declares nothing
|
||||
- [x] `FACTS_FORMAT` 7 → 8
|
||||
- [x] 24 behavioural tests in `crates/vlog_semantic/tests/interfaces.rs` plus
|
||||
an `#[ignore]`d corpus-cost probe; 2 e2e sessions; 7 pins beside the
|
||||
widened filters they cover (`symbols.rs`, `tokens.rs`, `completion.rs`,
|
||||
`candidates.rs`, `design_hierarchy.rs`, `hierarchy.rs`,
|
||||
`vlog_refactor::{ports, instantiate}`); the two kind pins in
|
||||
`tests/workspace.rs` flipped
|
||||
- [x] Corpus acceptance measured before/after at the same trunk commit
|
||||
- [ ] Not done, and not planned here: `program`'s own kind; a modport's
|
||||
*direction* list as a legality check; struct-member chains (round 2's
|
||||
standing gap, `docs/topo.md` §2.9-13)
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-01 — dev
|
||||
|
||||
**A. `SymbolKind::Interface`.** `bind_module` reads `Module::kw` and declares
|
||||
`Interface` for `interface`, `Module` for everything else including `program`
|
||||
(`bind.rs`). `ScopeKind` was left alone — argued in Assumptions.
|
||||
|
||||
`SymbolKind::is_instantiable()` (`model.rs`) was added rather than spelling
|
||||
`Module | Interface` at each site, because "a thing you can instantiate" is
|
||||
one idea and it appears in nine places across three crates. Every one of them
|
||||
behaved for interfaces before this round *because interfaces were Modules*, so
|
||||
widening the filter is what keeps the behaviour rather than what changes it.
|
||||
The sites, each verified to be a "can you instantiate it" test and not a "is
|
||||
it literally a module" test:
|
||||
|
||||
- `vlog_semantic/src/resolve.rs` — `Target::Module` and `Target::Port`, via
|
||||
the new `is_instantiable` predicate handed to `named_at_file_scope` /
|
||||
`owning_scope` / `file_symbol` (which took a `SymbolKind` and now take a
|
||||
`fn(SymbolKind) -> bool`, so `Target::Package` stays exactly as narrow as it
|
||||
was).
|
||||
- `vlog_semantic/src/resolve.rs` — `container_scope` and `member_scope`.
|
||||
- `vlog_semantic/src/workspace.rs` — `is_unit`, and the new
|
||||
`instantiable_units()`.
|
||||
- `vlog_semantic/src/bind.rs` — `enclosing_unit_name`, which is what a
|
||||
clocking block's `type_name` is read off.
|
||||
- `lucisv_server/src/completion.rs` — `nearest_definition` and
|
||||
`module_header` (the two ghost-instantiation lookups) and `module_detail`,
|
||||
which used to hard-code the label `"module"` and now reads the kind off the
|
||||
index, because a card saying "module" over an `interface` is precisely the
|
||||
C2 wrong answer.
|
||||
- `lucisv_server/src/candidates.rs` — the module-name table behind
|
||||
`Candidates::modules`.
|
||||
- `lucisv_server/src/design_hierarchy.rs` — the roots of the sidebar snapshot
|
||||
and its own test's cross-check. The wire schema is untouched: the rows are
|
||||
the same shape, there are simply interfaces among them, exactly as there
|
||||
were before this round.
|
||||
- `lucisv_server/src/hierarchy.rs` — `declarations_of`, so call hierarchy on
|
||||
an interface still finds its declaration.
|
||||
- `vlog_refactor/src/ports.rs` and `src/instantiate.rs` — the three unit
|
||||
lookups behind port refactorings, `module_definition` and `module_names`.
|
||||
|
||||
Each widened filter got a pin beside it, so a later round cannot narrow one
|
||||
back without a test saying what it broke: `symbols.rs`
|
||||
(`an_interface_its_modport_and_its_clocking_block_are_named_and_iconed`),
|
||||
`tokens.rs` (`the_new_kinds_reuse_the_legend_rather_than_growing_it`, which
|
||||
also pins the legend's length),
|
||||
`completion.rs` (`an_interface_completes_as_an_interface`),
|
||||
`candidates.rs` (`an_interface_is_in_the_module_table`),
|
||||
`design_hierarchy.rs`
|
||||
(`an_interface_is_a_row_and_its_instance_a_child_like_any_other`, schema 2
|
||||
asserted), `hierarchy.rs`
|
||||
(`the_cursor_on_an_interface_instantiation_prepares_the_interface`),
|
||||
`vlog_refactor::ports`
|
||||
(`a_port_refactoring_finds_an_interface_the_way_it_finds_a_module` — adding a
|
||||
port to an interface rewrites its instantiation too) and
|
||||
`vlog_refactor::instantiate`
|
||||
(`an_interface_is_a_unit_this_module_will_instantiate`). The refactor pins
|
||||
live in the `src` files' own `#[cfg(test)]` modules, because
|
||||
`crates/vlog_refactor/tests/` is not this lane's to edit.
|
||||
|
||||
Exhaustive matches that had to gain arms (the compiler named all four):
|
||||
|
||||
- `lucisv_server/src/symbols.rs::kind_label` — `"interface"`, `"modport"`,
|
||||
`"clocking"`. This is the hover label C2 was about.
|
||||
- `lucisv_server/src/symbols.rs::lsp_kind` — `Interface | Modport =>
|
||||
INTERFACE` (a modport is a named view *of* an interface), `Clocking =>
|
||||
EVENT`.
|
||||
- `lucisv_server/src/tokens.rs::symbol_type` — `Interface | Modport => Class`,
|
||||
`Clocking => Variable`, with the legend argued in Assumptions.
|
||||
- `lucisv_server/src/completion.rs::completion_kind` — `Interface | Modport =>
|
||||
INTERFACE`, `Clocking => EVENT`.
|
||||
|
||||
`type_def.rs::type_use_at` gained `Interface` beside `Typedef | Class |
|
||||
Module`: an interface name in a type position is a type use like any other.
|
||||
|
||||
**B. The export rule.** `is_exported` gained an `Interface` arm. The module
|
||||
arm is byte-for-byte what it was, and its pin
|
||||
(`member_access.rs::an_instance_head_reaches_a_module_in_another_file`) is
|
||||
untouched; `interfaces.rs::a_modules_internals_are_still_not_exported` asserts
|
||||
the two rules side by side.
|
||||
|
||||
**C. Modport symbols.** `bind_modport` declares from `ModportDecl::name_span`
|
||||
with `ModportDecl::span` as the declaration span — this modport's own extent
|
||||
(`mp (input a, output b)`), not the whole `modport a (…), b (…);` statement,
|
||||
which would make two modports of one declaration hover identically. Hover
|
||||
renders the *lines* a span falls on, so the card still reads `modport mp
|
||||
(input a, output b);`.
|
||||
|
||||
Every name in the port list — the signals of `input`/`output`/`inout`/`ref`,
|
||||
the methods of `import`/`export`, the block of `clocking cb` — is one new
|
||||
target, `Target::InScope`: looked up in exactly the scope it is written in and
|
||||
nowhere outward, `None` (no reference at all) on a miss. One target rather
|
||||
than four, because the lookup is identical for all of them; the direction
|
||||
keyword is a legality question, not a resolution one.
|
||||
|
||||
**D. The glued type name.** `bind_data_type`'s bare-name branch now splits
|
||||
`bus_if.mp` and binds both halves: the interface as the `Target::Type` it
|
||||
always was, the modport as a new `Target::TypeMember { unit }`, which resolves
|
||||
through `type_here` on exactly the terms `member_of`'s last link does —
|
||||
in-file the interface's own scope (hit, or nothing), cross-file the composed
|
||||
path `bus_if::mp` that `follow_one` reads back as `member(bus_if, mp)`. This
|
||||
is what `docs/features/ansi-first-port/README.md` meant by "the tail is where
|
||||
to bind them"; it covers the ANSI port spelling and `virtual bus_if.mp vif`
|
||||
alike, since both reach the same function.
|
||||
|
||||
`Binder::modport_tail` derives the tail's range from the interface half's,
|
||||
because a `DataType` has no span. It is verified twice — the next byte must be
|
||||
a literal `.`, and `exact_or_empty` must confirm the bytes after it spell the
|
||||
modport — so a spelling this crate cannot place costs a reference and never
|
||||
mislocates one. `type_name_of` is unchanged: a `virtual bus_if.mp vif` handle
|
||||
still records `type_name = bus_if` (Assumptions).
|
||||
|
||||
`b_if.mp` in a connection needed no new code and was verified rather than
|
||||
assumed: it is an ordinary `Target::MemberOf` whose head is an instance, whose
|
||||
declared type is the interface, whose member table now holds the modport.
|
||||
|
||||
**E. Clocking blocks.** `bind_clocking` declares a named block with an event
|
||||
and records `type_name = <nearest enclosing module or interface>`, which is the
|
||||
whole of how `vif.cb.data` works — the chase is round 2's, untouched. The
|
||||
event's `@( ... )` list binds as an ordinary sensitivity list (`bind_timing`
|
||||
was split so `bind_sens_list` could be reached from both places), and each
|
||||
`ClockingSignal` name is another `Target::InScope`. `default clocking cb;`
|
||||
(name, no event) selects a block declared elsewhere in the same scope and is
|
||||
recorded as a *use*; an anonymous `default clocking @(...)` declares and
|
||||
records nothing. A clocking block inside a module gets the same treatment,
|
||||
which is the testbench shape.
|
||||
|
||||
**F. `FACTS_FORMAT` 7 → 8**, with the round-trip test's kind array extended.
|
||||
|
||||
**G. Hover** needed nothing beyond the label, as predicted: verified over the
|
||||
wire (`e2e.rs::an_interface_and_its_modport_hover_as_what_they_are`) that a
|
||||
modport hovers as ``**modport** `mp` `` above its own line.
|
||||
|
||||
**Deviations from the brief.** Three, all argued above: `ScopeKind` was not
|
||||
given an `Interface` variant (no lookup rule differs); `IndexCounts` reports
|
||||
interfaces in a **new field** rather than folding them into `modules`, so no
|
||||
existing number silently changes meaning; and the semantic-token legend was
|
||||
left alone, so `Interface`/`Modport` keep the `class` highlight rather than
|
||||
gaining a token type that would renumber the wire contract.
|
||||
|
||||
**One test flips by design, outside this lane.**
|
||||
`vlog_refactor/tests/rename.rs::renaming_the_modport_half_of_a_port_type_is_refused`
|
||||
now fails, and reading its failure is the point: renaming `mp` in `bus_if.mp
|
||||
bus` produces `bus_if.sv 28..30 → "mp2"` (the `modport mp` declaration) and
|
||||
`top.sv 19..21 → "mp2"` (the type-position use), which is exactly the rename a
|
||||
modport-with-a-symbol should do and exactly what the test's own comment said
|
||||
was impossible while the modport was unbound. The refactor engine did not have
|
||||
to change. The test is left as it stands, per TODO.md §16 and the file
|
||||
ownership: `vlog_refactor`'s tests are the lead's call at merge.
|
||||
|
||||
### Corpus acceptance and cost
|
||||
|
||||
`cargo test -p vlog_semantic --release --test corpus -- --nocapture` and the
|
||||
new `#[ignore]`d probe `what_interface_semantics_cost_the_index` in
|
||||
`tests/interfaces.rs`. "Before" was measured in a detached worktree at trunk
|
||||
(`ff67281`) with the probe copied in — same corpus, same machine.
|
||||
|
||||
| 860-file corpus | before (`ff67281`) | after | delta |
|
||||
|---|---:|---:|---:|
|
||||
| symbols | 26 812 | **26 844** | +32 |
|
||||
| references | 98 919 | **99 237** | +318 (+0.32 %) |
|
||||
| resolved in-file | 70.1 % | **70.3 %** | |
|
||||
| external candidates | 20.7 % | 20.6 % | |
|
||||
| inherited candidates | 7.9 % | 7.9 % | |
|
||||
| **unresolved** | 1 256 (1.27 %) | **1 203 (1.21 %)** | **−53** |
|
||||
| names unplaced | 0 | **0** | 0 |
|
||||
| indexed units | 902 | 902 | 0 |
|
||||
| — of which modules / interfaces | 561 / 0 | **535 / 26** | |
|
||||
| indexed members | 11 937 | **12 298** | +361 |
|
||||
| store references | 55 588 | 56 249 | +661 |
|
||||
| store bytes (all 860 records) | 3 112 102 | **3 149 609** | **+37 507 (+1.21 %)** |
|
||||
| time to read all 860 records | ~221 ms | ~220 ms | noise |
|
||||
|
||||
**Unresolved fell, which is the number that matters.** It has been flat at
|
||||
1 256 through two previous rounds; this is the first round to move it, and it
|
||||
moved down. The 53 are uses of a clocking block's or a modport's name — `@(cb)`,
|
||||
`cb.data`, `default clocking cb;` — that used to be lexical misses inside an
|
||||
interface or a testbench with nothing to bind them, and now name a
|
||||
declaration. `names unplaced` stays at 0: every span this round derives (the
|
||||
modport tail) is verified before it is recorded.
|
||||
|
||||
**The store delta is entirely the 26 interfaces.** Per-record diffing (before
|
||||
against after, path length normalized — the worktree's own path is 79 bytes
|
||||
longer, which inflates every record equally and is not a measurement) shows
|
||||
**26 records grew and not one shrank**, and they are exactly the corpus's 26
|
||||
interface files: `clk_rst_if.sv` +4 739, `core_ibex_fcov_if.sv` +4 989,
|
||||
`core_ibex_dut_probe_if.sv` +3 369, and so on down. That is the intended
|
||||
purchase: an interface's signals are now in the member table, which is what
|
||||
makes `vif.sig` cross-file, and it costs 1.21 % of the store for the whole
|
||||
workspace. (The path-normalized "before" total, 3 112 102, reproduces the
|
||||
figure `docs/features/class-member-access/README.md` recorded for the same
|
||||
commit to the byte — which is the check that the normalization is a
|
||||
correction and not a fudge.)
|
||||
|
||||
Cost to a lookup: none new. `Target::InScope` is one `HashMap` read;
|
||||
`Target::TypeMember` is `type_here`, the same walk a type reference already
|
||||
takes; the clocking hop is `member_type`, which round 2 already put on the
|
||||
path. No file is read and nothing is parsed in either layer.
|
||||
|
||||
### Gates
|
||||
|
||||
- `cargo fmt --all -- --check` clean.
|
||||
- `cargo clippy --all-targets --workspace` zero warnings.
|
||||
- `cargo test --workspace --no-fail-fast` — **2 789 passed, 1 failed, 38
|
||||
ignored**. The one failure is the by-design `vlog_refactor` rename flip
|
||||
described above.
|
||||
- `cargo build -p lucisv_server` + `node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` OK.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-01 — QA agent. Verdict: SHIP.**
|
||||
|
||||
### Gates
|
||||
|
||||
- `cargo fmt --all -- --check`: clean.
|
||||
- `cargo clippy --all-targets --workspace`: zero warnings.
|
||||
- `cargo test --workspace --no-fail-fast`: **2 790 passed, 0 failed, 38
|
||||
ignored** — every test green, including the lead's rewritten
|
||||
`vlog_refactor::rename::renaming_the_modport_half_of_a_port_type_renames_the_modport`
|
||||
(the dev's gates before that flip were 2 789/1/38, exactly the delta the
|
||||
brief predicted).
|
||||
- `cargo build --release -p lucisv_server`: clean.
|
||||
- `node editors/vscode/smoke.js target/release/lucisv-server`: `smoke: OK`.
|
||||
- Note: `cargo fmt -- --check` first reported one unformatted block in
|
||||
`crates/vlog_refactor/tests/rename.rs` (the lead's just-landed rename flip);
|
||||
it was already fixed on disk by the time this pass re-ran the check a
|
||||
minute later (re-verified clean). No action needed from this pass.
|
||||
|
||||
### Scope
|
||||
|
||||
`git diff --stat` matches the README's file list plus the lead's own
|
||||
`rename.rs` flip: `vlog_semantic/src/{model,bind,resolve,workspace,facts}.rs`,
|
||||
the new `tests/interfaces.rs` and the `tests/workspace.rs` kind-flips;
|
||||
`lucisv_server/src/{symbols,tokens,completion,candidates,design_hierarchy,
|
||||
hierarchy,type_def}.rs` + `tests/e2e.rs`; `vlog_refactor/src/{ports,
|
||||
instantiate}.rs` + `tests/rename.rs`; `docs/features/interface-semantics/README.md`
|
||||
(new) and the four amended READMEs (`interfaces`, `ansi-first-port`,
|
||||
`type-definition`, `class-member-access`); `docs/topo.md`; `TODO.md`.
|
||||
`vlog_parser` and `editors/*` are untouched (`git diff --stat` empty for
|
||||
both). The semantic-token legend is unchanged: `tokens.rs::token_types()`
|
||||
still returns 14 entries in the same order, and `symbol_type` maps
|
||||
`Interface | Modport → Class`, `Clocking → Variable` — no new token type, no
|
||||
renumbering. No `unwrap()`/`expect()`/`panic!` was introduced outside
|
||||
`#[cfg(test)]` modules — checked every `+` line touching a changed library
|
||||
file; every `expect(...)` hit is inside a `mod tests` block.
|
||||
|
||||
### Attacking the resolver (checklist item 3)
|
||||
|
||||
Ten scratch tests beyond `interfaces.rs`'s own 24 (temporary
|
||||
`crates/vlog_semantic/tests/qa_interfaces_attack.rs`, deleted after this
|
||||
pass — no bug found, nothing to pin):
|
||||
|
||||
- A modport port naming a signal the interface lacks, with a **file-scope
|
||||
`logic other;` lure of the same name** — records nothing, does not walk out
|
||||
to the lure. **Pass.**
|
||||
- A `modport mp (...)` written inside a `module` (illegal SV) — does not
|
||||
panic, and the names it references resolve honestly against that module's
|
||||
own scope (a plausible answer for a shape that should never parse this far,
|
||||
never a wrong one). **Pass.**
|
||||
- A clocking signal that names something the interface does not declare —
|
||||
resolves to nothing. **Pass.**
|
||||
- A clocking block declared inside a module: `@(cb)` resolves to the block,
|
||||
`cb.data` resolves to the aliased signal, both in-file. **Pass** (also
|
||||
confirmed live in the shipped `a_clocking_block_in_a_module_behaves_the_same_way`).
|
||||
- `virtual bus_if.mp vif; vif.b` where `b` is a signal of the interface but
|
||||
**not** in modport `mp` — resolves to `b`'s own declaration, confirming the
|
||||
documented superset (a modport restricts direction, not membership).
|
||||
**Pass.**
|
||||
- `b_if.mp` (member access to a modport through a handle) — resolves to the
|
||||
modport symbol itself, as documented. **Pass.**
|
||||
- `bus_if.mp bus` port head, `bus.sig` inside the module body, cross-file —
|
||||
resolves to the interface's signal. **Pass.**
|
||||
- Same port head, `bus.mp` — resolves to the modport. **Pass.**
|
||||
- `remove_file` on an interface's file drops its modport and clocking block
|
||||
from `WorkspaceIndex::member` (both empty afterward). **Pass.**
|
||||
|
||||
No wrong answers, no panics, in any of the ten. Full text was in
|
||||
`scratchpad/qa_repro/qa_interfaces_attack.rs` during the pass; deleted from
|
||||
the tree per the brief (revert unless pinning a bug) since none of the ten
|
||||
found one.
|
||||
|
||||
### Corpus acceptance, reproduced exactly
|
||||
|
||||
`cargo test -p vlog_semantic --release --test corpus -- --nocapture`:
|
||||
**26 844 symbols, 99 237 references — 70.3% resolved in-file, 20.6% external,
|
||||
7.9% inherited, 1.21% unresolved (1 203), 0 names unplaced** — matches the
|
||||
README's table to the digit.
|
||||
|
||||
`cargo test -p vlog_semantic --release --test interfaces
|
||||
what_interface_semantics_cost_the_index -- --ignored --nocapture`:
|
||||
**3 149 609 store bytes, 902 units, 12 298 members, 56 249 references** —
|
||||
matches the README's table to the digit.
|
||||
|
||||
### Opentitan (checklist item 4 — the headline)
|
||||
|
||||
`git -C .../opentitan status --short`: exactly the three pre-existing
|
||||
owner-modified files (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`),
|
||||
unchanged before and after this pass. Every probe went through the release
|
||||
server over stdio (`--stdio --verbose`), `rootUri` = the opentitan root,
|
||||
`index.scope: workspace` pushed via `didChangeConfiguration` — the same
|
||||
methodology `docs/performance_take2.md` and the prior QA rounds used. No
|
||||
`lucisv <path>` was ever run directly against the tree.
|
||||
|
||||
17 probes (real corpus finds, grepped before writing the driver, not
|
||||
invented): every answer correct, zero wrong.
|
||||
|
||||
| # | construct | file:line | result | timing (cold / warm) |
|
||||
|---|---|---|---|---|
|
||||
| 1 | `vif.cb.scl_i` (`vif` a `virtual i2c_if` **task argument**, concrete type — the genuine cross-file chain the round exists for) | `i2c_agent/i2c_monitor.sv:136` | hover: `logic scl_i;` declared `i2c_if.sv:16` | 0.04 / 0.03 ms |
|
||||
| 2 | same site, `cb` | same | hover: **clocking** `cb`, declared `i2c_if.sv:30` | 0.02 / 0.01 ms |
|
||||
| 3 | same site, `scl_i`, `textDocument/definition` | same | jumps to `i2c_if.sv:16`, correct span | 0.02 / 0.01 ms |
|
||||
| 4 | `cb.scl_i` in-file | `i2c_agent/i2c_if.sv:44` | hover: `logic scl_i;` | 0.01 / 0.01 ms |
|
||||
| 5 | `clocking cb @(...)` own declaration | `i2c_if.sv:30` | hover: **clocking** `cb` | 0.01 / 0.01 ms |
|
||||
| 6 | `modport mon_tx_mp(...)` own declaration | `uart_agent/uart_if.sv:24` | hover: **modport** `mon_tx_mp` | 0.01 / 0.00 ms |
|
||||
| 7 | `clocking mon_tx_cb @(...)` own declaration | `uart_if.sv:21` | hover: **clocking** `mon_tx_cb` | 0.00 / 0.01 ms |
|
||||
| 8 | `cfg.vif.mon_tx_mp` (`cfg` a `CFG_T` class **parameter** in `dv_base_monitor`) | `uart_agent/uart_monitor.sv:49` | `null` — no elaboration of type parameters is in scope this round (documented); informational, not wrong | 0.00 ms |
|
||||
| 9 | same site, `.mon_tx_cb` | same | `null`, same reason | 0.00 ms |
|
||||
| 10 | `cfg.vif.uart_rx` (`cfg` a class parameter again) | `uart_agent/uart_driver.sv:19` | `null`, same reason | 0.00 ms |
|
||||
| 11 | `clk_rst_if clk_rst_if(...)` instantiation type name | `ip/uart/dv/tb/tb.sv:31` | hover: **interface**, declared `clk_rst_if.sv:15` | 0.10 / 0.02 ms |
|
||||
| 12 | `uart_if uart_if();` instantiation type name | `tb.sv:34` | hover: **interface**, declared `uart_if.sv:5` | 0.02 / 0.02 ms |
|
||||
| 13 | `interface clk_rst_if (` own declaration | `common_ifs/clk_rst_if.sv:15` | hover: **interface** `clk_rst_if` | 0.01 / 0.01 ms |
|
||||
| 14 | `clocking host_cb @(...)` own declaration | `tl_agent/tl_if.sv:21` | hover: **clocking** `host_cb` | 0.01 / 0.00 ms |
|
||||
| 15 | `modport host_mp(...)` own declaration | `tl_if.sv:26` | hover: **modport** `host_mp` | 0.00 / 0.00 ms |
|
||||
| 16 | `output h2d = h2d_int;` — the value-bound clocking item, live in real code | `tl_if.sv:23` | hover on `h2d_int`: the interface's own `tlul_pkg::tl_h2d_t h2d_int;` — confirms the LHS declares and only the RHS is a use | 0.00 / 0.00 ms |
|
||||
| 17 | `cfg.vif.device_cb.d2h` (`cfg` a class parameter again) | `tl_agent/tl_device_driver.sv:38` | `null` ×2, same reason | 0.00 ms |
|
||||
|
||||
Every probe answered sub-millisecond, cold and warm; the three `cfg.vif.*`
|
||||
misses (8, 9, 10, 17) are the same documented, expected shape the
|
||||
class-member-access QA round already recorded for `cfg.clk_rst_vif` — no
|
||||
elaboration of a class-typed parameter — and are informational, not defects
|
||||
(the checklist's own criterion: a missing answer on an out-of-scope shape is
|
||||
informational; only a wrong answer is REWORK-class). Probe 16 is the one
|
||||
that most directly exercises "a clocking item written `output tms = expr;`
|
||||
declares a name of the block's own... only the value is bound" against real
|
||||
UVM code rather than a fixture.
|
||||
|
||||
**Store size and scan time, trunk (`ff67281`) vs this tree**, both measured
|
||||
by running the actual release server (`--stdio --verbose`) against the full
|
||||
opentitan checkout with a cleared `~/Library/Caches/lucisv` cache each time
|
||||
(same LSP driver, same methodology as the hover probes — a stronger check
|
||||
than a synthetic probe, since it is the real served index):
|
||||
|
||||
| | before (`ff67281`) | after (this tree) |
|
||||
|---|---:|---:|
|
||||
| cold scan, 3 976 files (3 skipped) | 3 006.76 ms | 3 003.09 / 3 000.06 ms (two runs) |
|
||||
| warm-from-cache scan | — (not measured on trunk) | 1 585.71 / 1 648.33 ms |
|
||||
| on-disk index-cache file size | 31 949 117 bytes | 32 208 241 bytes (**+259 124, +0.81%**) |
|
||||
|
||||
No regression in scan time (same order as `docs/performance_take2.md`'s
|
||||
~2.9–3.0 s baseline, noise-dominated). The +0.81% cache-file growth is in the
|
||||
same direction as, and smaller in magnitude than, the README's own
|
||||
860-file-corpus figure (+1.21% of `FileFacts::encode` bytes) — the served
|
||||
cache file bundles additional index structures (path tables, etc.) the raw
|
||||
per-record byte count does not, so the two are not the same measurement, but
|
||||
both agree the interface member-table growth is modest. Probe answers were
|
||||
byte-identical across the cold and warm runs (diffed the full probe output),
|
||||
confirming determinism end to end through the real cache path, not just
|
||||
`fingerprint`/`absorb` in isolation.
|
||||
|
||||
**Diagnostics, 5 DV files with interfaces, trunk vs this tree**: `i2c_if.sv`,
|
||||
`uart_if.sv`, `tl_if.sv`, `clk_rst_if.sv`, `i2c_monitor.sv` — **0 → 0 on
|
||||
every file, both binaries.** Unchanged, as required.
|
||||
|
||||
### Other checklist items
|
||||
|
||||
- **Design hierarchy schema**: `design_hierarchy.rs`'s diff is two `units_of
|
||||
(SymbolKind::Module) → instantiable_units()` swaps plus one new pinned
|
||||
test (`an_interface_is_a_row_and_its_instance_a_child_like_any_other`,
|
||||
asserts `schemaVersion == 2` and the same row shape with an interface
|
||||
simply among the rows) — read in full, no wire-schema change. Confirmed by
|
||||
reading the diff rather than an external before/after JSON compare (the
|
||||
pinned test already is that compare, in-tree and green).
|
||||
- **Rename**: the shipped `e2e.rs` test
|
||||
(`renaming_an_interface_signal_rewrites_its_modport_clocking_and_a_handle_use`)
|
||||
covers the declaration, the modport list, the clocking block and a
|
||||
cross-file `vif.sig` handle in one edit set — read in full, correct edit
|
||||
count and line numbers. `renaming_the_modport_half_of_a_port_type_renames_the_modport`
|
||||
(the lead's flip, `vlog_refactor/tests/rename.rs:360`) covers the
|
||||
declaration-side modport rename rewriting a type-position use and leaving
|
||||
an unrelated `logic mp;` and the interface's own name alone — read in
|
||||
full, matches the Handshakes section's promise exactly.
|
||||
`bus.a` through an interface-typed **port** head was not separately pinned
|
||||
by a rename test; the qa attack suite above confirms the member access
|
||||
itself resolves correctly (`bus.sig`, `bus.mp`) and rename reads through
|
||||
the same resolution, so this is a coverage gap, not a behavior gap —
|
||||
informational, filed here rather than reworked.
|
||||
- **`program` stays `Module`**: confirmed
|
||||
(`an_interface_is_its_own_kind_and_a_program_is_not`), hover label
|
||||
"module" on a `program` — informational, documented, not a defect.
|
||||
- **Determinism**: `an_interface_survives_encode_and_decode_unchanged` and
|
||||
`incrementally_indexing_an_interface_gives_the_index_a_build_would` are
|
||||
both in `interfaces.rs` and green; this pass added
|
||||
`remove_file` dropping a modport/clocking from the member table (see
|
||||
attacks above) and confirmed probe answers are byte-identical across a
|
||||
cleared-cache cold run and a warm-from-cache run on the full opentitan
|
||||
tree.
|
||||
|
||||
### Docs (checklist item 5)
|
||||
|
||||
- Feature README: complete against the template (Goal/Assumptions/
|
||||
Handshakes/Status-TODO/Work log/QA log/Review all present).
|
||||
- The four amended READMEs (`interfaces`, `ansi-first-port`,
|
||||
`type-definition`, `class-member-access`) and `docs/topo.md`: read in full,
|
||||
accurate to the shipped code — verified `type_def.rs::type_use_at`
|
||||
literally matches `Typedef | Class | Module | Interface` as
|
||||
`type-definition`'s amendment claims, and `bind_data_type` /
|
||||
`modport_tail` literally do what `ansi-first-port`'s amendment describes.
|
||||
- **The dev's two filed requests, recorded for the lead**: (1) `editors/`
|
||||
— if VS Code ever wants a distinct interface colour, the semantic-token
|
||||
legend needs an `interface` type **appended** (never inserted) plus one
|
||||
changed arm in `tokens.rs::symbol_type`; (2) `vlog_parser` — `DataType`
|
||||
still carries no span, so `Binder::modport_tail` derives and
|
||||
double-verifies the modport tail's range by scanning; giving `DataType` a
|
||||
span (the standing `vlog-semantic` handshake item 2) would delete that
|
||||
function outright. Neither is blocking; both are exactly as filed in this
|
||||
README's Handshakes section.
|
||||
- `TODO.md` §16: QA line ticked with this session's numbers (see below).
|
||||
|
||||
## Review
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-01 — lead.** Approved and committed.
|
||||
|
||||
- Read the binder, resolver and index hunks in full. The three design calls
|
||||
are right and each is argued in the work log: `ScopeKind` unchanged (a
|
||||
scope's kind governs lookup, which module/interface/program share; what
|
||||
differs is export, a property of the declaration); `Target::InScope` for
|
||||
modport and clocking-internal names (scope-local, nothing on a miss — a
|
||||
lexical walk would have landed `modport mp (input other_if)` on a
|
||||
file-scope lure, the wrong-answer class this project forbids); and
|
||||
`Target::TypeMember { unit }` resolved through round 1's `type_here`
|
||||
three-way so the modport half of `bus_if.mp` reaches the modport in-file
|
||||
or as the composed path `bus_if::mp` cross-file with no new workspace
|
||||
machinery. The clocking block carrying `type_name` = its enclosing unit
|
||||
so `vif.cb.data` rides round 2's chase unchanged is exactly the shape the
|
||||
lead's brief sketched, and the dev verified `b_if.mp` needed no code
|
||||
rather than assuming it.
|
||||
- `SymbolKind::is_instantiable()` threaded through every Module-exact
|
||||
filter, each pinned in place, is what keeps interfaces in the module
|
||||
table, the ghost, the design hierarchy and the refactorings — behavior
|
||||
unchanged for the user while the kind becomes honest ("interface" on the
|
||||
card, `INTERFACE` in the outline). `IndexCounts.interfaces` kept separate
|
||||
so "modules" still means modules. The semantic-token legend deliberately
|
||||
not grown (its indices are wire contract) — filed for the editor lane if
|
||||
a distinct colour is ever wanted.
|
||||
- **The number that matters:** unresolved fell 1 256 → 1 203 on the corpus,
|
||||
the first movement in three rounds — the `@(cb)` / `cb.data` / `default
|
||||
clocking cb;` names that had nothing to bind. Store +1.21 % on the corpus,
|
||||
+0.81 % on opentitan; scan time unchanged.
|
||||
- **Ruling, the refactor pin**: `renaming_the_modport_half_of_a_port_type_is_refused`
|
||||
pinned the no-symbol era; a modport is a symbol now and renaming it from a
|
||||
type-position use must rewrite the declaration and every type-position use
|
||||
— flipped by the lead to `..._renames_the_modport` with a tighter set
|
||||
(count 2; the other modport, an unrelated `mp` and the interface's own
|
||||
name untouched).
|
||||
- QA re-derived the corpus numbers to the digit, ran ten scratch attacks
|
||||
(lure isolation, modport in a module, superset access through a
|
||||
modport-typed handle, `remove_file` dropping modports/clocking from the
|
||||
member table) and 17 live opentitan probes with zero wrong answers and
|
||||
every hover sub-millisecond cold and warm; the opentitan checkout holds
|
||||
only the owner's three pre-existing edits.
|
||||
- Gates re-run by the lead: fmt clean, clippy zero warnings, 2 790 passed /
|
||||
0 failed, smoke OK. `docs/topo.md`: §2.9-7 struck as delivered, handshake
|
||||
row added. Ships as 0.24.0 (FACTS_FORMAT 8).
|
||||
@@ -95,18 +95,17 @@ Promised / changed for others:
|
||||
|
||||
Requests to other owners (not done here):
|
||||
|
||||
- **`vlog_semantic`**: an interface is currently declared as
|
||||
`SymbolKind::Module`, which is what makes go-to-definition on an
|
||||
interface *instantiation* work today for free (an instantiation
|
||||
resolves its module name against the same index). Whether interfaces
|
||||
deserve their own `SymbolKind::Interface` — and with it
|
||||
`lucisv_server`'s `LspKind::INTERFACE` in `symbols.rs` instead of
|
||||
`LspKind::CLASS` — is the semantic owner's call; it is a mechanical
|
||||
change across `model.rs`, `symbols.rs`, `hover.rs` and `workspace.rs`,
|
||||
which is why it is not made here. Likewise, a `modport` name and a
|
||||
`clocking` block name are plausible symbols, and the signal names
|
||||
inside both are *references* to nets declared in the enclosing
|
||||
interface; neither is bound today.
|
||||
- ~~**`vlog_semantic`**: `SymbolKind::Interface`, plus modport and
|
||||
clocking symbols.~~ **Delivered 2026-09-01** —
|
||||
`docs/features/interface-semantics/README.md`. An interface is
|
||||
`SymbolKind::Interface`, with `LspKind::INTERFACE` and the hover label
|
||||
"interface"; a `modport` is `SymbolKind::Modport` and a named
|
||||
`clocking` block is `SymbolKind::Clocking`; every signal, method and
|
||||
block name written inside either is a reference to the enclosing
|
||||
interface's own declaration; and an interface exports its signals, so
|
||||
`vif.sig` resolves across files. Go-to-definition on an interface
|
||||
*instantiation* still works — through `SymbolKind::is_instantiable()`
|
||||
rather than through the shared kind.
|
||||
- **expressions owner**: `corpus/ibex/dv/formal/check/top.sv:432` now
|
||||
parses past its interface/`default clocking` blockers and fails on
|
||||
`(data_we_o -> …)`, the implication operator in an ordinary
|
||||
|
||||
@@ -12,6 +12,26 @@ loop, document state, position arithmetic, and one small handler per
|
||||
capability. It deliberately contains no analysis of its own; anything that
|
||||
looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
|
||||
## Starting it: the argument contract
|
||||
|
||||
`lucisv-server` needs **no arguments** — that is the spawn every editor uses,
|
||||
the one `editors/vscode/smoke.js` drives, and it is unchanged. Since
|
||||
2026-08-29 it also *accepts* exactly one:
|
||||
|
||||
| argument | effect |
|
||||
|---|---|
|
||||
| *(none)* | The shipped server. Silent unless something is worth saying. |
|
||||
| `--verbose` | Every operation says how long it took, as `timing:` lines in the client's log channel (`window/logMessage`, `MessageType::LOG`). Repeats are idempotent. See `docs/features/verbose-timing/README.md` |
|
||||
| `--stdio` | Accepted and changes nothing: stdio is the only transport this server has. It is here because `vscode-languageclient` appends it for `TransportKind.stdio` — the spawn every real VS Code session makes — and rejecting it crashed the extension the moment strict parsing shipped (lead hotfix, 2026-08-29). The smoke and restart harnesses spawn the binary directly, which is why nothing in the loop caught it; `smoke.js` now spawns with `--stdio` so the library's real spawn shape stays covered. |
|
||||
| anything else | `error: unknown option: <arg>` and `usage: lucisv-server [--verbose] [--stdio]` on **stderr**, exit **2** — the CLI's own wording and its "an error occurred" code. Nothing is started |
|
||||
|
||||
There is no `-v`, no `--help` and no `--version`: one spelling for the one
|
||||
flag, and the version number lives on the `lucisv` CLI, which is where
|
||||
`tools/release.sh` reads it. Anything that is not a startup decision is an
|
||||
`lucisv.*` setting instead, pushed or pulled over the protocol — a flag can
|
||||
only be changed by spawning again, which is why `lucisv.verbose` is the one
|
||||
VS Code setting that restarts the server.
|
||||
|
||||
## Capabilities as shipped
|
||||
|
||||
| LSP request | Engine it consumes | Notes |
|
||||
@@ -28,7 +48,7 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` |
|
||||
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built |
|
||||
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md` |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md`. The `file:line` half of a cross-file heading costs **no file access**: the line is recorded when the file is indexed (`Def::lines`), so only the snippet still reads, once per file per generation of it through `Workspace::file_view`: `docs/features/hover-line-index/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
|
||||
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
|
||||
@@ -270,6 +290,19 @@ folder brings it into scope. `"lucisv.index.scope": "workspace"` restores the
|
||||
pre-2026-08-27 behaviour in full. Rules, the clamp, the close decision and the
|
||||
one `.gitignore` gap: `docs/features/index-scope/README.md`.
|
||||
|
||||
**And scope-relative in *time*, since 2026-08-28** (scan-interleave). A
|
||||
**startup** scan of more than 64 files no longer blocks the message loop: it
|
||||
indexes one file at a time and answers whatever the client has already sent
|
||||
between two of them, so the first request of a session comes back in
|
||||
milliseconds instead of waiting out the whole scan (780 ms → 15.5 ms cold over
|
||||
200 files). The price is that such an answer reflects the index **as of that
|
||||
moment** — a declaration in a file the scan has not reached yet does not exist
|
||||
yet, in exactly the sense a declaration outside the scope does not exist. Two
|
||||
narrowings keep that from reaching anywhere it is not worth it: a scan of 64
|
||||
files or fewer runs one shot as it always did, and a request queued *behind* a
|
||||
message that asked for a rescan waits for that rescan, so the loop's order
|
||||
contract is unchanged. `docs/features/scan-interleave/README.md`.
|
||||
|
||||
**Open buffers override disk** in every index rebuild: the scope is walked,
|
||||
each file read, and then every open document with a path replaces the disk
|
||||
copy (adding itself if it exists only in the editor). So the index never
|
||||
@@ -478,9 +511,12 @@ called by the request handler.
|
||||
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
|
||||
Result<String, FormatError>` and `Config { max_width, indent_width }`.
|
||||
|
||||
**Promised to nobody yet.** This crate is a leaf: it has no library target and
|
||||
nothing depends on it. The editor packaging round (TODO.md §6) will consume
|
||||
the binary's name and its stdio contract, nothing else.
|
||||
**Promised to the editors:** the binary's name, its stdio contract, and — since
|
||||
2026-08-29 — its *argument* contract: no arguments required, `--verbose` the
|
||||
only one accepted, every other one refused with exit 2 (the table under
|
||||
"Starting it" above; TOPO.md §1.2's `editors/vscode ◀──▶ lucisv_server` row;
|
||||
`docs/features/verbose-timing/README.md`). Beyond that this crate is a leaf: it
|
||||
has no library target and nothing in the workspace depends on it.
|
||||
|
||||
**Requested of other modules** — none of these block this round, and none was
|
||||
done here:
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
# null-items
|
||||
|
||||
## Goal
|
||||
|
||||
Accept the **null item** — a lone `;` written where a module, generate,
|
||||
package, interface, program or class item belongs, and at file scope. It is
|
||||
legal SystemVerilog (IEEE 1800-2017 A.1.4:
|
||||
`package_or_generate_item_declaration ::= … | ;`, `class_item ::= … | ;`, and
|
||||
`description → package_item` reaches it at file scope), it means nothing, and
|
||||
people write it all the time — after `endgenerate`, after a generate block's
|
||||
`end`, after `endmodule`. lucisv rejected every one of those with
|
||||
`parse error: expected item (found ";")`, which is what the owner hit when
|
||||
they wrote `endgenerate;` after a perfectly good generate-`for` loop. (The
|
||||
generate-`for` itself was never the problem: every spelling of it already
|
||||
parsed and round-tripped, and this feature pins three real-world examples to
|
||||
keep it that way.)
|
||||
|
||||
Three things ship together: `ItemKind::Empty` in the parser, a
|
||||
token-preserving layout rule in the formatter (a `;` written on the same line
|
||||
as the item before it stays on that line), and a default-on lint,
|
||||
`empty-item`, whose safe fix deletes the `;` — the equivalent of slang's
|
||||
`-Wempty-member` ("an unnecessary semicolon is located in a non-procedural
|
||||
scope (such as a module body)"). The procedural sibling — the null
|
||||
*statement*, `initial begin ; end` — already worked and is untouched, as is
|
||||
`endfunction;`/`endtask;`, which the `end_semi` flag on `FunctionDecl` /
|
||||
`TaskDecl` has recorded since the classes round (`parser.rs`,
|
||||
`parse_function_decl`: "the stray `;` is a null class item"). That flag is the
|
||||
precedent this work generalizes; it is deliberately left alone, so the two
|
||||
mechanisms do not overlap.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A `;` at item position is always a null item.** Nothing else in the item
|
||||
grammar can start with `;`, so the one-token test in `parse_item_kind` is
|
||||
unambiguous. Before this change the token was a hard error there, so no
|
||||
previously-parsing source changes meaning.
|
||||
- **`endfunction;` / `endtask;` keep going through `end_semi`.** The parser
|
||||
consumes that `;` inside `parse_function_decl`/`parse_task_decl` before the
|
||||
item loop ever sees it, so it never becomes an `ItemKind::Empty`. Two
|
||||
spellings of the same source fact would be worse than one; the existing one
|
||||
already prints back where it was written.
|
||||
- **"Same line" is a question about the previous *sibling item*, not the
|
||||
previous token.** See Handshakes for the argument; the consequence is that a
|
||||
null item that is the *first* item of a body always prints on its own line
|
||||
(`module m;` ⏎ ` ;` ⏎ `endmodule`, `generate` ⏎ ` ;` ⏎ `endgenerate`),
|
||||
because there is no sibling to glue to.
|
||||
- **A `//` comment can never stand between the previous item and a glued
|
||||
`;`.** It would swallow the `;` to end of line, so the only comment that
|
||||
fits in a newline-free gap is a single-line block comment, which prints
|
||||
inline and keeps the `;` after it. This is what makes gluing safe: the
|
||||
formatter can never append `;` after a line comment.
|
||||
- **A null item declares nothing and references nothing**, so
|
||||
`vlog_semantic`'s `bind.rs` treats it as a leaf, and `vlog_linter`'s
|
||||
catch-all `visit.rs` walk needs no arm.
|
||||
- **The 820-file corpus contains no null item**, so its output must stay
|
||||
byte-identical. Any drift there is a bug in this feature, not a style
|
||||
change.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Consumed
|
||||
|
||||
- `vlog_parser::ast::Item`/`Meta` — the null item's comments ride the ordinary
|
||||
`Meta` (leading, trailing), exactly like any other item; its `span` is the
|
||||
`;` token alone.
|
||||
- `vlog_formatter`'s `Fmt::src` and item spans — the same way `align.rs` and
|
||||
`format.rs`'s `eq_offset` / `open_paren_offset` / `default_has_colon`
|
||||
already ask the source a layout question the AST does not answer.
|
||||
- `vlog_linter`'s `registry::Rule`, `visit::walk_items`, `Fix::safe` and the
|
||||
`.lint` harness's `----` fix section.
|
||||
|
||||
### Promised (exhaustive-match arms this variant costs)
|
||||
|
||||
Per `docs/topo.md` §3.3, a new `ItemKind` variant costs an arm everywhere the
|
||||
match is exhaustive. Added by this lane:
|
||||
|
||||
| file | arm |
|
||||
|---|---|
|
||||
| `crates/vlog_parser/src/ast.rs` | the variant itself, `ItemKind::Empty` |
|
||||
| `crates/vlog_parser/src/parser.rs` | `parse_item_kind`'s `;` branch |
|
||||
| `crates/vlog_parser/tests/spans.rs` | `ItemKind::Empty => {}` (a leaf; the item's own span is checked by the caller) |
|
||||
| `crates/vlog_formatter/src/format.rs` | `item_kind`'s `ItemKind::Empty => text(";")`, plus the `item_seq` glue rule |
|
||||
| `crates/vlog_semantic/src/bind.rs` | folded into the leaf group `\| ItemKind::Verbatim(_) => {}` |
|
||||
|
||||
Catch-all matches that needed nothing, confirmed by compiling: `vlog_linter`'s
|
||||
`visit.rs` / `signals.rs`, `vlog_formatter`'s `fence.rs` / `range.rs` /
|
||||
`verify.rs`, `vlog_refactor`'s `ports.rs` / `instantiate.rs`, `vlog_semantic`'s
|
||||
`instantiations.rs` / `classes.rs`, and the server's `completion.rs`,
|
||||
`type_def.rs`, `linked.rs`, `selection.rs`, `symbols.rs`, `tokens.rs`,
|
||||
`on_type.rs`, `type_hierarchy.rs`.
|
||||
|
||||
### The glued/own-line decision, and where "same line" is decided
|
||||
|
||||
**Decided in the formatter, from `src` spans; no parser flag.** `item_seq` is
|
||||
the one place that emits the separator between two sibling items, and the
|
||||
question the glue asks is exactly the one it is already answering ("what goes
|
||||
between item *n-1* and item *n*"). A parser-recorded flag would answer a
|
||||
*different* question — "was there a newline since the previous **token**" —
|
||||
which differs precisely where it matters least and hurts most: for the first
|
||||
item of a body the previous token is the opener (`generate`, the header `;`,
|
||||
`begin`), and gluing there would mean reaching back into a construct's
|
||||
header layout from its body's item list. It would also put a formatter-only
|
||||
layout fact into the AST that every other consumer must ignore. The source
|
||||
check is one `contains('\n')` over the gap between the previous item's
|
||||
`span.end` and the `;`'s `span.start`, which is the established idiom in this
|
||||
file.
|
||||
|
||||
The rule, then:
|
||||
|
||||
- a null item whose `;` has **no newline** between it and the previous
|
||||
sibling item prints **glued** to that item's last line: `endgenerate;`,
|
||||
`end;`, `;;`, `endmodule;`;
|
||||
- **otherwise** — a newline in the gap, no previous sibling, a leading
|
||||
comment, an attribute, or a format-off fence opening on it — it prints `;`
|
||||
on its own line at the current indent.
|
||||
|
||||
Both are fixed points: re-parsing glued output finds no newline in the gap and
|
||||
glues again; re-parsing own-line output finds one and does not. Both
|
||||
directions are pinned in `tests/cases/null_items.cases`.
|
||||
|
||||
Alignment: `param_decl_row` returns `None` for any non-`ParamDecl` item and
|
||||
`align_groups` breaks a run at a `None` row, so a null item between two
|
||||
`parameter` declarations splits the alignment group with no new code. Pinned
|
||||
by a case.
|
||||
|
||||
### Filed (nothing)
|
||||
|
||||
No cross-module request; nothing is owed by another module. Every file this
|
||||
lane touched:
|
||||
|
||||
| file | change |
|
||||
|---|---|
|
||||
| `crates/vlog_parser/src/ast.rs` | `ItemKind::Empty` |
|
||||
| `crates/vlog_parser/src/parser.rs` | the `;` branch in `parse_item_kind` |
|
||||
| `crates/vlog_parser/tests/spans.rs` | the leaf arm |
|
||||
| `crates/vlog_parser/tests/null_items.rs` | **new** — the per-scope parser tests the brief asked for |
|
||||
| `crates/vlog_formatter/src/format.rs` | `item_kind` arm, `item_seq` glue, `glued_null_item` |
|
||||
| `crates/vlog_formatter/tests/cases/null_items.cases` | **new** — 22 layout/idempotency cases |
|
||||
| `crates/vlog_formatter/tests/verification.rs` | three masked-corruption pairs |
|
||||
| `crates/vlog_semantic/src/bind.rs` | the leaf arm |
|
||||
| `crates/vlog_linter/src/rules/empty_item.rs` | **new** — the rule |
|
||||
| `crates/vlog_linter/src/rules/mod.rs` | `pub mod empty_item;` |
|
||||
| `crates/vlog_linter/src/registry.rs` | one line in `all_rules()` |
|
||||
| `crates/vlog_linter/tests/cases/empty_item.lint` | **new** — 20 lint/fix cases |
|
||||
| `docs/features/null-items/README.md` | **new** — this document |
|
||||
| `TODO.md` | §14 ticked |
|
||||
|
||||
`vlog_formatter/src/align.rs` was **not** touched: the group split falls out
|
||||
of `param_decl_row` returning `None`, so the rule the brief allowed for was
|
||||
not needed. `verify.rs` was not touched either (invariant 4). Two files are
|
||||
outside the brief's literal list and are recorded here rather than assumed:
|
||||
`vlog_parser/tests/null_items.rs` (the brief asked for parser unit tests but
|
||||
named no file) and `vlog_linter/src/rules/mod.rs` (a new rule module cannot
|
||||
be registered without it).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `ItemKind::Empty` — a leaf variant, span = the `;`, comments through
|
||||
`Meta`.
|
||||
- [x] `parse_item_kind` accepts `;`; every item list reaches it (they all go
|
||||
through `item_or_recover` → `parse_item`).
|
||||
- [x] Tolerant mode emits no diagnostic for it (it is a successful parse, not
|
||||
a recovery).
|
||||
- [x] Formatter: glued / own-line layout, idempotent both ways.
|
||||
- [x] Alignment groups are not joined across a null item.
|
||||
- [x] Blast-radius arms (`format.rs`, `bind.rs`, `spans.rs`).
|
||||
- [x] `verify.rs` untouched; three rejection pairs added to
|
||||
`tests/verification.rs` anyway.
|
||||
- [x] Lint `empty-item`, default on, safe fix, `.lint` case with fix output.
|
||||
- [x] `tests/cases/null_items.cases` — the owner's shape, every reproduction,
|
||||
slang's two examples, three systemverilog.io generate examples.
|
||||
- [x] Parser unit tests per scope.
|
||||
- [x] `TODO.md` §14 ticked.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-01 — dev
|
||||
|
||||
Reproduced the lead's list against the tree at `1e30ea0` first: `b.sv`
|
||||
(`endgenerate;`), `e.sv` (lone `;` at module scope), `f1` (`generate ;
|
||||
endgenerate`), `f2` (`end;` inside a region), `f3`/`f4`/`f5`
|
||||
(package/interface/class), `f7` (`endmodule;`), `f9` (region-less `end;` and
|
||||
`;;`) all failed with `expected item (found ";")`; `a`/`c`/`d` (three
|
||||
generate-`for` spellings), `f8` (procedural null statement) and `f6`
|
||||
(`endfunction;`/`endtask;`) already passed. Same verdicts the lead reported.
|
||||
|
||||
**Parser.** `ItemKind::Empty` added to `ast.rs` as a unit variant directly
|
||||
before `Error`, and one branch at the top of `parse_item_kind`:
|
||||
|
||||
```rust
|
||||
if self.cur().is_sym(";") {
|
||||
self.bump();
|
||||
return Ok(ItemKind::Empty);
|
||||
}
|
||||
```
|
||||
|
||||
Every item list in the parser — file, module/interface/program body, package
|
||||
body, class body, `generate` region, `parse_gen_block`'s begin/end body and
|
||||
its single-item body — goes through `item_or_recover` → `parse_item` →
|
||||
`parse_item_kind`, so one branch covers all eight scopes. Verified by test
|
||||
rather than by reading, per the brief: `tests/null_items.rs` parses one case
|
||||
per scope strictly and asserts an `Empty` item with `src[span] == ";"`.
|
||||
|
||||
The branch sits *before* the `TokenKind` match, not inside it, because the
|
||||
lexer's symbol tokens are matched by text (`is_sym`), not by a `TokenKind`
|
||||
variant per symbol; that is how the rest of the file tests for punctuation.
|
||||
|
||||
**Formatter.** `item_kind` gets `ItemKind::Empty => text(";")`. The layout
|
||||
lives in `item_seq`, which now tracks the previous item that actually emitted
|
||||
docs and suppresses the separator when `glued_null_item` says so. The
|
||||
predicate refuses to glue when the null item has a leading comment, an
|
||||
attribute, a blank line before it, or a fence opening on it — each of those
|
||||
gives the `;` docs of its own that must not be appended to the previous
|
||||
line — and finally asks the source whether the gap holds a newline.
|
||||
|
||||
**Blast radius.** `cargo check --workspace` named exactly three other
|
||||
exhaustive matches: `format.rs` (the arm above), `bind.rs` (folded into the
|
||||
existing leaf group), `spans.rs` (`Empty => {}`). Nothing else in the eight
|
||||
crates or the server needed a line, which the Handshakes table records.
|
||||
|
||||
**Safety net.** `verify.rs` untouched, per CLAUDE.md invariant 4. Three
|
||||
masked-corruption pairs added to `tests/verification.rs`: an output that drops
|
||||
the `;`, one that moves it to the other side of a comment, and one that moves
|
||||
an item-level `;` into an adjacent procedural block. All three are rejected by
|
||||
the net as it stands, which is the point of writing them down.
|
||||
|
||||
**Lint.** `empty-item`, default on, safe fix, listed between
|
||||
`case-missing-default` and `enum-name-style` (the registry is asserted
|
||||
alphabetical). The fix deletes the `;` plus the horizontal whitespace before
|
||||
it, and takes the newline too when what stood on that line was nothing but
|
||||
whitespace and other null items — so `;;;` on a line leaves no blank line
|
||||
behind, while `endgenerate; // note` becomes `endgenerate // note` with the
|
||||
comment untouched and `; // why` leaves the comment on its line. A final
|
||||
guard refuses to emit a fix whose range covers anything but `;` and
|
||||
whitespace: the range is built so that it cannot, and the check makes
|
||||
"comments are never dropped" true by construction rather than by argument.
|
||||
Both shapes are in `tests/cases/empty_item.lint`, whose harness re-lints to a
|
||||
fixpoint and re-formats the fixed text.
|
||||
|
||||
**Cases.** `tests/cases/null_items.cases`: 22 cases — the owner's shape, each
|
||||
reproduction from the lead's list, slang's `-Wempty-member` / `-Wempty-stmt`
|
||||
examples, the glued/own-line idempotency pair in both directions, the
|
||||
comment shapes, the alignment-group split, and the three systemverilog.io
|
||||
generate examples verbatim (16-input mux, `assert property` inside a
|
||||
generate-`for`, the memory `case` with a nested `for` and hierarchical
|
||||
instantiations) so a regression in generate-`for` is caught here too. The
|
||||
harness re-formats every expected output, so each case is an idempotency
|
||||
assertion as well as a layout one.
|
||||
|
||||
Parser coverage lives in `crates/vlog_parser/tests/null_items.rs`: one source
|
||||
per scope, asserting `src[span] == ";"`; the `;;;` split; the comment
|
||||
attachment; tolerant mode's silence; and that `endfunction;`/`endtask;` still
|
||||
produce no null item.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets
|
||||
--workspace` zero warnings; `cargo test --workspace` 2709 passed / 0 failed
|
||||
(1 formatter case-table run covering 22 new cases, 1 lint case-table run
|
||||
covering 21 new ones, 6 new parser tests, 3 new verification tests);
|
||||
`scripts/corpus_gate.sh corpus` → `{"passing":813,"total":820,"pct":99.1}`,
|
||||
exit 0, zero verification errors and zero crashes — the baseline unchanged.
|
||||
Byte-identity was measured directly rather than inferred: a worktree at
|
||||
`1e30ea0` was built and both binaries were run over all 820 corpus files —
|
||||
**813 identical, 0 differing, 7 refused by both** (release and debug builds
|
||||
agree). `cargo build -p lucisv_server` + `node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` → OK, 20 messages.
|
||||
|
||||
Hand checks beyond the suites, each re-formatted to confirm a fixed point: a
|
||||
null item after a `` `define`` and inside both arms of an `` `ifdef``; `` `endif; ``;
|
||||
a CRLF file; an attributed `(* keep *) ;`; and `--lines` range runs that touch
|
||||
the null item, the item before it and neither.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-01 — QA
|
||||
|
||||
**Verdict: SHIP.**
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` zero warnings. `cargo test --workspace`: 2709 passed / 0 failed
|
||||
before my addition, matching the dev's number exactly (summed every `test
|
||||
result:` line by hand); 2710 / 0 after adding one more verification test
|
||||
(below). `scripts/corpus_gate.sh corpus` →
|
||||
`{"passing":813,"total":820,"pct":99.1,...}` with all four failure categories
|
||||
at their pre-existing counts, 0 verification errors, 0 crashes. `cargo build
|
||||
-p lucisv_server` + `node editors/vscode/smoke.js target/debug/lucisv-server`
|
||||
→ OK, 20 messages.
|
||||
|
||||
**Scope.** `git status --porcelain` / `git diff --stat` match the README's
|
||||
file list exactly, with one addition the dev's list did not carry:
|
||||
`docs/topo.md` (a `null-items` row added to §2.1 and §2.4, plus the doc-count
|
||||
line and the `vlog_parser` feature-list row bumped) — reasonable and
|
||||
consistent with how every other single-lane feature in this repo's history
|
||||
self-registers in topo.md; not flagged as scope creep. `verify.rs` confirmed
|
||||
absent from the diff (`git diff --name-only | grep verify.rs` → nothing).
|
||||
No `unwrap()`/`expect()`/`panic!` introduced in library code — the two
|
||||
`format.rs` matches (declarators, guarded by `items.len() == 1`) and every
|
||||
`parser.rs`/`registry.rs` match are pre-existing and sit inside `#[cfg(test)]`
|
||||
modules, confirmed by diff (this feature's parser.rs diff is exactly the
|
||||
6-line `;`-branch add; nothing near those test lines).
|
||||
|
||||
**Doc finding (fixed directly, low severity).** The Filed table
|
||||
(README:144, and the identical claim in `TODO.md`'s round-up) said
|
||||
`empty_item.lint` holds "21 lint/fix cases"; counting `====`-delimited blocks
|
||||
and `# ` case-name headers gives **20** (7 carry a `----` fix section, not
|
||||
8). Miscount only — the harness (`lint_case_tables`) counts the same file the
|
||||
same way and every case passes; nothing about the shipped behavior changes.
|
||||
Fixed the README's line to 20; left `TODO.md`'s narrative prose alone since
|
||||
it does not state a count. `null_items.cases`' claimed 22 is exact (`grep -c
|
||||
'^# '` → 22).
|
||||
|
||||
**Parser + formatter attack (scratch `cargo run --example`, reverted after —
|
||||
nothing here needed pinning beyond what the dev already has).** Every scope
|
||||
in the checklist: first/last item of a module body, between two `assign`s in
|
||||
an alignment group (splits correctly, columns differ across the split —
|
||||
confirmed against the case at README-adjacent `null_items.cases:186`),
|
||||
immediately after `(* attr *)`, both arms of `` `ifdef ``/`` `else ``/``
|
||||
`endif ``, a `;` directly after `` `endif ``, after the `generate` keyword,
|
||||
after `endgenerate`, `end;` after generate-`for`/generate-`if`/named
|
||||
(`end : g;`) blocks, `;;;`, class/package/interface(with modport)/program
|
||||
bodies, file scope between `endmodule` and `module`. All parsed, formatted,
|
||||
and idempotent (`format(format(x)) == format(x)` checked directly, not just
|
||||
via the case harness). Comment shapes — trailing line comment glued
|
||||
(`endgenerate; // note`), trailing block comment glued, a block comment
|
||||
alone on the null item's line, a line comment separating `endgenerate` from
|
||||
a next-line `;` (stays own-line, correctly not glued across it), a leading
|
||||
comment with a blank line above (blank preserved) — all round-tripped
|
||||
correctly. CRLF file with `endgenerate;\r\n` formats and converges (CRLF→LF
|
||||
is pre-existing general formatter behavior, not particular to this feature).
|
||||
|
||||
**One interaction checked and found pre-existing, not a regression.** A
|
||||
`;` on its own line immediately after `endfunction` (e.g. inside a class,
|
||||
between two methods) never becomes an `ItemKind::Empty`: `parse_function_decl`'s
|
||||
`end_semi = self.eat_sym(";")` (parser.rs, untouched by this diff) is
|
||||
whitespace/newline-blind — it eats the very next token regardless of an
|
||||
intervening newline — so that `;` is absorbed into `FunctionDecl::end_semi`
|
||||
and reprinted glued onto `endfunction`'s line, changing layout (not content)
|
||||
on the first pass. Verified byte-for-byte identical on a worktree built from
|
||||
`1e30ea0` (pre-feature) with the same input: this is standing `end_semi`
|
||||
behavior this feature explicitly declines to touch (Assumptions), not
|
||||
something introduced here. No action taken.
|
||||
|
||||
**Safety net (verify.rs).** Read all three new tests (7 pairs): dropped `;`
|
||||
in two directions plus an invented one, a null item moved across a one-line
|
||||
block comment (both directions: comment-then-semicolon vs
|
||||
semicolon-then-comment, and a leading full-line comment swapped past the
|
||||
`;`), and a null item's `;` swapped between an item slot and a procedural
|
||||
statement slot. Ran `cargo test -p vlog_formatter --test verification
|
||||
null_item` — all 3 tests / 7 pairs pass (i.e. `verify_equivalence` correctly
|
||||
returns `Err` for every one). Read `verify.rs` in full: it is a strict
|
||||
positional token-stream comparison (whitespace-blind, with only multi-line
|
||||
directive/attribute/comment text trimmed per-line and the `@(*)`
|
||||
canonicalization) — nothing in it forgives a token reorder, so every pair
|
||||
above was expected to be rejected by construction, not by luck.
|
||||
|
||||
Added the checklist's suggested gap test — a null item carried from one
|
||||
`` `ifdef `` arm to the other — as
|
||||
`a_null_item_moved_from_one_ifdef_arm_to_the_other_is_rejected` in
|
||||
`crates/vlog_formatter/tests/verification.rs` (kept; it is a real
|
||||
regression pin, distinct from the existing pairs since the item list is
|
||||
flat across `Directive` items and a directive-adjacent reorder was the one
|
||||
shape not yet attacked). Confirmed rejected; noted in the test's own comment
|
||||
that this was expected to hold given `verify.rs`'s positional design, so
|
||||
this is a pinned confirmation, not a bug find.
|
||||
|
||||
**LSP smoke (checklist item 3, tolerant mode + diagnostics + code action).**
|
||||
`crates/vlog_parser/tests/null_items.rs::tolerant_parsing_reports_no_diagnostic`
|
||||
covers the parser side. For the editor-visible side, drove
|
||||
`target/debug/lucisv-server` headlessly over stdio (hand-rolled framing
|
||||
copied from `editors/vscode/smoke.js`'s pattern, run from the scratchpad, not
|
||||
added to the tree): opened a buffer containing `endgenerate;`, requested
|
||||
`textDocument/codeAction` over the `;`. Result: `publishDiagnostics` carries
|
||||
no parse-error (severity-1) diagnostic, only an `empty-item` warning
|
||||
(severity 2, code `empty-item`, message "unnecessary `;`; a null item does
|
||||
nothing"); the code action response offers both the single-finding quick fix
|
||||
(`lucisv: drop a `;` that stands where an item belongs [empty-item]`,
|
||||
`isPreferred: true`) and `source.fixAll.lucisv`, both producing the correct
|
||||
edit. Exactly the "warning, not a parse error, with a working fix" contract
|
||||
the checklist asks for.
|
||||
|
||||
**Opentitan sweep (read-only throughout).** `git -C
|
||||
/Users/guoliangchen/repo/opentitan status --porcelain` before and after:
|
||||
unchanged, exactly the three expected pre-existing owner-modified files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`). Swept all 3,943 real `.sv`/`.svh` files
|
||||
(32 symlinks excluded, same file count the clocking-wave baseline used) with
|
||||
this feature's release `lucisv --no-cache --check`: **12** files exit
|
||||
outside {0,1}, not 11 — but the 12th is
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, one of the three files with a local
|
||||
uncommitted owner edit (`parse error: 749:1: expected declaration or
|
||||
instantiation (found "as")`, clearly mid-edit). Built a second release
|
||||
binary from a `git stash` of this feature's diff (i.e. trunk `1e30ea0`) and
|
||||
swept the identical file list: **same 12 files, byte-identical set** (`diff`
|
||||
of the two sorted failing-file lists is empty). So the standing 11-failure
|
||||
grammar baseline is unchanged, and the 12th is the owner's own local WIP on
|
||||
a file already flagged as "leave alone" — not a lucisv regression in either
|
||||
direction, and not something this feature's parser change touches (it is a
|
||||
`typedef`/enum-ish token error, nothing to do with a null item). Restored
|
||||
this feature's worktree state (`git stash pop`) and rebuilt before
|
||||
continuing; `git status --porcelain` on the lucisv tree also confirmed clean
|
||||
of scratch artifacts (temporary `cargo run --example` files removed after
|
||||
use). Lint sweep: `lucisv check --no-cache` over all 3,943 files, `grep -c
|
||||
empty-item` → **0** — opentitan has no null items, matching the feature's
|
||||
own stated assumption.
|
||||
|
||||
**Overall:** every gate green, scope matches modulo the topo.md
|
||||
self-registration (normal), one doc miscount fixed, one interaction traced
|
||||
to pre-existing `end_semi` behavior and confirmed not a regression, the
|
||||
safety net's 7 pairs plus 1 QA-added pair all correctly rejected, the LSP
|
||||
contract (warning + working fix, no false parse error) verified live, and
|
||||
the opentitan sweep confirmed byte-identical to trunk. No blocking findings.
|
||||
|
||||
## Review
|
||||
|
||||
*(reserved for the lead)*
|
||||
|
||||
**2026-09-01 — lead.** Approved and committed.
|
||||
|
||||
- The owner's report was "for loop inside generate"; the lead's diagnosis
|
||||
before dispatch was that every generate-for spelling — and the three
|
||||
systemverilog.io examples — already parsed, and that the failing token was
|
||||
the null item after `endgenerate`. The dev built exactly that, and the
|
||||
case file pins both halves: the online examples (so a generate-for
|
||||
regression is caught here too) and every null-item scope.
|
||||
- Read the load-bearing code in full. The parser branch is one line at the
|
||||
top of `parse_item_kind`. `glued_null_item` refuses any `;` that carries
|
||||
docs of its own (leading comment, attribute, blank line, fence), so the
|
||||
glue only ever appends a bare `;` — and deciding it from `src` spans in
|
||||
`item_seq` rather than a parser flag is the right call: it is a layout
|
||||
fact about the gap between siblings, asked where that gap is laid out,
|
||||
the same idiom `eq_offset` and `default_has_colon` use. The lint's
|
||||
`deletion` range ends in a guard that admits only `;`/whitespace bytes,
|
||||
which makes swallowing a same-line comment structurally impossible
|
||||
(invariant 3), and `;;` yields two adjacent non-overlapping fixes.
|
||||
- Exhaustive-arm cost was exactly the three §3.3 predicts (`format.rs`,
|
||||
`bind.rs`, `tests/spans.rs`); every other walker is catch-all. `verify.rs`
|
||||
untouched, seven attack pairs from the dev plus QA's eighth (a `;` moved
|
||||
between `` `ifdef `` arms), all rejected.
|
||||
- Corpus byte-identical at 813/820, measured by the dev against a
|
||||
pre-change worktree and re-run by QA. Opentitan sweep identical to trunk
|
||||
file-for-file (the twelfth "failure" is the owner's in-progress `ast.sv`
|
||||
edit, present before the round); `empty-item` fires zero times there,
|
||||
confirming the tree has no null items and nothing moved.
|
||||
- QA's informational note stands as designed: an own-line `;` right after
|
||||
`endfunction`/`endtask` is still absorbed by the older `end_semi`
|
||||
mechanism rather than becoming `ItemKind::Empty`; behavior is unchanged
|
||||
from trunk and the lint deliberately does not report it. Worth a future
|
||||
tidy (fold `end_semi` into the null item) but not this round's.
|
||||
- Gates re-run by the lead before commit: fmt clean, clippy zero warnings,
|
||||
full suite green (2 710), corpus gate 813/820, smoke OK. `docs/topo.md`
|
||||
gains a grammar-lane row and a linter-lane row. Ships as 0.21.0 —
|
||||
formatter output changes for files that contain a null item, so the
|
||||
version bump is owed by the format-cache rule as well.
|
||||
@@ -0,0 +1,437 @@
|
||||
# out-of-class constraints
|
||||
|
||||
## Goal
|
||||
|
||||
Parse the **out-of-block constraint definition** — `constraint C::name { ... }`
|
||||
written at file or package scope, the body of a class's `extern constraint`
|
||||
prototype (IEEE 1800 §18.5.2) — in both strict and tolerant modes. It is the
|
||||
constraint sibling of `function C::method(...)`, which lucisv has parsed since
|
||||
the `classes` round. `syntax_coverage.md`'s bucket 1 measured it as the single
|
||||
largest gap in the OpenTitan sweep: **45 files** blocked outright, and — the
|
||||
real damage — a tolerant-mode recovery cascade that turned one construct into
|
||||
up to **322** spurious diagnostics in a single buffer, because the parse error
|
||||
lands one token into a construct whose body the recovery loop then resynchronizes
|
||||
inside. A widely-`` `include``d DV base class in that state is not "slightly
|
||||
degraded" in an editor; it is unusable for diagnostics.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The scope prefix carries no meaning lucisv needs.** The whole item is an
|
||||
`ItemKind::Verbatim` leaf, so nothing downstream asks which class a
|
||||
constraint belongs to. The chain is consumed and discarded, exactly as the
|
||||
body's `dist`/`solve`/`->` grammar is copied rather than modelled. If a
|
||||
future round wants "go to the `extern constraint` prototype from its
|
||||
definition," it will need a real node — see Handshakes.
|
||||
- **Any `::` chain length is accepted** (`pkg::cls::name`), because
|
||||
`parse_method_name` — the out-of-body method path being reused — accepts
|
||||
one, and rejecting longer chains would be extra code buying nothing. The
|
||||
corpus only exhibits the two-part form (88 of 88 occurrences across the 45
|
||||
files; measured, not assumed).
|
||||
- **No new legal-position check.** `constraint C::name { ... }` is now accepted
|
||||
wherever a plain `constraint name { ... }` was, including inside a class
|
||||
body, where the LRM does not permit it. lucisv is a formatter, not an
|
||||
elaborator; the existing `parse_constraint` already accepts a bare
|
||||
`constraint c;` prototype at file scope for the same reason. Being more
|
||||
permissive than the LRM in a position no real code writes costs nothing and
|
||||
keeps the change to one call.
|
||||
- The `.cases` and fixture harnesses auto-discover their files, so a new
|
||||
`.cases` file is additive (relied on when placing the formatter coverage —
|
||||
see Handshakes).
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed, unchanged:**
|
||||
|
||||
- `classes` — `verbatim_since` / `skip_balanced` / `RawText`, and
|
||||
`ItemKind::Verbatim` as the leaf. No change to any of them. This round is
|
||||
the sixth producer of `ItemKind::Verbatim` and adds no variant, so the
|
||||
`topo.md` §2.2 new-AST-variant checklist (formatter arm, `bind.rs` arm,
|
||||
`spans.rs` arm, `visit.rs` arm) **does not apply**: every consumer already
|
||||
has its `ItemKind::Verbatim` arm and none of them changed.
|
||||
- `classes` — `parse_method_name`, the out-of-body `C::method` scoped-name
|
||||
path, now called from `parse_constraint` as well. Its contract is unchanged
|
||||
(it splits a `::` chain into scope + final name); this caller keeps neither
|
||||
half.
|
||||
- `error-recovery` — `parse_source_tolerant` is untouched. The cascade
|
||||
collapse is a pure consequence of the construct parsing: no error node is
|
||||
produced, so there is nothing to resynchronize from.
|
||||
|
||||
**Promised to others:**
|
||||
|
||||
- **Semantics / index: an out-of-block constraint contributes nothing** — no
|
||||
symbol for the constraint name, no reference for any name inside the body,
|
||||
no scope. This is *deliberately identical* to the in-class case, which
|
||||
`class-semantics`'s README already states as rule 2 ("Verbatim members stay
|
||||
opaque") and pins with a test. Mechanically it is the same
|
||||
`ItemKind::Verbatim(_) => {}` arm in `bind.rs:372`, reached by the same item
|
||||
walker; item position never entered into it. Verified empirically on the
|
||||
shape (a class with `extern constraint`, its out-of-block definition, and an
|
||||
out-of-body method): symbols are exactly `{Class my_seq, Var num_trans,
|
||||
Function configure}`, zero references anywhere inside the constraint block,
|
||||
and every offset in the file is panic-free for `definition_of` /
|
||||
`symbol_at` / `reference_at`.
|
||||
- **Request to the lead (not acted on):** if that promise should be *pinned*
|
||||
rather than documented, the edit is one new test in
|
||||
`crates/vlog_semantic/tests/classes.rs`, next to the existing
|
||||
`constraint`/`covergroup` opacity test at line ~604, asserting the same
|
||||
three facts on the out-of-block shape. Not written here because
|
||||
`crates/vlog_semantic` is in this lane's file list only "if an arm is
|
||||
needed", and no arm is needed.
|
||||
- **Ownership note (flagged for merge):** requirement 3 of this lane's brief
|
||||
asks for formatter snapshot + idempotency coverage, but
|
||||
`crates/vlog_formatter/tests/*` belongs to Lane B. Resolved by adding
|
||||
**one new file** and editing none:
|
||||
`crates/vlog_formatter/tests/cases/out_of_class_constraints.cases`. The
|
||||
`cases.rs` harness auto-discovers `tests/cases/*.cases` and asserts *both*
|
||||
the expected output and idempotency of that output, so this single file
|
||||
satisfies the requirement with zero textual overlap with Lane B's work.
|
||||
- **Handed on:** `hw/dv/sv/cip_lib/seq_lib/cip_base_vseq.sv` — the worst
|
||||
cascade in the corpus — now advances past this blocker to bucket 10
|
||||
(`type_t'{...}`, a cast applied to an assignment-pattern literal) at
|
||||
`cip_base_vseq.sv:1462`. That bucket belongs to TODO §11's mop-up round.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Parser: `parse_constraint` accepts an optional `Ident ::` scope chain
|
||||
before the constraint name, via `parse_method_name`.
|
||||
- [x] All 45 bucket-1 OpenTitan files stop failing on this construct;
|
||||
44 parse and format clean, 1 advances to a different bucket.
|
||||
- [x] No new failure anywhere in the 3,943-file sweep (set difference, not
|
||||
just counts).
|
||||
- [x] Tolerant cascade measured before and after with the standalone
|
||||
`parse_source_tolerant` probe.
|
||||
- [x] Parser unit tests (5) in `parser.rs`'s test module.
|
||||
- [x] Tolerant regression test in `crates/vlog_parser/tests/error_recovery.rs`.
|
||||
- [x] Span-walker coverage: a new `SOURCES` entry in
|
||||
`crates/vlog_parser/tests/spans.rs` (byte coverage, span nesting,
|
||||
name spans, token reconstruction — all reused, no new assertions needed).
|
||||
- [x] Formatter snapshot + idempotency: 5 cases in a new
|
||||
`out_of_class_constraints.cases`.
|
||||
- [x] Corpus gate: 813/820, exactly the baseline, no regression.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- [ ] **Not done, deliberately:** no node for the constraint name, so
|
||||
go-to-definition from `constraint C::x` to `extern constraint x;` does
|
||||
not work. Same gap the in-class form has had since `classes`; closing it
|
||||
is a real-AST decision, not a parser fix.
|
||||
- [ ] **Not done, out of scope:** `cip_base_vseq.sv`'s next blocker
|
||||
(bucket 10, cast-to-assignment-pattern).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-29 — dev (Lane A)
|
||||
|
||||
**Root cause, confirmed by reading not by inference.** `parse_constraint`
|
||||
(`crates/vlog_parser/src/parser.rs`) called `self.expect_name()?` — one
|
||||
identifier — and then demanded `{` or `;`. On `constraint C::name {` that
|
||||
fails at the `::`, reporting `expected `{` (found "::")` positioned on the
|
||||
class name, one token *before* the real surprise. Exactly the diagnosis
|
||||
`syntax_coverage.md` recorded.
|
||||
|
||||
**The fix is one call.** `self.expect_name()?` → `self.parse_method_name()?`.
|
||||
`parse_method_name` is the existing out-of-body-method path (`function void
|
||||
my_class::configure(...)`); it consumes a `::` chain and splits scope from
|
||||
name. `parse_constraint` keeps neither, because the item it returns is a
|
||||
`RawText` span. Plus a doc-comment paragraph saying why.
|
||||
|
||||
**Design choice: verbatim reuse, no new AST variant.** The brief's expectation
|
||||
held up against the code. `ItemKind::Constraint` does not exist — a constraint
|
||||
has always been an `ItemKind::Verbatim(RawText)` leaf (`classes`' deliberate
|
||||
"don't model the grammar, copy the bytes"), and `parse_item_kind` already
|
||||
dispatches `"constraint"` at item position (line 1332), which is the same
|
||||
function that parses file-scope, package-scope and module-scope items. So the
|
||||
out-of-block form was *already* routed to the right parser from the right
|
||||
position; only the name grammar was too narrow. Consequences: no `ast.rs`
|
||||
change, no `format.rs` arm, no `bind.rs` arm, no `spans.rs` arm, no
|
||||
`visit.rs` arm, no `verify.rs` change (invariant 4 does not engage — nothing
|
||||
in the safety net was widened). Blast radius: one function body.
|
||||
|
||||
**Measured on the real OpenTitan checkout** (`/Users/guoliangchen/repo/opentitan`,
|
||||
3,943 `.sv`/`.svh` files, `--no-cache --check`, read-only; the tree's one
|
||||
pre-existing modification, `hw/ip/aes/dv/tb/tb.sv`, was there before and after
|
||||
and is not this round's).
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| files failing (whole sweep) | 151 | **107** |
|
||||
| bucket-1 files failing on `expected `{` (found "::")` | 45 | **0** |
|
||||
| bucket-1 files parsing + formatting clean | 0 | **44** |
|
||||
| bucket-1 files advanced to a *different* bucket | — | 1 |
|
||||
| files that newly fail (set difference) | — | **0** |
|
||||
|
||||
The single file that still fails, `hw/dv/sv/cip_lib/seq_lib/cip_base_vseq.sv`,
|
||||
no longer fails on a constraint: it now reaches line 1462 and stops on
|
||||
`addr_mask_t'{addr, mask}` — bucket 10, a distinct documented gap owned by the
|
||||
mop-up round. This is the ordinary corpus-check "a fix advances a file into
|
||||
the next bucket" outcome, and it is why the honest headline is *45 of 45
|
||||
unblocked, 44 of 45 fully clean*.
|
||||
|
||||
**Tolerant-mode cascade, the LSP half.** Probed with a standalone crate
|
||||
path-depending on this worktree's `vlog_parser` and calling
|
||||
`parse_source_tolerant` directly (`syntax_coverage.md`'s method 1 — necessary
|
||||
because `lucisv check`'s exit code deliberately discards `ParseDiagnostic`s).
|
||||
Over the same 45 files:
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| total tolerant diagnostics | **1 349** | **1** |
|
||||
| files with any diagnostic | 45 | 1 |
|
||||
| mean per file | 30.0 | 0.02 |
|
||||
| `cip_base_vseq.sv` (worst) | 322 | 1 *(the bucket-10 cast, not a cascade)* |
|
||||
| `hmac_base_vseq.sv` | 274 | **0** |
|
||||
| `aon_timer_base_vseq.sv` | 79 | **0** |
|
||||
| `ac_range_check_base_vseq.sv` | 67 | **0** |
|
||||
| `tl_seq_item.sv` | 60 | **0** |
|
||||
|
||||
The cascade does not shrink, it disappears: the construct parses, so no error
|
||||
node is created and the recovery loop is never entered. The one surviving
|
||||
diagnostic is a clean single-point report of a different, real gap.
|
||||
|
||||
**Formatter round-trip.** Idempotency was checked on all 45 real corpus files
|
||||
by formatting each through stdin twice (never writing to the corpus):
|
||||
**44 idempotent, 0 non-idempotent, 1 unformattable** (the bucket-10 file). For
|
||||
each of the 44, every `constraint C::name` header present in the input is
|
||||
present in the output — the verbatim capture reproduces the block byte for
|
||||
byte, and `format_source`'s own token-equivalence check (invariant 1) passed
|
||||
on all 44, which is what actually guarantees no comment or token was lost.
|
||||
Layout behaviour matches the in-class constraint exactly and needed no printer
|
||||
work: the block's *absolute* indent is re-set to its item position, its
|
||||
*relative* interior layout is untouched (`classes`' documented rule).
|
||||
|
||||
**Corpus gate.** `scripts/corpus_gate.sh` against the pinned 820-file corpus:
|
||||
`{"passing":813,"total":820,...}`, 0 verification errors, 0 crashes — exactly
|
||||
the recorded baseline, no regression. The pinned corpus contains no
|
||||
out-of-block constraint, which is precisely why this gap went unmeasured until
|
||||
the full-OpenTitan sweep; the strict-superset rule holds.
|
||||
|
||||
**Tests added.**
|
||||
|
||||
- `crates/vlog_parser/src/parser.rs` (test module, new section):
|
||||
- `an_out_of_block_constraint_is_a_file_scope_verbatim_item` — the leaf, and
|
||||
that its text is its own source slice.
|
||||
- `an_out_of_block_constraint_scope_may_be_a_chain` — `pkg::cls::name`.
|
||||
- `an_out_of_block_constraint_lives_in_a_package_too` — package scope.
|
||||
- `an_out_of_block_constraint_keeps_its_trailing_semicolon_and_comments` —
|
||||
the stray `;` is inside the capture, the leading and trailing comments are
|
||||
outside it and both survive (invariant 3).
|
||||
- `an_in_class_constraint_still_rejects_a_scope_free_syntax_error` — the
|
||||
widened name must not swallow `constraint c:: {` or `constraint 4::x`;
|
||||
both still error, with the message pinned.
|
||||
- `crates/vlog_parser/tests/error_recovery.rs`:
|
||||
`out_of_block_constraints_do_not_cascade` — the miniature of the real shape
|
||||
(class with two `extern constraint` prototypes and an `extern function`,
|
||||
then their out-of-block definitions), asserting **zero** tolerant
|
||||
diagnostics and strict/tolerant agreement.
|
||||
- `crates/vlog_parser/tests/spans.rs`: one new `SOURCES` entry, which the
|
||||
file's existing exhaustive walkers pick up for free — token/byte coverage,
|
||||
span nesting, name-span slicing, source reconstruction.
|
||||
- `crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` (new
|
||||
file): 5 cases — prototype + definition, package re-indent, scope chain with
|
||||
a stray `;` and comments on both sides, empty body, and a body exercising
|
||||
the constraint sub-grammar (`dist`, `->`, `foreach`, `if`/`else`). The
|
||||
harness asserts expected-output *and* idempotency for each.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
|
||||
clean (no new warnings, no `#[allow]`); `cargo test --workspace` green —
|
||||
35 test binaries, 0 failures.
|
||||
|
||||
**Deviations from the brief.** One, declared above under Handshakes: the
|
||||
formatter coverage requirement (3) lands in a directory Lane B owns. Handled
|
||||
as a single new file with no edits to any existing Lane B file, flagged here
|
||||
and in the lane report rather than done silently.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-29 — QA (Lane A)
|
||||
|
||||
Verdict: **SHIP**. No corruption, no cascade regression, no gate slippage
|
||||
found. One test added (see below); everything else in this entry is
|
||||
verification, not redesign.
|
||||
|
||||
**Grammar-widening attacks** (charter item 1) — probed the built
|
||||
`lucisv --stdout -` on adversarial inputs, all behaving safely (correct
|
||||
error or correct accept, never a crash, never silent corruption):
|
||||
|
||||
- `constraint ::name { a == 0; }` → `1:12: expected identifier (found "::")`.
|
||||
- `constraint C:: { a == 0; }` → `1:16: expected identifier (found "{")`
|
||||
(already pinned by the dev's own
|
||||
`an_in_class_constraint_still_rejects_a_scope_free_syntax_error`).
|
||||
- `constraint pkg::cls::inner::deep_c { ... }` (3-part chain) — **accepts**.
|
||||
Judged and pinned here: a 3+-part chain is not realizable SV (classes
|
||||
don't nest, so the longest legal chain a real out-of-body definition can
|
||||
have is `pkg::class::name`), but this is a pure-verbatim leaf — the chain
|
||||
text is consumed and discarded, nothing downstream trusts its structure —
|
||||
so accepting more than the LRM allows costs nothing and matches the
|
||||
README's own Assumptions section, which already makes this call. Not a
|
||||
defect.
|
||||
- `constraint new { a == 0; }` (keyword-shaped name) — accepts, because
|
||||
`"new"` is deliberately not a lexer keyword
|
||||
(`crates/vlog_parser/src/token.rs:334`) and `expect_name` only checks
|
||||
`TokenKind::Ident`. Pre-existing `expect_name` behavior, not a widening
|
||||
`parse_method_name` introduces.
|
||||
- Escaped identifiers on either side of `::` (`` \my-class ::name ``) —
|
||||
accept; the lexer already tags an escaped identifier `Ident`
|
||||
(`crates/vlog_parser/src/lexer.rs:301-314`), so this is old lexer behavior,
|
||||
not new surface from this round.
|
||||
- `constraint C::name;` (a scope on a *prototype*, no body) — **accepts**,
|
||||
producing a verbatim `constraint C::name;` item. This shape doesn't occur
|
||||
in the corpus and isn't a real `extern constraint` (those live in-class,
|
||||
unscoped) — but same reasoning as the chain-depth point: pure verbatim
|
||||
capture, no data trusted downstream, matches "no new legal-position check"
|
||||
in Assumptions. Flagging it here so it's a documented, not accidental,
|
||||
permissiveness.
|
||||
- `constraint C::name { ... }` at **module scope** (illegal SV) — accepts,
|
||||
exactly as the Assumptions section already states it would (the bare form
|
||||
already had this permissiveness pre-round). Not new.
|
||||
- `constraint` as the last token of the file, and `constraint C::name` with
|
||||
no body at EOF — both give clean, correctly-positioned parse errors
|
||||
(`expected identifier (found "<eof>")`, `` expected `{` (found "<eof>") ``),
|
||||
no panic, no hang.
|
||||
- `constraint 4::x { ... }` — `1:12: expected identifier (found "4")`
|
||||
(already pinned by the dev's test of the same name).
|
||||
|
||||
None of these findings block shipping: every widened-acceptance case is
|
||||
already named and justified in the feature's own Assumptions section, and
|
||||
none of them can corrupt output because the whole item stays a byte-exact
|
||||
verbatim span. No new test added for this item — the two shapes worth
|
||||
pinning (`::` with no name, digit as scope) were already covered by the
|
||||
dev's tests, and I've recorded the judgment on chain depth and the
|
||||
prototype-with-scope shape here rather than in code, since they're accepted
|
||||
permissiveness, not bugs.
|
||||
|
||||
**Verbatim integrity** (charter item 2) — built `lucisv` release binary from
|
||||
this worktree and round-tripped by hand (format twice, diff outputs; also
|
||||
compared against source where relevant):
|
||||
|
||||
- String containing `}` inside the body — idempotent, brace inside the
|
||||
string does not confuse `skip_balanced`.
|
||||
- Block comment containing `{`/`}` inside the body — idempotent.
|
||||
- `` `ifdef ``/`` `else ``/`` `endif `` inside the body — idempotent (the
|
||||
whole conditional is inside the verbatim span, never interpreted).
|
||||
- CRLF line endings inside the body — idempotent; CRLF is normalized to LF
|
||||
on the way in, which is pre-existing whole-file lexer behavior unrelated
|
||||
to this round, not something this change introduces.
|
||||
- A `constraint C::name { ... }` nested three packages deep with
|
||||
inconsistent absolute indentation and extra relative indentation in the
|
||||
body — confirmed the `RawText.col` dedent contract (topo §2.2) holds: the
|
||||
block's absolute indent resets to its item position, every line's
|
||||
*relative* offset from the original `constraint` line is preserved
|
||||
exactly, and the result is idempotent.
|
||||
- All 5 cases in the dev's new
|
||||
`crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` pass,
|
||||
confirmed the harness (`crates/vlog_formatter/tests/cases.rs:178`) actually
|
||||
asserts idempotency per case, not just expected output.
|
||||
|
||||
**Cascade honesty** (charter item 3) — built a standalone probe crate
|
||||
depending on this worktree's `vlog_parser` (`parse_source_tolerant`
|
||||
directly), run against the real `/Users/guoliangchen/repo/opentitan`
|
||||
checkout, read-only throughout (`git status --porcelain` before and after:
|
||||
only the pre-existing `hw/ip/aes/dv/tb/tb.sv` modification, untouched).
|
||||
|
||||
- Reproduced the dev's 5 named files exactly, both sides, via
|
||||
`git stash`/`stash pop` on `crates/vlog_parser/src/parser.rs` alone:
|
||||
|
||||
| file | before | after |
|
||||
|---|---|---|
|
||||
| `cip_base_vseq.sv` | 322 | 1 (bucket-10, not a cascade) |
|
||||
| `hmac_base_vseq.sv` | 274 | 0 |
|
||||
| `aon_timer_base_vseq.sv` | 79 | 0 |
|
||||
| `ac_range_check_base_vseq.sv` | 67 | 0 |
|
||||
| `tl_seq_item.sv` | 60 | 0 |
|
||||
|
||||
- 5 more bucket-1 files of my own choosing (`alert_esc_seq_item.sv`,
|
||||
`dv_base_env_cfg.sv`, `kmac_app_agent_cfg.sv`,
|
||||
`adc_ctrl_filter_cfg.sv`, `aon_timer_common_vseq.sv`): before 3/40/1/10/5,
|
||||
after all 0. Cascade collapse confirmed on a sample the dev didn't hand-pick.
|
||||
- 20 files sampled from outside the failing set (mixed `dv/`/`rtl/`,
|
||||
various IPs, one from `vendor/`) probed before and after the same
|
||||
stash/pop: **byte-identical diagnostic counts both sides** (one file,
|
||||
`rng_agent/rng_driver.sv`, carries 1 diagnostic both before and after —
|
||||
pre-existing, unrelated to this change). No new tolerant diagnostic
|
||||
anywhere in the sample.
|
||||
|
||||
**Strict-superset discipline** (charter item 4) — reproduced independently,
|
||||
not trusted from the write-up:
|
||||
|
||||
- Corpus gate: `scripts/corpus_gate.sh` against
|
||||
`/Users/guoliangchen/repo/verilogrustformatter/corpus` (the worktree has
|
||||
no local `corpus/`, it's gitignored) → `{"passing":813,"total":820,...}`,
|
||||
0 verification errors, 0 crashes. Exact match to the claimed baseline.
|
||||
- Whole-sweep count: built the release binary with the fix stashed out and
|
||||
back in, ran `lucisv --no-cache --check` over all 3,943 real-OpenTitan
|
||||
`.sv`/`.svh` files both ways. **151 → 107**, exact match.
|
||||
- Set difference: `comm -23` between the after-failing and before-failing
|
||||
file lists → **0 newly-failing files**; `comm -13` → 44 newly-fixed files
|
||||
(151 − 107 = 44, consistent). The 45th named file
|
||||
(`cip_base_vseq.sv`) confirmed still failing, but on a *different*
|
||||
diagnostic: `1462:65: expected `)` (found "'{")`, i.e. line 1462's
|
||||
`addr_mask_t'{addr, mask}` — exactly the claimed bucket-10 advance, not a
|
||||
constraint failure.
|
||||
- Idempotency on all 44 newly-clean files (not the dev's sampled subset —
|
||||
the full 44): scripted format-twice-and-diff over each; **0 failures, 0
|
||||
non-idempotent**.
|
||||
|
||||
**The three flagged deviations** (charter item 5):
|
||||
|
||||
- (a) `crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` —
|
||||
`git status --porcelain` shows it `??` (untracked, new-file-only); no
|
||||
existing Lane B file touched. Confirmed the harness exercises idempotency
|
||||
for it (see above). Genuinely additive, as claimed.
|
||||
- (b) `TODO.md` §11 — diffed the worktree's version against
|
||||
`git show master:TODO.md`: the only difference is Lane A's own checkbox
|
||||
(unchecked → checked) and one added summary line under Lane A's item.
|
||||
Lane B's subsection and the "serial, after Lane A merges" section are
|
||||
byte-identical to trunk. The trivially-parallel merge claim holds.
|
||||
- (c) The un-pinned `vlog_semantic` opacity promise — per my small-fix
|
||||
license and the charter's explicit instruction, added the test the dev
|
||||
specified in Handshakes:
|
||||
`crates/vlog_semantic/tests/classes.rs::an_out_of_block_constraint_is_absent_but_nothing_crashes`,
|
||||
next to the existing `verbatim_members_are_absent_but_nothing_crashes`.
|
||||
One correction while writing it: my first draft assumed the *out-of-block
|
||||
definition* was the only opaque part and that the in-class `extern
|
||||
constraint num_trans_c;` prototype would still produce a `num_trans_c`
|
||||
symbol — it does not; the prototype is itself an `ItemKind::Verbatim`
|
||||
leaf too (parsed by the same `parse_constraint`), so neither the
|
||||
prototype nor the definition binds a symbol. Fixed the assertion to match
|
||||
reality (confirmed by running the test against the actual analyzer output
|
||||
before asserting) rather than the assumption. Test passes.
|
||||
|
||||
**Full gates** (charter item 6), re-run after adding the `vlog_semantic`
|
||||
test: `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
|
||||
clean, 0 warnings; `cargo test --workspace` green (35 test binaries, 0
|
||||
failures, includes the new test); corpus gate 813/820 as above.
|
||||
|
||||
**Findings summary** (severity — all informational/non-blocking, nothing
|
||||
found that requires rework):
|
||||
|
||||
- INFO: `parse_constraint` now accepts several shapes the OpenTitan corpus
|
||||
never exercises and the LRM doesn't sanction (chains deeper than 2,
|
||||
a scoped prototype with no body, module-scope placement) — all already
|
||||
named as deliberate in the feature's Assumptions section and all
|
||||
incapable of corrupting output, since the entire item is a byte-exact
|
||||
verbatim capture. No action needed; recorded here so the judgment call is
|
||||
visible to reviewers who don't re-derive it.
|
||||
- INFO: the dev's Handshakes-proposed `vlog_semantic` test had a wrong
|
||||
assumption baked into its own description (that `extern constraint
|
||||
num_trans_c;` binds a symbol); the corrected version now pins the real
|
||||
behavior (neither prototype nor definition binds a symbol).
|
||||
|
||||
**Tests added:** 1 —
|
||||
`crates/vlog_semantic/tests/classes.rs::an_out_of_block_constraint_is_absent_but_nothing_crashes`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead.** Reviewed after QA's clean SHIP; gates re-run on
|
||||
the worktree. This round is the loop at its best-case: the analysis
|
||||
sweep named the bucket, the fix is one line reusing a path the grammar
|
||||
already had, the blast radius is zero by construction (verbatim leaf,
|
||||
no new variant), and the payoff is the largest single coverage move
|
||||
available — 45 files unblocked and a 1,349-diagnostic tolerant cascade
|
||||
reduced to one honest report. QA's stash-based before/after on
|
||||
previously-clean files is the check that matters for a grammar
|
||||
widening (a cascade that moved would have hidden), and its correction
|
||||
of the dev's own specified-but-wrong semantic test (extern prototypes
|
||||
are verbatim too) is exactly why the QA leg exists. The deliberate
|
||||
over-acceptances (deep scope chains, scoped prototypes, module-scope
|
||||
placement) are recorded as judgment calls with the corruption argument
|
||||
attached — acceptable for a byte-exact capture. Accepted; merged by
|
||||
the lead. parser.rs is now free for the directive-split round.
|
||||
@@ -112,6 +112,14 @@ Handshake `docs/features/type-definition/README.md` filed, delivered here).
|
||||
reference stays exactly what it was, absent from the overlay, and
|
||||
`ExternalResolutions::counts()` does not grow. `ExternalTarget`,
|
||||
`Definition` and every other overlay type are unchanged.
|
||||
**Amended 2026-09-01 by class-member-access** (topo §2.9-9): when the paths
|
||||
find nothing, the recorded **`base` is chased** — `member(base, name)`, then
|
||||
up the workspace's `extends` edges (`WorkspaceIndex::base_of`) with a
|
||||
visited set. The "record an entry only when something lands" rule is
|
||||
unchanged and is what still keeps an unanswerable inherited candidate out
|
||||
of the overlay; what changed is that the paths are no longer the only thing
|
||||
tried. The order matters and is the one stated here: an import path that
|
||||
can supply the name still wins over the base.
|
||||
|
||||
**Promised to consumers:** the overlay answers more references and invents
|
||||
nothing. Every `Def` it returns is still a real file-scope declaration whose
|
||||
|
||||
@@ -18,7 +18,7 @@ the parser's limit and needs no counter of its own.
|
||||
## The invariant
|
||||
|
||||
> **No input can make AST depth exceed `MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH`
|
||||
> (64 + 256 = 320 layers) on any root-to-leaf path**, so every recursive walk
|
||||
> (64 + 1024 = 1088 layers) on any root-to-leaf path**, so every recursive walk
|
||||
> over the tree — the formatter's, the `Doc` tree's, and the implicit
|
||||
> recursive `Drop` — is bounded too.
|
||||
|
||||
@@ -29,7 +29,7 @@ finishes:
|
||||
| | counter | limit | charged by |
|
||||
|---|---|---|---|
|
||||
| **Nesting** — one parser recursion per layer | `depth` | `MAX_NESTING_DEPTH` = 64 | the 5 gated `parse_*` functions |
|
||||
| **Chains** — a loop that wraps what it already built | `links` | `MAX_CHAIN_LENGTH` = 256 | postfix segments, binary/`inside` operator chains |
|
||||
| **Chains** — a loop that wraps what it already built | `links` | `MAX_CHAIN_LENGTH` = 1024 | postfix segments, binary/`inside` operator chains, a bare event control's path |
|
||||
|
||||
The chain counter exists because a loop can deepen the AST without deepening
|
||||
the parser: `a.b.b.b…` costs `parse_postfix` a single frame but builds one
|
||||
@@ -39,8 +39,8 @@ landed (QA finding, 2026-08-19).
|
||||
|
||||
Because both counters accumulate along a path rather than per construct,
|
||||
nesting and chains cannot multiply: a chain inside another chain's operand
|
||||
stacks on top of it, so `f(a.b…)(a.b…)…` is bounded by the same 320 layers,
|
||||
not by 64 × 256.
|
||||
stacks on top of it, so `f(a.b…)(a.b…)…` is bounded by the same 1088 layers,
|
||||
not by 64 × 1024.
|
||||
|
||||
## Assumptions
|
||||
|
||||
@@ -86,8 +86,8 @@ not by 64 × 256.
|
||||
|
||||
```
|
||||
MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs)
|
||||
MAX_CHAIN_LENGTH = 256
|
||||
PARSE_STACK_SIZE = 16 MiB
|
||||
MAX_CHAIN_LENGTH = 1024 (was 256 until 2026-08-29)
|
||||
PARSE_STACK_SIZE = 32 MiB (was 16 MiB until 2026-08-29)
|
||||
```
|
||||
|
||||
The first two bound the input. The third bounds nothing — it is what the
|
||||
@@ -100,7 +100,7 @@ Going one past either limit produces an ordinary parse error:
|
||||
|
||||
```
|
||||
error: rtl/deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk")
|
||||
error: rtl/chain.sv: parse error: 2:525: expression chain too long (limit 256) (found ".")
|
||||
error: rtl/chain.sv: parse error: 2:525: expression chain too long (limit 1024) (found ".")
|
||||
```
|
||||
|
||||
### Why 64 — measured, not guessed
|
||||
@@ -165,7 +165,7 @@ costs three more levels (the statement plus `parse_ternary`/`parse_unary` for
|
||||
its expression). The parser's own boundary unit tests use the empty-block
|
||||
construction (62/63); `vlog_formatter`'s use the ones with content.
|
||||
|
||||
### Why 256 for chains
|
||||
### Why 256 for chains — superseded 2026-08-29, see "Why 1024" below
|
||||
|
||||
Same method, measuring inputs sized to sit exactly *at* the limits so the
|
||||
formatter really walks them (min surviving thread stack, debug / release):
|
||||
@@ -190,7 +190,67 @@ fits). Charging chain links against `MAX_NESTING_DEPTH` instead would have
|
||||
capped those at ~60 terms and rejected real code; that is why chains get
|
||||
their own, larger budget rather than sharing the nesting one.
|
||||
|
||||
### The stack the limit needs — re-measured 2026-08-28
|
||||
### Why 1024 for chains — 2026-08-29
|
||||
|
||||
**256 was not enough for real code.** OpenTitan's generated register files
|
||||
build one `|` chain per register file, `(addr_hit[N] & (|(PERMIT[N] &
|
||||
~reg_be))) | …`, so the chain length tracks the register count. A high-water
|
||||
probe over all 3,943 files (a scratchpad copy with the limit raised out of the
|
||||
way and `links` recorded; never built inside the repo) says what they need:
|
||||
|
||||
| file | links |
|
||||
|---|---|
|
||||
| `top_earlgrey/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` | **567** |
|
||||
| `top_englishbreakfast/…/pinmux_reg_top.sv` | 519 |
|
||||
| `top_darjeeling/…/pinmux_reg_top.sv` | 502 |
|
||||
| `top_darjeeling/…/alert_handler_reg_top.sv` | 397 |
|
||||
| `top_earlgrey/…/alert_handler_reg_top.sv` | 353 |
|
||||
| `rv_dm/rtl/rv_dm_mem_reg_top.sv` | 280 |
|
||||
| `top_darjeeling/…/rv_core_ibex_cfg_reg_top.sv` | 266 |
|
||||
|
||||
3,932 of the 3,943 files stay under 128; five sit in 257–512 and two pass 512.
|
||||
Seven files were rejected outright at 256, which is the acceptance failure this
|
||||
budget exists to avoid.
|
||||
|
||||
**What a link costs, re-measured at the new sizes** (same method: one trial per
|
||||
subprocess, bisect the smallest surviving thread stack, whole `format_source`;
|
||||
rustc 1.97.1):
|
||||
|
||||
| shape | debug | release |
|
||||
|---|---|---|
|
||||
| postfix chain (`a.b…`), 640 links | 5 911 KiB | 375 KiB |
|
||||
| postfix chain, 768 | 7 079 KiB | 455 KiB |
|
||||
| postfix chain, **1024** | **9 430 KiB** | 615 KiB |
|
||||
| postfix chain, 1280 | 11 798 KiB | 775 KiB |
|
||||
| `+` chain / the real `or_chain` shape, 2048 terms | 567 KiB | 183 KiB |
|
||||
| 28 nested `case` + a 1024-link postfix chain inside | **9 894 KiB** | 727 KiB |
|
||||
| 64 nested `case` (trips depth) + a 1024-link chain inside | 5 959 KiB | 775 KiB |
|
||||
|
||||
Per link, from the slope: **9.20 KiB debug**, 0.63 KiB release — consistent
|
||||
with the ~9 KiB the 2026-08-19 round measured at 256. Binary-operator chains,
|
||||
which is what the generated files actually contain, are ~40× cheaper because
|
||||
`binary_chain` flattens the left spine; the *postfix* chain is what the budget
|
||||
has to be safe for.
|
||||
|
||||
**Two things this changes.**
|
||||
|
||||
1. **Chains now set the global worst case.** At 256 a maximal chain peaked at
|
||||
~2.4 MiB against nesting's ~5.9, which is why both earlier rounds could say
|
||||
"the chain budget does not move the worst case". At 1024 it peaks at
|
||||
~9.4 MiB alone and **9 894 KiB** inside nesting, so that sentence is retired:
|
||||
`PARSE_STACK_SIZE` is now measured against the chain.
|
||||
2. **The additive-composition argument is unchanged, and the measurement shows
|
||||
it directly.** 64 nested `case` *with* a 1024-link chain inside bisects to
|
||||
exactly the same byte as without it (5 959 KiB), because tripping the depth
|
||||
limit peaks in the parser while a chain peaks in the formatter. Nothing
|
||||
multiplies.
|
||||
|
||||
**Why 1024 and not 640.** 640 would clear today's largest file by 13 % — a fit,
|
||||
not a margin, on a number that grows with design size, and this limit has now
|
||||
been outgrown once. 1024 is 1.8× the measured maximum and costs 3.5 MiB of
|
||||
debug stack over 640, which the constant below absorbs.
|
||||
|
||||
### The stack the limit needs — re-measured 2026-08-28, and again 2026-08-29
|
||||
|
||||
Same method as above (subprocess per trial, bisect the smallest thread stack
|
||||
that survives), but over the *whole* consumer pipeline this time —
|
||||
@@ -234,17 +294,21 @@ Three things the same sweep settles:
|
||||
its own; it is two orders of magnitude under the walk that produced the
|
||||
tree. Same for the tolerant recovery: strict and tolerant parses of the
|
||||
same limit-tripping input bisect to the same byte.
|
||||
- **Chains still do not move the worst case.** A 256-link chain alone peaks
|
||||
at 2487 KiB debug (~9 KiB per link); the same chain inside 58 nested `case`
|
||||
measures 5895 KiB — identical to that nesting without any chain, because
|
||||
the two peak in different phases. The additive-composition argument above
|
||||
is unchanged.
|
||||
- **16 MiB is the constant, and it is margin rather than a fit.** 8 MiB —
|
||||
what the CLI's pool used and what a stock main thread happens to have —
|
||||
is 1.33× the debug worst case, and the last two years of this number moving
|
||||
(3.9 → 5.9 MiB, no parser change) say that is not enough room. 16 MiB is
|
||||
2.7×, costs address space rather than memory (thread stacks are committed a
|
||||
page at a time), and is the size the feature's tests already spawned.
|
||||
- ~~**Chains still do not move the worst case.**~~ **Retired 2026-08-29.** It
|
||||
was true at `MAX_CHAIN_LENGTH = 256`: a 256-link chain alone peaked at
|
||||
2487 KiB debug (~9 KiB per link), and the same chain inside 58 nested `case`
|
||||
measured 5895 KiB — identical to that nesting without any chain, because the
|
||||
two peak in different phases. At 1024 the chain peaks at ~9.4 MiB and *is*
|
||||
the worst case. The phase argument still holds; only the ranking changed.
|
||||
- ~~**16 MiB is the constant.**~~ **Superseded 2026-08-29 by 32 MiB**, for the
|
||||
same reason 16 replaced 8: the margin, not the fit, is the point. The
|
||||
measured worst case is now **~9.7 MiB debug** (a maximal chain inside
|
||||
nesting, 9 894 KiB) rather than ~5.9; 16 MiB would be 1.65× of that, below
|
||||
the 2.7× this feature settled on for a failure mode that aborts instead of
|
||||
returning. 32 MiB is **3.3×**, costs address space rather than memory (thread
|
||||
stacks are committed a page at a time), and is what the feature's tests now
|
||||
spawn. The full 2026-08-29 measurement is under "Why 1024 for chains" above
|
||||
and in `docs/features/clocking-wave/README.md`.
|
||||
|
||||
## Where the counters sit
|
||||
|
||||
@@ -294,6 +358,7 @@ missed):
|
||||
|---|---|
|
||||
| `parse_postfix` | `a.b`, `a::b`, `a[i]`, `a[m:l]`, `a(args)`, `a'(x)`, `a++`/`a--` — one link per segment |
|
||||
| `parse_binary` | `a + b + c…` (one link per operator, any precedence) and `a inside {…} inside {…}` |
|
||||
| `parse_bare_event_name` | `@a.b.c`, `@a["k"].b` — the `.name` / `[expr]` segments of a paren-less event control's hierarchical path (added 2026-08-29; the `.name` half of this loop existed un-charged before, which was the last instance of the hole below) |
|
||||
|
||||
Not charged at all, and why:
|
||||
|
||||
@@ -357,7 +422,7 @@ not inflate depth — the output of a max-depth file re-parses inside
|
||||
- **Promised to `vlog_formatter`:** AST depth on any path is bounded by
|
||||
`vlog_parser::parser::MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` (both public,
|
||||
so tests and any future consumer can reference them instead of hard-coding
|
||||
64 and 256). The formatter may keep its recursive walk as long as every
|
||||
64 and 1024). The formatter may keep its recursive walk as long as every
|
||||
path is a structural descent and no public API accepts an externally built
|
||||
AST.
|
||||
- **Requirement on future `vlog_parser` work:** any new loop that wraps the
|
||||
@@ -464,6 +529,34 @@ Round 3 — the stack the limit needs (2026-08-28, from a QA finding on
|
||||
- [x] `cargo test --workspace` (2425), `cargo clippy --all-targets`,
|
||||
`cargo fmt --check` all clean.
|
||||
|
||||
Round 4 — the chain budget real code outgrew (2026-08-29, from the
|
||||
testbench-syntax wave's round 2; see `docs/features/clocking-wave/README.md`):
|
||||
|
||||
- [x] Measured what real code needs before choosing anything: a per-file
|
||||
high-water probe over all 3,943 OpenTitan files. Longest chain **567**
|
||||
(`pinmux_reg_top.sv`); seven files were rejected at 256.
|
||||
- [x] Re-measured the per-link stack cost across four lengths so the slope is
|
||||
measured rather than assumed: **9.20 KiB per postfix link** in a debug
|
||||
build, 0.63 KiB in release.
|
||||
- [x] `MAX_CHAIN_LENGTH` 256 → **1024** (1.8× the measured maximum), and the
|
||||
invariant restated: 64 + 1024 = **1088 layers**.
|
||||
- [x] `PARSE_STACK_SIZE` 16 → **32 MiB**, from the re-measured worst case
|
||||
(**9 894 KiB** debug: a maximal chain inside statement nesting) at the
|
||||
same 2.7×-or-better margin the 2026-08-28 round argued for.
|
||||
- [x] The "chains do not move the worst case" claim retired with the
|
||||
measurement that retires it; the phase argument that makes the two
|
||||
counters additive re-verified at the new size (64 nested `case` with and
|
||||
without a 1024-link chain bisect to the same byte).
|
||||
- [x] The last un-charged chain loop found and closed:
|
||||
`parse_sens_list`'s paren-less `@a.b.c` path boxed a layer per `.name`
|
||||
without charging `link()`. Now `parse_bare_event_name`, charging both
|
||||
segment kinds and restoring the count it started from, with a test.
|
||||
- [x] `deep_nesting.rs` gained the combined worst case
|
||||
(`a_maximal_chain_inside_deep_nesting_formats`), and its past-the-limit
|
||||
case now spells `MAX_CHAIN_LENGTH + 1` instead of a hard-coded 1500.
|
||||
- [x] `MAX_NESTING_DEPTH` left at 64: nothing in this round changes which
|
||||
nesting a file may use.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
@@ -696,6 +789,48 @@ two pre-existing helpers re-pointed at the constant). `cargo clippy
|
||||
`crates/vlog_semantic/tests/deep_nesting.rs` (new),
|
||||
`docs/features/parallel-files/README.md`, `TODO.md`, this README.
|
||||
|
||||
### 2026-08-29 — dev, the chain budget real code outgrew
|
||||
|
||||
Written as part of the testbench wave's round 2; the full narrative, the
|
||||
whole-tree distribution and the probe method are in
|
||||
`docs/features/clocking-wave/README.md`. What matters here:
|
||||
|
||||
- **The trigger was acceptance, not a crash.** Seven real OpenTitan files —
|
||||
generated register tops — were being *rejected* with `expression chain too
|
||||
long (limit 256)`. The 2026-08-19 round chose 256 for exactly this reason
|
||||
("256 covers a 256-term generated sum") against a smaller tree; the tree
|
||||
grew. Measured the whole 3,943-file distribution rather than the seven, so
|
||||
the new number is chosen against the shape of real generated code (max 567,
|
||||
five files in 257–512, two over 512) instead of against the failures.
|
||||
- **Re-measured the slope, did not extrapolate the old number.** Four chain
|
||||
lengths (640/768/1024/1280), debug and release, bisected one trial per
|
||||
subprocess. 9.20 KiB per postfix link debug — close to the ~9 KiB measured at
|
||||
256, so the cost is genuinely linear and 1024 lands where arithmetic says.
|
||||
- **The honest finding: this round breaks one of the feature's own claims.**
|
||||
Both earlier rounds concluded that raising the chain budget is free on the
|
||||
stack, because chains peaked at 2.4 MiB against nesting's 5.9. At 1024 a
|
||||
maximal chain peaks at 9.4 MiB alone and 9.9 MiB inside nesting, so the chain
|
||||
is now the global worst case and the claim is retired above rather than
|
||||
quietly left standing. What survives — and was re-verified, not assumed — is
|
||||
the *reason* it was ever true: the two peak in different phases, so they
|
||||
compose additively. 64 nested `case` with and without a 1024-link chain
|
||||
inside bisect to the identical 5 959 KiB.
|
||||
- **`PARSE_STACK_SIZE` follows the measurement, as designed.** 16 MiB is 1.65×
|
||||
the new worst case; the constant's whole argument is margin over fit, so it
|
||||
moves to 32 MiB (3.3×). No consumer changes: every parse site already spells
|
||||
the constant, which is exactly what round 3 put it there for.
|
||||
- **One un-charged chain loop found while working nearby.**
|
||||
`parse_sens_list`'s paren-less `@a.b.c` path built one `Expr::Member` per
|
||||
segment in a loop without charging `link()` — the `Box::new(previous)` shape
|
||||
this README's Handshakes makes a standing requirement, missed because the
|
||||
loop lives in the event-control code rather than in `parse_postfix`. Lifted
|
||||
into `parse_bare_event_name`, charging both segment kinds and restoring the
|
||||
count it started from; `a_bare_event_control_charges_the_chain_budget` pins
|
||||
it.
|
||||
- Files touched here: `crates/vlog_parser/src/parser.rs` (three doc comments,
|
||||
the two constants, the new chain site),
|
||||
`crates/vlog_formatter/tests/deep_nesting.rs`, this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
@@ -89,6 +89,26 @@ corrupt.
|
||||
cursor is at module-item position. Nothing in `pairs.rs` was changed: the
|
||||
gate is built entirely from its published output, so editor-scopes keeps
|
||||
ownership of the matcher.
|
||||
- **Amended 2026-08-30 — where the plan is offered changed; the plan did not.**
|
||||
M4's completion item carried the whole instantiation. The owner's two-level
|
||||
ruling moved that to ghost text: the completion popup offers module *names*
|
||||
(level 1, a table scan), and `inline.rs` plans exactly one instantiation once
|
||||
the name before the cursor matches a module exactly and a space is typed
|
||||
after it (level 2; round 2 also replaced `module_definition`'s ambiguity
|
||||
refusal on that path with the server's `nearest_definition` chooser —
|
||||
`module_definition` itself is unchanged for its own callers). Every fact
|
||||
below still holds — the same `instantiation_plan`, the same `render_with`,
|
||||
the same auto-connect rule, the same `has_escaped_identifier` flag consulted
|
||||
before snippet encoding — but the *consumer* of the snippet spelling is now
|
||||
`inline.rs` rather than `completion::item`, which is gone. The escaped-name
|
||||
fallback differs on that path and only there: an inline completion has no
|
||||
plain-text spelling to fall back to, so such a plan is declined rather than
|
||||
inserted plainly (see *Escaped identifiers* and
|
||||
`docs/features/inline-instantiation/README.md`). Signature help and inlay
|
||||
hints, the other two consumers of `instantiation_plan`, are untouched.
|
||||
(Lead correction 2026-08-30: this entry originally said "`lucisv/instantiate`,
|
||||
the code action and the command are untouched" — no such action or command
|
||||
has ever existed; M4's user-facing surface was the popup skeleton alone.)
|
||||
- **Promises `lucisv_server`**: `instantiation_plan` never panics and never
|
||||
returns a plan whose plain rendering fails to parse — corpus-verified over
|
||||
all 454 modules, plus escaped-identifier cases the corpus does not contain
|
||||
@@ -196,17 +216,25 @@ the *names* are written by the layout, outside every hole: there is no encoding
|
||||
of `.\W}idth (${1:8})` that a snippet parser reads back correctly. **Ruling
|
||||
(lead-approved): a plan containing any escaped identifier is inserted as plain
|
||||
text**, tabstops and all sacrificed, even when the client advertised
|
||||
`snippetSupport`. `InstantiationPlan::has_escaped_identifier` is the test;
|
||||
`completion.rs::item` is the one place it is consulted. The user gets a correct
|
||||
skeleton with every default filled in and no tabstops to tab through — a small
|
||||
loss, confined to a naming style almost nobody uses, and the alternative is
|
||||
inserting text that does not parse.
|
||||
`snippetSupport`. `InstantiationPlan::has_escaped_identifier` is the test. The
|
||||
user gets a correct skeleton with every default filled in and no tabstops to
|
||||
tab through — a small loss, confined to a naming style almost nobody uses, and
|
||||
the alternative is inserting text that does not parse.
|
||||
|
||||
**Amended 2026-08-30.** `completion.rs::item` was the one place the flag was
|
||||
consulted; that item is gone with the two-level split, and the flag is now read
|
||||
by `inline.rs`'s instantiation ghost alone (lead correction: not also by a
|
||||
`lucisv/instantiate` rendering — no such command exists). The ruling above is unchanged **wherever a plain-text spelling
|
||||
exists**. Ghost text has none — an inline completion carries no
|
||||
`insertTextFormat` and no `snippetSupport` to negotiate, so "insert it plainly"
|
||||
is not an option there — and the ghost therefore *declines* such a plan
|
||||
outright. Same principle (never write text that does not parse), the only
|
||||
answer that path has.
|
||||
|
||||
Regression-tested at both levels: the engine renders a parseable plain skeleton
|
||||
for a module whose module, parameter and port names are all escaped (two of
|
||||
them carrying `$` and `}`), and the server's own `item` returns
|
||||
`InsertTextFormat::PlainText` with no `${` anywhere for exactly that module,
|
||||
with the inserted text re-parsed in the assertion.
|
||||
them carrying `$` and `}`), and `inline.rs`'s
|
||||
`a_plan_with_an_escaped_identifier_gets_no_ghost` pins the server side.
|
||||
|
||||
## How precise the position gate is
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ pub fn propagate_ports(files: &[(PathBuf, String)], file: &Path, offset: u32)
|
||||
pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32)
|
||||
-> Vec<PortAction>;
|
||||
pub fn may_have_port_action(text: &str, offset: u32) -> bool;
|
||||
// added 2026-08-28, for the server's file-set question:
|
||||
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String>;
|
||||
pub fn enclosing_module(text: &str, offset: u32) -> Option<String>;
|
||||
```
|
||||
|
||||
`files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence
|
||||
@@ -339,14 +342,85 @@ neither is offered where the refactoring would be refused. They answer for the
|
||||
**start** of the requested range: a code action is about where the cursor is.
|
||||
|
||||
A code-action request arrives on **every cursor move**, and computing an
|
||||
answer means reading the whole in-scope file set and building an index — a
|
||||
fifth of a second on a large workspace, on a single-threaded server. So the
|
||||
engine exposes a cheap one-file question, `may_have_port_action(text, offset)`:
|
||||
one parse of the buffer itself, no workspace and no I/O, answering "is this
|
||||
position inside a port element, a non-ANSI port declaration, or an
|
||||
instantiation?". The server asks it *before* materializing anything. It cannot
|
||||
hide a refactoring: all three start by locating exactly one of those three
|
||||
constructs.
|
||||
answer used to mean reading the whole in-scope file set and building an index
|
||||
— a fifth of a second on a large workspace, on a single-threaded server, and
|
||||
2.9 s on OpenTitan's 3 976 files, with every queued definition and hover
|
||||
waiting behind it. Two things keep that off the cursor path, and both are the
|
||||
engine's own walk:
|
||||
|
||||
- `may_have_port_action(text, offset)` — one parse of the buffer itself, no
|
||||
workspace and no I/O, answering "is this position inside a port element, a
|
||||
non-ANSI port declaration, or an instantiation?". The server asks it
|
||||
*before* materializing anything. It cannot hide a refactoring: all three
|
||||
refactorings start by locating exactly one of those three constructs.
|
||||
- `port_action_modules(text, offset)` — the same walk saying *which* module it
|
||||
found, so the server can hand the engine that module's own fan-out instead
|
||||
of the workspace. `may_have_port_action` is this function asked for
|
||||
emptiness (one walk, two readers), which is what keeps the gate and the
|
||||
fan-out from ever disagreeing about which positions carry an action.
|
||||
|
||||
### The file set a port action reads — why a subset is the same answer
|
||||
|
||||
`Workspace::module_sources(file, modules)` (`lucisv_server/src/state.rs`)
|
||||
builds the file set both `ports::code_actions` and `ports::execute` hand to the
|
||||
engine. It is `sources()` narrowed to four rungs:
|
||||
|
||||
1. **the file the request names** — the open buffer's text, as always;
|
||||
2. **every file declaring one of `modules`** — `index.units(name)`;
|
||||
3. **every file that instantiates one** — `index.instantiations_of(name)` —
|
||||
**or otherwise refers to one** — `index.references_to(def)`;
|
||||
4. **every open buffer**, whatever it contains.
|
||||
|
||||
The answer is *equal* to the whole-workspace answer, and the argument is one
|
||||
per way a file can influence the result:
|
||||
|
||||
- **A file the plan can edit.** `plan_add`/`plan_remove` loop over the whole
|
||||
scope, but `instantiation_edits`/`disconnection_edits` write nothing in a
|
||||
file that does not textually contain the module name and parse an
|
||||
instantiation of it under `collect_instantiations`. That census — module
|
||||
bodies, packages, nested modules, generate regions (`if`/`for`/`case`), and
|
||||
`bind` — is walk-for-walk the one `vlog_semantic::instantiations::sites`
|
||||
performs to record the index's instantiation edges, so rung 3 names exactly
|
||||
the files that could gain or lose a connection. `plan_propagate` edits the
|
||||
cursor's file alone. **One gap**: `edges_of` drops a site with no owning
|
||||
module — an instantiation written at *file scope*, illegal SystemVerilog a
|
||||
tolerant parse still produces — and the engine would have edited it. Rung 3's
|
||||
second half covers it: an instantiation's module name is a
|
||||
`Target::Module` reference wherever it is written, so the file appears in
|
||||
`references_to` even when it is nobody's edge.
|
||||
- **A file that decides `locate_module`'s verdict.** Every one of them is in
|
||||
rung 2, *all* of them, so a module declared twice still produces the "lucisv
|
||||
will not guess which module's ports these are" refusal instead of quietly
|
||||
picking the one definer that happened to be in the set. Rung 2 is the reason
|
||||
the set is built from `units(name)` rather than from a single definition.
|
||||
- **A file the verifier watches.** `check::watched_files` widens verification
|
||||
to every file spelling the module name, edited or not, and compares each
|
||||
one's declarations and resolutions before and after. For a file that is not
|
||||
edited, "before" and "after" differ only if some *anchor* moved — and an
|
||||
anchor is a local declaration (its own text, unchanged) or a def in the
|
||||
rebuilt index (pre-shifted through the edits by `Shifts`, which is why an
|
||||
insertion in the module's file does not read as a difference). An anchor
|
||||
that could move is by construction a reference *into* the edited module or
|
||||
its members — which is a `references_to` posting, rung 3. Every other file's
|
||||
print is identical on both sides whether it is in the set or not, so
|
||||
omitting it cannot turn a refusal into an offer.
|
||||
- **A file the index has not seen.** An unsaved buffer's live text can add or
|
||||
remove any of the above, and the edges are only as fresh as the last save —
|
||||
so rung 4 takes every open buffer whole, exactly as `collect_sources` does.
|
||||
|
||||
Everything else about the set is `collect_sources`'s rules unchanged: each
|
||||
file's text is the open buffer's when there is one and disk otherwise, a
|
||||
buffer on the large-file fast path contributes nothing, and a file over
|
||||
`lucisv.index.maxFileSize` is not read.
|
||||
|
||||
Pinned by four tests in `lucisv_server/src/ports.rs`, each asserting against
|
||||
the whole-workspace computation rather than a transcription of it:
|
||||
`a_code_action_answers_what_the_whole_workspace_would`,
|
||||
`an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen`,
|
||||
`a_module_declared_twice_is_refused_through_the_subset_as_well`,
|
||||
`a_command_computes_over_the_subset_and_answers_the_same`, plus
|
||||
`the_files_a_code_action_reads_are_the_modules_own_fan_out`, which asserts the
|
||||
noise files really are absent (4 files read of 44).
|
||||
|
||||
**Commands** (`workspace/executeCommand`, advertised in
|
||||
`executeCommandProvider`):
|
||||
@@ -390,7 +464,19 @@ engine's sentence verbatim, M2's precedent.
|
||||
- **A port refactoring is a rare, user-initiated request**, so re-parsing the
|
||||
in-scope files that mention the module (twice: once to plan, once to verify)
|
||||
is affordable. The substring prefilter M2 introduced keeps it to a handful of
|
||||
files. Measured below.
|
||||
files. Measured below. **Amended 2026-08-28**: a *code action* is not rare —
|
||||
it arrives on every cursor move — so the files handed to the engine are the
|
||||
module's fan-out rather than the workspace (above).
|
||||
- **The index is the server's authority on where a module is declared and
|
||||
instantiated.** The fan-out is read from it, so a port action sees the
|
||||
workspace as far as the index describes it: a file changed on disk with
|
||||
nothing telling this server, or a file a startup scan has not reached yet,
|
||||
is a file the action does not read. That is the same rule every other
|
||||
index-backed answer already lives by — definition, hover, references, the
|
||||
code lens, the call hierarchy — and the file watcher is what keeps it true.
|
||||
Before 2026-08-28 a port action re-read the whole scope from disk and was
|
||||
the one answer in the server that could see further than the index; it no
|
||||
longer is.
|
||||
- **Two spaces** are used for the one indentation lucisv has to invent (a body
|
||||
declaration in a module with no items at all). Every other insertion copies an
|
||||
indentation that is already in the file.
|
||||
@@ -436,6 +522,27 @@ engine's sentence verbatim, M2's precedent.
|
||||
- `warnings` are informational: an `Ok` with warnings is still safe to apply.
|
||||
- `PortAction.title` is user-facing text; the server does not rewrite it.
|
||||
|
||||
**Consumed from `vlog_semantic`, added 2026-08-28** (no change required):
|
||||
`WorkspaceIndex::{instantiations_of, references_to}` — the incremental-index
|
||||
edge and posting tables — are what make the file set a lookup instead of a
|
||||
workspace read. The equality argument above leans on one property of theirs:
|
||||
`edges_of` records the census `instantiations::sites` walks, which is the walk
|
||||
`ports::collect_instantiations` performs. If either walk grows a node kind the
|
||||
other does not, the fan-out stops being a superset of the editable files —
|
||||
so **they must move together**.
|
||||
|
||||
**Requested of `lucisv_server`'s rename surface (follow-up, not this round):**
|
||||
`rename` and `prepare_rename` still call `ws.sources()` and run the engine
|
||||
over every in-scope file. On the synthetic 504-file workspace the port probe
|
||||
uses, `prepare_rename` costs **249 ms** (of which `sources()` alone is 14.5
|
||||
ms — the rest is the index build and the analyses over every file);
|
||||
`textDocument/prepareRename` is sent when the user presses the rename key, not
|
||||
per cursor move, so it does not block the way the code action did. The subset
|
||||
for a rename is a *different* argument from this one — a rename must see every
|
||||
file that could name the symbol, and the postings table
|
||||
(`references_to`/`references_are_ambiguous`) is the candidate — so it is filed
|
||||
here rather than guessed at now.
|
||||
|
||||
**Changed in `lucisv_server`** (protocol layer only): `code_action::wanted` is
|
||||
now `pub` so the port actions can honor the same `only` filter the lint actions
|
||||
do; `server.rs` gained the `workspace/executeCommand` arm and the port-action
|
||||
@@ -467,6 +574,11 @@ call inside the existing `textDocument/codeAction` arm; `main.rs` advertises
|
||||
- [x] `lucisv_server`: code actions, three commands, capabilities
|
||||
- [x] `may_have_port_action` — the one-file pre-check that keeps a
|
||||
cursor-move-frequency code-action request off the workspace walk
|
||||
- [x] The file set a port action reads is the module's fan-out through the
|
||||
index, not `sources()` (2026-08-28): `port_action_modules` /
|
||||
`enclosing_module` in the engine, `Workspace::module_sources` in the
|
||||
server, one builder for both callers, with the equality argument above
|
||||
and five equivalence tests
|
||||
- [x] Conditional-compilation guard on both insertion paths: refuse inside an
|
||||
arm, warn when the list carries directives at all (QA HIGH #1)
|
||||
- [x] Preprocessor warnings on removal — macro-invocation arguments and
|
||||
@@ -652,6 +764,62 @@ still `Ok((6, 18))` in 0.36 s, so the guard false-refuses nothing in real RTL.
|
||||
One clippy-driven tidy while there: the header planner's arguments are now a
|
||||
`File { text, path, tokens }` struct rather than eight positional parameters.
|
||||
|
||||
**2026-08-28 — dev agent.** `textDocument/codeAction` no longer reads the
|
||||
workspace per cursor move. The owner's instrumented session on OpenTitan
|
||||
measured 3 111 ms and 3 015 ms for a code action against 0.01–0.44 ms for
|
||||
every other request; VS Code sends one on nearly every cursor move and the
|
||||
server is single-threaded, so a cursor resting on an instantiation — which is
|
||||
exactly where F12 leaves it — held every queued definition and hover behind
|
||||
it. That is the "goto definition is slow" report: the definition answered in
|
||||
microseconds and stood in a three-second queue.
|
||||
|
||||
What changed:
|
||||
|
||||
- **`vlog_refactor::port_action_modules`** — `may_have_port_action`'s walk,
|
||||
returning the module names it found instead of a bool, and
|
||||
`may_have_port_action` is now that function asked for emptiness. One walk,
|
||||
two readers, so the gate and the fan-out cannot drift; a byte-by-byte
|
||||
equality test over a mixed file pins the two against each other.
|
||||
**`vlog_refactor::enclosing_module`** is the same question for the command
|
||||
path, where `lucisv.addPort` takes a position anywhere in a module —
|
||||
`module_at` made public, which is precisely what `ModuleRef::At` resolves
|
||||
with, so the server names the module the engine will name.
|
||||
- **`Workspace::module_sources`** — the one file-set builder, used by
|
||||
`ports::code_actions` and by all three commands through `ports::sources_at`.
|
||||
Four rungs and the equality argument are written up under "The file set a
|
||||
port action reads" above; the two decisions worth repeating here are that
|
||||
**all** definers of the name go in (or an ambiguous module would stop
|
||||
refusing) and that `references_to` goes in beside `instantiations_of` (or a
|
||||
file-scope instantiation, which records no edge, would stop being edited).
|
||||
- Both callers share the builder, so there is no second code path with a
|
||||
second answer; `execute` computes the names per command shape rather than
|
||||
materializing anything before it knows what it was asked.
|
||||
|
||||
Measured, release:
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| synthetic 504 files, cursor on a port instantiated in 3 of them | 725 ms | **0.41 ms** |
|
||||
| OpenTitan (3 976 files), cursor on a port of `adc_ctrl_core`, action offered | 4.56 s | **7.1 ms** |
|
||||
| OpenTitan, cursor on a `prim_fifo_sync` instantiation (36-file fan-out) | 2.93 s | **83 ms** |
|
||||
|
||||
The last row is the honest ceiling: `prim_fifo_sync` is instantiated all over
|
||||
OpenTitan, so its fan-out is 36 real files and the engine parses them twice
|
||||
(plan, then verify) — 1.3 ms of that is reading them, the rest is the engine.
|
||||
A module with a normal fan-out is the middle row. The synthetic probe is
|
||||
`perf::a_code_action_at_an_instantiation_before_and_after`, which prints the
|
||||
before column, the after column and `sources()` alone; the OpenTitan numbers
|
||||
were taken with a throwaway probe against the local checkout and deleted, since
|
||||
no test may depend on it. Both OpenTitan cursors were also checked for
|
||||
*equality* against the whole-workspace computation — same titles, same edited
|
||||
file counts — beside the five equivalence tests in the suite.
|
||||
|
||||
Deliberately untouched: `rename`/`prepare_rename`'s `sources()` calls, filed as
|
||||
a Handshake follow-up with its number (249 ms on the synthetic workspace).
|
||||
Gates: `cargo fmt` clean, `cargo clippy --all-targets` clean, `cargo test`
|
||||
green workspace-wide, `node editors/vscode/smoke.js` OK against the release
|
||||
binary.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-24 — QA agent.**
|
||||
@@ -1179,8 +1347,87 @@ counts across all three QA passes are themselves evidence against scope
|
||||
creep. The one imprecision found (over-broad trailing-directive warning
|
||||
text) is cosmetic, safe-direction, and not blocking.
|
||||
|
||||
**2026-08-28 — QA agent.** Round on the codeAction-fan-out change: `Workspace::module_sources` replacing `ws.sources()` for `textDocument/codeAction` and the three port commands. Adversarial charter: find a file the whole-workspace computation would have edited (or that would change/refuse the answer) missing from the subset — refactoring correctness, invariant-1-adjacent.
|
||||
|
||||
### Gates
|
||||
|
||||
- `cargo fmt --all -- --check` — clean.
|
||||
- `cargo clippy --all-targets` — clean, zero warnings, workspace-wide (one warning surfaced from a QA-added test — `map_or(true, …)` → `is_none_or(…)` — fixed directly, small and unambiguous).
|
||||
- `cargo test --workspace` — green, **2482** passed, 0 failed, 0 measured (28 `#[ignore]`d perf probes not run) — includes the 6 permanent regression tests added this round (below). `lucisv_server`'s own unit suite: **1249** passed, 28 ignored. `vlog_refactor` unit: 72, `tests/ports.rs`: 52 (dev added 2: the byte-sweep pinning `may_have_port_action`/`port_action_modules` against each other, and `enclosing_module`'s own test).
|
||||
- `node editors/vscode/smoke.js target/release/lucisv-server` — OK (had to pass the binary path explicitly; `lucisv-server` is not on `PATH` in this environment, not a project issue).
|
||||
- Reproduced the synthetic perf claim exactly: `perf::a_code_action_at_an_instantiation_before_and_after` (`--release`) printed **724 ms → 409 µs**, `sources()` alone **14.4 ms**, `prepareRename` **250 ms** — matches the README's 725 ms / 0.41 ms / 14.5 ms / 249 ms table to the reported precision.
|
||||
- Reproduced the OpenTitan claim's *shape* independently, with a throwaway probe (added to `perf.rs`, run, then reverted — not in the tree): cursor on a port of `adc_ctrl_core.sv` went **3.13 s → 3.17 ms**; cursor on a `prim_fifo_sync` instantiation (in `otp_ctrl.sv`, a different real fan-out site than the dev's) went **3.08 s → 84.6 ms** — both essentially the dev's numbers (4.56 s→7.1 ms; 2.93 s→83 ms) to within what a different instantiation site and a warm/cold FS cache would explain. Both probe cursors landed on offsets that produced 0 offered actions on *both* sides (an imprecise offset, not a bug), but the **parity held** (0 == 0) in both cases, which is the property that matters here. No test depends on the checkout, per the brief.
|
||||
|
||||
### Attack angles from the brief, and what I found
|
||||
|
||||
**1. Missing-file attacks — all held.** Wrote 4 new permanent regression tests attacking the exact scenarios the brief named, each asserting the subset's `code_actions`/`module_sources` answer against `whole_workspace_at` (the dev's own reference function) or `ws.sources()`:
|
||||
|
||||
- `qa_file_scope_instantiation_lands_in_the_subset` (`crates/lucisv_server/src/ports.rs`) — an owner-less instantiation (`sub u_fs (.clk(c), .rst(r));` at file scope, no enclosing module) records **no** `InstantiationEdge` (confirmed directly: `edges_of` requires an owner), yet the file lands in `module_sources` and the subset's answer matches the whole-workspace one exactly. This is the dev's rung-3-second-half claim (`references_to` catching what `instantiations_of` structurally cannot) — verified empirically, not just by reading `resolve.rs`'s `named_at_file_scope`/`bind_instantiation` code path that makes it true. This was the brief's most specific, most load-bearing ask ("verify it actually lands in `references_to`") and it does.
|
||||
- `qa_generate_block_instantiation_lands_in_the_subset` — an instantiation inside a `generate for` body is a real `InstantiationEdge` (confirmed) and its file is in the subset, subset == whole-workspace.
|
||||
- `qa_escaped_module_name_instantiation_parity_with_whole_workspace` — an escaped-identifier instantiation (`` \sub u_esc (...) ``). Whatever the parser/binder does with the escape (resolve it to `sub` or treat it as a distinct name — did not chase which, since it is a pre-existing lexical question this round did not touch), the subset and whole-workspace answers agree. Framed as a parity check rather than a correctness check of escaping itself, since a bug there would be M1/M2-era and out of this round's scope.
|
||||
- `qa_add_port_by_position_still_fans_out_to_instantiation_files` — the dev's own equivalence test (`a_command_computes_over_the_subset_and_answers_the_same`) only exercises `lucisv.addPort` with a **module-name** argument, which reaches `module_sources` directly. The **Position** argument goes through a different function (`sources_at`, used by all three commands and by nothing else previously tested at the command layer) — confirmed it still reaches all 3 instantiating files, matching `ws.sources()`'s answer byte-for-byte.
|
||||
- Not separately tested as a new attack, but read and reasoned through carefully: `.*` connections, hierarchical-reference-only files, and macro-expanded module names. `.*` sites are structurally ordinary `Instantiation` nodes to `edges_of`/`collect_instantiations` (connection *style* plays no part in either census), so they get the same edge as a named-connection site — no special case to miss. A file whose only relationship to the module is a hierarchical reference to one of its ports (no instantiation) is not in scope for *either* the old or the new computation (neither `collect_instantiations` nor `edges_of` would ever find or edit it), so it cannot be a point of divergence. A macro-expanded module name is one opaque token to lucisv's non-preprocessing binder in both the old and new code paths equally (documented Assumption, unchanged) — not a regression this round could introduce.
|
||||
- Did **not** separately verify a duplicate-module-name-under-macro or a nested-module-inside-a-package instantiation; ran out of budget. Low-risk: `collect_instantiations`/`edges_of` both explicitly walk `ItemKind::Package{items,..}` identically (confirmed by direct side-by-side read of both functions, `crates/vlog_semantic/src/instantiations.rs:68-105` vs `crates/vlog_refactor/src/ports.rs:489-518` — they are the same match arms in the same order, which is exactly the Handshake's "walk-for-walk" claim, verified by inspection rather than by a fresh test).
|
||||
|
||||
**2. Refusal-parity attacks.**
|
||||
|
||||
- Duplicate-definer-already-indexed: the dev's own `a_module_declared_twice_is_refused_through_the_subset_as_well` covers this (re-ran, passes).
|
||||
- New module in an **unsaved buffer the index has never heard of at all** (not stale — genuinely absent): `qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled` — a module declared only in a brand-new, never-saved-to-disk buffer, with the cursor inside that same buffer. Rung 1 ("the file the request names") is what carries it, since rung 2 (`index.units`) is empty for a name the index has never indexed. Confirmed it still offers the action correctly (`lucisv: remove port \`b\` (no instantiation in scope)`), no panic, no silent no-op.
|
||||
- **Index stale vs. disk — the one place I judged rather than just tested.** `qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption`: wrote a *second* definer of `sub` straight to the filesystem, bypassing the server (`fs::write`, no `rebuild_index`, no `set_document`). Confirmed: the subset computation, unaware of the new file, does **not** refuse — it offers the action as if the module were still uniquely declared, which is a real, observable divergence from `ws.sources()`'s always-fresh-from-disk answer (the old code path *would* have refused here). Judged against invariant 1, not against freshness, per the brief's own framing: this cannot corrupt anything, because the engine is handed exactly the files in the subset and has no I/O of its own — `dupe.sv` is never read and never appears in the produced edit (asserted directly). The worst case is a **stale-but-internally-consistent** answer (an edit that is fully verified against the files it actually saw), not a wrong-and-unverified one. This is exactly the trade-off the dev's own Assumptions section documents ("the index is the server's authority... a file changed on disk with nothing telling this server is a file the action does not read") and explicitly parallels every other index-backed LSP answer in the server (definition, hover, references). I agree with the dev's framing: this is a disclosed staleness trade-off, not a hidden safety gap, and does not violate "never corrupt code." Confirmed the parity is restored the moment the index is told (`rebuild_index()` → refuses, matching whole-workspace).
|
||||
|
||||
**3. Gate ⟺ subset coherence — verified by direct code comparison, no divergence found.** `may_have_port_action` is now defined literally as `!port_action_modules(...).is_empty()` (`crates/vlog_refactor/src/ports.rs:159`), so the two cannot drift by construction; the only residual risk was a logic bug introduced while refactoring the original single-`bool` walk into a `Vec<String>`-returning one. Diffed the two versions line-by-line: the only structural change is `.any(...)` → `.filter(...).map(...).collect()` over the same predicate, which is behavior-preserving (a multi-match, if the tolerant parser ever produced overlapping instantiation spans, would just widen the returned module list — still correctly non-empty, never a false negative). The dev's own new test (`the_pre_check_names_the_module_whose_files_the_action_will_need`, `crates/vlog_refactor/tests/ports.rs`) sweeps every byte offset of a mixed file and asserts `may_have_port_action(text, offset) == !port_action_modules(text, offset).is_empty()` — re-ran it, passes. No old-vs-new crafted-file attack found a gate-false position the old whole-workspace path would have offered an action for, because the "old path" *is* this same walk (`may_have_port_action` was never a separately-maintained function — it's the same code, just newly able to say which module).
|
||||
|
||||
**4. Command parity — held**, including the position-argument case above (attack 1's `qa_add_port_by_position...` doubles as this). `REMOVE_PORT`/`PROPAGATE_PORTS` both go through `sources_at`, which unions `port_action_modules` (what the offset directly names — a port, or an instantiation's own module) with `enclosing_module` (the module the offset sits textually inside) — read `locate_module`'s `ModuleRef::At` (`ports.rs:379-413`) and `locate_port`/`plan_propagate`'s own module-name derivation to confirm `sources_at` always names a superset of what the engine will independently look up for each of the three commands; for `propagate_ports` specifically the extra `enclosing_module` name is unnecessary (the README says propagate only ever touches the cursor's own file) but harmless — it can only add files, never omit the one that matters.
|
||||
|
||||
**5. Verifier integrity.** Read this one by construction rather than by attack: `check::watched_files` and the whole verifier only ever see the files handed to `Scope::build(files)` — the crate does no I/O of its own (Handshakes, unchanged this round). So "an edit corrupts a file outside the subset" is not reachable as a distinct failure mode in this design: the engine cannot write to, or even read, a file that was never in the set. The only failure mode a wrong subset can produce is the one attack angle 1 covers (a file that *should* have been edited is silently skipped) — which is why I put the budget there instead of trying to construct a doomed "verifier misses an out-of-subset corruption" scenario that the architecture rules out by construction.
|
||||
|
||||
### Tests added (all permanent, all in `crates/lucisv_server/src/ports.rs`'s `mod tests`)
|
||||
|
||||
`qa_file_scope_instantiation_lands_in_the_subset`, `qa_generate_block_instantiation_lands_in_the_subset`, `qa_escaped_module_name_instantiation_parity_with_whole_workspace`, `qa_add_port_by_position_still_fans_out_to_instantiation_files`, `qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled`, `qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption`. No probe files left in the tree; the only non-test-only edit was the `map_or` → `is_none_or` clippy fix inside my own new test code (nothing in the dev's code touched).
|
||||
|
||||
### Summary
|
||||
|
||||
| Claim | Verdict |
|
||||
|---|---|
|
||||
| `cargo fmt`/`cargo clippy`/`cargo test --workspace`/smoke | **Pass** |
|
||||
| File-scope (owner-less) instantiation lands in the subset via `references_to` | **Pass, confirmed empirically** — the brief's most specific ask |
|
||||
| Generate-block instantiation, escaped-identifier parity | **Pass** |
|
||||
| `ModuleArgument::Position` (not just `Name`) still fans out correctly | **Pass, confirmed** — previously untested combination |
|
||||
| Ambiguous-module refusal, via the index | **Pass** (dev's own test, re-verified) |
|
||||
| Unsaved brand-new module (index has never heard of it) | **Pass** |
|
||||
| Index stale vs. disk (duplicate definer unindexed) | **Behaves as documented**: a stale-but-verified answer, never a corruption; matches the Assumptions section's own framing |
|
||||
| Gate (`may_have_port_action`) ⟺ fan-out (`port_action_modules`) coherence | **Pass, verified by construction + the dev's byte-sweep test** |
|
||||
| Command parity across all three commands | **Pass** |
|
||||
| Verifier cannot touch a file outside the subset | **True by construction** (no I/O in the crate) |
|
||||
| Perf claims (synthetic + OpenTitan) | **Reproduced**, synthetic to the reported precision, OpenTitan to the same order of magnitude on different cursor sites |
|
||||
|
||||
No corruption, no false refusal, no lost feature, and no missing-file divergence found anywhere I could construct one. The one real, novel-to-this-round behavior change (index staleness vs. `sources()`'s always-fresh disk read) is pre-existing in spirit everywhere else in the server, is disclosed prominently in the feature's own Assumptions section, and cannot produce a corrupt edit by the crate's own no-I/O architecture — so I am not filing it as a finding, only recording that I attacked it deliberately and it held.
|
||||
|
||||
**Verdict: SHIP.** No blocking or non-blocking findings this round.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead, codeAction fan-out round.** Reviewed after QA's
|
||||
clean SHIP; gates re-run independently (fmt clean, clippy silent, 2482
|
||||
workspace tests green). This closes the owner's original report from
|
||||
the root: the "slow F12" was a 3–4.5 s codeAction on every cursor move
|
||||
blocking the single-threaded loop, and the fix is the house pattern —
|
||||
the index's fan-out instead of `ws.sources()` — with the sufficiency
|
||||
argument written before the speed was trusted. The dev's fourth rung
|
||||
(`references_to`, because `edges_of` drops owner-less file-scope
|
||||
instantiations) is exactly the kind of gap that separates a subset from
|
||||
a superset, found by reading rather than by failing; QA confirmed it
|
||||
empirically and pinned it. The one behavior change — a port action now
|
||||
sees the workspace as the index describes it, so an unindexed on-disk
|
||||
duplicate yields a stale offer instead of a fresh refusal — is
|
||||
disclosed in Assumptions, cannot corrupt (the engine does no I/O of
|
||||
its own; QA proved the untouched file untouched), and aligns this
|
||||
answer with every other index-backed one. 4.56 s → 7.1 ms on
|
||||
opentitan, 83 ms honest ceiling at a 36-file fan-out, both reproduced
|
||||
by QA on different cursors. The prepareRename follow-up (250 ms on the
|
||||
synthetic; 2.5–3 s measured on opentitan in performance.md) is Lane A
|
||||
of the performance wave. Accepted; committed by the lead.
|
||||
|
||||
**2026-08-24 — lead.** Reviewed after QA round 2's ship verdict; gates run
|
||||
independently (1170 tests, 0 failures, clippy silent). The splice verifier
|
||||
plus per-feature shape check is the right division — the verifier stays
|
||||
|
||||
@@ -29,6 +29,12 @@ pub fn prepare_rename(files: &[(PathBuf, String)], file: &Path, offset: u32)
|
||||
-> Result<RenameTarget, String>;
|
||||
pub fn rename(files: &[(PathBuf, String)], file: &Path, offset: u32, new_name: &str)
|
||||
-> Result<RefactorEdit, String>;
|
||||
|
||||
// Added 2026-08-28 (the performance wave). Same question, no file set.
|
||||
pub fn prepare_rename_here(semantics: &Semantics, external: &ExternalResolutions,
|
||||
index: &WorkspaceIndex, offset: u32)
|
||||
-> Result<RenameTarget, String>;
|
||||
pub fn rename_name_at(semantics: &Semantics, offset: u32) -> Option<String>;
|
||||
```
|
||||
|
||||
`files` is **the boring option**: the in-scope files as `(path, text)` pairs —
|
||||
@@ -47,6 +53,15 @@ Deviations from the milestone sketch, and why:
|
||||
parameter would be cast at both ends of every call.
|
||||
- **`prepare_rename` returns a `RenameTarget`**, not a bare range: the editor
|
||||
wants the placeholder too, and it is the identifier's own text.
|
||||
- **`prepare_rename_here` takes an analysis rather than a file set** (added
|
||||
2026-08-28). The server already holds every argument it needs for the open
|
||||
buffer, so this asks nothing of the filesystem; `prepare_rename` stays as
|
||||
the whole-workspace oracle the parity tests measure it against. See "The
|
||||
file set a rename reads" below.
|
||||
- **`rename_name_at` decides nothing.** It answers only "which identifier is
|
||||
under this cursor", which is what the server needs to ask the index for the
|
||||
fan-out. Every refusal stays with `rename`, which is the call that has the
|
||||
files; a second opinion here could only disagree with it.
|
||||
|
||||
## What can be renamed
|
||||
|
||||
@@ -131,6 +146,300 @@ shape for refactorings).
|
||||
needs to decide whether to open the rename box at all: everything else needs a
|
||||
new name to judge.
|
||||
|
||||
## The file set a rename reads (2026-08-28)
|
||||
|
||||
Until this round both entry points were handed `Workspace::sources()` — every
|
||||
in-scope file, read from disk — and built a whole `WorkspaceIndex` over it
|
||||
before answering anything. On OpenTitan (3 976 files) that cost **1.7–3.0 s
|
||||
for `prepareRename`** and **3.2–8.7 s for `rename`**, on a single-threaded
|
||||
server where everything the editor sent next waited behind it. `prepareRename`
|
||||
is what the rename key sends *before the box opens*, so those seconds were a
|
||||
frozen editor on a keypress that had committed to nothing.
|
||||
|
||||
Two different fixes, because they are two different questions.
|
||||
|
||||
### `prepareRename`: the buffer already holds the answer
|
||||
|
||||
The question is "is this a renameable symbol, and what are its range and
|
||||
placeholder". `prepare_rename_here` answers it from the open buffer's own
|
||||
`Semantics`, the `ExternalResolutions` overlay the server keeps beside it, and
|
||||
the index — **no file is read and nothing is parsed**. Measured: 238 ms →
|
||||
**200 ns** on the synthetic 504-file workspace, 1.604 s → **135 ns** on
|
||||
OpenTitan.
|
||||
|
||||
#### Refusal-by-refusal parity
|
||||
|
||||
Every refusal `prepare_rename` can produce, and what the cheap path does with
|
||||
it. Deferring a refusal to `rename` is allowed — LSP explicitly permits an
|
||||
optimistic `prepareRename` — and losing one is not: a deferred refusal is
|
||||
still delivered, in the same words, by the `rename` that follows.
|
||||
|
||||
| # | Refusal (its own sentence) | Where it comes from | Cheap path |
|
||||
|---|---|---|---|
|
||||
| 3 | *"… is not one of the files lucisv indexes …"* | the request's file absent from `files` | **unreachable either way.** `sources()` contains every open buffer with a path, and this handler is only reached for one; a fast-path (large) buffer is refused by `server.rs` before it gets here. |
|
||||
| — | *"the file could not be analyzed."* | `Scope::analysis` of an in-range index | **dead code in both**: the index came from `index_of`, so the lookup cannot miss. |
|
||||
| 4 | *"there is no symbol to rename at this position."* | no reference and no symbol at the offset | **reproduced** — `reference_id_at` / `symbol_at` on the buffer. |
|
||||
| 5 | *"… is not resolved to any declaration …"* | `Resolution::NotFound` | **reproduced** — single-file resolution, in the buffer. |
|
||||
| 6 | *"… could only come from the base class `B` …"* | `Resolution::InheritedCandidate` | **reproduced** — same. |
|
||||
| 7 | *"… is declared outside the files lucisv indexes …"* | `ExternalTarget::StillUnresolved` / absent | **reproduced** — the overlay is `resolve_external` against this same index, which is the call `Scope::declaration_across_files` makes. |
|
||||
| 8 | *"… is declared in more than one indexed file …"* (from a cross-file use) | `ExternalTarget::Ambiguous` | **reproduced** — same overlay. |
|
||||
| 9 | *"… is declared in more than one indexed file …"* (from the declaration) | `declaration.scope == file_scope && index.units(name).len() > 1` | **reproduced** — the buffer knows the scope, the index knows the count. |
|
||||
| 11a | *"lucisv cannot find where `x` is spelled in its declaration …"*, declaration **in this buffer** | empty `name_span` | **reproduced.** |
|
||||
| 11b | the same sentence, declaration in **another** file | that file's fresh `name_span` | **deferred.** The index only ever records a non-empty span, so this can only fire on a file whose analysis disagrees with the index — which means reading it. |
|
||||
| — | *"`x`'s declaring file is not in scope."* | `index_of` on the declaring path | **deferred** (and unreachable in practice: `sources()` is a superset of the index's files). |
|
||||
| — | *"the declaring file could not be analyzed."* / *"lucisv cannot locate the declaration of `x`."* | the declaring file's own analysis | **deferred**, same reason. |
|
||||
| 1, 2, 10, 12, 13 | new-name validity, same name, ambiguous use onto this declaration, capture, token drift | — | **not `prepare_rename`'s at all**; they always were `rename`'s. |
|
||||
|
||||
Pinned by `rename::tests::the_buffer_answers_a_prepare_exactly_as_the_workspace_does`
|
||||
and its five siblings, which ask both entry points the same question at **every
|
||||
byte** of hostile buffers — packages and qualified names, a name declared
|
||||
twice, nothing resolving, generate blocks and macros, a file that does not
|
||||
parse — and fail on any reworded refusal, any different answer, and any
|
||||
refusal the cheap path *invents*. Deferrals are counted, never asserted away.
|
||||
|
||||
**The one divergence, stated exactly.** Rule 9's count comes from the index,
|
||||
and the index is rebuilt on save, not on keystroke (`state.rs`), so an unsaved
|
||||
edit that adds or removes a file-scope declaration of the name is not in it.
|
||||
`prepare_rename` counts the same declarations over the *current* texts. Both
|
||||
directions are possible in principle; both are the ordinary index-staleness
|
||||
window every other index-backed answer in this server lives in, and the
|
||||
sentence itself says "indexed file". `rename` re-derives the count from the
|
||||
current texts and is the authority.
|
||||
|
||||
### `rename`: the symbol's fan-out, and why it is enough
|
||||
|
||||
`Workspace::rename_sources` (state.rs) builds the file set from what the index
|
||||
already holds. Its rungs, for the request's file, every open buffer, and each
|
||||
spelling `N` in `{old_name, new_name}`:
|
||||
|
||||
1. **every file declaring `N`** — `WorkspaceIndex::workspace_symbols(N)`
|
||||
filtered to the exact name, which covers units *and* members (ports,
|
||||
parameters, package and class members);
|
||||
2. **every file the index recorded a use of one of those declarations in** —
|
||||
`references_to(def)`, for **every** such declaration, not only the target's;
|
||||
3. **every file instantiating `N`** — `instantiations_of(N)`;
|
||||
4. **every file whose `` `define`` table names `N` or spells it in a macro
|
||||
body** — a walk over the `DefineTable`s the index already holds (no file is
|
||||
read), asking the same `vlog_refactor::contains_word` that
|
||||
`Scope::define_sites` decides with, so the fan-out and the warning cannot
|
||||
disagree about which files carry one;
|
||||
5. **the units that export `N` as a member**, and every file declaring,
|
||||
referring to or instantiating one of them — how a third file's `.N(...)`
|
||||
connection or `u::N` is reached.
|
||||
|
||||
and, for the **new name only**, a sixth:
|
||||
|
||||
6. **every file that spells the new name in a use this workspace had to look
|
||||
outside that file to answer — including the uses it could not answer at
|
||||
all** — `WorkspaceIndex::files_spelling(N)`, a walk over the per-file
|
||||
records (no file is read, nothing is parsed). Rungs 1–5 are all keyed by a
|
||||
*declaration*, and a use that resolved to nothing has no declaration to be
|
||||
keyed by; this is the rung that finds it. Why only the new name needs it is
|
||||
argued under "The dangling-use case" below.
|
||||
|
||||
Rung 6 is the only one whose cost grows with the workspace rather than with
|
||||
the symbol, so it is measured on its own: **852 µs on OpenTitan's 3 976 files
|
||||
in the worst case** — a name nothing spells, where the walk cannot
|
||||
short-circuit — and 402 µs for `clk_i`, which 681 files spell. Building the
|
||||
whole file set is 4.75 ms, most of it the other five rungs'
|
||||
`workspace_symbols` scan and `` `define`` walk. Against a rename that costs
|
||||
105 ms and used to cost 3.5 s, a sub-millisecond linear scan is the boring
|
||||
implementation and stays one; a name-keyed side map is the fallback if a
|
||||
workspace ever makes it visible, and nothing measured here comes close.
|
||||
|
||||
#### The sufficiency argument
|
||||
|
||||
**Lemma (name-locality of resolution).** A reference spelling `N` is resolved
|
||||
by `vlog_semantic::follow_paths`, which tries the reference's recorded paths in
|
||||
order and, for each, calls `follow_one` — and `follow_one` returns either
|
||||
`index.units(N)` or `index.member(u, N)` for some unit name `u`. **Both are
|
||||
keyed by `N`, and both are contributed only by files that declare the name
|
||||
`N`** (as a unit, or as a member of some unit). Rung 1 puts every one of those
|
||||
files in the set. Therefore, for every path list and every unit name,
|
||||
`follow_one(subset, N, ·) == follow_one(whole, N, ·)`, so
|
||||
`follow_paths(subset, N, ·) == follow_paths(whole, N, ·)`: **every reference
|
||||
spelling `N` resolves in the subset exactly as it resolves in the whole
|
||||
workspace.** ∎
|
||||
|
||||
Three consequences, which are the three things that could have gone wrong:
|
||||
|
||||
- **No missed edit.** `Scope::collect_occurrences` emits a span in file *i*
|
||||
only when *i* is the declaring file, or when a reference in *i* spelling the
|
||||
old name resolves to the target declaration. The declaring file is rung 1.
|
||||
A file with such a reference resolves the same way in the whole workspace
|
||||
(Lemma), so the index recorded a posting for it — rung 2. Hence every file
|
||||
the whole-workspace rename would edit is in the set. This is the
|
||||
invariant-1 claim, and it is asserted directly, not only through an
|
||||
equality, by `every_file_the_workspace_rename_edits_is_in_the_fan_out`.
|
||||
- **No extra edit.** The converse of the same Lemma: a file in the subset
|
||||
cannot resolve a reference *onto* the target that the whole workspace
|
||||
resolves elsewhere. Without rung 1 this was a live corruption route — drop
|
||||
the file declaring `p::x` and a `p::x`/`q::x` reference would fall through
|
||||
to `q::x` and be renamed — which is why rung 1 is `workspace_symbols` and
|
||||
not `units`.
|
||||
- **The verifier keeps its reach.** `check::watched_files` watches every file
|
||||
spelling the old *or the new* name. In the subset it can only watch what it
|
||||
was given, so the new name gets rungs 1–6 of its own — which is what keeps
|
||||
refusal 12 (capture) alive: `the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere`
|
||||
builds exactly the third file whose existing reference the rename would make
|
||||
ambiguous, and the subset holds it because it is in the *new* name's
|
||||
postings.
|
||||
|
||||
#### The dangling-use case, and why the sixth rung is the new name's alone
|
||||
|
||||
The Lemma settles what a name *resolves to*. It does not by itself settle
|
||||
which files hold a use of that name, and rungs 1–5 answer that question only
|
||||
through declarations: a file is in the set because it declares the name,
|
||||
because a posting keys it to a declaration of the name, because it
|
||||
instantiates the name, because a macro table mentions it, or because it names
|
||||
the unit that exports it. **A use that resolved to nothing is keyed by
|
||||
nothing.** `merge_references` drops a `StillUnresolved` result rather than
|
||||
posting it, which is correct for `references_to` — there is no declaration to
|
||||
post it against — and is exactly the hole.
|
||||
|
||||
That hole is real and it costs a *refusal*, not a warning. Take
|
||||
`import taken_pkg::*` in a file with no other tie to the rename: today it
|
||||
resolves to nothing, and `check::print` records `Anchor::Unresolved`. Rename a
|
||||
package to `taken_pkg` and the same use resolves — `Anchor::External` — which
|
||||
is a changed meaning in a file the rename never edits, and refusal 12 exists
|
||||
to refuse exactly that. QA found this on 2026-08-28 and reproduced it; the
|
||||
lead ruled it not shippable, and rung 6 is the fix.
|
||||
|
||||
**The old name has no analogous case, and this is why.** A rename only ever
|
||||
*removes* declarations of the old name — it renames them away — and never adds
|
||||
one. So for a use spelling the old name:
|
||||
|
||||
- if it **resolves**, its declaration is one of the declarations of the old
|
||||
name, so the file is in `references_to` of that declaration — and rung 2
|
||||
walks *every* declaration of the name, not only the target's. Already in the
|
||||
set.
|
||||
- if it **resolves to nothing**, it still resolves to nothing afterwards.
|
||||
`follow_one` looks the name up in `units(old)` and `member(u, old)`; the
|
||||
rename only takes entries out of those, and a lookup cannot start succeeding
|
||||
because a candidate was taken away. `Anchor::Unresolved` before,
|
||||
`Anchor::Unresolved` after — nothing for the verifier to see, so nothing
|
||||
lost by not reading the file.
|
||||
- if it **resolves ambiguously**, the escape hatch below fires and the whole
|
||||
scope is handed over anyway.
|
||||
|
||||
Pinned from both ends: `a_dangling_import_of_the_new_name_is_refused_by_both_paths`
|
||||
(the new name's case, now parity rather than a disclosed gap) and
|
||||
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own` (the old name's,
|
||||
which asserts both that the new-name rung fires when the dangling spelling is
|
||||
the *destination* and that nothing is pulled in when it is merely a bystander).
|
||||
|
||||
#### The escape hatch
|
||||
|
||||
Refusal 10 — *some other reference resolves ambiguously onto this
|
||||
declaration* — is the one the postings cannot locate: an ambiguous use is
|
||||
recorded against the declarations it could name (`references_are_ambiguous`)
|
||||
and **not** against the file that writes it. Rather than lose that refusal,
|
||||
`rename_sources` hands back the whole `sources()` the moment the index says
|
||||
**any** declaration of either spelling is ambiguously referenced. Correct and
|
||||
slow beats fast and silent. Pinned by
|
||||
`an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope`.
|
||||
|
||||
**How often it fires, measured.** On OpenTitan the `aes` and `clk_rst_if`
|
||||
cursors narrow to 7 and 114 files of 3 976; a cursor on a `.clk_i` port
|
||||
connection falls back to all 3 976 — some declaration named `clk_i` somewhere
|
||||
in the checkout is ambiguously referenced, and the hatch is deliberately
|
||||
asked about *every* declaration of the name rather than about the target
|
||||
alone. The answer is still right there (edits identical, all 652 warnings
|
||||
identical); it is simply not faster. **The obvious narrowing — ask only about
|
||||
the declaration the cursor resolves to, which is the only one refusal 10
|
||||
tests — is left for a later round on purpose**: it needs the target `Def`
|
||||
identified server-side, which reintroduces the buffer-staleness question the
|
||||
rest of this design keeps on one side of a line. Filed, not guessed at.
|
||||
|
||||
#### The staleness premise, stated exactly
|
||||
|
||||
> The index is the server's authority on which files declare a name and which
|
||||
> files use it. A file changed on disk with nothing telling this server — no
|
||||
> save, no watcher event, no rescan — or a file a startup scan has not reached
|
||||
> yet, is a file a rename does not read. **Open buffers are the one exemption:
|
||||
> every open buffer is in the set whatever the index holds, and the engine
|
||||
> re-analyzes it from its current text, so unsaved edits are seen in full.**
|
||||
|
||||
This is the same rule definition, hover, references, the code lens and the
|
||||
call hierarchy already live by, and the file watcher is what keeps it true. It
|
||||
is what the port refactorings adopted on 2026-08-28, one round earlier. What
|
||||
it costs a rename specifically: a reference living only in a file whose disk
|
||||
copy moved unseen is a reference the rename does not rewrite **and cannot
|
||||
refuse over** — `check::verify` re-analyzes the subset, so a file outside it
|
||||
is not compared before and after. Before this round `rename` was, with
|
||||
`prepareRename` and the port actions, one of the few answers in this server
|
||||
that could see *further* than the index; it no longer is.
|
||||
|
||||
#### The residue — what the subset cannot see
|
||||
|
||||
Written out rather than argued away. Each of these is a file whose only
|
||||
mention of a name is something the index records no declaration, posting,
|
||||
instantiation edge, macro definition or external-reference fact for. **After
|
||||
the 2026-08-28 rework there is exactly one, and it costs a warning — no edit
|
||||
and no refusal:**
|
||||
|
||||
- **One warning flavour, and it is the loudest item on this page — measured,
|
||||
not hypothetical.** `Scope::warnings` produces three sentences. Two are read
|
||||
off a file's `` `define`` table (*"`x` is also a macro defined at …"* and
|
||||
*"`x` appears in the body of macro `M` …"*) and **both survive**: the index
|
||||
holds every file's table, and rung 4 walks it
|
||||
(`the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read`).
|
||||
The third comes from a **macro invocation whose arguments spell the name**,
|
||||
and that one needs the file's token stream. A file outside the fan-out no
|
||||
longer produces it.
|
||||
|
||||
On the real OpenTitan checkout, at two cursors, with **no edit lost at
|
||||
either**:
|
||||
|
||||
```
|
||||
aes -> aes_core_top edits identical (7 files, 7 edits)
|
||||
warnings 7 -> 0, every one of them a
|
||||
macro-invocation sentence:
|
||||
`aes` in the arguments of `CONNECT_TL_DEVICE_IF`
|
||||
at tb__xbar_connect.sv:30 and :47 (twice),
|
||||
`DRIVE_CHIP_TL_DEVICE_IF` at :97, :140, :161,
|
||||
`uvm_error` at keymgr_dpe_scoreboard.sv:644
|
||||
|
||||
clk_rst_if -> clk_rst_thing edits identical (114 files, 275 edits)
|
||||
warnings 64 -> 61, the three lost being
|
||||
`uvm_fatal` invocations
|
||||
```
|
||||
|
||||
Those macro invocations really do still spell the old name after the
|
||||
rename, and saying so is the whole point of the warning.
|
||||
`tb__xbar_connect.sv` mentions `aes` **only** inside macro-invocation
|
||||
tokens, and the index models those in no table at all: a macro invocation is
|
||||
one opaque token, contributing no declaration, no reference, no
|
||||
instantiation edge and no define entry, so nothing short of reading and
|
||||
lexing the file can find it.
|
||||
|
||||
**This is a lead decision, and it is stated here rather than buried.** The
|
||||
narrowing costs no edit and no refusal — the same runs assert the edit sets
|
||||
byte-identical — but it costs the user a real piece of news. Recovering it
|
||||
as things stand means running the warning pass over `sources()` while the
|
||||
edits and the verification run over the fan-out: at least the 200–241 ms
|
||||
workspace read plus a `tokenize` of every file spelling the name, which is
|
||||
most of the win this round is for. The right answer is a
|
||||
**macro-invocation census in `FileFacts`**, which would make this rung an
|
||||
index lookup like the other five; that is a `vlog_semantic` change, and it
|
||||
is filed as a request below rather than guessed at here.
|
||||
- **No lost refusal.** The first draft of this round had one — a file whose
|
||||
only mention of the new name was a use that resolved to nothing — and it is
|
||||
**closed**, by rung 6. See "The dangling-use case" above for the argument
|
||||
and the two tests. It is recorded here rather than deleted because the
|
||||
shape is worth remembering: every rung keyed by a *declaration* is blind to
|
||||
a use that has none, and a rename's whole job is to change which
|
||||
declarations exist.
|
||||
- **Nothing else.** A file whose occurrences of either name are strays — a
|
||||
comment, a string, a local declaration inside a module, a hierarchical tail
|
||||
— resolves identically before and after the edit, so the whole-workspace
|
||||
verifier had nothing to say about it either.
|
||||
|
||||
The alternative considered and not taken: hand the engine the whole file list
|
||||
but a *prebuilt* index, which narrows nothing and would still cost the
|
||||
`sources()` read (200–241 ms on OpenTitan) plus an index clone. It is recorded
|
||||
here so the choice is visible rather than implied.
|
||||
|
||||
## The verification story
|
||||
|
||||
Two independent checks, both run in memory on the edited text, before
|
||||
@@ -230,7 +539,18 @@ implemented:
|
||||
the index's `FileId`s describe the same texts.
|
||||
- A rename is a rare, user-initiated request, so re-analyzing candidate files
|
||||
twice (once before the edit, once after) is affordable. No caching, no
|
||||
incrementality.
|
||||
incrementality. **Amended 2026-08-28**: a *prepareRename* is not rare — it
|
||||
is what the rename key sends before the box opens — and "the candidate
|
||||
files" is now the symbol's fan-out through the index rather than the whole
|
||||
scope. See "The file set a rename reads".
|
||||
- **The index is the server's authority on where a name is declared and
|
||||
used** (2026-08-28). The fan-out is read from it, so a rename sees the
|
||||
workspace as far as the index describes it: a file changed on disk with
|
||||
nothing telling this server, or one a startup scan has not reached, is a
|
||||
file the rename does not read. Open buffers are exempt — every one of them
|
||||
is in the set whatever the index holds. The exact premise, what it costs and
|
||||
what it does not, is written out under "The staleness premise, stated
|
||||
exactly".
|
||||
- Refactored output is *edited source*, not reformatted source (umbrella
|
||||
Handshakes): the edits are minimal, and the user runs the formatter
|
||||
separately.
|
||||
@@ -256,10 +576,64 @@ implemented:
|
||||
ranges that slice back to the name — every edit span is one of these, and
|
||||
the engine re-checks the slice before emitting it.
|
||||
|
||||
**Consumed from `vlog_semantic`, added 2026-08-28** (no change required):
|
||||
`WorkspaceIndex::{workspace_symbols, references_to, references_are_ambiguous,
|
||||
instantiations_of, defines}` — the posting, edge and macro tables — are what make
|
||||
the rename's file set a lookup instead of a workspace read. The sufficiency
|
||||
argument leans on one published property of theirs, and it is worth naming so
|
||||
it moves under supervision: **`references_to`'s postings are built by
|
||||
`merge_references`, which resolves each recorded reference with the same
|
||||
`follow_paths` `resolve_external` uses.** If those two ever stop being the one
|
||||
function, the postings stop being a superset of the files a rename must edit.
|
||||
The same goes for `workspace_symbols` covering both the `units` and the
|
||||
`members` tables: rung 1 of the fan-out *is* that coverage.
|
||||
|
||||
**Changed in `vlog_semantic`** (lead-authorized 2026-08-28 after QA, strictly
|
||||
additive — the second such change this feature has made, the first being M2's
|
||||
`Target::Declaration`):
|
||||
|
||||
- **`WorkspaceIndex::files_spelling(name) -> impl Iterator<Item = FileId>`** —
|
||||
every file holding an external reference *fact* spelling `name`, resolved or
|
||||
not. New query, no new state, no format change: it reads the
|
||||
`FileFacts::references` records the index already keeps, and
|
||||
`FACTS_FORMAT` is untouched. Logged in `docs/features/vlog-semantic/README.md`'s
|
||||
work log, as M2's change was.
|
||||
- **Why it had to live there.** The records are `pub(crate)`, and the question
|
||||
— "which files hold a use spelled `N` that this index had to look outside
|
||||
that file to answer" — is a question about the index's own tables. The
|
||||
alternative was for the server to re-derive it by reading and analyzing
|
||||
files, which is the workspace read this whole round removes.
|
||||
- **The contract it carries:** `references_to` is keyed by the declaration a
|
||||
use *landed on*, so a use that landed on nothing is in no posting.
|
||||
`files_spelling` is the same records asked by spelling instead, which is
|
||||
what makes it answer for the unresolved ones. If `facts_from_analysis` ever
|
||||
stops recording an unresolved external candidate — today it records every
|
||||
`ExternalCandidate`/`InheritedCandidate` with a non-empty path list — rung 6
|
||||
stops closing the dangling-use case and this section must be re-read.
|
||||
|
||||
**Promised to `lucisv_server`** (and to any future CLI):
|
||||
|
||||
- `rename` never panics and never returns a partial edit: `Ok` means every
|
||||
edit in it verified together, `Err` means nothing at all is to be applied.
|
||||
- `prepare_rename_here` refuses in the *same sentences* `prepare_rename` does,
|
||||
or defers to `rename`; it never invents a refusal `prepare_rename` would
|
||||
not have made. The parity table above is the contract, and the byte-by-byte
|
||||
parity tests are the enforcement.
|
||||
- `rename_name_at` names the identifier `prepare_rename`'s `RenameTarget`
|
||||
would name, at every offset where `prepare_rename` answers at all
|
||||
(`the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on`).
|
||||
|
||||
**Requested of `vlog_semantic` (filed 2026-08-28, not taken):** a
|
||||
**macro-invocation census in `FileFacts`** — per file, the macro invocations
|
||||
it writes and the identifier-shaped words in their arguments. It is the one
|
||||
piece of the rename's warning set the index cannot answer, and its absence is
|
||||
the measured residue above: on OpenTitan, renaming `aes` loses seven
|
||||
"`aes` appears in the arguments of the macro invocation …" warnings because
|
||||
the files holding them contribute nothing else about `aes`. The census would
|
||||
be one more `Vec` on a record `FACTS_FORMAT` already versions, read off the
|
||||
token stream the parse already produced, and it would turn
|
||||
`Scope::macro_use_warnings` from a workspace lex into a lookup — for the port
|
||||
refactorings' identical scan as much as for this one.
|
||||
- `RefactorEdit.edits` is sorted by path; each file's edits are sorted by
|
||||
start offset, non-overlapping and non-empty.
|
||||
- `warnings` are informational only — an `Ok` result with warnings is still
|
||||
@@ -312,6 +686,19 @@ a much larger change than an end label and is not part of M2.
|
||||
- [x] Tests: 64 in `vlog_refactor` (14 unit incl. 8 masked-corruption attacks,
|
||||
48 behavior, 2 corpus), 3 new in `vlog_semantic`, 8 in `lucisv_server`
|
||||
(7 in `rename.rs`, 1 capability), 1 e2e session
|
||||
- [x] `prepareRename` answered from the open buffer and the index rather than
|
||||
from `sources()` (2026-08-28): `prepare_rename_here` in the engine, the
|
||||
refusal-by-refusal parity table above, and six byte-by-byte parity
|
||||
suites against `prepare_rename` as the oracle
|
||||
- [x] `rename` computed over the symbol's fan-out rather than the whole scope
|
||||
(2026-08-28): `Workspace::rename_sources` in the server,
|
||||
`rename_name_at` in the engine, the sufficiency argument above, the
|
||||
ambiguity escape hatch, and equivalence tests over hostile workspaces
|
||||
- [x] The dangling-use rung (2026-08-28, QA-driven rework):
|
||||
`WorkspaceIndex::files_spelling` and rung 6 of the fan-out, applied to
|
||||
the new name, which closes the one refusal the first draft lost. The
|
||||
old name's exemption is argued under "The dangling-use case" and pinned
|
||||
by its own test
|
||||
- [ ] Deferred: rename in comments and strings (rope's `docs=True`) — the
|
||||
umbrella lists it as an option, off by default, "until asked for"
|
||||
- [ ] Deferred: renaming a module together with its file
|
||||
@@ -473,6 +860,158 @@ Checks after the rework: `cargo fmt --all -- --check` clean,
|
||||
`cargo clippy --all-targets` zero warnings workspace-wide,
|
||||
`cargo test --workspace` green at 1085 tests (was 1072).
|
||||
|
||||
**2026-08-28 — dev agent (performance wave, Lane A).** The rename family stops
|
||||
reading the workspace. `performance.md`'s two worst rows were
|
||||
`textDocument/rename` (3.6–8.7 s) and `textDocument/prepareRename`
|
||||
(2.5–3.0 s), both of them `ws.sources()` followed by a whole `WorkspaceIndex`
|
||||
build; the measurer's own push-back — that `prepareRename` is what the rename
|
||||
key sends *before the box opens*, not a rare user gesture — is the framing
|
||||
this round took.
|
||||
|
||||
Everything argued under "The file set a rename reads" above. The decisions
|
||||
worth repeating here:
|
||||
|
||||
- **`prepare_rename_here` takes an analysis, not a file set.** The server
|
||||
already holds the buffer's `Semantics`, its `ExternalResolutions` overlay
|
||||
and the index, and the overlay is `resolve_external` against that same
|
||||
index — which is the exact call `Scope::declaration_across_files` makes. So
|
||||
every refusal that depends on *which* declaration a use names is reproduced
|
||||
rather than approximated, and only the four that need the declaring file's
|
||||
own text are deferred. `prepare_rename` stays, as the oracle the parity
|
||||
tests measure against; the refusal sentences were factored into five
|
||||
functions so the two paths cannot word one situation two ways.
|
||||
- **The fan-out's first rung is `workspace_symbols`, not `units`.** This is
|
||||
the rung the whole equality argument turns on and the one that was easy to
|
||||
get wrong: `follow_paths` looks a reference's *own* name up, in `units(N)`
|
||||
or `member(u, N)`, and both tables are contributed only by files that
|
||||
declare the name `N`. Drop the file declaring `p::x` from the set and a
|
||||
reference with paths `[p::, q::]` falls through to `q::x` and is renamed —
|
||||
an *over*-edit, corruption in the direction nobody looks. With rung 1 in
|
||||
place the Lemma makes the subset's resolution of every reference spelling
|
||||
either name identical to the workspace's, which is what buys "no missed
|
||||
edit" and "no extra edit" at once.
|
||||
- **The new name gets the whole fan-out too**, or refusal 12 (capture) dies:
|
||||
the file whose existing reference a rename would make ambiguous is in the
|
||||
*new* name's postings and in nothing of the old name's.
|
||||
- **The ambiguity escape hatch.** An ambiguous use is recorded against the
|
||||
declarations it could name, never against the file that writes it, so
|
||||
refusal 10 cannot be reached from a subset. `rename_sources` hands back
|
||||
`sources()` when the index reports one. Slow and correct beats fast and
|
||||
silent.
|
||||
- **`willRenameFiles`** got the same treatment through the include graph —
|
||||
written up in `docs/features/file-operations/README.md`, including the
|
||||
four-line `IncludeGraph::includers` accessor, which is the one file this
|
||||
round touched outside its stated scope and is flagged there for the lead.
|
||||
|
||||
Measured, `--release`, and the equality checked as well as the clock:
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| OpenTitan (3 976 files), `prepareRename` on the `aes` instantiation | 1.663 s | **139 ns** |
|
||||
| OpenTitan, `rename` of `aes` (7 files edited) | 3.467 s | **105.5 ms** (7-file fan-out) |
|
||||
| synthetic 504 files, `prepareRename` on a module name | 251 ms | **212 ns** |
|
||||
| synthetic 504 files, `rename` (4 files edited) | 486 ms | **370 µs** |
|
||||
|
||||
(All four re-taken after the 2026-08-28 rework below, so the table describes
|
||||
the shipped code. The earlier round measured 1.604 s → 135 ns, 3.284 s →
|
||||
103.6 ms, 238 ms → 200 ns and 465 ms → 294 µs on the same corpus: the sixth
|
||||
rung is inside the noise, which is what the separate rung measurement above
|
||||
says directly.)
|
||||
|
||||
The OpenTitan numbers were taken with throwaway probes against the local
|
||||
checkout and deleted — no test may depend on it. The reproducible probe is
|
||||
`perf::a_rename_before_and_after`. The throwaway also swept **every 7th byte
|
||||
of `tb.sv`** comparing `prepare_rename_here` against `prepare_rename`: **564
|
||||
offsets, all identical, zero deferrals** — the parity table's contract holding
|
||||
over real code, not only over the six synthetic buffers in the suite.
|
||||
|
||||
**What the OpenTitan sweep found, and it is not nothing.** At the `aes` cursor
|
||||
the two edit sets are byte-identical (7 files) and the *warnings* are 7 → 0:
|
||||
`tb__xbar_connect.sv` and `keymgr_dpe_scoreboard.sv` spell `aes` only inside
|
||||
macro-invocation tokens, which the index does not model in any table. Written
|
||||
up in full under "The residue", with the cost of recovering it and a filed
|
||||
request for the `FileFacts` macro-invocation census that would make it a
|
||||
lookup. **It is a lost warning, never a lost edit or a lost refusal, and it is
|
||||
the lead's call at review** — the honesty gate the brief asked for.
|
||||
|
||||
Deliberately not done: `check::watched_files` still sweeps the file list it is
|
||||
given with `contains_word`, which is now the fan-out rather than the
|
||||
workspace; no attempt was made to narrow it further, because it is O(files in
|
||||
the set) over text already in memory.
|
||||
|
||||
Gates: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` clean
|
||||
workspace-wide, `cargo test --workspace` green, `node editors/vscode/smoke.js`
|
||||
OK against the release binary.
|
||||
|
||||
**2026-08-28 — dev agent (QA-driven rework: the lost refusal is closed).** The
|
||||
lead ruled the round's "one lost refusal" residue not shippable — *a silently
|
||||
weaker refusal is not a residue we ship* — and directed the fix. QA had found
|
||||
it, reproduced it and pinned it as
|
||||
`known_residue_a_dangling_import_of_the_new_name_is_a_lost_refusal`; that test
|
||||
is now `a_dangling_import_of_the_new_name_is_refused_by_both_paths` and
|
||||
asserts parity through `same_answer` instead of pinning the divergence.
|
||||
|
||||
The diagnosis, which is what makes the fix a rung rather than a patch: **rungs
|
||||
1–5 are every one of them keyed by a declaration.** A file is in the set
|
||||
because it declares the name, because a posting keys it to a declaration of
|
||||
it, because it instantiates it, because a macro table mentions it, or because
|
||||
it names the unit exporting it. A use that resolved to *nothing* has no
|
||||
declaration to be keyed by — `merge_references` drops a `StillUnresolved`
|
||||
result rather than posting it, correctly, since there is nothing to post it
|
||||
against — and a rename's whole job is to change which declarations exist. So
|
||||
`import taken_pkg::*` of a package nobody declares yet was invisible to the
|
||||
fan-out and became meaningful the moment the rename landed, which is exactly
|
||||
what capture rule 12 refuses over.
|
||||
|
||||
What changed:
|
||||
|
||||
- **`WorkspaceIndex::files_spelling(name)`** — one additive, lead-authorized
|
||||
`vlog_semantic` query: every file holding an external reference *fact*
|
||||
spelling the name, resolved or not. No new state, no new field,
|
||||
`FACTS_FORMAT` untouched; it reads the `FileFacts::references` records the
|
||||
index already keeps, which is the only reason the answer is available at all
|
||||
without reading files. Logged in `docs/features/vlog-semantic/README.md`'s
|
||||
work log as M2's `Target::Declaration` was, and the recording rule it rests
|
||||
on is written into both Handshakes sections so it moves under supervision.
|
||||
- **Rung 6 of `Workspace::rename_sources`**, `want_spellers`, applied to the
|
||||
**new name only**. The old name provably needs nothing: a rename only ever
|
||||
*removes* declarations of it, a resolving use of it is already in rung 2
|
||||
(which walks every declaration of the name, not only the target's), and a
|
||||
non-resolving one cannot start resolving because a candidate was taken away.
|
||||
That argument is written out under "The dangling-use case" and pinned from
|
||||
the other side by `a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`,
|
||||
which checks both that the new-name rung fires when the dangling spelling is
|
||||
the destination and that nothing is pulled in when it is a bystander.
|
||||
- The Lemma is unchanged — it was always about what a name *resolves to*, and
|
||||
it was always sound. What it never claimed, and what the sufficiency
|
||||
argument now says out loud, is which files *hold* a use. Rung 6 is that
|
||||
second question's answer.
|
||||
|
||||
**The rung's cost, measured** (the lead asked for the number, and for a
|
||||
name-keyed side map as the fallback if it were large — it is not). On
|
||||
OpenTitan's 3 976 files: **852 µs** for a name nothing spells, which is the
|
||||
worst case because `any()` cannot short-circuit, and **402 µs** for `clk_i`,
|
||||
which 681 files spell. The whole file-set build is 4.75 ms, most of it the
|
||||
other rungs. `rename` itself went 103.6 ms → 105.5 ms, i.e. unchanged against
|
||||
a 3.5 s baseline. On the synthetic 504-file corpus the rung is 49.8 µs of a
|
||||
128.7 µs set build; both are printed by `perf::a_rename_before_and_after`,
|
||||
which grew two lines for them.
|
||||
|
||||
Re-verified after the rework, against the real OpenTitan checkout: all four
|
||||
cursors still byte-identical (`aes` 7 files, `clk_rst_if` 114 files, `.clk_i`
|
||||
4 files), the capture refusal on `aes` → `prim_fifo_sync` still verbatim, the
|
||||
warning counts unmoved. The refusal parity table is unaffected — it is
|
||||
`prepareRename`'s, and neither entry point's refusal set changed; what changed
|
||||
is which files `rename` reads before producing rule 12's.
|
||||
|
||||
**The macro-invocation warning residue stands as documented** — the lead
|
||||
accepted it on the record, and the `FileFacts` macro-invocation census remains
|
||||
filed as the real fix.
|
||||
|
||||
Gates after the rework: `cargo fmt --all -- --check` clean,
|
||||
`cargo clippy --all-targets` clean workspace-wide, `cargo test --workspace`
|
||||
green, `node editors/vscode/smoke.js` OK against the release binary.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-24 — QA agent.**
|
||||
@@ -883,8 +1422,336 @@ surface (hierarchical tails, `defparam` paths, mismatched/redeclared end
|
||||
labels) is honestly disclosed and consistent with the "lucisv does not
|
||||
preprocess / does not elaborate" boundary the umbrella already draws.
|
||||
|
||||
**2026-08-28 — QA agent (performance wave, Lane A).** Verified the round that
|
||||
moves `prepareRename` and `rename` off `ws.sources()`. Adversarial charter:
|
||||
find a rename that edits, warns or refuses differently than the
|
||||
whole-workspace path would, or a `prepareRename` that lies. Worked in
|
||||
`.claude/worktrees/agent-a2cccf825469bf247`.
|
||||
|
||||
### Gates
|
||||
|
||||
- `cargo fmt --all -- --check` — clean, after fixing formatting in QA's own
|
||||
additions (`cargo fmt --all`; the dev's diff itself was already clean).
|
||||
- `cargo clippy --all-targets` — clean, zero warnings, forced re-check after
|
||||
`touch`ing every file this round changed.
|
||||
- `cargo test --workspace` — green, 0 failures, across every crate (doc-tests
|
||||
included).
|
||||
- `node editors/vscode/smoke.js target/release/lucisv-server` — OK, 10
|
||||
messages, against a freshly built release binary carrying this round's diff
|
||||
plus QA's added tests.
|
||||
- Numbers reproduced against the actual code under review (not trusted from
|
||||
the Work log), `cargo test --release -p lucisv_server --bin lucisv-server
|
||||
perf:: -- --ignored --nocapture --test-threads=1`: `prepareRename` 238.29 ms
|
||||
→ **179 ns**; `rename` 466.54 ms → **294.9 µs**; `willRenameFiles` scope-read
|
||||
11.39 ms → includers-read **15.1 µs**. All within noise of the Work log's
|
||||
claims. (Two unrelated corpus-dependent perf tests failed in this worktree
|
||||
because `corpus/` is not checked out here — pre-existing, unaffected by this
|
||||
diff, confirmed present in `HEAD` before this round's changes.)
|
||||
- Real OpenTitan checkout (`/Users/guoliangchen/repo/opentitan` @ `0098135264`,
|
||||
3979 files, matching `performance.md`'s provenance), driven over real LSP/
|
||||
stdio with a client pointed at this worktree's own `target/release/
|
||||
lucisv-server` (not the dev's throwaway probes, and not the earlier
|
||||
"instrumented" binary from the measurer's session): cold workspace scan
|
||||
settled in 2 940.7 ms; six repeated `rename`s of `aes` averaged **~104 ms**
|
||||
and all edited exactly the 7 files the Work log names (`tb.sv`, `aes.sv`,
|
||||
`aes_wrap.sv`, `aes_tb.sv`, and the three `*_pd_main.sv` top-level
|
||||
instantiation sites); four repeated `prepareRename`s on the same cursor
|
||||
averaged **~0.05 ms** client-observed (the LSP round trip, not the dev's
|
||||
in-process 135 ns — consistent with `performance.md`'s own 0.02–0.33 ms
|
||||
transport floor: the request now costs essentially nothing but the pipe).
|
||||
**All three gates and the numbers: pass, claims confirmed.**
|
||||
|
||||
### Confirmed finding (HIGH, disclosed by the dev, verified real and exactly
|
||||
as bounded) — the residue's "one lost refusal"
|
||||
|
||||
The README's own "The residue" section names a case the fan-out cannot catch:
|
||||
a file whose only mention of the **new** name is a bare reference that
|
||||
resolves to nothing today (an `import new_name::*` of a package that does not
|
||||
exist yet, or a type spelled `new_name`). The whole-workspace verifier refuses
|
||||
such a rename (capture rule 12: the import would start meaning something);
|
||||
the fan-out never reads that file, so it returns `Ok` instead — a materially
|
||||
weaker answer, not merely a lost warning like the macro-invocation case below
|
||||
it. I built the minimal repro and pinned it as a permanent regression test,
|
||||
`crates/lucisv_server/src/rename.rs`,
|
||||
`known_residue_a_dangling_import_of_the_new_name_is_a_lost_refusal`: package
|
||||
`cfg_pkg` renamed to `taken_pkg`, with a third file `module strayer; import
|
||||
taken_pkg::*; endmodule` that declares, references (under the old name) and
|
||||
instantiates nothing. `vlog_refactor::rename` over the whole scope refuses
|
||||
(`"...would change what taken_pkg means in stray.sv..."`); over
|
||||
`Workspace::rename_sources`'s real output, it succeeds silently. Confirmed
|
||||
this is exactly as narrow as documented — every attack in the next section
|
||||
(new-name declared elsewhere, new-name instantiated elsewhere, new-name
|
||||
reached via a member connection) is still caught by rungs 1/3/5, so the gap is
|
||||
precisely "an unresolved bare reference to the new name, nothing else." This
|
||||
is not a new defect: it is the dev's own disclosed residue, verified to
|
||||
reproduce exactly as written and correctly bounded. Recorded per CLAUDE.md
|
||||
invariant 4's spirit (a widened forgiveness needs attack tests proving the
|
||||
boundary) even though this is a narrowing, not `verify.rs`, because the same
|
||||
"guilty until proven innocent, with tests" discipline applies to any new gap
|
||||
between the fast and slow paths. **This is the one item that needs the lead's
|
||||
explicit ruling** before ship — the brief's own honesty gate.
|
||||
|
||||
### Attacks that held — no divergence found
|
||||
|
||||
All added as permanent regression tests in `crates/lucisv_server/src/rename.rs`
|
||||
unless noted, run against the real `Workspace::rename_sources`/
|
||||
`prepare_rename_here` production code paths, not reimplementations:
|
||||
|
||||
- **Escaped-identifier instantiation** (`\sub u_weird (...)`- a different
|
||||
name to `vlog_semantic` than `sub`, a pre-existing simplification this round
|
||||
did not touch): `an_escaped_identifier_instantiation_does_not_break_fan_out_parity`.
|
||||
Both paths call the identical engine, so the escaped spelling is untouched
|
||||
by both, byte-identical — the fan-out dropping the file (it posts nowhere)
|
||||
changes nothing observable, since the whole-workspace run's own watch of it
|
||||
is also a no-op.
|
||||
- **Same spelling, different symbol kind** (a module named `sub` vs. an
|
||||
unrelated wire also named `sub` in a different module):
|
||||
`a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out`. The
|
||||
unrelated wire's file and declaration are never touched.
|
||||
- **Escape hatch discovered on the second spelling, not the first** — the
|
||||
ambiguity is on the *new* name only, so `fan_out_of`'s loop over `[name,
|
||||
new_name]` must not leak a partially-built, too-narrow `wanted` set when it
|
||||
bails on the second iteration:
|
||||
`the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous`. Falls
|
||||
back to the whole scope correctly; `Workspace::rename_sources`'s early
|
||||
`return self.sources()` on the first ambiguous hit (state.rs, `fan_out_of`)
|
||||
discards the partial set rather than returning it, exactly as needed.
|
||||
- **Prepare parity fuzz beyond the dev's six buffers**
|
||||
(`crates/vlog_refactor/src/rename.rs`): a valid head followed by an
|
||||
unparseable tail, CRLF line endings, multi-byte UTF-8 text ahead of the
|
||||
probed identifiers, and a macro-heavy buffer (`` `ifdef``/`` `define``/
|
||||
`` `BUMP(x)`` all in one file) — every offset of every buffer, no
|
||||
divergence, no invented refusal.
|
||||
- **Include-graph-adjacent attacks on `willRenameFiles`**, in
|
||||
`crates/lucisv_server/src/file_ops.rs`: an include chain `a.svh -> b.svh`
|
||||
with a third file `c.sv -> a.svh` (renaming `b.svh` narrows to `a.svh` only,
|
||||
correctly leaves `c.sv` unedited since it never spells `b.svh`,
|
||||
`an_include_chain_narrows_to_the_direct_includer_of_the_moved_file`), and a
|
||||
case-mismatched include spelling (`` `include "DEFS.svh"`` against a real
|
||||
`defs.svh` on this case-insensitive filesystem,
|
||||
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`) — both
|
||||
narrow in correctly and rewrite correctly.
|
||||
- **Deferred-refusal reachability (rule 11b).** Attempted to construct a case
|
||||
where the declaring file (in another file from the buffer) has an empty
|
||||
`name_span`, which is the one row the parity table marks "deferred" rather
|
||||
than "reproduced." Could not construct one through the public parsing API:
|
||||
the name-span contract (`vlog-semantic`'s Handshakes, and this feature's own
|
||||
"every edit span originates in a parsed node") guarantees a non-empty span
|
||||
on every declaring node the binder records, so this refusal looks
|
||||
unreachable through any real workspace state today, in the same way the two
|
||||
"—" rows in the parity table are marked unreachable. Not fixed or asserted
|
||||
either way — flagging for the record rather than claiming coverage the
|
||||
suite does not have.
|
||||
|
||||
### Not attempted / out of scope for this round
|
||||
|
||||
The end-label, hierarchical-tail, `defparam`, and escaped-identifier
|
||||
*declaration* findings from the 2026-08-24 rounds above are pre-existing and
|
||||
untouched by this diff — re-read, not re-attacked. The `willCreateFiles`/
|
||||
`willDeleteFiles` non-goals in file-operations are unrelated to this round.
|
||||
|
||||
### Summary
|
||||
|
||||
| Claim | Verdict |
|
||||
|---|---|
|
||||
| Gates (fmt/clippy/test/smoke) | **Pass** |
|
||||
| Numbers (synthetic probes + real OpenTitan, this worktree's own build) | **Pass, reproduced independently** |
|
||||
| Sufficiency argument (name-locality lemma) | **Holds** under every attack tried: escaped identifiers, same-spelling different symbols, mid-walk ambiguity, prepare-parity fuzz, include-chain/case-mismatch narrowing |
|
||||
| The residue — macro-invocation warning loss | Reproduces exactly as measured on OpenTitan (7→0, 64→61); no edit or refusal lost, only the one warning flavour; already the lead's disclosed call |
|
||||
| The residue — "one lost refusal" (dangling import of the new name) | **Confirmed real, reproducible, and exactly as bounded** — a genuinely weaker answer than the whole-workspace path, not just a lost warning. **Needs the lead's explicit ruling before ship.** |
|
||||
|
||||
**Verdict: REWORK-gate, not ship-as-is** — not because anything is broken by
|
||||
accident, but because the one item the brief calls "gate the subset path
|
||||
behind that honesty (lead decides at review)" has not yet had that decision
|
||||
made. Every other attack in the adversarial charter held. My recommendation,
|
||||
for the lead: this is very likely acceptable to ship (it is a narrowing of a
|
||||
*refusal*, not an edit — CLAUDE.md invariant 1 is about edits, and none is
|
||||
lost or wrong here), especially since the parallel macro-invocation-warning
|
||||
residue was already accepted; but "very likely acceptable" is not the same as
|
||||
"decided," and the brief was explicit that this exact honesty gate needs a
|
||||
lead ruling, not a QA one.
|
||||
|
||||
**2026-08-29 — QA agent (re-verification of the rework: rung 6,
|
||||
`WorkspaceIndex::files_spelling`).** Focused pass, not a full re-run, on the
|
||||
lead-authorized fix for the HIGH finding above: the flipped test
|
||||
(`a_dangling_import_of_the_new_name_is_refused_by_both_paths`) and the new
|
||||
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`, plus "The
|
||||
dangling-use case" section's argument (rung 6 is the new name's alone because
|
||||
a rename only ever *removes* declarations of the old name). Charter: attack
|
||||
rung 6's completeness, attack the old-name exemption with a shadowing/
|
||||
"unmasking" hunt, verify the tests actually assert what they claim, spot-check
|
||||
the rung's cost, run the gates. Worked in the same worktree.
|
||||
|
||||
### Rung 6 completeness — three new attacks, all pass
|
||||
|
||||
Read `WorkspaceIndex::files_spelling` (`crates/vlog_semantic/src/workspace.rs`)
|
||||
and `resolve.rs`'s `Target::{Package,Unit,UnitMember}`/`miss` machinery to find
|
||||
every way a real reference could spell the new name and end up with a
|
||||
`Resolution` whose `paths` are empty (invisible to `files_spelling`, since
|
||||
`facts_from_analysis` only records `ExternalCandidate`/`InheritedCandidate`
|
||||
with a non-empty path list). The exhaustive case split: **every** miss on
|
||||
`Target::Package`, `Target::Unit`, `Target::UnitMember` — including the head
|
||||
of `p::x` and an `extends`/`implements` base — always pushes at least the bare
|
||||
name onto its paths (`named_at_file_scope`'s `None` arm, `unit()`'s unconditional
|
||||
`external.push(name.to_string())`, `unit_member`'s two unconditional
|
||||
`ExternalCandidate` arms), so all of those are recorded regardless of whether
|
||||
they resolve. The **only** empty-paths cases are `this_member`/`super_member`
|
||||
(always `paths: Vec::new()`) and a plain `Target::Lexical` miss inside a class
|
||||
with `extends` when no import in scope supplies anything
|
||||
(`miss()`'s `InheritedCandidate { base, paths: external }` with `external`
|
||||
empty) — and for exactly these, `resolve_external` can *never* produce an
|
||||
overlay entry (`follow_paths` on an empty list is `StillUnresolved` by
|
||||
construction, unconditionally, both before and after any rename, because the
|
||||
paths are fixed by the file's own unedited text), so the reference's `Anchor`
|
||||
is provably invariant and excluding the file costs nothing on either path.
|
||||
|
||||
Three permanent regression tests added to `crates/lucisv_server/src/rename.rs`
|
||||
to check this empirically rather than trust the proof alone:
|
||||
|
||||
- `a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6` — a
|
||||
class `extends taken_base` where `taken_base` is declared nowhere; renaming
|
||||
a package to `taken_base` is refused by both paths, and rung 6 pulls the
|
||||
file in via the `Target::Unit` path (a genuinely different resolution
|
||||
target than the import case rung 6 was built for). Passes.
|
||||
- `an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung`
|
||||
— the one real empty-paths shape (a bare identifier inside a class that
|
||||
extends an existing, unrelated base, no import in scope). Confirmed
|
||||
`files_spelling` does **not** pull the file in, and confirmed (via
|
||||
`same_answer`) that excluding it changes nothing — the rename still
|
||||
succeeds identically on both paths. Passes, both assertions.
|
||||
- `a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal`
|
||||
— a wire declared and used only locally in a third file, sharing the new
|
||||
name's spelling. `files_spelling` correctly excludes it (it is a
|
||||
`ReferenceFact::Local`, which the function's own `match` arm returns
|
||||
`false` for), and the rename succeeds with no edit to that file. This is
|
||||
also directly what `files_spelling_finds_the_uses_no_posting_can_be_keyed_by`
|
||||
in `crates/vlog_semantic/tests/workspace.rs` pins at the query's own level
|
||||
(`quiet.sv`'s local wire named `absent_pkg` is excluded from
|
||||
`named("absent_pkg")`) — read and re-run, still passes.
|
||||
|
||||
### Old-name exemption — shadowing/"unmasking" hunt, none found
|
||||
|
||||
Tried to construct exactly the counterexample the charter asked for: two
|
||||
packages `p_pkg` and `q_pkg` both exporting a member spelled `shared_name`, a
|
||||
third file importing both (`p_pkg` first, so "first-written import wins"
|
||||
resolves `shared_name` to `p_pkg`'s declaration today), then renaming *away*
|
||||
`p_pkg::shared_name` — the hypothesis being that the importer's reference
|
||||
would silently fall through to `q_pkg`'s pre-existing, unrelated declaration
|
||||
without the importer's file being in the fan-out.
|
||||
|
||||
It doesn't happen, and reading why is the actual finding: the importer's
|
||||
`shared_name` reference currently *resolves to the rename target itself*, so
|
||||
it is not a bystander a removal could silently redirect — it is an edit site.
|
||||
`Scope::collect_occurrences` rewrites it to the new name along with the
|
||||
declaration, so the text never says `shared_name` again for `follow_paths` to
|
||||
re-resolve against `q_pkg`. Generalizing: any reference that could possibly
|
||||
be affected by removing declarations of the old name must itself spell the
|
||||
old name (the workspace tables are keyed by literal name string, so a
|
||||
reference to an unrelated name cannot be touched by removing entries under a
|
||||
different key), and by the Lemma such a reference either (a) resolves to the
|
||||
target — edited away, not orphaned — or (b) resolves to a *different*
|
||||
existing declaration of the same name — already in the set, because rung 1
|
||||
(`workspace_symbols`, not `units`) walks *every* declarer of the name and rung
|
||||
2 posts against each one, not only the target's — or (c) resolves to nothing
|
||||
— stays resolving to nothing, since removing a candidate cannot manufacture a
|
||||
new match. There is no fourth case, so there is no shadowing route the old
|
||||
name needs a rung for. Verified empirically as well as by this argument:
|
||||
`removing_the_old_names_winning_declaration_does_not_escape_the_fan_out`
|
||||
(added to `crates/lucisv_server/src/rename.rs`) builds the exact scenario
|
||||
above and confirms the fan-out includes both `q.sv` (rung 1, every declarer)
|
||||
and `user.sv` (rung 2, posted against `p_pkg`'s declaration), that the rename
|
||||
succeeds, edits exactly the declaration and the importer's reference, and
|
||||
never touches `q_pkg`'s unrelated declaration. **The old-name exemption
|
||||
argument held under attack — no counterexample found, and the reason none
|
||||
exists is now written into the test itself, not just asserted.**
|
||||
|
||||
### Tests genuinely assert what they claim — sabotage-verified
|
||||
|
||||
Read every test named above plus the dev's flipped/new ones
|
||||
(`a_dangling_import_of_the_new_name_is_refused_by_both_paths`,
|
||||
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own`) end to end, then
|
||||
sabotaged rung 6 out (`Workspace::rename_sources`, wrapped the
|
||||
`want_spellers` call in `if false { … }`) and re-ran the whole
|
||||
`rename::tests::` module:
|
||||
|
||||
- **Failed, as they must**: `a_dangling_import_of_the_new_name_is_refused_by_both_paths`,
|
||||
`a_dangling_use_of_the_old_name_needs_no_rung_of_its_own` (the file "the
|
||||
fan-out lost the refusal … and edited 1 files instead" — exactly the
|
||||
pre-rework residue, reproduced on demand), and the new
|
||||
`a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6`.
|
||||
- **Still passed, as they must** (they test cases that provably do not
|
||||
depend on rung 6): the empty-paths test, the local-only-symbol test, the
|
||||
shadowing/unmasking test, and every pre-existing fan-out test.
|
||||
|
||||
Reverted the sabotage (`git diff crates/lucisv_server/src/state.rs` after
|
||||
reverting shows zero trace of it) and re-ran — all 26 tests in
|
||||
`rename::tests::` pass again. This is the strongest confirmation available
|
||||
short of formal proof: the tests that claim to depend on rung 6 actually do,
|
||||
and the tests that claim not to actually don't.
|
||||
|
||||
### Numbers, spot-checked
|
||||
|
||||
Release probe (`cargo test --release -p lucisv_server --bin lucisv-server
|
||||
perf::a_rename_before_and_after -- --ignored --nocapture --test-threads=1`),
|
||||
against this worktree's own freshly rebuilt binary: file-set build **137.2
|
||||
µs**, of which `files_spelling` **52.1 µs**; rename fan-out **396.1 µs**;
|
||||
`prepareRename` whole-workspace **249.5 ms** → buffer+index **212 ns**. All
|
||||
within noise of the Work log's 128.7/49.8/370/238/200 µs-and-ns figures.
|
||||
|
||||
Real OpenTitan checkout, over actual LSP/stdio with a client pointed at this
|
||||
worktree's own rebuilt `target/release/lucisv-server` (not a throwaway
|
||||
in-process probe): six repeated `rename`s of `aes` on a cold workspace scan
|
||||
(3 015.7 ms settle) averaged **~118 ms** (107–134 ms), consistent with the
|
||||
Work log's 105.5 ms and my own prior-round measurement of ~104 ms — the
|
||||
spread is machine noise, not a regression from rung 6. Re-requested the same
|
||||
`aes` → `aes_core_renamed_qa2` rename directly (not just repeated identical
|
||||
renames) and got the **same 7 files, same edit counts** as my prior-round
|
||||
spot check, confirming rung 6 changes nothing about the real edit set.
|
||||
|
||||
### Gates
|
||||
|
||||
`cargo fmt --all -- --check` clean. `cargo clippy --all-targets` clean (forced
|
||||
re-check after `touch`ing every file this rework changed, zero warnings —
|
||||
including in the three new tests, one `unused_must_use` warning caught and
|
||||
fixed on the way, noted so it isn't mistaken for a dev-side issue). `cargo
|
||||
test --workspace`: **0 failures**, no panics, workspace-wide (34 test binaries
|
||||
including doc-tests). `node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 10 messages.
|
||||
|
||||
### Verdict
|
||||
|
||||
**SHIP.** The rework closes the HIGH finding exactly as claimed: rung 6 is
|
||||
complete under every completeness attack tried (including two shapes — the
|
||||
extends-base case and the empty-paths InheritedCandidate case — the dev's own
|
||||
writeup didn't walk through explicitly), the old-name exemption holds under a
|
||||
genuine shadowing/unmasking attempt (with the reason now understood and
|
||||
tested, not just asserted), the flipped and new tests are not vacuously
|
||||
passing (sabotage-confirmed), and the rung's cost is sub-millisecond on
|
||||
OpenTitan with no measurable end-to-end regression. No new findings. The
|
||||
macro-invocation warning residue is unchanged and remains the lead's
|
||||
already-accepted, separately-tracked call.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead, performance-wave Lane A.** Reviewed after QA's
|
||||
initial REWORK-gate, the fix round, and QA's SHIP on re-verification;
|
||||
gates re-run on the worktree (fmt clean, clippy silent, 2518 workspace
|
||||
tests green). The round's spine is the name-locality lemma, and the
|
||||
rework is what made it whole: rungs 1–5 are all keyed by declarations,
|
||||
so the dangling-use capture case — a refusal, not a warning — needed
|
||||
rung 6 (`files_spelling`, over the reference facts the index already
|
||||
keeps, FACTS_FORMAT untouched), and the lead ruled the residue
|
||||
unshippable rather than documentable. QA then enumerated resolve.rs's
|
||||
full miss taxonomy to prove the rung's two blind spots workspace-
|
||||
invariant, hunted a shadowing counterexample to the old-name exemption
|
||||
and found the lemma held, and sabotage-verified the parity tests bite.
|
||||
That is the loop working as designed. prepareRename 1.66 s → 139 ns,
|
||||
rename 3.47 s → 105 ms with the rung costing 852 µs worst-case,
|
||||
willRename 249 ms → 14 ms; byte-parity swept at four real cursors and
|
||||
564 offsets. The accepted macro-invocation warning residue and the
|
||||
FileFacts macro census stay filed; the includes.rs accessor deviation
|
||||
was the correct refusal to copy a scan. Accepted; merged by the lead.
|
||||
|
||||
**2026-08-24 — lead.** Reviewed the full diff after QA round 2's ship
|
||||
verdict; ran the three gates independently (1085 tests, 0 failures, clippy
|
||||
silent). The two-layer verification in `check.rs` is the right safety story
|
||||
|
||||
@@ -47,6 +47,12 @@ predicate, and three handlers.
|
||||
be paired with different bytes; an open file contributes live spans instead.
|
||||
Location conversion fetches and line-indexes each touched file once, however
|
||||
many occurrences it contains.
|
||||
- **`documentHighlight` is a *document* answer even for a cross-file name**
|
||||
(2026-08-28). The cursor on an instantiated module, or on a `.port` in a
|
||||
connection list, highlights that name's uses **in this file** — the workspace
|
||||
overlay is consulted to learn *which declaration* the cursor names, never to
|
||||
widen the answer past the buffer. So the same position can answer 1 here and
|
||||
7 to `references`, and both are right.
|
||||
- **Read/write is not distinguished** in `documentHighlight`. LSP permits a
|
||||
plain `Text` kind, and telling a read from a write in Verilog means
|
||||
classifying continuous vs. procedural assignment, port direction and
|
||||
@@ -140,6 +146,20 @@ decision.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] **`documentHighlight` answered nothing on a cross-file name
|
||||
(2026-08-28, performance wave Lane B):** `performance.md` §7 reported it
|
||||
returning 0 results at *every* opentitan position tried — the `aes`
|
||||
instantiation, the `.clk_i` port connection, at both scopes, before and
|
||||
after a widen — while `references` at the same positions returned 7 and
|
||||
10. **Not a benchmark mistake: a real bug**, reproduced in a five-line
|
||||
fixture and fixed. Root cause and the argument are in the work log
|
||||
below; the regression tests are
|
||||
`nav::tests::a_cross_file_name_highlights_its_uses_in_this_file` and, over
|
||||
the wire at the same two positions,
|
||||
`e2e::cross_file_references_folding_and_highlights_round_trip_over_the_wire`
|
||||
ids 6 and 7. Still fast now that it answers: **0.05–0.15 ms** against the
|
||||
0.03–0.12 ms it took to answer nothing.
|
||||
|
||||
- [x] **References latency with a big buffer open (2026-08-28):** measure both
|
||||
directions of a cross-file references request while a 1.4 MB, 40 000-line
|
||||
`top.sv` is an open document, then fix what the numbers convict. Landed:
|
||||
@@ -210,6 +230,54 @@ decision.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-28 — documentHighlight answered nothing on a cross-file name
|
||||
|
||||
**The report.** `performance.md` §7: `documentHighlight` returned 0 results at
|
||||
every opentitan position tested, while `references` answered at the same
|
||||
positions. It was fast because it was doing nothing, which is the kind of
|
||||
result a benchmark that only times things rewards.
|
||||
|
||||
**Reproduced first, in five lines.** A `top.sv` that instantiates a `sub`
|
||||
declared in another file, with two instantiations and a `.clk_i` connection on
|
||||
each. `references` at the module name answered 3; `document_highlights` at the
|
||||
same byte answered `None`. That is
|
||||
`a_cross_file_name_highlights_its_uses_in_this_file`, written to fail before
|
||||
anything was changed.
|
||||
|
||||
**Root cause.** `document_highlights` asked `symbol_at`, which is
|
||||
`Semantics::reference_at(offset).resolved()` or `Semantics::symbol_at(offset)`
|
||||
— **both of them single-file questions**. A name this file *uses* but does not
|
||||
*declare* has no in-file symbol at all: `analyze` records the use as an
|
||||
external candidate and leaves it to the workspace layer, so `reference_at`
|
||||
resolves to nothing and `symbol_at` finds no declaration. An instantiated
|
||||
module's name and a `.port` in a connection list are exactly that shape, and
|
||||
they are most of what a cursor lands on in a testbench.
|
||||
|
||||
`references` never had the bug because it reads `doc.external` — the workspace
|
||||
overlay — through `leaves_this_file`/`indexed_target`. The two handlers were
|
||||
answering the same question from different halves of the same document, and
|
||||
only one half had been wired up. The existing highlight tests all used a
|
||||
signal declared in the file under test, which is why the suite was green.
|
||||
|
||||
**The fix**, `nav::external_occurrences`: when `symbol_at` finds nothing, ask
|
||||
the overlay for the reference at the cursor, and if the workspace answered it,
|
||||
collect every reference in *this* file that spells the same name and that the
|
||||
overlay answered the same way. Same-name-and-same-answer rather than
|
||||
same-name: two uses of `clk_i` that resolve into different modules are
|
||||
different symbols, and comparing the whole `defs()` slice rather than its
|
||||
first entry keeps two *ambiguous* uses together only when they are ambiguous
|
||||
between the same declarations. A use the index cannot answer is still left
|
||||
alone, so the editor keeps its own word highlighting — the contract the rest
|
||||
of the function already honours.
|
||||
|
||||
It stays a **document** highlight: one file's occurrences, which is why the
|
||||
opentitan `aes` position now answers 1 where `references` answers 7. That is
|
||||
not a smaller answer to the same question; `tb.sv` instantiates `aes` once.
|
||||
|
||||
Nothing outside `nav.rs` changed — the handler in `server.rs` already had the
|
||||
document in hand, and `Document::external` is already beside `Document::
|
||||
semantics`, so no signature moved.
|
||||
|
||||
### 2026-08-28 — references latency with a big buffer open
|
||||
|
||||
The owner reported find-references from a *use site* in a big open `top.sv`
|
||||
@@ -858,8 +926,108 @@ dev's original shape plus exactly my one addition.
|
||||
TODO.md discrepancy) left for the lead to reconcile — neither is a
|
||||
correctness or safety issue in the shipped feature.
|
||||
|
||||
### 2026-08-28 — QA agent (performance wave Lane B: the documentHighlight fix)
|
||||
|
||||
Verdict: **the fix is correct and holds under attack. One genuine behavioral
|
||||
divergence from `references` found and recorded (not a bug, but the lead
|
||||
should see it before calling the two "cross-checked").**
|
||||
|
||||
**Reproduced the original bug, live.** Built this worktree's release binary,
|
||||
pointed a copy of the scratchpad's `lspclient.py`/`bench.py` harness at it
|
||||
(`SERVER` edited to `target/release/lucisv-server`, `ROOT` unchanged at
|
||||
`/Users/guoliangchen/repo/opentitan`), and ran `bench.py nav workspace -`
|
||||
against the real checkout: `documentHighlight(aes)` and
|
||||
`documentHighlight(.clk_i)` now each return **1 result** (the `tb.sv`-local
|
||||
occurrence — correctly fewer than `references`'s 7/10, since `references`
|
||||
is workspace-wide and highlight is this-file-only by contract), where
|
||||
`performance.md` §7 recorded 0. Confirms the fix end-to-end, not just in
|
||||
the unit suite.
|
||||
|
||||
**Attacked the grouping logic (charter item 4) with three new permanent
|
||||
tests in `nav.rs`:**
|
||||
|
||||
1. `an_ambiguous_instantiation_highlights_where_references_gives_up` — two
|
||||
files both declare `module dup`, instantiated twice in a third file.
|
||||
`document_highlights` correctly groups both instantiations (same
|
||||
ambiguous def set). **Finding, not a bug**: `references` at the same
|
||||
position returns *empty*, not the same answer — traced to
|
||||
`indexed_target` (`nav.rs`), which only builds an `IndexedTarget` from
|
||||
`Definition::External([def])`, exactly one candidate; an ambiguous
|
||||
external use (2+ candidates) makes it return `None`, so `references()`
|
||||
falls through to `in_file_references`, which requires a *local* symbol
|
||||
(`symbol_at`) that an external use does not have — net empty, and this
|
||||
is pre-existing, unrelated to this round. `document_highlights`'s new
|
||||
`external_occurrences` has no such restriction: it groups by the
|
||||
overlay's whole answer, ambiguous sets included. This is a genuine
|
||||
divergence from "highlights == references-in-this-file at the same
|
||||
position", though arguably the *better* behavior (answering something
|
||||
reasonable beats forcing the editor's own word-highlighter to fall back
|
||||
to nothing) — recorded per the charter's instruction to cross-check
|
||||
rather than assumed away.
|
||||
2. `two_uses_ambiguous_between_different_def_sets_do_not_group` — the sin
|
||||
the charter names directly. Building this took two attempts: my first
|
||||
version used two module-scope `import p1::*; import p2::*;` wildcards
|
||||
expecting position-scoped ambiguity, and it failed — both usages grouped
|
||||
together (lines `[3, 5]` where I expected `[3]` and `[5]` separately).
|
||||
Root cause, traced through `bind.rs::bind_module` /
|
||||
`follow_paths`/`follow_one`: imports are collected per-scope and tried
|
||||
*in declaration order*, and `follow_paths` returns on the **first** path
|
||||
with any answer — so multiple wildcard imports of packages that each
|
||||
independently declare the same member never produce a multi-package
|
||||
`Ambiguous`; each reference resolves against whichever imported package
|
||||
is tried first. Real ambiguity comes from **duplicate declarations of
|
||||
the same entity** (two files declaring the same module/package), not
|
||||
from multiple distinct wildcard imports. Rebuilt the test around two
|
||||
*different* modules (`dup_a`, `dup_b`), each duplicated across two
|
||||
files, both exposing a port named identically (`same_port`) and
|
||||
connected in the same top module — same `reference.name`, disjoint
|
||||
ambiguous def sets (`dup_a`'s two files vs. `dup_b`'s two files). Passes:
|
||||
the two connections do not group. This is the test that actually proves
|
||||
`external_occurrences`'s `defs()` comparison (not just the name match)
|
||||
is load-bearing.
|
||||
3. `an_unanswered_external_use_declines_rather_than_guessing` — an import
|
||||
of a package the workspace does not declare, and a member reference the
|
||||
overlay cannot place. `document_highlights` returns `None` (declines),
|
||||
confirming the empty-`defs()` early-out and preserving the editor's
|
||||
own word-highlighting fallback.
|
||||
|
||||
**Cross-file name collision (charter item 4, "local at one position,
|
||||
external at another")**: traced by hand rather than by a new test —
|
||||
`external_occurrences` only ever matches a candidate occurrence through
|
||||
`doc.external.get(at)`, which is populated only for references the
|
||||
workspace overlay actually resolved (`resolve_external`,
|
||||
`vlog_semantic::workspace`); a same-spelled local declaration/use has no
|
||||
entry there, so `None == Some(target.defs())` excludes it automatically.
|
||||
No counter-example found.
|
||||
|
||||
**Reference-id indexing**: confirmed `ReferenceId(i)` in
|
||||
`vlog_semantic::lib.rs` corresponds exactly to index `i` in
|
||||
`Semantics::references()`'s backing `Vec` (`self.references.get(id.0 as
|
||||
usize)`), so `external_occurrences`'s `enumerate()` + `ReferenceId(*at as
|
||||
u32)` round trip is not an off-by-one risk.
|
||||
|
||||
**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test
|
||||
--workspace` (1261 passed), `node editors/vscode/smoke.js
|
||||
target/release/lucisv-server` — all clean, run against the worktree
|
||||
including my three additions.
|
||||
|
||||
No fixes applied to feature code — the fix is correct as shipped. Three
|
||||
permanent regression tests added to `nav.rs`. No commits.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead, performance-wave Lane B (documentHighlight).**
|
||||
The zero-results report was a real bug with a clean root cause: both
|
||||
cursor questions were single-file, so a name this file uses but does
|
||||
not declare had no answer, and every existing test used a declared
|
||||
name. The fix reads the overlay and groups by the whole defs() slice —
|
||||
the conservative equality — and was written failing-first with the two
|
||||
exact opentitan positions pinned over the wire. QA's INFORMATIONAL
|
||||
asymmetry (highlight answers on a globally-ambiguous target where
|
||||
references declines) is pre-existing, arguably correct — a highlight
|
||||
is file-local and read-only — and is now recorded here rather than
|
||||
discovered again. Accepted.
|
||||
|
||||
**2026-08-28 — lead, references-latency round.** Reviewed after QA's
|
||||
clean SHIP; gates re-run independently (fmt clean, clippy silent, 2407
|
||||
workspace tests green). Measure-first discipline held: the probes were
|
||||
|
||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user