Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
17214ac8db | ||
|
|
d4eb8f48ff | ||
|
|
cf32e92e58 | ||
|
|
097498da23 | ||
|
|
4f7b4a9f91 | ||
|
|
574ab833e3 | ||
|
|
12d0bbad51 | ||
|
|
de8a7e129c | ||
|
|
611dd23069 | ||
|
|
a4f23db2c7 | ||
|
|
d94f9e3de0 | ||
|
|
94b130aca1 | ||
|
|
efe67bde65 | ||
|
|
e70d979e51 | ||
|
|
b2d778eb8d | ||
|
|
27fc216df3 | ||
|
|
4665641e42 | ||
|
|
bc606dd6bd | ||
|
|
5e98b1a669 | ||
|
|
2e258df9a7 | ||
|
|
e4b1f55c12 | ||
|
|
5e4aa7bd6f | ||
|
|
7266b13702 | ||
|
|
8c8cfc538e | ||
|
|
8d070a4277 | ||
|
|
64d6e9a55d | ||
|
|
cebb333bd7 | ||
|
|
0a93143bfb | ||
|
|
ec65e0831f | ||
|
|
a399f81ad9 | ||
|
|
20ad318d4e | ||
|
|
7cd439f500 | ||
|
|
c47b16a65e | ||
|
|
17fb2129db | ||
|
|
8dc8f6489f | ||
|
|
33d2f2814f | ||
|
|
203e9b1a4f | ||
|
|
839a28ec8d | ||
|
|
662e323802 | ||
|
|
0e740d77ec | ||
|
|
3bc61f9eab | ||
|
|
01c76067e8 | ||
|
|
34938fbcf1 | ||
|
|
5d0725c158 | ||
|
|
dbd2f176aa | ||
|
|
6523c604bb | ||
|
|
e165c37a3a | ||
|
|
00c03eccf9 | ||
|
|
80b9afdfe3 | ||
|
|
c2ea1a11f6 | ||
|
|
aa303ce9ae | ||
|
|
d3081d6aaf |
No files matched your search
@@ -1,9 +1,15 @@
|
||||
# Release: pushing a tag `vX.Y.Z` builds every distribution artifact and
|
||||
# publishes a Gitea release with the CHANGELOG section for that version as
|
||||
# its notes. The artifact set is exactly what tools/release.sh --cross
|
||||
# produces: host (Apple Silicon) + x86_64 macOS + static-musl Linux +
|
||||
# RHEL 8-compatible linux-gnu + Windows binaries for both lucisv and
|
||||
# lucisv-server, the platform-independent .vsix, and SHA256SUMS.
|
||||
# its notes. What the release page carries is the seven .vsix packages —
|
||||
# the universal one, the five (darwin-arm64/darwin-x64/linux-x64/
|
||||
# linux-arm64/win32-x64) with the lucisv + lucisv-server binaries embedded,
|
||||
# and the all-platforms one carrying every pair at once — plus SHA256SUMS.
|
||||
# Every package is a must: a missing one fails the release, by name
|
||||
# (tools/prune_release_assets.sh). The loose binaries are still built for
|
||||
# every target
|
||||
# (the packages are made from them) and still audited, but they are not
|
||||
# attached: anyone who wants a standalone binary builds it with
|
||||
# `cargo build --release` (docs/features/editor-platform-vsix).
|
||||
#
|
||||
# The release fails, deliberately, when the tag does not match the
|
||||
# workspace version or CHANGELOG.md has no section for it: every release
|
||||
@@ -30,6 +36,11 @@ jobs:
|
||||
echo "tag $GITHUB_REF_NAME does not match crate version $v" >&2
|
||||
exit 1
|
||||
}
|
||||
# The release page ships extension packages only: all seven checked by
|
||||
# name, SHA256SUMS filtered down to them and re-verified, the loose
|
||||
# binaries (needed to build and audit the packages) dropped.
|
||||
- name: Keep only the extension packages
|
||||
run: tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"
|
||||
- name: Extract the release notes from CHANGELOG.md
|
||||
run: tools/release_notes.sh "${GITHUB_REF_NAME#v}" > dist/RELEASE_NOTES.md
|
||||
- name: Create the release and attach the artifacts
|
||||
|
||||
+673
@@ -4,6 +4,679 @@ 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.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
|
||||
open file, found by measurement and removed, plus a stack-safety hole
|
||||
closed.
|
||||
|
||||
### References stop sweeping the open buffer
|
||||
|
||||
The open-document overlay in find-references did index lookups for
|
||||
every reference in every open buffer. A spelled-name prefilter and a
|
||||
hoisted file lookup take a 70 000-reference open `top.sv` from 3.2 ms
|
||||
to **0.11 ms** per request, both directions; in-file references and
|
||||
occurrence highlighting on a heavily used signal drop ~40 %. Answers
|
||||
are byte-identical — the old refactor walk remains the tested oracle.
|
||||
|
||||
### A rescan reuses what open buffers already analyzed
|
||||
|
||||
Jumping into a folder the index scope had not reached triggered a
|
||||
rescan that re-parsed every open buffer's text twice — once for index
|
||||
facts, once for completion words. Both now come from the analysis the
|
||||
buffer already holds (one implementation per path, byte-identical facts
|
||||
pinned over the corpus): the folder-widening jump drops from **228 ms
|
||||
to 23 ms**, and didSave's incremental update rides the same reuse.
|
||||
|
||||
### The stack now fits the nesting limit by construction
|
||||
|
||||
The parser's 64-level nesting limit only turns over-deep input into an
|
||||
error on a stack big enough to reach level 64 — an assumption that had
|
||||
drifted out from under the 2026-08 measurement (~94 KiB per level in
|
||||
debug under rustc 1.97; a default 2 MiB thread aborted near level 30).
|
||||
`PARSE_STACK_SIZE` (16 MiB) is now applied at every parse-reaching
|
||||
thread, both binaries' work included — the CLI previously aborted under
|
||||
a 1 MiB main stack (`ulimit`, win32 default) on 500 nested `begin`s and
|
||||
now emits an ordinary diagnostic. Deep-nesting suites across four
|
||||
crates pin it, sabotage-verified.
|
||||
|
||||
## 0.13.0 — 2026-08-28
|
||||
|
||||
Editor responsiveness, and hover for old-style ports.
|
||||
|
||||
### Typing costs one reanalysis, not one per keystroke
|
||||
|
||||
`didChange` no longer reparses and re-lints the buffer on every
|
||||
keystroke. The text the server holds is still exactly current after
|
||||
every notification; only the analysis is deferred, and it runs at the
|
||||
first moment anything needs it — the next request, the next
|
||||
non-`didChange` notification, or a 150 ms quiet period. A burst of ten
|
||||
keystrokes in a 10 000-line file therefore costs one 31 ms reanalysis
|
||||
instead of ten. The visible consequence: intermediate diagnostics
|
||||
states are no longer published, so squiggles for a half-typed line that
|
||||
was finished a moment later never appear. Every state that is published
|
||||
is one the buffer really passed through. Closing a file that was
|
||||
mid-edit discards its pending change instead of analyzing it, so it
|
||||
costs one publish — the one that clears its squiggles — and not two.
|
||||
|
||||
The one case this makes slower is a single keystroke followed by
|
||||
nothing at all: it now waits out the quiet period before publishing,
|
||||
164 ms instead of one reanalysis. Editors ask for something after every
|
||||
change — semantic tokens, inlay hints, highlights — and any request
|
||||
flushes the buffer before it is answered, so the latency a user
|
||||
actually meets is 4.4 ms in a 1 000-line file and 37.6 ms in a
|
||||
10 000-line one.
|
||||
|
||||
### Hover shows a non-ANSI port's real declaration
|
||||
|
||||
A port declared the old way — named in the module header, completed in
|
||||
the body by `input signed [31:0] data_in;` — now hovers as two fenced
|
||||
sections: the header line, then the body declaration that carries the
|
||||
direction, the type and the width. Go-to-definition offers both, the
|
||||
body declaration first. It works cross-file, into files that are not
|
||||
open, because the span travels through the workspace index. An
|
||||
old-style task or function argument (`task t(a);` finished by
|
||||
`input [7:0] a;`) reads the same way. Each section also carries every
|
||||
comment that documents it: the lines above it, the comment beside it,
|
||||
and the lines below it when nothing else could claim them — all three
|
||||
at once where all three are written.
|
||||
|
||||
### Faster hover and navigation
|
||||
|
||||
A hover into a closed file reads that file once instead of twice (34 ms
|
||||
→ 16.3 ms on a 31.7 MB file), and resolving a live declaration looks
|
||||
its name up instead of walking every symbol in the buffer. Measurements
|
||||
and how to reproduce them: `docs/perf/README.md`.
|
||||
|
||||
### Cursor-position answers stop walking the whole buffer
|
||||
|
||||
Expand-selection, on-type formatting, the completion scope gates and
|
||||
the inline template trigger each used to scan every token in the file
|
||||
to find the one at the cursor. They now binary-search for it: 77 µs →
|
||||
20 ns in a 10 000-line buffer, and 130 µs → 36 ns for the widest of
|
||||
them. No answer changed — each swap is pinned by a test that compares
|
||||
it against the scan it replaced at every byte of the buffer.
|
||||
|
||||
The persistent index cache's record format changed to carry the new
|
||||
span, so the first session after upgrading rebuilds its index rather
|
||||
than reading the old store.
|
||||
|
||||
## 0.12.1 — 2026-08-27
|
||||
|
||||
Hover shows the cross-file declaration itself. A name declared in
|
||||
another file — a port at an instantiation, a module instance, a package
|
||||
member — now renders its declaration's source line, fenced and
|
||||
highlighted, under the existing "declared in `file:line`" heading:
|
||||
direction, type and width for a port, the header line for a module.
|
||||
Snippets come from the live buffer when the declaring file is open
|
||||
(unsaved edits included) and from disk otherwise, with a
|
||||
boundary-checking guard that drops the snippet rather than ever
|
||||
showing a wrong line, and caps of 5 lines / 400 characters for
|
||||
netlist-sized declarations. No settings and no index format change.
|
||||
|
||||
## 0.12.0 — 2026-08-27
|
||||
|
||||
The indexed-navigation release: find-all-references stops paying a
|
||||
project scan per request.
|
||||
|
||||
### References become a lookup
|
||||
|
||||
Each indexed file now persists compact reference facts — same-file uses
|
||||
of its exported declarations, plus unresolved cross-file candidates —
|
||||
and the workspace index resolves them once into
|
||||
declaration-to-occurrence postings. `textDocument/references` reads
|
||||
that posting list and overlays every open buffer's live analysis, so
|
||||
unsaved additions, deletions and moved declarations stay visible with
|
||||
no request-time scan: **0.06 ms per request over an 820-file workspace
|
||||
where the old walk cost 22 ms (~350×)**. The old walk remains rename's
|
||||
engine and is pinned equal to the indexed answer by test; ambiguity
|
||||
still degrades to the in-file answer exactly as before.
|
||||
|
||||
### Cursor lookups stop sweeping
|
||||
|
||||
Declaration, reference and macro-token lookups under the cursor —
|
||||
hover, definition, references entry points — binary-search sorted
|
||||
position tables instead of scanning every symbol in the buffer, and
|
||||
`` `include`` definition inspects only the cursor's line.
|
||||
|
||||
### One-time cache rebuild
|
||||
|
||||
The persisted facts format moved to version 2 for the new reference
|
||||
records. An existing index cache from 0.11.0 is discarded whole on
|
||||
first open and rebuilt — one re-scan, never a misread record.
|
||||
|
||||
## 0.11.0 — 2026-08-27
|
||||
|
||||
The large-workarea release: a project too big to scan is now a project
|
||||
lucisv keeps up with. Six owner-requested rounds, one dev/QA/review
|
||||
cycle each.
|
||||
|
||||
### Indexing starts where you are
|
||||
|
||||
`lucisv.index.scope` defaults to `folder`: the index covers the folders
|
||||
your open files live in — raised `lucisv.index.scopeDepth` ancestor
|
||||
levels — and widens as you open more. Cross-file answers are
|
||||
scope-relative until the scope reaches a folder; a filelist still
|
||||
defines the whole project, and `"workspace"` restores the previous
|
||||
walk exactly (the same code path, not an equal-output one). **This is
|
||||
a behavior change for workspace users without a filelist** — the
|
||||
migration is that one setting.
|
||||
|
||||
### One file changed, one file merged
|
||||
|
||||
A save re-indexes only the saved file — 33 ms where the corpus rescan
|
||||
cost 1.5 s — through an index whose incremental histories are
|
||||
byte-identical to fresh builds. Instantiation counts, incoming calls
|
||||
and subtype answers now come from edge tables built at index time
|
||||
(code lens 92 ms → 0.26 ms), so they read as of the index rather than
|
||||
of unsaved keystrokes.
|
||||
|
||||
### The index survives a restart
|
||||
|
||||
Per-file index records persist under the editor's workarea storage
|
||||
(`lucisv.index.persist`, on by default), keyed by content hash: a
|
||||
crashed or closed session resumes where it stopped, cached files fly
|
||||
through the progress bar, and the end message says how many came from
|
||||
cache. The cache is a performance artifact with a per-record checksum
|
||||
— a damaged entry costs a re-parse, never an answer.
|
||||
|
||||
### Netlists open instantly
|
||||
|
||||
Above `lucisv.largeFile.threshold` (4 MiB) a buffer skips the pipeline
|
||||
entirely: a 104 MB netlist opens in 40 ms, viewport syntax
|
||||
highlighting answers in a quarter of a millisecond, and same-file
|
||||
definition/references run as bounded text scans. Most other features
|
||||
deliberately answer nothing there. Fixing this path's long-line
|
||||
behavior also made ordinary files' semantic tokens up to 9× faster.
|
||||
|
||||
### The scan explains itself
|
||||
|
||||
The indexing bar counts `n/total` through the files; the output
|
||||
channel logs each file as indexed, cached, or skipped;
|
||||
`lucisv.index.maxFileSize` (1 MiB default) keeps generated files out
|
||||
of the index, with skips counted in the closing message.
|
||||
|
||||
## 0.10.2 — 2026-08-27
|
||||
|
||||
The works-anywhere release: a seventh extension package that carries
|
||||
**every platform's binaries in one file**, and a Marketplace-grade
|
||||
extension page.
|
||||
|
||||
### The all-platforms package
|
||||
|
||||
`lucisv-<version>-all.vsix` embeds all five platforms' `lucisv` and
|
||||
`lucisv-server` pairs under `bin/<platform>-<arch>/`, and the extension
|
||||
picks the right pair at runtime from `process.platform` and
|
||||
`process.arch`. It is deliberately target-less, which makes it the
|
||||
package for machines the targeted five cannot name: Alpine (VS Code
|
||||
there asks for an `alpine-*` target, but reports plain `linux` at
|
||||
runtime, so the static musl binaries just work), mixed fleets, or one
|
||||
file mirrored internally. The cost is download size — about 13 MB
|
||||
against 3 MB for a single-platform package — and nothing else. The
|
||||
resolution order is unchanged: an explicit `lucisv.serverPath` first,
|
||||
then the bundled binary (flat `bin/` before the platform subdirectory),
|
||||
then `PATH`. Details: `docs/features/editor-platform-vsix/README.md`.
|
||||
|
||||
### One consolidated release flow
|
||||
|
||||
The release workflow's publish-only-the-packages logic now lives in
|
||||
`tools/prune_release_assets.sh`, and it requires **all seven** packages
|
||||
by name — five platform, `all`, and the universal no-binary fallback —
|
||||
before anything is published; a missing one fails the release. Every
|
||||
tagged release follows this same flow with no manual steps beyond the
|
||||
version bump, the changelog section, and the tag.
|
||||
|
||||
### A Marketplace-grade extension page
|
||||
|
||||
`editors/vscode/README.md` is rewritten for end users — install matrix,
|
||||
capability tables, snippet library, settings ladder, troubleshooting —
|
||||
with an icon and diagrams, and the manifest gains the Marketplace
|
||||
metadata (icon, banner, keywords, categories). Troubleshooting now also
|
||||
names the duplicate-hover trap: the pre-rename **vfmt** extension left
|
||||
installed next to lucisv attaches a second language server, and every
|
||||
hover and diagnostic shows twice. Uninstall `vfmt` and reload.
|
||||
|
||||
## 0.10.1 — 2026-08-27
|
||||
|
||||
The install-in-one-step release: the VS Code extension now ships as
|
||||
**platform-specific packages with the binaries inside**, and the release
|
||||
page carries exactly those packages — nothing to build, nothing to put on
|
||||
`PATH`.
|
||||
|
||||
### Platform packages for the VS Code extension
|
||||
|
||||
Five new `.vsix` packages — `darwin-arm64`, `darwin-x64`, `linux-x64`,
|
||||
`linux-arm64`, `win32-x64` — each embedding that platform's `lucisv` and
|
||||
`lucisv-server` under `bin/` inside the extension. Install the one
|
||||
matching your machine with `code --install-extension` and the extension
|
||||
spawns its own server; both Linux packages are statically linked (musl),
|
||||
so they run on any distro, and `linux-arm64` is a **new build target**
|
||||
altogether. The extension resolves the server as: an explicitly set
|
||||
`lucisv.serverPath` first, then the bundled binary (made executable on
|
||||
activation — VSIX extraction drops the bit), then `PATH` — so pointing at
|
||||
your own `target/release` build still works, and clearing the setting
|
||||
falls back to the bundled server. The universal `lucisv-<version>.vsix`
|
||||
(no binaries, server from `PATH`) remains the fallback for platforms
|
||||
without a package. Details and the verification story:
|
||||
`docs/features/editor-platform-vsix/README.md`.
|
||||
|
||||
### The release page ships packages only
|
||||
|
||||
A tagged release now publishes the six `.vsix` files and `SHA256SUMS`,
|
||||
nothing else. Every platform package is checked by name before publishing
|
||||
— a missing one fails the release — and the per-platform binaries are
|
||||
still built and audited (static-linkage, glibc ceiling, file types) since
|
||||
the packages embed them, but no longer attached as loose assets: a
|
||||
standalone binary is a `cargo build --release` away. The host package's
|
||||
embedded server is smoke-tested through a full LSP session, straight out
|
||||
of the zip, on every release.
|
||||
|
||||
## 0.10.0 — 2026-08-27
|
||||
|
||||
The audit-complete release: TODO.md §9c, the last section of the LSP
|
||||
3.18 audit, shipped one feature per dev/QA/review round — plus the two
|
||||
cross-crate rounds the audit's findings demanded.
|
||||
|
||||
### Go to type definition
|
||||
|
||||
From a name to its type's declaration: variable to typedef, handle to
|
||||
class, instance to module, signal to interface — one redirection into
|
||||
the same two-layer resolution F12 uses, cross-file included.
|
||||
|
||||
### The semantic layer answers cross-file types (and only types)
|
||||
|
||||
Unqualified type-position misses now reach the workspace overlay, so
|
||||
`bus_if bus;` and `my_cls h;` resolve into other files — including
|
||||
inside extending (UVM-style) classes. Value-position identifiers
|
||||
deliberately do not: QA proved a typo could otherwise rename an
|
||||
unrelated same-named module cross-file, and the promotion was narrowed
|
||||
to exactly the positions that name types. 418 corpus references gained
|
||||
a jump target; none lost one. Cross-file interface rename works.
|
||||
|
||||
### The parser accepts direction-less first ANSI ports
|
||||
|
||||
`module m (bus_if bus, input logic clk);` — the normal spelling for
|
||||
interface ports — parses, along with modport-qualified and
|
||||
package-scoped first ports. All 820 corpus files format
|
||||
byte-identically to before, proven by hash on both sides.
|
||||
|
||||
### Linked editing, code lens, on-type formatting
|
||||
|
||||
Closing labels (`endmodule : m`, `end : blk`) edit as one. Every
|
||||
module carries an instantiation-count lens whose click jumps to the
|
||||
sites. Typing `;` reformats the finished statement through the
|
||||
verified engine; a newline indents the new line through a model that
|
||||
agrees with the formatter on 77k corpus lines.
|
||||
|
||||
### Type hierarchy
|
||||
|
||||
Supertypes and subtypes over `extends`, one hop per request, riding
|
||||
the overlay's cross-file resolution.
|
||||
|
||||
### Renaming a file rewrites its includes
|
||||
|
||||
`workspace/willRenameFiles` rewrites every `` `include`` that
|
||||
resolves to a moved file — resolution, never name matching — with a
|
||||
three-check safety net that refuses rather than guesses, edits
|
||||
addressed to pre-rename URIs, and directory renames for free.
|
||||
|
||||
### Workspace folders and pulled configuration
|
||||
|
||||
Folders added or removed mid-session reindex on the spot; clients
|
||||
using the modern configuration-pull model get their settings through
|
||||
the same parser as the push, so the two can never drift.
|
||||
|
||||
### Multi-range formatting
|
||||
|
||||
`textDocument/rangesFormatting` — the request VS Code's client
|
||||
library was asking for all along — formats any set of ranges in one
|
||||
verified pass, the same call the CLI's `--lines a-b,c-d` makes.
|
||||
Snippet workspace edits and server-provided documents are assessed
|
||||
and parked with evidence until a shipping client can consume them.
|
||||
|
||||
## 0.9.0 — 2026-08-26
|
||||
|
||||
The performance-model release: TODO.md §9b, the high-value half of the
|
||||
LSP 3.18 audit, shipped one feature per dev/QA/review round.
|
||||
|
||||
### Incremental text sync
|
||||
|
||||
A keystroke now costs one range on the wire, not the whole file. Edits
|
||||
are applied by one pure function with clamping rules inherited from the
|
||||
existing position converter — a backwards range becomes a pure
|
||||
insertion, the only reading that cannot lose text — cross-checked
|
||||
against an independent reference model over 400 randomized edit
|
||||
sequences. One notification is still one reparse, one diagnostics
|
||||
generation, one publish.
|
||||
|
||||
### Format on save (willSaveWaitUntil)
|
||||
|
||||
The protocol's native format-on-save hook, for editors without one of
|
||||
their own. Off by default (`lucisv.formatOnSave`) so it never fights an
|
||||
editor that already formats on save; when on, it is the formatting
|
||||
request with a different trigger — same engine, same verified-output,
|
||||
all-or-nothing contract. The one protocol gap (no editor tab size on
|
||||
this path) is documented rather than papered over.
|
||||
|
||||
### Semantic tokens: range and delta
|
||||
|
||||
`semanticTokens/range` answers just the lines the editor is showing;
|
||||
`full/delta` answers edits against the previous result instead of the
|
||||
whole token set. One tokenizer and one pure encoder serve full, range
|
||||
and delta, proven byte-identical to the old encoder over a 41k-token
|
||||
corpus file; the delta's single-edit diff carries the classic
|
||||
prefix/suffix overlap trap, deliberately broken twice (dev and QA,
|
||||
independently) to prove the suite catches it.
|
||||
|
||||
### A progress bar on indexing
|
||||
|
||||
Every workspace rescan — the startup build included — now shows a real
|
||||
progress bar in clients that support one: what is being indexed, no
|
||||
invented percentages, and an honest file count when it comes down.
|
||||
|
||||
### $/cancelRequest
|
||||
|
||||
The server reads its backlog in bursts and answers a request whose
|
||||
cancel arrived alongside it with RequestCancelled instead of computing
|
||||
it — completion requests a fast typist already outran no longer cost a
|
||||
parse each. Cancellation is stateless by construction: a cancel matters
|
||||
only next to its own request, everything else is dropped on sight, and
|
||||
no cancel can talk the server out of a shutdown. Enabled by the
|
||||
server's first thread — a 12-line forwarder that makes the client's
|
||||
backlog observable at all through lsp-server's rendezvous channels.
|
||||
|
||||
## 0.8.0 — 2026-08-26
|
||||
|
||||
The protocol-compliance release: the server was audited line-by-line
|
||||
against the LSP 3.18 specification (the full gap list is TODO.md §9),
|
||||
and the three findings that matter most shipped in one round.
|
||||
|
||||
### Port commands now actually edit (workspace/applyEdit)
|
||||
|
||||
`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked
|
||||
as *commands* did nothing in every stock client: the server returned the
|
||||
`WorkspaceEdit` as the `executeCommand` result, which the protocol does
|
||||
not define and which `vscode-languageclient` and Neovim both drop. (The
|
||||
code-action lightbulb path was never affected — those edits ride inline.)
|
||||
The server now pushes the edit as a `workspace/applyEdit` request with a
|
||||
label for the undo stack, answers `null`, and reads the client's verdict:
|
||||
a refusal becomes an error popup naming the command and the editor's own
|
||||
reason. A client that never advertised `workspace.applyEdit` keeps the
|
||||
old return-the-edit behavior — for that one it is the only thing that
|
||||
could ever work.
|
||||
|
||||
### Pull diagnostics (LSP 3.17)
|
||||
|
||||
`textDocument/diagnostic` and `workspace/diagnostic` are served, from the
|
||||
same parse+lint pass the push model publishes — one computation, two
|
||||
deliveries, proven byte-identical in tests. Reports carry a `resultId`
|
||||
and answer `unchanged` when nothing that feeds them has moved, so a
|
||||
client re-pulling on focus changes costs nothing. A client that pulls is
|
||||
pushed nothing at all — never both models for one client. Clients that
|
||||
don't advertise the capability keep today's push behavior untouched.
|
||||
Workspace reports cover the open buffers, which is the only scope this
|
||||
server has ever diagnosed.
|
||||
|
||||
### Expand selection (textDocument/selectionRange)
|
||||
|
||||
One keystroke grows the selection from the identifier through the
|
||||
statement, the enclosing `begin`/`end`, the process, the module, out to
|
||||
the whole file. Chains are built from what the server already computes —
|
||||
token spans, the tolerant parse's item/statement spans, and the
|
||||
rainbow's own scope-pair matcher, which keeps expansion working in the
|
||||
half-edited files where you actually reach for it. Every step strictly
|
||||
contains the last; a sweep over all 860 corpus files (6,880 positions)
|
||||
holds the invariant everywhere.
|
||||
|
||||
## 0.7.2 — 2026-08-26
|
||||
|
||||
Honest columns, honest docs, and a CI that enforces the headline number.
|
||||
|
||||
@@ -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.7.2"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.2"
|
||||
version = "0.19.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# lucisv — Language Utility for Coding In SystemVerilog
|
||||
|
||||
A Verilog/SystemVerilog formatter and linter in Rust.
|
||||
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
|
||||
|
||||
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
|
||||
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
|
||||
@@ -610,30 +610,43 @@ go-to-definition, references and document/workspace symbols — the full list,
|
||||
and what is deliberately *not* advertised yet, is in
|
||||
`docs/features/lucisv-server/README.md`.
|
||||
|
||||
**The binary comes from the same build as the CLI.** Download it from the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases) for your
|
||||
platform, or build it yourself:
|
||||
**VS Code needs no separate binary**: every release on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
|
||||
platform-specific `.vsix` with both binaries inside it — pick yours
|
||||
(`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`)
|
||||
and sideload it:
|
||||
|
||||
```bash
|
||||
code --install-extension lucisv-<version>-darwin-arm64.vsix
|
||||
```
|
||||
|
||||
— or take `lucisv-<version>-all.vsix`, which carries all five platforms' binaries
|
||||
in one file and picks the right pair at startup, when the machine is not known
|
||||
in advance (or is Alpine, which VS Code never offers a Linux package to).
|
||||
|
||||
Every other editor (and the universal `lucisv-<version>.vsix`, the fallback
|
||||
for platforms not listed) finds `lucisv-server` on `PATH`; the binary comes
|
||||
from the same build as the CLI:
|
||||
|
||||
```bash
|
||||
cargo build --release # target/release/lucisv-server (and target/release/lucisv)
|
||||
cp target/release/lucisv-server ~/.local/bin/ # anywhere on PATH
|
||||
```
|
||||
|
||||
Every editor below defaults to finding `lucisv-server` on `PATH`; each also
|
||||
accepts an absolute path if you would rather leave the binary in `target/`.
|
||||
Each editor also accepts an absolute path if you would rather leave the
|
||||
binary in `target/`.
|
||||
|
||||
**VS Code** — a thin extension in `editors/vscode/` whose entire job is
|
||||
registering the file types and starting the server:
|
||||
registering the file types and starting the server (bundled, from `PATH`, or
|
||||
from the `lucisv.serverPath` setting). To build the packages yourself:
|
||||
|
||||
```bash
|
||||
tools/release.sh # builds dist/lucisv-<version>.vsix
|
||||
code --install-extension dist/lucisv-<version>.vsix
|
||||
tools/release.sh # dist/lucisv-<version>.vsix + the host platform package
|
||||
code --install-extension dist/lucisv-<version>-darwin-arm64.vsix
|
||||
```
|
||||
|
||||
The `.vsix` is also attached to every release on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases). Sideloading it
|
||||
is the supported install; the extension is not on any marketplace. To package it by hand instead: `cd editors/vscode && npm ci &&
|
||||
npx @vscode/vsce package`.
|
||||
Sideloading is the supported install; the extension is not on any
|
||||
marketplace.
|
||||
|
||||
Settings are listed in `editors/vscode/README.md`, along with the full steps,
|
||||
the F5 development flow and troubleshooting.
|
||||
@@ -665,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
|
||||
@@ -694,20 +711,26 @@ expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
|
||||
|
||||
Prebuilt downloads live on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases): every tagged
|
||||
version carries `lucisv` and `lucisv-server` for Apple Silicon and Intel
|
||||
macOS, static-musl and RHEL 8-compatible glibc Linux, and Windows, plus the
|
||||
`.vsix` and a `SHA256SUMS` to verify them with
|
||||
(`shasum -a 256 -c SHA256SUMS`). Copy the two binaries onto your `PATH` and
|
||||
sideload the extension with `code --install-extension`. The macOS binaries
|
||||
are smoke-tested on the build machine; the Linux and Windows ones are
|
||||
cross-built and audited (file type, dynamic-linkage, glibc-version ceiling),
|
||||
not executed — there is no Linux or Windows machine in the loop.
|
||||
version carries **seven `.vsix` packages** — platform-specific ones for
|
||||
Apple Silicon and Intel macOS, x86-64 and ARM64 Linux (static musl) and
|
||||
Windows, each with `lucisv` and `lucisv-server` embedded, an
|
||||
all-platforms one carrying every pair at once for unknown or mixed
|
||||
machines, plus the universal no-binary fallback — and a `SHA256SUMS` to
|
||||
verify them with
|
||||
(`shasum -a 256 -c SHA256SUMS`). Sideload the one for your machine with
|
||||
`code --install-extension`. Standalone binaries are not published; build
|
||||
them with `cargo build --release` (or `tools/release.sh --cross` for the
|
||||
full set — the release binaries are cut from the same scripts). The macOS
|
||||
binaries inside the packages are smoke-tested on the build machine; the
|
||||
Linux and Windows ones are cross-built and audited (file type,
|
||||
dynamic-linkage, glibc-version ceiling), not executed — there is no Linux
|
||||
or Windows machine in the loop.
|
||||
|
||||
To build the same artifact set yourself:
|
||||
|
||||
```bash
|
||||
tools/release.sh # host binaries + the .vsix + SHA256SUMS, into dist/
|
||||
tools/release.sh --cross # ...plus the four cross-built platforms
|
||||
tools/release.sh --cross # ...plus the four cross-built platforms and the all package
|
||||
```
|
||||
|
||||
The script itself publishes nothing anywhere; publishing is CI's job —
|
||||
|
||||
@@ -149,8 +149,8 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
- [x] **[R] Parallel file processing.** ruff's speed story is embarrassing
|
||||
parallelism over files. `main.rs` formats serially; use `rayon`
|
||||
par_iter over the collected file list (formatting is already pure).
|
||||
→ `crates/lucisv/src/main.rs`; pool sizing (8 MiB worker stacks, per the
|
||||
recursion-limit handshake), the reworked panic hook and the
|
||||
→ `crates/lucisv/src/main.rs`; pool sizing (`vlog_parser::PARSE_STACK_SIZE`
|
||||
worker stacks, per the recursion-limit handshake), the reworked panic hook and the
|
||||
ordered-reporting determinism argument in
|
||||
`docs/features/parallel-files/README.md`. `--threads N` pins the worker
|
||||
count; output is byte-identical at any count. 3.6× on 10 cores.
|
||||
@@ -491,7 +491,12 @@ later:
|
||||
typedef names → (file, span) across all workspace files, so header
|
||||
imports (`import pkg::*;`) and instantiations resolve to definitions
|
||||
in other files. Start as a full-scan-on-startup index (Verilog
|
||||
codebases are small); incrementality comes with salsa later.
|
||||
codebases are small); ~~incrementality comes with salsa later~~ — one file
|
||||
at a time since 2026-08-27, without salsa
|
||||
(`docs/features/incremental-index/README.md`); and ~~re-scanned from zero on
|
||||
every startup~~ — what a scan learns persists since 2026-08-27, so a reopened
|
||||
workspace indexes from records rather than parses and an interrupted scan
|
||||
resumes (`docs/features/index-persistence/README.md`).
|
||||
→ `vlog_semantic::WorkspaceIndex::build(files) `+
|
||||
`resolve_external(&Semantics, &WorkspaceIndex) -> ExternalResolutions`,
|
||||
a two-layer design: the index is a full scan (860 corpus files in 0.7 s),
|
||||
@@ -558,6 +563,54 @@ later:
|
||||
- [ ] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa;
|
||||
don't take that dependency until hover/definition across files exists.
|
||||
Per-file recompute is fine at Verilog file sizes.
|
||||
**Partly answered without salsa, 2026-08-27**
|
||||
(`docs/features/incremental-index/README.md`): `WorkspaceIndex::update_file`
|
||||
replaces one file's contribution and provably gives the index a whole build
|
||||
would have, so a save costs 33 ms instead of 1.5 s over the corpus. No query
|
||||
graph and no dependency tracking — the salsa question is still open, and is
|
||||
still deferred. **A second piece answered without salsa, 2026-08-27**
|
||||
(`docs/features/index-persistence/README.md`): every file's `FileFacts` are
|
||||
written to a content-keyed store as a scan parses them, so the recompute a
|
||||
*new session* would otherwise repeat is skipped instead — 1.8x on a whole
|
||||
corpus rescan, and a scan interrupted halfway resumes where it stopped.
|
||||
**A third piece answered without salsa, 2026-08-28**
|
||||
(`docs/features/change-debounce/README.md`): the per-keystroke recompute a
|
||||
query graph would have made unnecessary is instead *not started* — a burst
|
||||
of `didChange`s is coalesced into one reanalysis. Still no query graph and
|
||||
no dependency tracking; the salsa question remains open and deferred.
|
||||
Measured costs for what a recompute actually is are now recorded in
|
||||
`docs/perf/README.md`. **Round 2, 2026-08-28**
|
||||
(`docs/features/interactive-latency/README.md`): that recompute is now
|
||||
broken down stage by stage, and 79 % of it is lexing and parsing. If the
|
||||
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
|
||||
@@ -591,12 +644,32 @@ section only tracks the milestones.
|
||||
|
||||
- [x] **M1 `filelist`** — EDA `.f` filelist defines the index scope
|
||||
(`-f` nesting, `+incdir+`/`+define+` recorded, env vars); fallback:
|
||||
workspace walk, then current file's directory when rootless.
|
||||
~~workspace walk, then current file's directory when rootless~~
|
||||
**the open files' own folders since 2026-08-27 (index-scope), with the
|
||||
workspace walk behind `lucisv.index.scope: "workspace"`; the filelist
|
||||
still outranks both. See `docs/features/index-scope/README.md`.**
|
||||
**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. **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
|
||||
@@ -627,3 +700,817 @@ section only tracks the milestones.
|
||||
CHANGELOG entry covering M7–M14.
|
||||
- [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion,
|
||||
organize imports, …) — triaged in the umbrella README after M5.
|
||||
|
||||
## 9. LSP 3.18 protocol audit (2026-08-26)
|
||||
|
||||
Systematic comparison of `lucisv_server` against the LSP 3.18
|
||||
specification. What we implement: hover, definition, references,
|
||||
documentHighlight, documentLink, document/workspace symbols, folding,
|
||||
semanticTokens/full, inlayHint, completion, inlineCompletion (3.18),
|
||||
signatureHelp, codeAction + executeCommand, rename + prepare,
|
||||
callHierarchy, formatting + rangeFormatting, push diagnostics, dynamic
|
||||
file-watcher registration, configuration push. Below is everything
|
||||
major that's missing, ordered by priority. The `resolve` endpoints
|
||||
(completionItem, codeAction, inlayHint, documentLink, workspaceSymbol)
|
||||
are **deliberately** unadvertised — every item is returned complete —
|
||||
and are not gaps.
|
||||
|
||||
### 9a. Compliance and high-value (round 1)
|
||||
|
||||
- [x] **`executeCommand` must deliver its edit via `workspace/applyEdit`.**
|
||||
Today `ports::execute`'s `WorkspaceEdit` is returned as the request's
|
||||
*result* (`server.rs`, `ports.rs:79`), which the spec does not define
|
||||
and standard clients drop on the floor — `vscode-languageclient` does
|
||||
not apply executeCommand results and `editors/vscode/extension.js`
|
||||
has no custom handler, so `lucisv.addPort`/`removePort`/`propagate`
|
||||
invoked as *commands* currently do nothing in every stock client (the
|
||||
code-action path is unaffected: those carry the edit inline). Fix:
|
||||
push a `workspace/applyEdit` request, return `null` as the command
|
||||
result, and read the `ApplyWorkspaceEditResponse` (the one client
|
||||
response we can no longer ignore wholesale). Gate on the client's
|
||||
`workspace.applyEdit` capability with the old return-the-edit
|
||||
behavior as the documented fallback.
|
||||
→ `docs/features/apply-edit/README.md`; the edit is pushed with a
|
||||
`lucisv: <command>` label, the result is `null`, and a refusal is shown
|
||||
as an ERROR naming the command. Watcher-registration answers stay
|
||||
ignored; `editors/vscode/extension.js` needed no change.
|
||||
- [x] **Pull diagnostics (3.17): `textDocument/diagnostic` +
|
||||
`workspace/diagnostic`.** The modern model — client controls timing,
|
||||
prioritizes visible editors, caches via `resultId`/`unchanged`.
|
||||
Advertise `DiagnosticOptions` (`inter_file_dependencies: true` — a
|
||||
save can change other files' diagnostics through the index;
|
||||
`workspace_diagnostics`), compute from the same parse+lint pass that
|
||||
feeds `publish`, answer `Unchanged` when the buffer version and index
|
||||
generation both stand. Keep push for clients that don't send
|
||||
`text_document.diagnostic` capability; never run both models for the
|
||||
same client (double diagnostics).
|
||||
→ `docs/features/pull-diagnostics/README.md`; one generation counter is
|
||||
the whole `resultId` (bumped by `set_document` and `reindex`), the
|
||||
push gate sits in `send_diagnostics` so the `didClose` clear is
|
||||
suppressed too, and `workspace/diagnostic` reports the open buffers —
|
||||
the honest limit, stated there.
|
||||
- [x] **`textDocument/selectionRange`** — expand-selection. Cheap for
|
||||
us: the scope-pair matcher (`pairs.rs`) and AST spans already give
|
||||
the nesting chain; walk offset → enclosing token → statement → item →
|
||||
scope → file, one linked chain per input position.
|
||||
→ `docs/features/selection-range/README.md`
|
||||
(`crates/lucisv_server/src/selection.rs`); token, AST, scope-pair and
|
||||
file ranges are collected and filtered down to what strictly nests. No
|
||||
expression step — deliberate, and recorded there.
|
||||
|
||||
### 9b. High-value, next rounds
|
||||
|
||||
- [x] **Incremental text sync** (`TextDocumentSyncKind::INCREMENTAL`).
|
||||
Full-buffer sync on every keystroke scales poorly; apply
|
||||
range-scoped `contentChanges` in order, with a full-text fallback on
|
||||
any malformed change. Touches `set_document` and the staleness model
|
||||
in `docs/features/lucisv-server/README.md`.
|
||||
→ `docs/features/incremental-sync/README.md`
|
||||
(`crates/lucisv_server/src/sync.rs`); one pure
|
||||
`apply_changes(text, changes) -> String` over `convert::Positions`, a
|
||||
fresh line table per change so each range sees the previous one's
|
||||
result, rangeless changes still replacing the whole buffer, and every
|
||||
desynced position clamped (line past EOF, character past line end,
|
||||
surrogate half rounds forward, `start > end` becomes an insertion).
|
||||
Still one `set_document` — one reparse, one generation bump, one
|
||||
publish — per notification. Advertised as `TextDocumentSyncOptions`
|
||||
with the open/close and `save.includeText: false` values a bare `Kind`
|
||||
already implied, so no client's save behavior moved.
|
||||
**Amended 2026-08-28** (`docs/features/change-debounce/README.md`): a
|
||||
`didChange` now only records the composed text; the reparse, the
|
||||
generation bump and the publish happen at the next *flush* — the next
|
||||
request, the next non-`didChange` notification, or a 150 ms quiet period —
|
||||
so a typing burst costs one of each instead of one per keystroke. The
|
||||
buffer's text is still exactly current after every notification; only its
|
||||
analysis is deferred, and intermediate diagnostics states are no longer
|
||||
published. **Measured 2026-08-28**
|
||||
(`docs/features/interactive-latency/README.md`): a burst of ten keystrokes
|
||||
over the wire produces exactly one `publishDiagnostics`, and a keystroke a
|
||||
request follows — the shape a real editor sends — round-trips in 4.8 ms at
|
||||
1 000 lines and 37 ms at 10 000.
|
||||
- [x] **`textDocument/willSaveWaitUntil`** — the protocol-native
|
||||
format-on-save hook (client-side `editor.formatOnSave` already works;
|
||||
this serves the editors without it).
|
||||
→ `docs/features/will-save-wait-until/README.md`; advertised as
|
||||
`willSaveWaitUntil: true` (the plain `willSave` notification stays
|
||||
unadvertised — there is nothing for us in it), and gated on a new
|
||||
`lucisv.formatOnSave` setting that is **off** by default, so a client
|
||||
with its own format-on-save never formats twice. On, it is
|
||||
`textDocument/formatting` with a different trigger: same engine, same
|
||||
all-or-nothing edit, same `[]` for an already-formatted buffer, and the
|
||||
settings ladder minus its `tabSize` rung because the request carries no
|
||||
`FormattingOptions`. Every save reason formats; an unopened buffer and
|
||||
the off state both answer `null`.
|
||||
- [x] **Semantic tokens `range` + `full/delta`** — we set
|
||||
`range: None` and no delta, so clients re-request whole-file token
|
||||
sets on every edit. Delta needs `resultId` bookkeeping per buffer.
|
||||
→ `docs/features/semantic-tokens-delta/README.md`; `tokens.rs` split
|
||||
into classification → absolute form → filter → one pure encoder, so
|
||||
all three requests share a tokenizer. `range: Some(true)` answers the
|
||||
overlapping tokens whole, **re-encoded from the start of the
|
||||
document** (a range answer is self-contained, not a slice), carries
|
||||
no `resultId` and is not what a later delta diffs against; an empty
|
||||
range answers nothing. `full: Delta { delta: true }` answers one
|
||||
`SemanticTokensEdit` replacing everything between the common prefix
|
||||
and the common suffix — **the suffix capped to what the prefix left**,
|
||||
because identical lines of Verilog encode identically and an uncapped
|
||||
suffix claims the same tokens twice. `resultId`s are minted per
|
||||
answer, stored by `full` and `full/delta` alike, dropped on
|
||||
`didClose`; an id the server does not hold is answered in full. No
|
||||
token request bumps the diagnostics generation. Not done:
|
||||
`workspace/semanticTokens/refresh`.
|
||||
- [x] **Work-done progress** — `reindex()` is a synchronous full
|
||||
rescan on every save with no `window/workDoneProgress` reporting;
|
||||
on a big filelist the server just goes quiet.
|
||||
→ `docs/features/work-done-progress/README.md`; every workspace
|
||||
rescan — the startup build, a save, a watched file, a changed
|
||||
`lucisv.exclude`/`filelist` — is wrapped in one
|
||||
`window/workDoneProgress/create` plus a `$/progress` begin/end pair
|
||||
on a fresh `lucisv-index-N` token, gated on the client's
|
||||
`window.workDoneProgress` (a client that did not ask is sent nothing
|
||||
at all, as the spec requires). `begin` goes out without waiting for
|
||||
the create's answer, because the rescan blocks the loop the moment
|
||||
it returns; the create's answer is ignored on the same path the
|
||||
watcher registrations' is. No percentage and no intermediate report
|
||||
— the rescan is one opaque call — and the `end` names the indexed
|
||||
file count, read off the index's own file list. The bar covers the
|
||||
scan, ending before the scope warnings and the republishes.
|
||||
→ **Superseded in part, 2026-08-27**: the rescan is no longer opaque.
|
||||
`docs/features/indexing-ux/README.md` adds
|
||||
`vlog_semantic::IndexBuilder`/`index_order`, so the bar now carries
|
||||
`n/total file.sv` and a counted percentage (throttled to at most
|
||||
1000 reports per rescan), a per-file `window/logMessage` under
|
||||
`lucisv.index.logFiles`, and a 1 MiB default walk-file size cap under
|
||||
`lucisv.index.maxFileSize` whose skips the `end` message counts.
|
||||
→ **Extended again, 2026-08-27**
|
||||
(`docs/features/index-persistence/README.md`): a file restored from the
|
||||
persistent index cache logs `cached:` rather than `indexing:` and is counted
|
||||
in the `end` message — `860 files indexed, 860 from cache` — so a rescan that
|
||||
flew past says why.
|
||||
→ **Extended once more, 2026-08-28**
|
||||
(`docs/features/index-scope/README.md`): a file that went into the index from
|
||||
an open buffer's own finished analysis — no parse, no store — logs
|
||||
`analyzed:` and adds nothing to the `end` message, so "from cache" still
|
||||
means the persistent store alone.
|
||||
→ **The other half of the size story, 2026-08-27**
|
||||
(`docs/features/large-file-mode/README.md`): the walk cap covers files
|
||||
nobody opened, and `lucisv.largeFile.threshold` (4 MiB) now covers the file
|
||||
that *is* open. Over it, a buffer is line-indexed and nothing else — 41 ms
|
||||
for 100 MB — coloured a viewport at a time by `semanticTokens/range`,
|
||||
answered `null`/empty everywhere else, and left out of the index entirely
|
||||
(the one exception to "an open buffer is never capped"). It logs
|
||||
`large-file fast path: <path> (<bytes> bytes)` once per buffer.
|
||||
Everything else above — the capability gate, the token scheme, the
|
||||
create's ignored answer, the ordering against the republish — is
|
||||
unchanged.
|
||||
- [x] **`$/cancelRequest`** — the loop handles requests sequentially
|
||||
and ignores cancellation; at minimum answer already-cancelled queued
|
||||
requests with `RequestCancelled`.
|
||||
→ `docs/features/cancel-request/README.md`; **completes §9b.** `run()`
|
||||
now reads in bursts — one blocking receive, then everything already
|
||||
queued behind it — and handles the burst **in arrival order**, so a
|
||||
`didChange` ahead of a request is still applied before that request is
|
||||
answered. A request the same burst also carries a cancel for is
|
||||
answered `RequestCancelled` (-32800) without being dispatched; the
|
||||
cancels themselves are consumed there and never reach
|
||||
`notification()`. A cancel naming no request in its burst is dropped
|
||||
on the spot — it refers to a request already answered, or to one that
|
||||
never arrived — so the feature holds no state between bursts, and a
|
||||
double cancel is harmless. `shutdown` is honoured before the cancelled
|
||||
set is consulted and so is never cancellable. Numeric and string ids
|
||||
both read; malformed cancels dropped. The design's one correction:
|
||||
`lsp-server` 0.10 wires its stdio transport with `bounded(0)`
|
||||
*rendezvous* channels, so a backlog never sits on
|
||||
`connection.receiver` at all — the loop forwards messages onto an
|
||||
unbounded `std::sync::mpsc` queue of its own on one small thread
|
||||
(std-only, no new dependency), which stops at `shutdown` so
|
||||
`handle_shutdown` still reads the `exit` that follows. Nothing already
|
||||
running is cancelled; that needs the worker pool §6 defers.
|
||||
|
||||
### 9c. Moderate value, Verilog-shaped
|
||||
|
||||
- [x] **Goto type definition** — from a net/variable use to its
|
||||
typedef/struct/enum/interface declaration; real value once
|
||||
`vlog_semantic` tracks declared types of bindings.
|
||||
→ delivered 2026-08-26 by `docs/features/type-definition/README.md`:
|
||||
`typeDefinitionProvider` + `crates/lucisv_server/src/type_def.rs`.
|
||||
`vlog_semantic` was *not* changed — a binding still carries no type,
|
||||
but the type name it was declared with is already a `Reference`, so
|
||||
the answer is `nav::definition` of that name's own offset, found from
|
||||
the parse tree. Covers typedefs (alias/enum/struct), interfaces,
|
||||
classes, module instances, `pkg::t`, `import pkg::*`, header
|
||||
parameters and task arguments; one hop per keypress on an alias
|
||||
chain; built-ins answer an empty list. Two requests recorded there:
|
||||
`vlog_semantic` should report an unqualified lexical miss as an
|
||||
external candidate (stood in for by a fenced index lookup), and
|
||||
`vlog_parser` cannot parse an ANSI header whose first port has no
|
||||
direction. Both landed: the first on 2026-08-26 by
|
||||
`docs/features/overlay-promotion/README.md`, the second the same day by
|
||||
`docs/features/ansi-first-port/README.md`.
|
||||
- [x] **Linked editing range** — edit `module m` and its
|
||||
`endmodule : m` label together (`end : label`, `endfunction : name`,
|
||||
etc.). A genuinely good fit for SV's closing labels.
|
||||
→ delivered 2026-08-26 by `docs/features/linked-editing/README.md`:
|
||||
`linkedEditingRangeProvider` + `crates/lucisv_server/src/linked.rs`.
|
||||
No engine change — the AST already records both name spans on one
|
||||
node (`name_span` + `end_label_span`), so the pair is a lookup and
|
||||
never a text match, which is what makes `begin : x begin : x ...
|
||||
end : x end : x` answer syntactically. Covers module/macromodule/
|
||||
interface, package, class, function, task, clocking, named
|
||||
`begin`/`fork`, generate blocks and the prefix-labelled `b : begin
|
||||
... end : b`. Two deliberate `null`s: an absent closing label (there
|
||||
is nothing to co-edit and this never offers to create one) and a
|
||||
mismatched one (the spec requires identical text, and linking would
|
||||
silently rewrite broken code). Escaped identifiers are excluded and
|
||||
the SV `wordPattern` is sent. `program ... endprogram : p` and the
|
||||
verbatim blocks (`property`/`sequence`/`covergroup`) are the only
|
||||
labelled constructs left out, because `vlog_parser` keeps no name
|
||||
span for them — recorded in that README's Handshakes.
|
||||
- [x] **Code lens** — "N instantiations" above each module header from
|
||||
the hierarchy index; `codeLens/resolve` unnecessary (counts are
|
||||
cheap), `workspace/codeLens/refresh` on reindex.
|
||||
→ delivered 2026-08-26 by `docs/features/code-lens/README.md`:
|
||||
`codeLensProvider` (`resolveProvider: false`) +
|
||||
`crates/lucisv_server/src/lens.rs`. One lens per module *and*
|
||||
interface declaration, on the declaration's own name span, reading
|
||||
"no instantiations" / "1 instantiation" / "N instantiations". The
|
||||
count is not a second census: `hierarchy::incoming` was split into
|
||||
`hierarchy::callers_of_each`, a batched form of the same walk, so the
|
||||
lens counts exactly what the call hierarchy would list — asserted by
|
||||
an equality test, not by restating the arithmetic. The batch is the
|
||||
primitive because `Workspace::sources()` re-reads the file set, so a
|
||||
three-module file is one walk (133 ms over the corpus) rather than
|
||||
three (93 ms each). Clicking runs `lucisv.showInstantiations`, which
|
||||
answers every site as a `Location` and pushes a `window/showDocument`
|
||||
for the first when the client advertised it; a module with no
|
||||
instantiations gets a display-only lens instead of a click that leads
|
||||
nowhere. `workspace/codeLens/refresh` goes out from `reindex()` after
|
||||
the progress bar comes down, gated on
|
||||
`workspace.codeLens.refreshSupport`. One request recorded there: an
|
||||
instantiation-edge table in `WorkspaceIndex` would make both this and
|
||||
`callHierarchy/incomingCalls` a lookup instead of a workspace walk —
|
||||
**delivered 2026-08-27, `docs/features/incremental-index/README.md`**:
|
||||
`instantiations_of` is the table, the walk is gone, and a whole file's
|
||||
lenses went 92 ms → 0.26 ms over the corpus.
|
||||
- [x] **On-type formatting** — conspicuous absence for a
|
||||
formatter-first server; candidate trigger: newline (indent the new
|
||||
line per block nesting), `;` (reformat the finished statement).
|
||||
→ delivered 2026-08-26 by `docs/features/on-type-formatting/README.md`:
|
||||
`documentOnTypeFormattingProvider` (`"\n"` + `[";"]`) +
|
||||
`crates/lucisv_server/src/on_type.rs`. Both candidate triggers, and
|
||||
only those two — not `}`, since SV closes its blocks with the word
|
||||
`end`. `;` goes through `format::range_formatting` unchanged, over
|
||||
the `;`'s own line, so that half is `textDocument/rangeFormatting`
|
||||
with a different trigger and no new formatting logic at all. `\n` is
|
||||
new logic outside the verified engine, so it is fenced two ways: the
|
||||
edit it builds can structurally only replace one line's leading
|
||||
whitespace with spaces (a wrong answer is a wrong indent, never a
|
||||
moved byte), and a corpus-wide agreement test formats every checked-in
|
||||
file with the real engine and forbids the model from disagreeing with
|
||||
the printer on any line of the output — 77 528 answered, 36 647
|
||||
declined, 0 disagreements, with a coverage floor so it cannot pass
|
||||
vacuously. Nine of the ten rules the model needed were found by that
|
||||
test rather than predicted, including that `vlog_formatter` cuddles a
|
||||
`begin` onto its header but not a `fork`. **The path never speaks**: a
|
||||
refusal is `[]` with no popup, and — a correction to the design — a
|
||||
broken `lucisv.toml` is not reported here either, because
|
||||
`warn_about_config`'s dedup is re-armed by the `didChange` every
|
||||
keystroke produces and would give one popup per character. One
|
||||
deviation recorded there: the `;` range is the `;`'s own line rather
|
||||
than its enclosing AST node's span, which is the same answer wherever
|
||||
both are defined and avoids asking for a whole-module reformat when
|
||||
the `;` is the one closing a module header. `pairs.rs` gained three
|
||||
`pub(crate)` accessors so the matcher and the indent model read one
|
||||
keyword table.
|
||||
- [x] **Type hierarchy (3.17)** — arguably the semantically correct
|
||||
home for the module hierarchy (and later interface/class extends
|
||||
chains); keep callHierarchy as the compatibility surface.
|
||||
→ delivered 2026-08-26 by `docs/features/type-hierarchy/README.md`:
|
||||
`typeHierarchyProvider` + `crates/lucisv_server/src/type_hierarchy.rs`,
|
||||
all three requests. **Classes, not modules** — the lead's scope call:
|
||||
an instantiation is a containment edge and `extends` is an inheritance
|
||||
edge, so the module hierarchy stays on callHierarchy exactly as this
|
||||
item's second clause asks, and typeHierarchy serves one node kind
|
||||
well. `supertypes` is not a new lookup: `extends Base` is already a
|
||||
`vlog_semantic` reference and overlay-promotion already made a bare
|
||||
cross-file class name reachable through it, so the answer is
|
||||
`definition_of` asked at the last byte of the extends name span —
|
||||
which is the tail of `pkg::base`, the whole of a bare `base`, and the
|
||||
bare name of a parameterized `base #(8)`. A base the workspace does
|
||||
not index (every UVM chain top) yields no item rather than a guess.
|
||||
`subtypes` is `hierarchy::callers_of_each`'s census in another key —
|
||||
~~one `sources()` pass, substring prefilter, deterministic sort — at
|
||||
55 ms over the 860-file corpus, 53 ms of it file I/O; the
|
||||
inheritance-edge table that would make it a lookup is filed beside the
|
||||
instantiation-edge table §9c's code-lens item already recorded.~~
|
||||
**Both tables shipped 2026-08-27** (`docs/features/incremental-index/README.md`):
|
||||
`subclasses_of` makes `subtypes` a lookup, 55 ms → 0.71 ms. Two
|
||||
gaps recorded there: `lsp-types` 0.97 has no `typeHierarchyProvider`
|
||||
field, so the capability is inserted into the serialized `initialize`
|
||||
result by hand, and `vlog_parser` rejects `interface class`, so
|
||||
`implements` can never resolve and no item can carry
|
||||
`SymbolKind::Interface`.
|
||||
- [x] **File operations** — `workspace/willRenameFiles`: renaming a
|
||||
`.sv/.svh` rewrites `` `include`` lines that reference it (the
|
||||
include graph exists); `didRename/didDelete` as cheaper index nudges
|
||||
than the watcher round-trip.
|
||||
→ delivered 2026-08-27 by `docs/features/file-operations/README.md`:
|
||||
`workspace.fileOperations` + `crates/lucisv_server/src/file_ops.rs`.
|
||||
An include is rewritten only when the graph says it **resolves** to
|
||||
the renamed file — never on a filename match, so two `defs.svh` in
|
||||
one workspace stay two files. The new spelling preserves the form
|
||||
where the new location allows it (bare stays bare when a rung reaches
|
||||
it, angled resolves through `+incdir+`s only, absolute stays
|
||||
absolute), shortest resolving suffix first, with a `../`-relative
|
||||
spelling as the last resort — which is also what answers a renamed
|
||||
include *directory*, since lucisv does not edit filelists. An include
|
||||
no spelling can reach is left exactly as written and named in a
|
||||
`window/showMessage` warning ("log all, show the first", the
|
||||
filelist rule): the server never invents a path that would not
|
||||
resolve. **Folders are handled**, not declined — LSP sends only the
|
||||
folder's URI and a folder is a path prefix, which is the same
|
||||
operation a file rename already was. The rule shipped with a mirror
|
||||
half the brief did not ask for: an include written *in* a file that
|
||||
moves breaks the same way and is re-spelled too. Every edit covers
|
||||
the path token alone (never the backtick, the delimiters or a
|
||||
trailing comment) and is verified three ways before it is emitted —
|
||||
re-scanned, re-lexed, and re-resolved against the filesystem the
|
||||
rename will leave behind. `didRename`/`didDelete` reindex through
|
||||
the same scope predicate the watcher uses, not deduplicated against
|
||||
it (a double rebuild is a re-read, never a different answer). One
|
||||
sweep is 54 ms over the 860-file corpus. `verify.rs` untouched.
|
||||
`includes.rs` gained `resolve_as_if` (so there is still exactly one
|
||||
copy of the EDA search order) and `normalize` became public; the
|
||||
standing request to extract one `lucisv_core::path::normalize` for
|
||||
the three private copies is still open.
|
||||
- [x] **`workspace/didChangeWorkspaceFolders`** — roots are read once
|
||||
at initialize; adding/removing a folder mid-session is ignored.
|
||||
→ delivered 2026-08-27 by `docs/features/folders-and-config/README.md`:
|
||||
`workspace.workspaceFolders { supported, changeNotifications }` +
|
||||
`Workspace::change_roots`. One rescan per *notification* — the event
|
||||
carries both lists, and the progress bar, the code-lens refresh and the
|
||||
diagnostics generation all ride inside the existing `reindex()`. An
|
||||
event that leaves the root set where it was costs nothing: a folder
|
||||
already held, one never held, an empty event, params that do not parse,
|
||||
a non-`file:` folder. A removed folder's files leave the index while
|
||||
its **open buffers stay open and keep being diagnosed** — no code was
|
||||
needed for that, since `collect_sources` appends every open document
|
||||
after the scope ladder has spoken — and removing the *last* folder
|
||||
simply becomes rung 3 of that ladder, the rootless case. The watcher
|
||||
determination is recorded there: the source glob is a base-less string
|
||||
pattern and so is workspace-wide (no re-registration), while the
|
||||
filelist watcher is an absolute path anchored at the first root and is
|
||||
re-registered when a folder change moves it. `state.rs` gained exactly
|
||||
one 8-line method.
|
||||
- [x] **`workspace/configuration` (server-pull)** — we rely solely on
|
||||
push `didChangeConfiguration`; clients are moving to the pull model.
|
||||
→ delivered 2026-08-27 by `docs/features/folders-and-config/README.md`:
|
||||
one `workspace/configuration` for the `lucisv` section at startup and
|
||||
again on every *empty* `didChangeConfiguration` (the 3.17 client's
|
||||
"something changed, ask me"), gated on `workspace.configuration`. A
|
||||
push with a payload still applies directly, so the legacy path is
|
||||
untouched; a client without the capability keeps exactly today's
|
||||
behaviour, empty-payload semantics included. **One parser** — the
|
||||
answer's entry 0 is wrapped back into the push shape and read by the
|
||||
same `settings::from_payload` — and **one applier**, so `exclude`/
|
||||
`filelist` cost the same rescan and the same watcher re-registration
|
||||
whichever door they came in. An error, a `null`, an empty array or junk
|
||||
all resolve to the defaults and none of them says anything to the user.
|
||||
The outstanding-request tracking was refactored from `applying:
|
||||
HashMap<RequestId, String>` to `pending: HashMap<RequestId, Pending>`,
|
||||
one map and one `match`, with the three-way interleave
|
||||
(applyEdit + progress create + configuration) under test. Known and
|
||||
stated, not fixed: a pulled setting can land after the first index
|
||||
build, exactly as a pushed one always could.
|
||||
- [x] **3.18 additions:** `textDocument/rangesFormatting` (multi-range,
|
||||
feeds format-modified-lines), snippet edits in `WorkspaceEdit`
|
||||
(would improve `addPort` cursor placement), and
|
||||
`workspace/textDocumentContent` (could serve a read-only "expanded
|
||||
macro" document).
|
||||
→ 2026-08-27 by `docs/features/lsp-318-extras/README.md`: **one
|
||||
shipped, two parked with evidence.** *Shipped* —
|
||||
`textDocument/rangesFormatting`, served as the `n`-range case of
|
||||
`rangeFormatting`: the ranges become one sorted, merged `LineRanges`
|
||||
(the constructor `--lines 3-9,40` already used, so unsorted,
|
||||
overlapping, adjacent and repeated ranges all normalize in the one
|
||||
place) and one `format_range` call, which keeps the all-or-nothing
|
||||
contract over the *union* rather than making it a per-range promise.
|
||||
`range_formatting` is now defined as the one-element call of it, so
|
||||
the reply shape, the refusal and the config warning are the same
|
||||
values and cannot drift; an empty `ranges` array is an ask for
|
||||
nothing, not an error. The capability is advertised by widening
|
||||
`documentRangeFormattingProvider` from `true` to
|
||||
`{ "rangesSupport": true }` — the spec's own
|
||||
`boolean | DocumentRangeFormattingOptions` union — **gated on the
|
||||
client having sent `textDocument.rangeFormatting.rangesSupport`**, so
|
||||
every client that shipped before this round sees the identical byte
|
||||
and only a 3.18 client sees the object; the handler is registered
|
||||
unconditionally. `lsp-types` 0.97 spells neither half, so the
|
||||
capability goes out through the `initialize_value()` JSON insertion
|
||||
(the type-hierarchy precedent) and the client flag is read from the
|
||||
**raw** initialize params before the typed decode drops it.
|
||||
*Parked* — **snippet `WorkspaceEdit` edits**: `lsp-types` 0.97 has no
|
||||
`SnippetTextEdit`, `WorkspaceEditClientCapabilities` has no
|
||||
`snippetEditSupport`, and the pinned `vscode-languageclient@9.0.1`
|
||||
has neither string anywhere in it, so a server sending one would be
|
||||
writing a literal `${1:name}` into the user's buffer. *Parked* —
|
||||
**`workspace/textDocumentContent`**: absent from `lsp-types` 0.97 and
|
||||
from the pinned client, and serving a custom URI scheme in VS Code
|
||||
needs a content provider the deliberately thin `extension.js` does
|
||||
not register; the expanded-macro view it would serve is also
|
||||
hover-sized today, not document-sized. Both have an exact re-check
|
||||
trigger recorded (one `node_modules` grep each). **This completes
|
||||
§9c.**
|
||||
|
||||
### 9d. Deliberately skipped (no Verilog use case)
|
||||
|
||||
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.
|
||||
+37
-11
@@ -32,12 +32,7 @@ use lucisv_core::config::Discovery;
|
||||
use lucisv_core::filelist;
|
||||
use lucisv_core::walk::{collect_files, EXTENSIONS};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
|
||||
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
|
||||
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
|
||||
/// input that trips the parser's nesting limit; rayon's own default is
|
||||
/// 2 MiB, which would put that crash back.
|
||||
const WORKER_STACK: usize = 8 * 1024 * 1024;
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let opts = match args::parse() {
|
||||
@@ -50,10 +45,40 @@ fn main() -> ExitCode {
|
||||
// Once, before any worker thread exists, so nothing ever races on it.
|
||||
install_panic_hook();
|
||||
|
||||
// Nothing parses on the main thread, because its stack is not ours to
|
||||
// state: 8 MiB on a stock macOS or Linux, whatever `ulimit -s` says in a
|
||||
// container, 1 MiB on Windows. The parser's nesting limit only turns
|
||||
// over-deep input into an error on a stack of at least
|
||||
// `PARSE_STACK_SIZE` — below that the overflow, which aborts the
|
||||
// process, comes first. A thread we spawn is the one stack whose size is
|
||||
// ours to guarantee. The pool's workers cover the file-at-a-time paths
|
||||
// (`build_pool`), but not the ones that never reach it: `-` reads and
|
||||
// formats a buffer right here, and so does `lucisv check -`.
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("lucisv".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || run(&opts));
|
||||
let handle = match spawned {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
eprintln!("error: could not start the worker thread: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match handle.join() {
|
||||
Ok(code) => code,
|
||||
// An uncontained panic, already printed by the hook above. 101 is
|
||||
// what the same panic on the main thread would have exited with.
|
||||
Err(_) => ExitCode::from(101),
|
||||
}
|
||||
}
|
||||
|
||||
/// The run itself, on the stack `main` sized for it.
|
||||
fn run(opts: &Options) -> ExitCode {
|
||||
match opts.command {
|
||||
Command::Format if opts.is_stdin() => run_stdin(&opts),
|
||||
Command::Format => run_files(&opts),
|
||||
Command::Check => run_check(&opts),
|
||||
Command::Format if opts.is_stdin() => run_stdin(opts),
|
||||
Command::Format => run_files(opts),
|
||||
Command::Check => run_check(opts),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,11 +297,12 @@ fn entry_for(content: u64, config: &Config) -> Entry {
|
||||
}
|
||||
|
||||
/// Builds rayon's global pool. Worker stacks are sized for the parser's
|
||||
/// recursion limit (see `WORKER_STACK`); `--threads 0` lets rayon pick.
|
||||
/// recursion limit (`PARSE_STACK_SIZE` — rayon's own default is 2 MiB, which
|
||||
/// would put the overflow back); `--threads 0` lets rayon pick the count.
|
||||
fn build_pool(opts: &Options) -> Result<(), String> {
|
||||
rayon::ThreadPoolBuilder::new()
|
||||
.num_threads(opts.thread_count())
|
||||
.stack_size(WORKER_STACK)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.build_global()
|
||||
.map_err(|e| format!("could not start the worker pool: {e}"))
|
||||
}
|
||||
|
||||
@@ -407,7 +407,8 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
|
||||
// costs two levels), so it parses — and needs several MiB of stack to
|
||||
// do it in a debug build: without the depth limit this family died at
|
||||
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
|
||||
// stack. This test crashes the process if the pool's 8 MiB is dropped.
|
||||
// stack. This test crashes the process if the pool's `PARSE_STACK_SIZE`
|
||||
// is dropped.
|
||||
let deep = format!(
|
||||
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"if (clk) begin\n".repeat(28),
|
||||
@@ -425,6 +426,34 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
|
||||
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash() {
|
||||
// The stdin path never touches the worker pool: it formats on the thread
|
||||
// `main` spawned, which is the only stack whose size lucisv gets to
|
||||
// state. 500 nested blocks are far past the parser's limit, so the run
|
||||
// must end with an ordinary parse error — and not with a SIGABRT, which
|
||||
// is what an unstated stack gives instead.
|
||||
let deep = format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"begin\n".repeat(500),
|
||||
"end\n".repeat(500)
|
||||
);
|
||||
let out = run_with_stdin(&["-"], &deep);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("nesting too deep"), "{}", stderr(&out));
|
||||
assert!(stdout(&out).is_empty(), "a rejected buffer prints nothing: {}", stdout(&out));
|
||||
|
||||
// And the deepest *legal* buffer formats on that same stack.
|
||||
let legal = format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"begin\n".repeat(58),
|
||||
"end\n".repeat(58)
|
||||
);
|
||||
let out = run_with_stdin(&["-"], &legal);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stdout(&out).contains("endmodule"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
|
||||
let dir = TempDir::new("configpar");
|
||||
|
||||
@@ -20,11 +20,11 @@
|
||||
//! See `docs/features/completion-core/README.md`.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
|
||||
@@ -53,8 +53,26 @@ pub struct Macro {
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Candidates {
|
||||
units: Vec<Candidate>,
|
||||
/// Every module name the index declares, in the order
|
||||
/// `WorkspaceIndex::workspace_symbols` puts them in — which is **`str`
|
||||
/// order, exactly**, so [`Candidates::has_module`] may binary-search it.
|
||||
///
|
||||
/// Its own table beside [`Candidates::units`] because tier 0 of a
|
||||
/// completion asks a different question of it: a *substring* match, not a
|
||||
/// prefix one, so it cannot ride the binary search the others do. What it
|
||||
/// buys is that the whole symbol table is no longer built and sorted per
|
||||
/// keystroke — see `docs/features/completion-core/README.md`, 2026-08-28.
|
||||
modules: Vec<String>,
|
||||
macros: Vec<Macro>,
|
||||
words: Vec<String>,
|
||||
/// How many in-scope files contain each word. What makes it possible to
|
||||
/// take one file's words back without re-lexing every other file
|
||||
/// ([`Candidates::update_file`]): a word is dropped from `words` exactly
|
||||
/// when the last file holding it stops holding it.
|
||||
word_files: HashMap<String, usize>,
|
||||
/// Each file's distinct words, so the count above can be decremented for
|
||||
/// the version of the file being replaced.
|
||||
per_file: HashMap<PathBuf, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Candidates {
|
||||
@@ -63,8 +81,169 @@ impl Candidates {
|
||||
/// `sources` is the list `Workspace::collect_sources` already produced for
|
||||
/// the index, so the files are read once and the only extra work is one
|
||||
/// lex per file — see the measurements in the feature README.
|
||||
pub fn build(index: &WorkspaceIndex, sources: &[(PathBuf, String)]) -> Candidates {
|
||||
Candidates { units: units_of(index), macros: macros_of(index), words: words_of(sources) }
|
||||
///
|
||||
/// `known` holds the words of the files whose token stream the caller
|
||||
/// already has — an open buffer's, lexed when the buffer was analyzed. A
|
||||
/// file listed there is not lexed again; a file absent from it is lexed
|
||||
/// here, exactly as every file used to be. The two produce the same words
|
||||
/// because they are the same function over the same tokens
|
||||
/// ([`words_of_tokens`]).
|
||||
pub fn build(
|
||||
index: &WorkspaceIndex,
|
||||
sources: &[(PathBuf, String)],
|
||||
mut known: HashMap<PathBuf, Vec<String>>,
|
||||
) -> Candidates {
|
||||
let (units, modules) = index_tables(index);
|
||||
let mut out =
|
||||
Candidates { units, modules, macros: macros_of(index), ..Candidates::default() };
|
||||
for (path, text) in sources {
|
||||
let words = match known.remove(path) {
|
||||
Some(words) => words,
|
||||
None => words_in(text),
|
||||
};
|
||||
for word in &words {
|
||||
*out.word_files.entry(word.clone()).or_default() += 1;
|
||||
}
|
||||
if !words.is_empty() {
|
||||
out.per_file.insert(path.clone(), words);
|
||||
}
|
||||
}
|
||||
out.words = out.word_files.keys().cloned().collect();
|
||||
sort_by_name(&mut out.words, |w| w.as_str());
|
||||
out
|
||||
}
|
||||
|
||||
/// Replace one file's contribution — the incremental form of
|
||||
/// [`Candidates::build`], for a rescan that only one file triggered
|
||||
/// (`docs/features/incremental-index/README.md`).
|
||||
///
|
||||
/// The two index-derived tables are re-derived from the index, which has
|
||||
/// already been updated and is the only thing they read. The word table is
|
||||
/// patched: this file's old words are given back and its new ones taken,
|
||||
/// so nothing else is re-lexed. The result is what a whole
|
||||
/// [`Candidates::build`] over the same files would have produced.
|
||||
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
|
||||
self.update_words(index, path, words_in(text));
|
||||
}
|
||||
|
||||
/// [`Candidates::update_file`] for a file whose words the caller already
|
||||
/// has — an open buffer's, read off the tokens it was analyzed from.
|
||||
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
|
||||
(self.units, self.modules) = index_tables(index);
|
||||
self.macros = macros_of(index);
|
||||
self.set_words(path, words);
|
||||
}
|
||||
|
||||
/// [`Candidates::update_words`] for a batch of files — the form a scan
|
||||
/// publishing what it has indexed so far uses.
|
||||
///
|
||||
/// One re-derivation of the two index tables for the whole batch rather
|
||||
/// than one per file: they are read off the index and nothing else, so
|
||||
/// doing it once at the end of the batch is doing it once with the same
|
||||
/// answer. The word table is patched per file exactly as it is there.
|
||||
/// **One re-sort of the word table for the whole batch, too**, which is
|
||||
/// what makes a scope widen over a big folder affordable: the table is a
|
||||
/// sorted `Vec`, and inserting each of a widen's tens of thousands of new
|
||||
/// words into it one at a time moves the tail of the table once per word.
|
||||
/// Counted per batch and merged once, the same batch is one pass
|
||||
/// (`docs/features/index-scope/README.md`, 2026-08-29 — 403 ms → 43 ms for
|
||||
/// the 1 807 files of opentitan's `hw/ip`).
|
||||
pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec<String>)>) {
|
||||
let mut touched: HashMap<String, bool> = HashMap::new();
|
||||
for (path, words) in batch {
|
||||
self.count_words(&path, words, &mut touched);
|
||||
}
|
||||
self.merge_words(touched);
|
||||
(self.units, self.modules) = index_tables(index);
|
||||
self.macros = macros_of(index);
|
||||
}
|
||||
|
||||
/// Drop one file's contribution entirely.
|
||||
pub fn remove_file(&mut self, index: &WorkspaceIndex, path: &Path) {
|
||||
(self.units, self.modules) = index_tables(index);
|
||||
self.macros = macros_of(index);
|
||||
self.set_words(path, Vec::new());
|
||||
}
|
||||
|
||||
/// Make `words` this file's words, adjusting the workspace-wide table.
|
||||
fn set_words(&mut self, path: &Path, words: Vec<String>) {
|
||||
let mut touched = HashMap::new();
|
||||
self.count_words(path, words, &mut touched);
|
||||
self.merge_words(touched);
|
||||
}
|
||||
|
||||
/// Make `words` this file's words in the per-file tables and the counts,
|
||||
/// leaving the sorted table to [`Candidates::merge_words`].
|
||||
///
|
||||
/// `touched` collects every word whose count this call moved, against
|
||||
/// **whether the workspace held it before the batch began** — recorded at
|
||||
/// the first touch, so a word a batch takes and gives back is correctly
|
||||
/// seen as never having moved.
|
||||
fn count_words(
|
||||
&mut self,
|
||||
path: &Path,
|
||||
words: Vec<String>,
|
||||
touched: &mut HashMap<String, bool>,
|
||||
) {
|
||||
for word in self.per_file.remove(path).unwrap_or_default() {
|
||||
let Some(count) = self.word_files.get_mut(&word) else { continue };
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
self.word_files.remove(&word);
|
||||
touched.entry(word).or_insert(true);
|
||||
}
|
||||
}
|
||||
for word in &words {
|
||||
let held = self.word_files.contains_key(word);
|
||||
let count = self.word_files.entry(word.clone()).or_default();
|
||||
*count += 1;
|
||||
if !held {
|
||||
touched.entry(word.clone()).or_insert(false);
|
||||
}
|
||||
}
|
||||
if !words.is_empty() {
|
||||
self.per_file.insert(path.to_path_buf(), words);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the sorted word table back in step with the counts, in one pass.
|
||||
///
|
||||
/// A word in `touched` that the counts still hold and the table does not is
|
||||
/// an insertion; one the counts have dropped and the table still holds is a
|
||||
/// removal; a word that ends where it started is neither. What comes out is
|
||||
/// the table [`Candidates::build`] would have sorted from the same counts,
|
||||
/// because [`word_cmp`] is a total order on distinct words — so merging a
|
||||
/// sorted run into a sorted table is that sort's own answer.
|
||||
fn merge_words(&mut self, touched: HashMap<String, bool>) {
|
||||
let mut added: Vec<String> = Vec::new();
|
||||
let mut dropped: HashSet<String> = HashSet::new();
|
||||
for (word, was_held) in touched {
|
||||
match (was_held, self.word_files.contains_key(&word)) {
|
||||
(false, true) => added.push(word),
|
||||
(true, false) => {
|
||||
dropped.insert(word);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if added.is_empty() && dropped.is_empty() {
|
||||
return;
|
||||
}
|
||||
sort_by_name(&mut added, |word| word.as_str());
|
||||
let held = std::mem::take(&mut self.words);
|
||||
let mut out = Vec::with_capacity(held.len() + added.len());
|
||||
let mut added = added.into_iter().peekable();
|
||||
for word in held {
|
||||
if dropped.contains(&word) {
|
||||
continue;
|
||||
}
|
||||
while let Some(new) = added.next_if(|new| word_cmp(new, &word) == Ordering::Less) {
|
||||
out.push(new);
|
||||
}
|
||||
out.push(word);
|
||||
}
|
||||
out.extend(added);
|
||||
self.words = out;
|
||||
}
|
||||
|
||||
/// Index names starting with `prefix`, case-insensitively.
|
||||
@@ -72,6 +251,35 @@ impl Candidates {
|
||||
matching(&self.units, prefix, |c| &c.name)
|
||||
}
|
||||
|
||||
/// Module names *containing* `query`, case-insensitively — what
|
||||
/// `vlog_refactor::module_names` answers, off a table instead of off the
|
||||
/// index. A substring match, so it is a scan; the table it scans holds one
|
||||
/// entry per module rather than one per declaration in the workspace.
|
||||
pub fn modules(&self, query: &str) -> Vec<&str> {
|
||||
self.modules
|
||||
.iter()
|
||||
.filter(|name| contains_ignore_case(name, query))
|
||||
.map(String::as_str)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the workspace declares a module spelled **exactly** `name`.
|
||||
///
|
||||
/// A binary search — `O(log n)` over the module table, no allocation and
|
||||
/// no file touched — because it is asked on every keystroke by the ghost
|
||||
/// instantiation (`docs/features/inline-instantiation/README.md`) and the
|
||||
/// answer is "no" almost every time. [`Candidates::modules`]'s substring
|
||||
/// scan answers a different question and costs `O(n)`.
|
||||
///
|
||||
/// Case-**sensitive**, unlike every other lookup here: this one decides
|
||||
/// whether to plan a real instantiation of a real module, and `Fifo` is
|
||||
/// not `fifo` to any Verilog tool. The table is in `str` order because
|
||||
/// `WorkspaceIndex::workspace_symbols` sorts by name with `str`'s own
|
||||
/// `Ord` — see [`index_tables`], which only dedups it.
|
||||
pub fn has_module(&self, name: &str) -> bool {
|
||||
self.modules.binary_search_by(|held| held.as_str().cmp(name)).is_ok()
|
||||
}
|
||||
|
||||
/// `` `define`` names starting with `prefix`, case-insensitively.
|
||||
pub fn macros(&self, prefix: &str) -> &[Macro] {
|
||||
matching(&self.macros, prefix, |m| &m.name)
|
||||
@@ -83,12 +291,28 @@ impl Candidates {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name the index carries, as a lookup table.
|
||||
fn units_of(index: &WorkspaceIndex) -> Vec<Candidate> {
|
||||
// The empty query means "everything"; it is paid once per index build
|
||||
// rather than once per keystroke, which is the whole point of this table.
|
||||
let mut out: Vec<Candidate> = index
|
||||
.workspace_symbols("")
|
||||
/// Every name the index carries, and the module names among them, from one
|
||||
/// pass over its symbol table.
|
||||
///
|
||||
/// One pass because that pass is the expensive part: `workspace_symbols("")`
|
||||
/// builds and sorts a record per declaration in the workspace, and the two
|
||||
/// tables want the same records. It is paid once per index build rather than
|
||||
/// once per keystroke, which is the whole point of both.
|
||||
fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
|
||||
let symbols = index.workspace_symbols("");
|
||||
// `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a
|
||||
// case-folded one — so same-named declarations are already adjacent and a
|
||||
// plain `dedup` leaves one entry per module name, in `str` order. That is
|
||||
// exactly what `vlog_refactor::module_names` does to the same list, minus
|
||||
// the per-keystroke rebuild, and the order is what
|
||||
// [`Candidates::has_module`] binary-searches.
|
||||
let mut modules: Vec<String> = symbols
|
||||
.iter()
|
||||
.filter(|symbol| symbol.container.is_none() && symbol.def.kind == SymbolKind::Module)
|
||||
.map(|symbol| symbol.name.to_string())
|
||||
.collect();
|
||||
modules.dedup();
|
||||
let mut out: Vec<Candidate> = symbols
|
||||
.into_iter()
|
||||
.map(|symbol| {
|
||||
let detail = match symbol.container {
|
||||
@@ -106,7 +330,7 @@ fn units_of(index: &WorkspaceIndex) -> Vec<Candidate> {
|
||||
sort_by_name(&mut out, |c| c.name.as_str());
|
||||
// A name two files declare is one completion item, not two.
|
||||
out.dedup_by(|a, b| a.name == b.name && a.kind == b.kind);
|
||||
out
|
||||
(out, modules)
|
||||
}
|
||||
|
||||
/// Every `` `define`` the workspace declares. `` `undef`` entries are skipped:
|
||||
@@ -132,27 +356,39 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Every identifier the in-scope files' token streams contain.
|
||||
fn words_of(sources: &[(PathBuf, String)]) -> Vec<String> {
|
||||
// Deduplicated as it is collected, not afterwards: a workspace holds two
|
||||
// orders of magnitude more identifier *tokens* than distinct identifiers
|
||||
// (900k against 17k over this repo's corpus), and copying every one of
|
||||
// them only to sort the copies away costs more than the lexing does.
|
||||
/// Every distinct identifier one file's token stream contains.
|
||||
///
|
||||
/// Deduplicated as it is collected, not afterwards: a workspace holds two
|
||||
/// orders of magnitude more identifier *tokens* than distinct identifiers
|
||||
/// (900k against 17k over this repo's corpus), and copying every one of them
|
||||
/// only to sort the copies away costs more than the lexing does.
|
||||
///
|
||||
/// `pub(crate)` because a scan lexes each file as it reaches it rather than in
|
||||
/// one pass at the end: no part of a scan may be longer than one file, or the
|
||||
/// message queue goes unanswered for the length of it
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(crate) fn words_in(text: &str) -> Vec<String> {
|
||||
// A file that does not lex contributes nothing rather than being guessed
|
||||
// at with a regex — the same all-or-nothing rule the lexer gives every
|
||||
// other consumer.
|
||||
let Ok(tokens) = tokenize(text) else { return Vec::new() };
|
||||
words_of_tokens(&tokens)
|
||||
}
|
||||
|
||||
/// [`words_in`] over a token stream the caller already lexed.
|
||||
///
|
||||
/// The whole of `words_in` after the lex, so a caller holding an open buffer's
|
||||
/// tokens gets the same words without lexing the buffer again. A buffer that
|
||||
/// did not lex holds no tokens and contributes nothing here either, which is
|
||||
/// the same all-or-nothing rule from the other side.
|
||||
pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec<String> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
for (_, text) in sources {
|
||||
// A file that does not lex contributes nothing rather than being
|
||||
// guessed at with a regex — the same all-or-nothing rule the lexer
|
||||
// gives every other consumer.
|
||||
let Ok(tokens) = tokenize(text) else { continue };
|
||||
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
|
||||
if !seen.contains(token.text.as_str()) {
|
||||
seen.insert(token.text.clone());
|
||||
}
|
||||
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
|
||||
if !seen.contains(token.text.as_str()) {
|
||||
seen.insert(token.text.clone());
|
||||
}
|
||||
}
|
||||
let mut out: Vec<String> = seen.into_iter().collect();
|
||||
sort_by_name(&mut out, |w| w.as_str());
|
||||
out
|
||||
seen.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Whether a token is a word worth offering.
|
||||
@@ -174,10 +410,13 @@ fn is_word(kind: TokenKind, text: &str) -> bool {
|
||||
/// Sort by name, case-insensitively first so [`matching`]'s binary search is
|
||||
/// valid, then exactly so equal names sit next to each other for `dedup`.
|
||||
fn sort_by_name<T>(items: &mut [T], name: impl for<'b> Fn(&'b T) -> &'b str) {
|
||||
items.sort_by(|a, b| {
|
||||
let (a, b) = (name(a), name(b));
|
||||
lower_cmp(a, b).then_with(|| a.cmp(b))
|
||||
});
|
||||
items.sort_by(|a, b| word_cmp(name(a), name(b)));
|
||||
}
|
||||
|
||||
/// The order [`sort_by_name`] puts names in, named so an incremental insert
|
||||
/// can find the one place a whole sort would have put a word.
|
||||
fn word_cmp(a: &str, b: &str) -> Ordering {
|
||||
lower_cmp(a, b).then_with(|| a.cmp(b))
|
||||
}
|
||||
|
||||
/// The entries whose name starts with `prefix`, case-insensitively.
|
||||
@@ -201,6 +440,17 @@ fn lower_cmp(a: &str, b: &str) -> Ordering {
|
||||
a.bytes().map(|c| c.to_ascii_lowercase()).cmp(b.bytes().map(|c| c.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
/// Whether `word` holds `query` anywhere in it, ignoring ASCII case — the
|
||||
/// match `WorkspaceIndex::workspace_symbols` makes, which
|
||||
/// [`Candidates::modules`] has to make the same way to answer the same set.
|
||||
fn contains_ignore_case(word: &str, query: &str) -> bool {
|
||||
if query.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let query = query.as_bytes();
|
||||
word.as_bytes().windows(query.len()).any(|window| window.eq_ignore_ascii_case(query))
|
||||
}
|
||||
|
||||
/// Whether `word` starts with `prefix`, ignoring ASCII case.
|
||||
pub fn starts_with_ignore_case(word: &str, prefix: &str) -> bool {
|
||||
word.len() >= prefix.len()
|
||||
@@ -218,7 +468,7 @@ mod tests {
|
||||
fn built(files: &[(&str, &str)]) -> Candidates {
|
||||
let sources = sources(files);
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
Candidates::build(&index, &sources)
|
||||
Candidates::build(&index, &sources, HashMap::new())
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -277,6 +527,105 @@ mod tests {
|
||||
assert_eq!(candidates.words("shared").len(), 1);
|
||||
}
|
||||
|
||||
/// A workspace whose module names cover every ordering trap the binary
|
||||
/// search could fall into: mixed case, a name that is a prefix of another,
|
||||
/// underscores and digits either side of the letters.
|
||||
fn modular() -> Candidates {
|
||||
let files: Vec<(&str, &str)> = vec![
|
||||
("/rtl/aes.sv", "module aes ();\nendmodule\n"),
|
||||
("/rtl/aes_core.sv", "module aes_core ();\nendmodule\n"),
|
||||
("/rtl/AES.sv", "module AES ();\nendmodule\n"),
|
||||
("/rtl/fifo2.sv", "module fifo2 ();\nendmodule\n"),
|
||||
("/rtl/fifo.sv", "module fifo ();\n logic aes_core;\nendmodule\n"),
|
||||
("/rtl/p.sv", "package pkg;\n localparam int W = 1;\nendpackage\n"),
|
||||
];
|
||||
built(&files)
|
||||
}
|
||||
|
||||
/// The table [`Candidates::has_module`] searches must be in the order it
|
||||
/// searches for — `str`'s own, which is what `workspace_symbols` sorts by
|
||||
/// and what `index_tables` does not disturb. Everything else here rests on
|
||||
/// this, so it is asserted rather than assumed.
|
||||
#[test]
|
||||
fn the_module_table_is_in_str_order_so_the_binary_search_is_valid() {
|
||||
let candidates = modular();
|
||||
let held = candidates.modules("");
|
||||
assert!(held.windows(2).all(|pair| pair[0] < pair[1]), "{held:?}");
|
||||
}
|
||||
|
||||
/// `has_module` is the `O(log n)` form of "is this name in `modules("")`",
|
||||
/// spelled case-sensitively. Checked against the scan it replaces, for
|
||||
/// every name in the workspace and a spread of near misses.
|
||||
#[test]
|
||||
fn has_module_agrees_with_the_module_list_on_membership() {
|
||||
let candidates = modular();
|
||||
let held: Vec<&str> = candidates.modules("");
|
||||
let probes = [
|
||||
"aes",
|
||||
"aes_core",
|
||||
"AES",
|
||||
"fifo",
|
||||
"fifo2",
|
||||
"Aes",
|
||||
"AES_CORE",
|
||||
"aes_",
|
||||
"aes_cor",
|
||||
"aes_cores",
|
||||
"",
|
||||
"pkg",
|
||||
"W",
|
||||
"zzz",
|
||||
"\\aes",
|
||||
];
|
||||
for probe in probes.iter().chain(held.iter()) {
|
||||
assert_eq!(
|
||||
candidates.has_module(probe),
|
||||
held.contains(probe),
|
||||
"has_module({probe:?}) against {held:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The substring list is case-*insensitive* and the exact probe is not —
|
||||
/// the one place the two deliberately disagree, and the reason the ghost
|
||||
/// instantiation never fires on `AES_CORE` when the module is `aes_core`.
|
||||
#[test]
|
||||
fn the_exact_probe_is_case_sensitive_where_the_substring_list_is_not() {
|
||||
let candidates = modular();
|
||||
assert!(candidates.modules("aes_core").contains(&"aes_core"));
|
||||
assert!(candidates.modules("AES_CORE").contains(&"aes_core"), "a substring match folds");
|
||||
assert!(candidates.has_module("aes_core"));
|
||||
assert!(!candidates.has_module("AES_CORE"), "an exact match does not fold");
|
||||
// …but a module really spelled in capitals is found by its own
|
||||
// spelling, which is the other half of the same rule.
|
||||
assert!(candidates.has_module("AES"));
|
||||
assert!(candidates.has_module("aes"));
|
||||
}
|
||||
|
||||
/// Only modules. A package, a parameter and an unknown name are all "no",
|
||||
/// however loudly the index knows the name otherwise.
|
||||
#[test]
|
||||
fn has_module_is_about_modules_and_nothing_else() {
|
||||
let candidates = modular();
|
||||
assert!(!candidates.has_module("pkg"), "a package is not instantiable");
|
||||
assert!(!candidates.has_module("W"));
|
||||
assert!(!candidates.has_module("aes_core_that_is_not_declared"));
|
||||
}
|
||||
|
||||
/// A module declared twice is one entry, so the probe still answers once —
|
||||
/// which file the ghost then reads is a different layer's business
|
||||
/// (`completion::nearest_definition` picks the copy nearest the buffer;
|
||||
/// until round 2 of 2026-08-30 the ghost declined outright instead).
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_one_entry_in_the_table() {
|
||||
let candidates = built(&[
|
||||
("/rtl/a.sv", "module dup ();\nendmodule\n"),
|
||||
("/rtl/b.sv", "module dup ();\nendmodule\n"),
|
||||
]);
|
||||
assert_eq!(candidates.modules(""), ["dup"]);
|
||||
assert!(candidates.has_module("dup"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_names_carry_their_kind_and_where_they_live() {
|
||||
let candidates = built(&[(
|
||||
@@ -324,4 +673,165 @@ mod tests {
|
||||
assert!(names.contains(&"seen"), "{names:?}");
|
||||
assert!(!names.contains(&"never_seen"), "{names:?}");
|
||||
}
|
||||
|
||||
/// The module table exists to answer what `vlog_refactor::module_names`
|
||||
/// answers without the index rebuilding its whole symbol table per
|
||||
/// keystroke, so the two must agree — set *and* order — at every query.
|
||||
/// A substring match, not a prefix one: `module_names` asks the index for
|
||||
/// `contains`, and `prim_aes_sbox` is an answer to `aes`.
|
||||
#[test]
|
||||
fn the_module_table_answers_exactly_what_module_names_answers() {
|
||||
let files = [
|
||||
("/rtl/aes.sv", "module aes;\nendmodule\npackage aes_pkg;\nendpackage\n"),
|
||||
("/rtl/aes_reg_top.sv", "module aes_reg_top;\nendmodule\n"),
|
||||
("/rtl/prim.sv", "module prim_aes_sbox;\nendmodule\nmodule PRIM_UPPER;\nendmodule\n"),
|
||||
("/rtl/other.sv", "interface i;\nendinterface\nclass c;\nendclass\n"),
|
||||
// A module name two files declare — one entry, not two.
|
||||
("/rtl/twin_a.sv", "module twin;\nendmodule\n"),
|
||||
("/rtl/twin_b.sv", "module twin;\nendmodule\n"),
|
||||
];
|
||||
let srcs = sources(&files);
|
||||
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let candidates = Candidates::build(&index, &srcs, HashMap::new());
|
||||
for query in ["", "a", "ae", "aes", "AES", "prim", "PRIM", "_", "twin", "zzz", "aes_reg"] {
|
||||
assert_eq!(
|
||||
candidates.modules(query),
|
||||
vlog_refactor::module_names(&index, query),
|
||||
"query {query:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (incremental-index, 2026-08-27): `word_files`'s exact bookkeeping
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_shared_word_dropped_from_one_file_is_still_offered_by_the_other() {
|
||||
let raw = [
|
||||
("/rtl/a.sv", "module a;\n logic shared;\nendmodule\n"),
|
||||
("/rtl/b.sv", "module b;\n logic shared;\nendmodule\n"),
|
||||
];
|
||||
let srcs = sources(&raw);
|
||||
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
|
||||
assert_eq!(candidates.words("shared").len(), 1, "premise: two files, one word");
|
||||
|
||||
let mut current = index.clone();
|
||||
current.update_file(PathBuf::from("/rtl/a.sv"), "module a;\nendmodule\n");
|
||||
candidates.update_file(¤t, Path::new("/rtl/a.sv"), "module a;\nendmodule\n");
|
||||
assert_eq!(candidates.words("shared").len(), 1, "b.sv still holds it — not given back");
|
||||
|
||||
current.update_file(PathBuf::from("/rtl/b.sv"), "module b;\nendmodule\n");
|
||||
candidates.update_file(¤t, Path::new("/rtl/b.sv"), "module b;\nendmodule\n");
|
||||
assert!(candidates.words("shared").is_empty(), "and now nothing holds it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updating_the_same_file_twice_in_a_row_never_double_counts_or_goes_negative() {
|
||||
// `set_words` decrements the *previous* call's words before counting
|
||||
// the new ones; the attack is a bug that decrements the same word
|
||||
// twice (an underflow — `usize` would panic in debug, wrap in
|
||||
// release) or forgets to re-add a word that survives across the two
|
||||
// calls.
|
||||
let raw = [("/rtl/a.sv", "module a;\n logic w1;\nendmodule\n")];
|
||||
let srcs = sources(&raw);
|
||||
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
|
||||
|
||||
let mut current = index.clone();
|
||||
let text2 = "module a;\n logic w2;\nendmodule\n";
|
||||
current.update_file(PathBuf::from("/rtl/a.sv"), text2);
|
||||
candidates.update_file(¤t, Path::new("/rtl/a.sv"), text2);
|
||||
assert!(candidates.words("w1").is_empty(), "w1 given back");
|
||||
assert_eq!(candidates.words("w2").len(), 1);
|
||||
|
||||
// The same update again, unchanged text.
|
||||
candidates.update_file(¤t, Path::new("/rtl/a.sv"), text2);
|
||||
assert!(candidates.words("w1").is_empty(), "still gone, not somehow negative-then-absent");
|
||||
assert_eq!(candidates.words("w2").len(), 1, "still exactly one, not doubled");
|
||||
|
||||
// `remove_file`, twice in a row.
|
||||
candidates.remove_file(¤t, Path::new("/rtl/a.sv"));
|
||||
assert!(candidates.words("w2").is_empty());
|
||||
candidates.remove_file(¤t, Path::new("/rtl/a.sv"));
|
||||
assert!(candidates.words("w2").is_empty(), "removing an already-removed file is a no-op");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_absorbed_leaves_the_word_table_a_whole_build_would_have_sorted() {
|
||||
// The scope widen's own path, and since 2026-08-29 the batch pays one
|
||||
// merge instead of one insert per word. The claim that buys is exact:
|
||||
// what comes out is the table `build` sorts from the same counts. The
|
||||
// hostile cases are all in this one batch — a word only one of the
|
||||
// batch's files still holds, a word the batch takes from one file and
|
||||
// gives back through another, a word nothing holds afterwards, and
|
||||
// case variants, which `word_cmp` orders case-insensitively first and
|
||||
// exactly second.
|
||||
let held = [
|
||||
(
|
||||
"/rtl/a.sv",
|
||||
"module a;\n logic Shared;\n logic only_a;\n logic gone;\nendmodule\n",
|
||||
),
|
||||
("/rtl/b.sv", "module b;\n logic shared;\n logic Only_B;\nendmodule\n"),
|
||||
];
|
||||
let after = [
|
||||
// `a.sv` rewritten: `gone` leaves the workspace, `only_a` leaves
|
||||
// this file but arrives in `c.sv` in the same batch.
|
||||
("/rtl/a.sv", "module a;\n logic Shared;\n logic zeta;\n logic Alpha;\nendmodule\n"),
|
||||
("/rtl/b.sv", "module b;\n logic shared;\n logic Only_B;\nendmodule\n"),
|
||||
(
|
||||
"/rtl/c.sv",
|
||||
"module c;\n logic shared;\n logic alpha;\n logic only_a;\nendmodule\n",
|
||||
),
|
||||
("/rtl/d.sv", "module d;\n logic ALPHA;\n logic mid;\nendmodule\n"),
|
||||
];
|
||||
|
||||
let held_srcs = sources(&held);
|
||||
let held_index =
|
||||
WorkspaceIndex::build(held_srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut widened = Candidates::build(&held_index, &held_srcs, HashMap::new());
|
||||
|
||||
let srcs = sources(&after);
|
||||
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let batch: Vec<(PathBuf, Vec<String>)> = after
|
||||
.iter()
|
||||
.filter(|(path, _)| *path != "/rtl/b.sv")
|
||||
.map(|(path, text)| (PathBuf::from(*path), words_in(text)))
|
||||
.collect();
|
||||
widened.absorb(&index, batch);
|
||||
|
||||
let rebuilt = Candidates::build(&index, &srcs, HashMap::new());
|
||||
assert_eq!(widened.words(""), rebuilt.words(""), "the whole table, in order");
|
||||
for prefix in ["", "a", "al", "ALPHA", "shared", "only", "only_a", "gone", "z", "zzz"] {
|
||||
assert_eq!(widened.words(prefix), rebuilt.words(prefix), "prefix {prefix:?}");
|
||||
}
|
||||
assert_eq!(widened.words("gone").len(), 0, "the word nothing holds any more");
|
||||
assert_eq!(widened.words("only_a").len(), 1, "taken and given back inside one batch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_extra_empty_and_noop_batches_do_not_disturb_the_table() {
|
||||
let held = [("/rtl/a.sv", "module a;\n logic w1;\n logic w2;\nendmodule\n")];
|
||||
let held_srcs: Vec<(PathBuf, String)> =
|
||||
held.iter().map(|(p, t)| (PathBuf::from(*p), t.to_string())).collect();
|
||||
let index = WorkspaceIndex::build(held_srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let mut c = Candidates::build(&index, &held_srcs, HashMap::new());
|
||||
let before = c.words("").to_vec();
|
||||
|
||||
// Empty batch: nothing to absorb.
|
||||
c.absorb(&index, Vec::new());
|
||||
assert_eq!(c.words(""), before.as_slice(), "empty batch changes nothing");
|
||||
|
||||
// Batch that re-declares exactly the same words for the same file
|
||||
// (the module name "a" included, or dropping it would be a real
|
||||
// change): no net change to the counts, so no add or drop should
|
||||
// survive to the merge.
|
||||
let batch: Vec<(PathBuf, Vec<String>)> = vec![(
|
||||
PathBuf::from("/rtl/a.sv"),
|
||||
vec!["a".to_string(), "w1".to_string(), "w2".to_string()],
|
||||
)];
|
||||
c.absorb(&index, batch);
|
||||
assert_eq!(c.words(""), before.as_slice(), "re-declaring the same words is a no-op");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -24,15 +24,20 @@ 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,
|
||||
/// in amortized O(1) each rather than [`position`](Self::position)'s
|
||||
/// O(offset within its line).
|
||||
pub fn walker(&self) -> PositionWalker<'_> {
|
||||
PositionWalker { positions: self, line: 0, line_start: 0, cursor: 0, units: 0 }
|
||||
}
|
||||
|
||||
/// The byte offset of an LSP position, clamped into the document.
|
||||
@@ -112,6 +117,62 @@ impl<'a> Positions<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A monotonic byte-offset → [`Position`] cursor, for a caller that has a
|
||||
/// whole sequence of offsets to convert and already has them in order.
|
||||
///
|
||||
/// [`Positions::position`] measures a line from its start on every call, which
|
||||
/// is free on ordinary source and quadratic when thousands of tokens sit on
|
||||
/// **one** very long line — the netlist shape the large-file fast path exists
|
||||
/// for, where it cost seconds per keystroke. The walker carries the
|
||||
/// measurement forward instead: one line lookup per call, and each byte of a
|
||||
/// line counted once however many offsets fall on it.
|
||||
///
|
||||
/// **Total, not merely fast.** An offset below the last one is not an error
|
||||
/// and never panics: the walker restarts at that line's start and re-measures,
|
||||
/// which is exactly the work [`Positions::position`] would have done. So every
|
||||
/// answer is that function's answer — by construction, and pinned by
|
||||
/// `the_walker_agrees_with_the_per_call_converter_on_every_shape`.
|
||||
pub struct PositionWalker<'a> {
|
||||
positions: &'a Positions<'a>,
|
||||
/// The 1-based line the cursor sits on. Zero before the first call, which
|
||||
/// is a line number no offset has, so the first call always restarts.
|
||||
line: u32,
|
||||
/// The byte offset that line starts at.
|
||||
line_start: u32,
|
||||
/// How far into the text the cursor has measured, on that line.
|
||||
cursor: u32,
|
||||
/// UTF-16 units of `line_start..cursor`, before the `\r` rule below.
|
||||
units: u32,
|
||||
}
|
||||
|
||||
impl PositionWalker<'_> {
|
||||
/// The LSP position of a byte offset — [`Positions::position`]'s answer,
|
||||
/// reached without re-measuring the line for offsets already passed.
|
||||
pub fn position(&mut self, offset: u32) -> Position {
|
||||
let offset = self.positions.floor_boundary(offset);
|
||||
let (line, _) = self.positions.index.line_col(offset);
|
||||
if line != self.line || offset < self.cursor {
|
||||
self.line = line;
|
||||
self.line_start = self.positions.index.line_range(line).map_or(0, |r| r.start);
|
||||
self.cursor = self.line_start;
|
||||
self.units = 0;
|
||||
}
|
||||
let step = self.positions.text.get(self.cursor as usize..offset as usize).unwrap_or("");
|
||||
self.units += utf16_len(step);
|
||||
self.cursor = offset;
|
||||
// The one `\r` `Positions::position`'s `strip_suffix` would drop: LSP
|
||||
// line content excludes the whole `\r\n`, and `\r` is one UTF-16 unit.
|
||||
let carriage = offset > self.line_start
|
||||
&& self.positions.text.as_bytes().get(offset as usize - 1) == Some(&b'\r');
|
||||
Position { line: line - 1, character: self.units - u32::from(carriage) }
|
||||
}
|
||||
|
||||
/// The LSP range of a byte range, whose two ends are in order already.
|
||||
pub fn range(&mut self, span: TextRange) -> Range {
|
||||
Range { start: self.position(span.start), end: self.position(span.end) }
|
||||
}
|
||||
}
|
||||
|
||||
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
|
||||
fn utf16_len(s: &str) -> u32 {
|
||||
s.chars().map(|c| c.len_utf16() as u32).sum()
|
||||
@@ -283,6 +344,171 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the monotonic walker
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A fixed-seed linear congruential generator — deterministic randomness
|
||||
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` and
|
||||
/// `tokens.rs` use.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every shape a byte → position converter has to survive: multi-byte and
|
||||
/// astral characters, CRLF, empty lines, a last line with no terminator,
|
||||
/// and a buffer that is one enormous line — the shape the walker exists
|
||||
/// for.
|
||||
fn fixtures() -> Vec<String> {
|
||||
let mut giant = String::from("module m; wire ");
|
||||
for n in 0..2_000 {
|
||||
giant.push_str(&format!("a{n},"));
|
||||
}
|
||||
giant.push_str("last;\nendmodule\n");
|
||||
let mut wide_and_wide = String::from("// é ✓ 🎉 ");
|
||||
for n in 0..500 {
|
||||
wide_and_wide.push_str(&format!("würe_{n}_✓, "));
|
||||
}
|
||||
wide_and_wide.push_str("\r\nendmodule\n");
|
||||
vec![
|
||||
String::new(),
|
||||
"module m;\nendmodule\n".to_string(),
|
||||
"// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule".to_string(),
|
||||
"ab\r\ncd\r\n\r\nef\r\n".to_string(),
|
||||
"\n".repeat(50),
|
||||
giant,
|
||||
wide_and_wide,
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walker_agrees_with_the_per_call_converter_on_every_shape() {
|
||||
let mut rng = Lcg(0x5EEDA11);
|
||||
for text in fixtures() {
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
let len = text.len() as u64;
|
||||
for trial in 0..20 {
|
||||
// Two strides, alternating: a crawl of a few bytes at a time
|
||||
// (many offsets on one line, which is what the walker is for)
|
||||
// and one that crosses the whole fixture in a few dozen steps.
|
||||
let stride = if trial % 2 == 0 { 4 } else { (len / 20).max(1) };
|
||||
let mut offset = rng.below(len + 1) as u32;
|
||||
let mut walker = positions.walker();
|
||||
for _ in 0..60 {
|
||||
assert_eq!(
|
||||
walker.position(offset),
|
||||
positions.position(offset),
|
||||
"{text:?} at {offset}"
|
||||
);
|
||||
offset += rng.below(stride * 2) as u32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walker_agrees_at_every_byte_of_a_gnarly_buffer() {
|
||||
// Ascending one byte at a time walks through the middle of every
|
||||
// multi-byte character and over both bytes of every `\r\n`.
|
||||
let text = "// é ✓ 🎉\r\nmodule mü;\n\r\n wire ✓a;\r\nendmodule";
|
||||
let index = LineIndex::new(text);
|
||||
let positions = Positions::new(text, &index);
|
||||
let mut walker = positions.walker();
|
||||
for offset in 0..=text.len() as u32 + 2 {
|
||||
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position() {
|
||||
// Out of order is debug-unreachable for the callers, but the walker
|
||||
// is total: a backwards offset restarts the measurement rather than
|
||||
// returning a stale column.
|
||||
let text = "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule";
|
||||
let index = LineIndex::new(text);
|
||||
let positions = Positions::new(text, &index);
|
||||
let mut rng = Lcg(0xBACC1);
|
||||
let mut walker = positions.walker();
|
||||
for _ in 0..500 {
|
||||
let offset = rng.below(text.len() as u64 + 4) as u32;
|
||||
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA attack (fix-round re-verification): the walker's restart is a
|
||||
/// per-line promise, not a per-document one. Two huge lines far apart,
|
||||
/// hit in alternation — the shape that would expose an accidental
|
||||
/// document-wide rescan hiding inside the "reset to line start" path.
|
||||
/// Each call still answers `Positions::position`'s answer exactly, and
|
||||
/// (checked by hand alongside this test, not asserted here to keep the
|
||||
/// test itself fast and non-flaky) costs only that one line's length,
|
||||
/// never the whole document's.
|
||||
#[test]
|
||||
fn a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly() {
|
||||
let mut text = String::new();
|
||||
text.push_str(&"a".repeat(20_000));
|
||||
text.push('\n');
|
||||
text.push_str(&"b".repeat(20_000));
|
||||
text.push('\n');
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
let line1_positions = [0u32, 1, 5_000, 19_999, 20_000];
|
||||
let line2_start = 20_001u32;
|
||||
let line2_positions =
|
||||
[line2_start, line2_start + 1, line2_start + 5_000, line2_start + 19_999];
|
||||
let mut walker = positions.walker();
|
||||
for round in 0..50 {
|
||||
let (a, b) = line1_positions
|
||||
.iter()
|
||||
.zip(line2_positions.iter().cycle())
|
||||
.nth(round % line1_positions.len())
|
||||
.expect("non-empty");
|
||||
for &offset in [*a, *b].iter() {
|
||||
assert_eq!(
|
||||
walker.position(offset),
|
||||
positions.position(offset),
|
||||
"round {round}, offset {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walkers_range_is_the_per_call_range() {
|
||||
let text = "module m;\r\n wire ✓a, b, c;\nendmodule\n";
|
||||
let index = LineIndex::new(text);
|
||||
let positions = Positions::new(text, &index);
|
||||
let mut walker = positions.walker();
|
||||
for span in [
|
||||
TextRange::new(0, 6),
|
||||
TextRange::new(9, 11),
|
||||
TextRange::new(13, 17),
|
||||
TextRange::new(20, 21),
|
||||
TextRange::new(30, text.len() as u32),
|
||||
] {
|
||||
assert_eq!(walker.range(span), positions.range(span), "{span:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walker_over_an_empty_document_answers_the_one_position_there_is() {
|
||||
with("", |p| {
|
||||
let mut walker = p.walker();
|
||||
assert_eq!(walker.position(0), pos(0, 0));
|
||||
assert_eq!(walker.position(99), pos(0, 0));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_document_has_one_position() {
|
||||
with("", |p| {
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
//! 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, SymbolKind, 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();
|
||||
for (name, def) in index.units_of(SymbolKind::Module) {
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// 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.units_of(vlog_semantic::SymbolKind::Module) {
|
||||
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:#?}"))
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,15 @@ pub const SOURCE: &str = "lucisv";
|
||||
/// error rather than add an opinion, and they exist at all only when the parse
|
||||
/// already failed (`pairs::missing_end_diagnostics`).
|
||||
pub fn all(doc: &Document) -> Vec<Diagnostic> {
|
||||
// A buffer on the large-file fast path was never parsed, so there is
|
||||
// nothing to say about it — and both passes below would read its *text*
|
||||
// (the lint context builds one, the fence filter scans for them), which is
|
||||
// the whole-file work the fast path exists to skip. The empty list is not
|
||||
// a silent no-op either: it is what clears the squiggles a buffer that has
|
||||
// just grown past the threshold left behind.
|
||||
if doc.large {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut all = diagnostics(doc);
|
||||
all.extend(crate::pairs::missing_end_diagnostics(doc));
|
||||
all.extend(crate::lint::diagnostics(doc));
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,15 +1,16 @@
|
||||
//! `textDocument/formatting` and `textDocument/rangeFormatting`.
|
||||
//! `textDocument/formatting`, `textDocument/rangeFormatting` and
|
||||
//! `textDocument/rangesFormatting`.
|
||||
//!
|
||||
//! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and
|
||||
//! these handlers keep it: either one whole-document edit built from verified
|
||||
//! output, or no edit at all and an error for the user to read. That holds for
|
||||
//! the range request too — its output is verified over the whole buffer, and
|
||||
//! what makes it a *range* format is which constructs it laid out, not which
|
||||
//! bytes it was allowed to replace.
|
||||
//! the range requests too — their output is verified over the whole buffer,
|
||||
//! and what makes a request a *range* format is which constructs it laid out,
|
||||
//! not which bytes it was allowed to replace.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::{FormattingOptions, Range, TextEdit};
|
||||
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
|
||||
@@ -60,6 +61,20 @@ pub fn settings_for(
|
||||
Settings { config: config_from(&file, client, options), problem }
|
||||
}
|
||||
|
||||
/// Resolve the settings governing a buffer for a request that carries no
|
||||
/// `FormattingOptions`.
|
||||
///
|
||||
/// `textDocument/willSaveWaitUntil` has no options field at all — the protocol
|
||||
/// simply does not carry one there. So the ladder `settings_for` documents
|
||||
/// runs with rung 3 missing, which is the same thing `indent_width` does for a
|
||||
/// lint fix: `lucisv.toml` > the pushed `lucisv.*` settings > the built-in
|
||||
/// default. Spelled as hard tabs and a zero width because `config_from` takes
|
||||
/// neither, so nothing is guessed on the user's behalf.
|
||||
pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) -> Settings {
|
||||
let none = FormattingOptions { tab_size: 0, insert_spaces: false, ..Default::default() };
|
||||
settings_for(doc, client, &none)
|
||||
}
|
||||
|
||||
/// Format a buffer.
|
||||
///
|
||||
/// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an
|
||||
@@ -74,29 +89,57 @@ pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, S
|
||||
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
||||
}
|
||||
|
||||
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
|
||||
///
|
||||
/// Spelled out here because `lsp-types` 0.97 predates it — the same reason
|
||||
/// `pairs::ScopePairsParams` is hand-rolled. See
|
||||
/// `docs/features/lsp-318-extras/README.md`.
|
||||
pub const RANGES_FORMATTING: &str = "textDocument/rangesFormatting";
|
||||
|
||||
/// `textDocument/rangesFormatting` params: one document, `n` ranges, one set
|
||||
/// of options.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RangesFormattingParams {
|
||||
pub text_document: TextDocumentIdentifier,
|
||||
pub ranges: Vec<Range>,
|
||||
pub options: FormattingOptions,
|
||||
}
|
||||
|
||||
/// Format the constructs a selection reaches, and nothing else.
|
||||
///
|
||||
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
|
||||
/// wants 1-based inclusive *lines*, so only the line numbers survive the
|
||||
/// conversion. An end position at character 0 still names its line — an
|
||||
/// editor's "select these three lines" ends at the start of the fourth — so
|
||||
/// a range that stops at a line's very beginning does not drag that line in
|
||||
/// unless it is also where the range started.
|
||||
///
|
||||
/// The reply is still one whole-document edit: the engine's contract is
|
||||
/// all-or-nothing over the file, and a partial run's output differs from the
|
||||
/// buffer only where it decided to differ.
|
||||
/// The one-range case of [`ranges_formatting`], which is where the whole
|
||||
/// answer lives — an `n`-range request is this request with `n` line spans.
|
||||
pub fn range_formatting(
|
||||
doc: &Document,
|
||||
config: &Config,
|
||||
range: Range,
|
||||
) -> Result<Option<TextEdit>, String> {
|
||||
let first = range.start.line.saturating_add(1);
|
||||
// An end at character 0 of a later line is the start of that line, not
|
||||
// any of its content.
|
||||
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
|
||||
let last = if ends_before_its_line { range.end.line } else { range.end.line + 1 };
|
||||
let lines = LineRanges::new([(first, last.max(first))])?;
|
||||
ranges_formatting(doc, config, std::slice::from_ref(&range))
|
||||
}
|
||||
|
||||
/// Format the constructs any of several selections reach, and nothing else.
|
||||
///
|
||||
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
|
||||
/// before the engine sees them, so overlapping, adjacent, repeated and
|
||||
/// unsorted input from the client all reach the same answer. No range is
|
||||
/// formatted on its own — one `format_range` call lays out the union, which is
|
||||
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
|
||||
/// rather than making it a promise per range.
|
||||
///
|
||||
/// The reply is still one whole-document edit: the engine's contract is
|
||||
/// all-or-nothing over the file, and a partial run's output differs from the
|
||||
/// buffer only where it decided to differ. An empty range list is not an
|
||||
/// error — it is an ask for nothing, answered with no edit.
|
||||
pub fn ranges_formatting(
|
||||
doc: &Document,
|
||||
config: &Config,
|
||||
ranges: &[Range],
|
||||
) -> Result<Option<TextEdit>, String> {
|
||||
if ranges.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
|
||||
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
@@ -104,6 +147,27 @@ pub fn range_formatting(
|
||||
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
||||
}
|
||||
|
||||
/// The 1-based inclusive line span an LSP range names.
|
||||
///
|
||||
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
|
||||
/// wants lines, so only the line numbers survive the conversion — which
|
||||
/// sidesteps the UTF-16 column question rather than solving it again. An end
|
||||
/// position at character 0 still names its line — an editor's "select these
|
||||
/// three lines" ends at the start of the fourth — so a range that stops at a
|
||||
/// line's very beginning does not drag that line in unless it is also where
|
||||
/// the range started.
|
||||
///
|
||||
/// One conversion, shared by both range requests: a second spelling of this
|
||||
/// rule would be a second thing to get wrong.
|
||||
fn lines_of(range: Range) -> (u32, u32) {
|
||||
let first = range.start.line.saturating_add(1);
|
||||
// An end at character 0 of a later line is the start of that line, not
|
||||
// any of its content.
|
||||
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
|
||||
let last = if ends_before_its_line { range.end.line } else { range.end.line.saturating_add(1) };
|
||||
(first, last.max(first))
|
||||
}
|
||||
|
||||
/// The indent width governing a buffer, for a lint fix that has to write
|
||||
/// spaces where a tab was.
|
||||
///
|
||||
@@ -495,6 +559,31 @@ mod tests {
|
||||
assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_without_options_climbs_the_same_ladder_without_rung_3() {
|
||||
// What `willSaveWaitUntil` resolves to: the protocol sends no
|
||||
// `FormattingOptions` with it, so the editor's tab size is simply not
|
||||
// one of the inputs.
|
||||
let tree = Tree::new("indent = 4\n");
|
||||
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let settings = settings_without_editor_options(doc, &pushed(None, Some(8)));
|
||||
assert_eq!(settings.config.indent_width, 4, "the config still wins");
|
||||
assert_eq!(settings.problem, None);
|
||||
|
||||
// With no config, the pushed setting is the highest rung there is.
|
||||
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8)));
|
||||
assert_eq!(settings.config.indent_width, 8);
|
||||
assert_eq!(settings.config.max_width, 60);
|
||||
// And with nothing pushed either, the built-in default — never a
|
||||
// guess from an option that was not sent.
|
||||
let settings = settings_without_editor_options(doc, &none());
|
||||
assert_eq!(settings.config.indent_width, Config::default().indent_width);
|
||||
assert_eq!(settings.config.max_width, Config::default().max_width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_leaves_the_pushed_settings_in_charge() {
|
||||
// Nothing from a broken `lucisv.toml` is used, so the next rung down is
|
||||
@@ -586,6 +675,145 @@ mod tests {
|
||||
assert!(!message.is_empty(), "the user needs something to read");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `rangesFormatting` — the union of the ranges, on the one engine
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Four items, one per line, so two disjoint ranges can reach two of them
|
||||
/// and leave the ones between untouched.
|
||||
const FOUR: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
|
||||
fn multi(text: &str, ranges: &[Range]) -> Result<Option<TextEdit>, String> {
|
||||
let (ws, uri) = document(text);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
ranges_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, ranges)
|
||||
}
|
||||
|
||||
/// The `new_text` a multi-range request answers with, or `None`.
|
||||
fn multi_text(text: &str, ranges: &[Range]) -> Option<String> {
|
||||
multi(text, ranges).expect("formats").map(|edit| edit.new_text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_ranges_lay_out_both_the_items_they_reach_and_nothing_between() {
|
||||
// Lines 2 and 4 selected, line 3 not: `b` keeps its bytes.
|
||||
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
|
||||
assert_eq!(both, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_range_answer_is_the_union_of_the_single_range_answers() {
|
||||
// The contract, stated as an equality rather than as a re-spelled
|
||||
// expectation: where two ranges do not interact, asking for both at
|
||||
// once is asking for each and taking both results. Line 2 formatted
|
||||
// alone, then line 4 formatted on *that* text, must be byte-identical
|
||||
// to one request naming both.
|
||||
let first = ranged(FOUR, at(1, 0, 1, 11)).expect("formats").expect("changed").new_text;
|
||||
let second = ranged(&first, at(3, 0, 3, 11)).expect("formats").expect("changed").new_text;
|
||||
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
|
||||
assert_eq!(both, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_arrive_unsorted_overlapping_adjacent_or_twice_and_mean_the_same_thing() {
|
||||
// `LineRanges::new` sorts and merges, and this asserts it through the
|
||||
// answer rather than restating the arithmetic. All four spellings name
|
||||
// lines 2 and 3.
|
||||
let want = multi_text(FOUR, &[at(1, 0, 2, 11)]).expect("changed");
|
||||
assert_eq!(want, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
||||
for (spelling, ranges) in [
|
||||
("unsorted", vec![at(2, 0, 2, 11), at(1, 0, 1, 11)]),
|
||||
("overlapping", vec![at(1, 0, 2, 4), at(2, 0, 2, 11)]),
|
||||
("adjacent", vec![at(1, 0, 1, 11), at(2, 0, 2, 11)]),
|
||||
("the same range twice", vec![at(1, 0, 2, 11), at(1, 0, 2, 11)]),
|
||||
] {
|
||||
assert_eq!(multi_text(FOUR, &ranges).as_deref(), Some(want.as_str()), "{spelling}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_range_list_is_an_ask_for_nothing_and_not_an_error() {
|
||||
// A client with no selections must not get a popup. `LineRanges::new`
|
||||
// refuses an empty list — that refusal is the CLI's (`--lines ''` is a
|
||||
// typo), and it is answered before the engine here.
|
||||
assert_eq!(multi(FOUR, &[]).expect("never an error"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_range_over_the_whole_buffer_is_the_whole_file_format() {
|
||||
let whole = multi_text(FOUR, &[at(0, 0, 99, 0)]).expect("changed");
|
||||
assert_eq!(whole, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
||||
// And so is every line named separately, which is the same union.
|
||||
let each: Vec<Range> = (0..5).map(|line| at(line, 0, line, 11)).collect();
|
||||
assert_eq!(multi_text(FOUR, &each).as_deref(), Some(whole.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_element_multi_range_request_is_the_single_range_request() {
|
||||
// `range_formatting` is *defined* as this call, so the two can never
|
||||
// drift — but the equality is what a client relies on, so it is
|
||||
// asserted rather than argued.
|
||||
for range in [at(1, 4, 1, 4), at(1, 0, 3, 0), at(3, 0, 3, 9), at(0, 0, 99, 0)] {
|
||||
assert_eq!(ranged(THREE, range), multi(THREE, &[range]), "{range:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() {
|
||||
// No partial output on either path (CLAUDE.md invariant #1), and the
|
||||
// same message: both are one `format_range` call away from the engine.
|
||||
let broken = "module m;\n wire ;\nendmodule\n";
|
||||
let one = ranged(broken, at(0, 0, 0, 9));
|
||||
let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]);
|
||||
assert!(one.is_err() && many.is_err(), "a broken buffer is refused both ways");
|
||||
assert_eq!(one, many, "byte-identical refusals, message included");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_range_format_is_a_fixed_point_under_the_same_ranges() {
|
||||
// Idempotency through the new path: format lines 2 and 4, then ask for
|
||||
// exactly the same two ranges on the answer — nothing left to do.
|
||||
let ranges = [at(1, 0, 1, 11), at(3, 0, 3, 11)];
|
||||
let once = multi_text(FOUR, &ranges).expect("changed");
|
||||
assert_eq!(multi_text(&once, &ranges), None, "the second run has nothing to say");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_range_request_over_already_formatted_lines_produces_no_edit() {
|
||||
let clean = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
assert_eq!(multi(clean, &[at(0, 0, 0, 9), at(1, 0, 1, 9)]).expect("formats"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_content_survives_a_multi_range_format_too() {
|
||||
// The columns are UTF-16 units and only the lines reach the engine, so
|
||||
// an emoji two lines up must not shift which items are laid out.
|
||||
let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
|
||||
let out = multi_text(text, &[at(2, 0, 2, 11), at(3, 0, 3, 11)]).expect("changed");
|
||||
assert_eq!(out, "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n");
|
||||
assert!(out.contains("é ✓ 🎉"), "comments are never dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_conversion_is_the_one_rangeformatting_always_used() {
|
||||
// Pinned directly, because both requests now share it: a cursor names
|
||||
// its own line; an end at character 0 of a *later* line stops one line
|
||||
// short; an end at character 0 on the start line does not.
|
||||
assert_eq!(lines_of(at(1, 4, 1, 4)), (2, 2), "a cursor");
|
||||
assert_eq!(lines_of(at(1, 0, 3, 0)), (2, 3), "select two lines");
|
||||
assert_eq!(lines_of(at(2, 0, 3, 0)), (3, 3), "select one line");
|
||||
assert_eq!(lines_of(at(2, 0, 2, 0)), (3, 3), "an empty range on its own line");
|
||||
assert_eq!(lines_of(at(0, 0, 99, 0)), (1, 99), "past the end of the buffer");
|
||||
// And it never produces a span `LineRanges` would refuse: line 0 is
|
||||
// impossible (1-based), and `last` can never fall below `first`.
|
||||
assert_eq!(lines_of(at(0, 0, 0, 0)), (1, 1), "the very first line");
|
||||
assert_eq!(
|
||||
lines_of(at(u32::MAX, 0, u32::MAX, 0)),
|
||||
(u32::MAX, u32::MAX),
|
||||
"a saturating add, not an overflow"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_content_survives_formatting() {
|
||||
let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n");
|
||||
|
||||
@@ -24,8 +24,10 @@ 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};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::instantiations::{self, Decl};
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
@@ -60,27 +62,67 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<CallHierarc
|
||||
/// Who instantiates this module: one call per **instantiating module**, with
|
||||
/// every instantiation site inside it.
|
||||
///
|
||||
/// Every in-scope file is walked, because the workspace index records what a
|
||||
/// file *declares* and not what it instantiates — there is no edge table to
|
||||
/// consult. A file whose text does not contain the name at all is skipped
|
||||
/// before it is parsed, which is what keeps the walk affordable: an
|
||||
/// instantiation of `fifo` has to write `fifo`.
|
||||
/// One name asked of the batch below, which is the only census in this server
|
||||
/// — the code lens counts what this lists.
|
||||
pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
|
||||
// Nothing this server hands out is nameless, so an empty name is a
|
||||
// malformed item — and the prefilter below matches every file for it,
|
||||
// which would read and parse the whole workspace to find nothing.
|
||||
if item.name.is_empty() {
|
||||
return Vec::new();
|
||||
callers_of_each(ws, &[item.name.as_str()]).pop().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Who instantiates each of `names`, answered one list per name in the order
|
||||
/// asked.
|
||||
///
|
||||
/// **A lookup in the workspace index's instantiation-edge table** since
|
||||
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
|
||||
/// file. The census is unchanged — the table is built by the same
|
||||
/// [`instantiations::sites`] walk this function used to run, at index time
|
||||
/// (`docs/features/incremental-index/README.md`) — and so is the answer's
|
||||
/// shape and order. What changed is the cost: only the files that really do
|
||||
/// instantiate one of the names are read, to turn the recorded byte spans into
|
||||
/// the protocol's line/character ranges.
|
||||
///
|
||||
/// The **batch** stays the primitive: `lens.rs` asks about every module
|
||||
/// declared in a buffer at once, and one file that instantiates three of them
|
||||
/// is read once for the batch rather than once per name.
|
||||
///
|
||||
/// An empty name is answered with nothing rather than looked up: nothing this
|
||||
/// server hands out is nameless, and a nameless question has no answer.
|
||||
pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyIncomingCall>> {
|
||||
let index = ws.index();
|
||||
let mut answers: Vec<Vec<CallHierarchyIncomingCall>> =
|
||||
names.iter().map(|_| Vec::new()).collect();
|
||||
// Every file holding an edge for any of the names, once, in path order.
|
||||
let mut files: Vec<vlog_semantic::FileId> = names
|
||||
.iter()
|
||||
.filter(|name| !name.is_empty())
|
||||
.flat_map(|name| index.instantiations_of(name).iter().map(|edge| edge.file))
|
||||
.collect();
|
||||
files.sort();
|
||||
files.dedup();
|
||||
for file in files {
|
||||
let Some(path) = index.path(file) else { continue };
|
||||
let Some(uri) = path_to_uri(path) else { continue };
|
||||
// The spans were recorded against the text the index was built from;
|
||||
// this is the text now. The two differ only for a buffer edited since
|
||||
// the last rebuild, which is the same staleness `item_in_file` has
|
||||
// always carried.
|
||||
let Some(text) = ws.text_of(path) else { continue };
|
||||
let line_index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &line_index);
|
||||
for (at, name) in names.iter().enumerate() {
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let edges = index.instantiations_of(name).iter().filter(|edge| edge.file == file);
|
||||
answers[at].extend(callers_in(&uri, &positions, edges));
|
||||
}
|
||||
}
|
||||
let mut calls: Vec<CallHierarchyIncomingCall> = Vec::new();
|
||||
for (path, text) in ws.sources() {
|
||||
calls.extend(callers_in(&path, &text, &item.name));
|
||||
for answer in &mut answers {
|
||||
answer.sort_by(|a, b| {
|
||||
(a.from.uri.as_str(), key(a.from.selection_range))
|
||||
.cmp(&(b.from.uri.as_str(), key(b.from.selection_range)))
|
||||
});
|
||||
}
|
||||
calls.sort_by(|a, b| {
|
||||
(a.from.uri.as_str(), key(a.from.selection_range))
|
||||
.cmp(&(b.from.uri.as_str(), key(b.from.selection_range)))
|
||||
});
|
||||
calls
|
||||
answers
|
||||
}
|
||||
|
||||
/// What this module instantiates: one call per **distinct instantiated
|
||||
@@ -120,37 +162,29 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOu
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every module in one file that instantiates `name`, with its sites.
|
||||
fn callers_in(path: &Path, text: &str, name: &str) -> Vec<CallHierarchyIncomingCall> {
|
||||
// An instantiation of `name` writes `name`. Nearly every file in a
|
||||
// workspace does not, and this is what keeps those files unparsed.
|
||||
if !text.contains(name) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(uri) = path_to_uri(path) else { return Vec::new() };
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let mut callers: Vec<(Decl, Vec<TextRange>)> = Vec::new();
|
||||
for site in instantiations::sites(&tree.items) {
|
||||
if site.inst.module != name {
|
||||
continue;
|
||||
}
|
||||
// An instantiation at file scope has no calling module to report.
|
||||
let Some(owner) = site.owner else { continue };
|
||||
match callers.iter_mut().find(|(decl, _)| decl.span == owner.span) {
|
||||
Some((_, spans)) => spans.push(site.inst.module_span),
|
||||
None => callers.push((owner, vec![site.inst.module_span])),
|
||||
/// One file's edges for one module, as incoming calls: one call per
|
||||
/// instantiating module, with every site inside it.
|
||||
///
|
||||
/// Sites are grouped by the declaration they sit in rather than by adjacency,
|
||||
/// because a module written inside another can put its own sites between two
|
||||
/// of the outer module's.
|
||||
fn callers_in<'a>(
|
||||
uri: &Uri,
|
||||
positions: &Positions,
|
||||
edges: impl Iterator<Item = &'a InstantiationEdge>,
|
||||
) -> Vec<CallHierarchyIncomingCall> {
|
||||
let mut callers: Vec<(&DeclSite, Vec<TextRange>)> = Vec::new();
|
||||
for edge in edges {
|
||||
match callers.iter_mut().find(|(owner, _)| owner.span == edge.owner.span) {
|
||||
Some((_, spans)) => spans.push(edge.site_span),
|
||||
None => callers.push((&edge.owner, vec![edge.site_span])),
|
||||
}
|
||||
}
|
||||
if callers.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let line_index = LineIndex::new(text);
|
||||
let positions = Positions::new(text, &line_index);
|
||||
callers
|
||||
.into_iter()
|
||||
.filter_map(|(decl, spans)| {
|
||||
.filter_map(|(owner, spans)| {
|
||||
Some(CallHierarchyIncomingCall {
|
||||
from: item(uri.clone(), &positions, decl)?,
|
||||
from: item_of(uri.clone(), positions, &owner.name, owner.name_span, owner.span)?,
|
||||
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
|
||||
})
|
||||
})
|
||||
@@ -160,20 +194,28 @@ fn callers_in(path: &Path, text: &str, name: &str) -> Vec<CallHierarchyIncomingC
|
||||
/// The hierarchy item for one module declaration, positioned against the text
|
||||
/// it was parsed from.
|
||||
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<CallHierarchyItem> {
|
||||
let name_span = decl.module.name_span;
|
||||
item_of(uri, positions, &decl.module.name, decl.module.name_span, decl.span)
|
||||
}
|
||||
|
||||
/// [`item`] from the parts, for a caller reading them out of the index's edge
|
||||
/// table rather than off a parse tree.
|
||||
fn item_of(
|
||||
uri: Uri,
|
||||
positions: &Positions,
|
||||
name: &str,
|
||||
name_span: TextRange,
|
||||
span: TextRange,
|
||||
) -> Option<CallHierarchyItem> {
|
||||
if name_span.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// The protocol requires `selectionRange` inside `range`; a declaration the
|
||||
// parser could not close is the case where that may not hold, and there
|
||||
// the name alone is the honest extent.
|
||||
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
|
||||
decl.span
|
||||
} else {
|
||||
name_span
|
||||
};
|
||||
let full =
|
||||
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
|
||||
Some(CallHierarchyItem {
|
||||
name: decl.module.name.clone(),
|
||||
name: name.to_string(),
|
||||
kind: SymbolKind::MODULE,
|
||||
tags: None,
|
||||
detail: None,
|
||||
@@ -309,7 +351,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let (path, text) = first.expect("at least one file");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
@@ -501,7 +543,7 @@ endmodule
|
||||
tree.write("files.f", "sub.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
|
||||
@@ -510,9 +552,15 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_instantiation_is_a_caller_before_it_is_saved() {
|
||||
// The sources a walk reads are the open buffers overlaid on disk, so a
|
||||
// just-typed instantiation counts.
|
||||
fn an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() {
|
||||
// Superseded this round (incremental-index, 2026-08-27):
|
||||
// `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the
|
||||
// census reading `Workspace::sources()` on every request, so a
|
||||
// keystroke in *another* buffer moved the count before anything
|
||||
// rebuilt. The census is the index's edge table now, and an index is
|
||||
// only ever as of its last build or update — which does fold every
|
||||
// open buffer in, so a save (or any other rescan trigger) makes the
|
||||
// edit count. The rule the test pins is the new one, from both sides.
|
||||
let (tree, mut ws, uri) = three("unsaved");
|
||||
let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone();
|
||||
assert_eq!(incoming(&ws, &root).len(), 2, "premise");
|
||||
@@ -520,7 +568,14 @@ endmodule
|
||||
let fresh = tree.path.join("other.sv");
|
||||
let other_uri = path_to_uri(&fresh).expect("uri");
|
||||
ws.set_document(other_uri, "module other;\nendmodule\n".to_string());
|
||||
assert_eq!(incoming(&ws, &root).len(), 1, "the buffer removed its instantiation");
|
||||
assert_eq!(
|
||||
incoming(&ws, &root).len(),
|
||||
2,
|
||||
"the buffer alone does not move the census — the index has not seen it"
|
||||
);
|
||||
// What a save does, and what the incremental path does with it.
|
||||
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
|
||||
assert_eq!(incoming(&ws, &root).len(), 1, "the edit removed its instantiation");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -909,17 +964,20 @@ endmodule
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn qa_perf_worst_case_common_word_module_name() {
|
||||
// A single-letter module name is a substring of nearly every file's
|
||||
// text, so the prefilter admits nearly everything — the worst case
|
||||
// the prefilter can face. Measures whether that worst case is still
|
||||
// sane, not a specific number.
|
||||
// A single-letter module name used to be the worst case there was: it
|
||||
// is a substring of nearly every file, so the prefilter over
|
||||
// `Workspace::sources()` admitted nearly everything. There is no
|
||||
// prefilter and no walk since 2026-08-27 — the census is a lookup in
|
||||
// the index's edge table, and a name nothing instantiates is an empty
|
||||
// slice — so this probe is kept for what it now measures: that the
|
||||
// shape which used to be the worst case is not a case at all.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus]);
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let item = CallHierarchyItem {
|
||||
name: "d".to_string(),
|
||||
kind: SymbolKind::MODULE,
|
||||
@@ -967,7 +1025,7 @@ endmodule
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus]);
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let uri = path_to_uri(&declaring).expect("uri");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7)
|
||||
|
||||
+1174
-25
File diff suppressed because it is too large.
Load diff
@@ -84,16 +84,29 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
|
||||
|
||||
/// Where `` `include``s are looked for, and which file includes which.
|
||||
///
|
||||
/// Rebuilt whole on every index rebuild, from the same source list: includes
|
||||
/// are a handful of lines per file, so there is nothing here worth updating
|
||||
/// incrementally.
|
||||
/// Rebuilt whole on every index rebuild, from the same source list — and
|
||||
/// patched one file at a time when only one file's text moved
|
||||
/// ([`IncludeGraph::update_file`]).
|
||||
#[derive(Debug, Default, Clone)]
|
||||
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`
|
||||
@@ -104,34 +117,123 @@ pub struct IncludeGraph {
|
||||
impl IncludeGraph {
|
||||
/// Scan every in-scope file for its `` `include``s and resolve them.
|
||||
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
||||
let mut graph = IncludeGraph {
|
||||
incdirs,
|
||||
edges: HashMap::new(),
|
||||
known: sources.iter().map(|(path, _)| path.clone()).collect(),
|
||||
folded: HashMap::new(),
|
||||
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
|
||||
// Learned before the edges: `resolve` consults both tables, and an edge
|
||||
// resolved against a half-filled one would be keyed inconsistently.
|
||||
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
|
||||
graph.relearn(&paths);
|
||||
for (path, text) in sources {
|
||||
graph.rescan_edges(path, text);
|
||||
}
|
||||
graph.respell();
|
||||
graph
|
||||
}
|
||||
|
||||
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
|
||||
///
|
||||
/// `known` is the index's file list as it stands *after* the update, which
|
||||
/// is what the known-file and folded-spelling tables are: cheap to rebuild
|
||||
/// from a list already in memory, and wrong to leave stale when a file has
|
||||
/// come or gone.
|
||||
///
|
||||
/// 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** 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);
|
||||
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.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),
|
||||
};
|
||||
// Built before the edges: `resolve` consults it, and an edge resolved
|
||||
// against a half-filled table would be keyed inconsistently.
|
||||
for (path, _) in sources {
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// index's file list. The same two loops [`IncludeGraph::build`] runs, over
|
||||
/// paths rather than over `(path, text)` pairs.
|
||||
fn relearn(&mut self, known: &[PathBuf]) {
|
||||
self.known = known.iter().cloned().collect();
|
||||
self.folded.clear();
|
||||
for path in known {
|
||||
let Some(key) = path.to_str().map(str::to_lowercase) else { continue };
|
||||
graph
|
||||
.folded
|
||||
self.folded
|
||||
.entry(key)
|
||||
// A second file with the same folded spelling makes the
|
||||
// spelling ambiguous, and an ambiguous one decides nothing.
|
||||
.and_modify(|found| *found = None)
|
||||
.or_insert_with(|| Some(path.clone()));
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
/// The `+incdir+` directories an include is looked for in, in filelist
|
||||
/// order — the search rungs past the including file's own directory.
|
||||
pub fn incdirs(&self) -> &[PathBuf] {
|
||||
&self.incdirs
|
||||
}
|
||||
|
||||
/// The file an `` `include`` names, or `None` when nothing on disk
|
||||
@@ -142,9 +244,45 @@ impl IncludeGraph {
|
||||
/// order. The `<angled>` form skips the own-directory rung, which is the C
|
||||
/// convention and the only difference the two spellings make here.
|
||||
pub fn resolve(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
|
||||
self.resolve_as_if(from, include, &|path| path.is_file())
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::resolve`], asked about a filesystem that has not
|
||||
/// happened yet: `exists` decides which paths are files.
|
||||
///
|
||||
/// The one search order, spent twice — `file_ops.rs` has to know where an
|
||||
/// include *will* land once a rename the client has announced goes
|
||||
/// through, and a second copy of the rung order there could disagree with
|
||||
/// this one in exactly the corner cases nobody tests. See
|
||||
/// `docs/features/file-operations/README.md`.
|
||||
pub fn resolve_as_if(
|
||||
&self,
|
||||
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 target.is_file().then(|| self.as_the_index_spells_it(normalize(target)));
|
||||
return exists(target).then(|| normalize(target));
|
||||
}
|
||||
let own = match include.system {
|
||||
true => None,
|
||||
@@ -153,8 +291,8 @@ impl IncludeGraph {
|
||||
own.into_iter()
|
||||
.chain(self.incdirs.iter().map(PathBuf::as_path))
|
||||
.map(|dir| dir.join(target))
|
||||
.find(|candidate| candidate.is_file())
|
||||
.map(|found| self.as_the_index_spells_it(normalize(&found)))
|
||||
.find(|candidate| exists(candidate))
|
||||
.map(|found| normalize(&found))
|
||||
}
|
||||
|
||||
/// A resolved path, re-spelled the way the index spells that file.
|
||||
@@ -187,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.
|
||||
///
|
||||
@@ -206,12 +356,43 @@ 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
|
||||
/// compares equal to the same file's path in the index. Symlinks are
|
||||
/// deliberately not resolved, matching `lucisv_core`'s lexical rule.
|
||||
fn normalize(path: &Path) -> PathBuf {
|
||||
///
|
||||
/// Public since 2026-08-27 so `file_ops.rs` folds a renamed file's path the
|
||||
/// same way a resolved include is folded — the two are compared, and a fourth
|
||||
/// private copy of this loop is the one thing that guarantees they disagree.
|
||||
pub fn normalize(path: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
@@ -271,7 +452,14 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec<DocumentLink> {
|
||||
/// The same computation the links use, so F12 and ctrl-click can never
|
||||
/// disagree about where a line goes.
|
||||
pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option<Location> {
|
||||
let (_, path) = resolved(ws, doc).into_iter().find(|(inc, _)| inc.span.contains(offset))?;
|
||||
// Definition is a cursor request, so inspect only its line. `documentLink`
|
||||
// still scans the whole file because it must return every include.
|
||||
let (line, _) = doc.line_index.line_col(offset);
|
||||
let line = doc.line_index.line_range(line)?;
|
||||
let text = doc.text.get(line.as_range())?;
|
||||
let include =
|
||||
include_on_line(text, line.start).filter(|include| include.span.contains(offset))?;
|
||||
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
|
||||
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
|
||||
}
|
||||
|
||||
@@ -514,7 +702,7 @@ mod tests {
|
||||
filelist: Some(tree.path.join("files.f").display().to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let path = tree.path.join(rel);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let text = fs::read_to_string(&path).expect("read");
|
||||
@@ -708,7 +896,7 @@ mod qa_scope_probe {
|
||||
filelist: Some(dir.join("files.f").display().to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -25,9 +25,9 @@ use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
|
||||
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::InstantiationPlan;
|
||||
use vlog_semantic::instantiations;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::instantiations;
|
||||
use crate::state::Workspace;
|
||||
|
||||
/// The ghost labels for one range of a buffer.
|
||||
@@ -280,7 +280,7 @@ endmodule
|
||||
}
|
||||
let path = tree.write("top.sv", top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
inlay_hints(&ws, &uri, range)
|
||||
@@ -321,7 +321,7 @@ endmodule
|
||||
let top = "module top;\n sub u1 (clk);\nendmodule\n";
|
||||
let path = tree.write("top.sv", top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
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 hints = inlay_hints(&ws, &uri, everything());
|
||||
@@ -708,7 +708,7 @@ endmodule
|
||||
let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n";
|
||||
let top_path = tree.write("top.sv", top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let sub_uri = path_to_uri(&sub_path).expect("uri");
|
||||
let top_uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(top_uri.clone(), top.to_string());
|
||||
@@ -758,7 +758,7 @@ endmodule
|
||||
top.push_str("endmodule\n");
|
||||
let path = tree.write("top.sv", &top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.clone());
|
||||
let screen = Range {
|
||||
@@ -793,7 +793,7 @@ endmodule
|
||||
top.push_str("endmodule\n");
|
||||
let path = tree.write("top.sv", &top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.clone());
|
||||
let _ = inlay_hints(&ws, &uri, everything());
|
||||
|
||||
@@ -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,29 +436,34 @@ 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
|
||||
// trigger token's `span.end`. Skipping it here is what lets a trigger at
|
||||
// the true end of the file still fire (QA find, 2026-08-25).
|
||||
let index = doc
|
||||
.tokens
|
||||
.iter()
|
||||
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset)?;
|
||||
//
|
||||
// Token ends rise across the vector, so the tokens ending at or before
|
||||
// `offset` are a prefix of it: no token outside that prefix could have
|
||||
// satisfied the reverse sweep this replaced, and inside it the sweep's
|
||||
// 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) {
|
||||
@@ -412,6 +587,29 @@ mod tests {
|
||||
(ws, uri, position)
|
||||
}
|
||||
|
||||
/// [`triggered`] used to sweep the token vector backwards from its end for
|
||||
/// the last non-`Eof` token ending at or before the cursor. It now bounds
|
||||
/// that sweep with a binary search; the token it lands on must be the same
|
||||
/// one at every byte.
|
||||
#[test]
|
||||
fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc
|
||||
.tokens
|
||||
.iter()
|
||||
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset);
|
||||
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
|
||||
let searched =
|
||||
doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof);
|
||||
assert_eq!(swept, searched, "at offset {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same, in a SystemVerilog buffer.
|
||||
fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) {
|
||||
asking_in("/rtl/top.sv", text, needle)
|
||||
@@ -1452,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 }
|
||||
}
|
||||
}]
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,897 @@
|
||||
//! The large-file fast path: what a buffer nobody lexed can still answer.
|
||||
//!
|
||||
//! A buffer over `lucisv.largeFile.threshold` is opened by
|
||||
//! [`crate::state::Document::large`] — one newline scan, no lex, no parse, no
|
||||
//! semantics, no index. This module is everything that then reads such a
|
||||
//! buffer *on demand*:
|
||||
//!
|
||||
//! * [`window`] lexes one viewport's worth of source for
|
||||
//! `textDocument/semanticTokens/range`, which is what paints the file;
|
||||
//! * [`definition`] and [`references`] scan the buffer once per request for a
|
||||
//! name.
|
||||
//!
|
||||
//! Nothing here is exact, and the rules it approximates by are stated in
|
||||
//! `docs/features/large-file-mode/README.md`. The contract is only that an
|
||||
//! answer costs a bounded amount of work and never a pass over the whole
|
||||
//! file — except the two scans, which are one linear pass and are measured.
|
||||
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{tokenize, LineIndex, TextRange};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// How far back [`inside_block_comment`] looks for the marker that decides
|
||||
/// whether a window opens inside `/* ... */`.
|
||||
///
|
||||
/// 64 KiB. A block comment longer than this is a licence header nobody is
|
||||
/// scrolled to the middle of, and the cost of the decision has to stay flat in
|
||||
/// the file's size: this is the one backwards read the fast path does, and it
|
||||
/// is a `memchr`-shaped search over a fixed slice however big the file is.
|
||||
const BACKSCAN: u32 = 64 * 1024;
|
||||
|
||||
/// The most source one window may lex, 1 MiB.
|
||||
///
|
||||
/// A client is free to ask for `semanticTokens/range` over the whole document
|
||||
/// — VS Code's own `_provideDocumentRangeSemanticTokens` command does exactly
|
||||
/// that — and answering it over 100 MB would be the whole-file pass this mode
|
||||
/// exists to avoid. A viewport plus the pages above and below it is a few tens
|
||||
/// of kilobytes, so the cap is three orders of magnitude clear of anything an
|
||||
/// editor asks for while scrolling.
|
||||
const MAX_WINDOW: u32 = 1024 * 1024;
|
||||
|
||||
/// How many times [`lex`] may shrink a window that does not lex before giving
|
||||
/// up on it. Each attempt drops the lines from the failure onwards, and the
|
||||
/// failure moves backwards every time, so this is a belt-and-braces bound
|
||||
/// rather than a number anything real reaches.
|
||||
const SHRINK_ATTEMPTS: usize = 4;
|
||||
|
||||
/// The most occurrences `textDocument/references` reports on a large buffer.
|
||||
/// A name in a netlist can occur a hundred thousand times, and a reference
|
||||
/// list nobody can read costs the editor more than it gives.
|
||||
pub const REFERENCE_LIMIT: usize = 1000;
|
||||
|
||||
/// One window of a large buffer, lexed.
|
||||
///
|
||||
/// Both fields are in **document** offsets: the caller never sees the slice
|
||||
/// the lexer actually ran on.
|
||||
pub struct Window {
|
||||
/// What the lexer made of the window. Empty when the window could not be
|
||||
/// lexed at all, which is not an error — it is a window whose text is one
|
||||
/// unterminated construct.
|
||||
pub tokens: Vec<Token>,
|
||||
/// Block-comment text the lexer was never shown: the tail of a comment the
|
||||
/// window opens inside, and the head of one it ends inside. Colouring
|
||||
/// these is the whole reason the fast path looks backwards at all.
|
||||
pub comments: Vec<TextRange>,
|
||||
}
|
||||
|
||||
/// Lex the lines `range` touches, and nothing else.
|
||||
///
|
||||
/// The window is snapped out to whole lines, capped at [`MAX_WINDOW`], and
|
||||
/// then treated as a self-contained piece of source. The two things that
|
||||
/// makes wrong, and what is done about each:
|
||||
///
|
||||
/// * **A comment the window opens inside.** Decided by a bounded backwards
|
||||
/// scan ([`inside_block_comment`]); the tail of the comment is returned as a
|
||||
/// comment span and the lexer starts after it.
|
||||
/// * **A construct the window ends inside.** The lexer is all-or-nothing, so
|
||||
/// an unterminated comment or string at the far edge would cost the whole
|
||||
/// window; [`lex`] shrinks the window to the last line that does lex, and
|
||||
/// what is left over is coloured as a comment when it opens one.
|
||||
pub fn window(doc: &Document, range: lsp_types::Range) -> Window {
|
||||
let text = &doc.text;
|
||||
let (start, end) = bounds(&doc.line_index, text.len() as u32, range);
|
||||
let mut comments = Vec::new();
|
||||
let mut from = start;
|
||||
if inside_block_comment(text, start) {
|
||||
let Some(rest) = text.get(start as usize..end as usize) else {
|
||||
return Window { tokens: Vec::new(), comments };
|
||||
};
|
||||
match rest.find("*/") {
|
||||
// The comment ends inside the window: colour its tail and lex
|
||||
// from the first byte after it.
|
||||
Some(at) => {
|
||||
from = start + at as u32 + 2;
|
||||
comments.push(TextRange::new(start, from));
|
||||
}
|
||||
// The whole window is inside one comment. Nothing to lex at all,
|
||||
// which is the cheapest window there is.
|
||||
None => {
|
||||
comments.push(TextRange::new(start, end));
|
||||
return Window { tokens: Vec::new(), comments };
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(slice) = text.get(from as usize..end as usize) else {
|
||||
return Window { tokens: Vec::new(), comments };
|
||||
};
|
||||
let (mut tokens, lexed) = lex(slice);
|
||||
for token in &mut tokens {
|
||||
rebase(token, from);
|
||||
}
|
||||
if let Some(tail) = trailing_comment(slice, lexed) {
|
||||
comments.push(TextRange::new(from + tail.start, from + tail.end));
|
||||
}
|
||||
Window { tokens, comments }
|
||||
}
|
||||
|
||||
/// The byte range one `Range` asks about, snapped out to whole lines and
|
||||
/// capped.
|
||||
///
|
||||
/// Both ends land on a character boundary: a line start and a line end always
|
||||
/// do, and the cap is floored onto one.
|
||||
fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) {
|
||||
let last = index.line_count();
|
||||
let first_line = (range.start.line + 1).min(last);
|
||||
let last_line = (range.end.line + 1).clamp(first_line, last);
|
||||
let start = index.line_range(first_line).map_or(0, |line| line.start);
|
||||
let mut end = index.line_range(last_line).map_or(len, |line| line.end);
|
||||
if end.saturating_sub(start) > MAX_WINDOW {
|
||||
// Snapped to the line the cap lands in where that helps, and cut
|
||||
// mid-line where it does not: a single line longer than the cap is
|
||||
// exactly the netlist shape the cap is for. A token cut in half at the
|
||||
// far edge still colours as what it started as.
|
||||
let capped = start + MAX_WINDOW;
|
||||
end = match index.line_range(index.line_col(capped).0) {
|
||||
Some(line) if line.end <= capped => line.end,
|
||||
_ => capped,
|
||||
};
|
||||
}
|
||||
(start, end.max(start))
|
||||
}
|
||||
|
||||
/// Whether the byte at `at` is inside a `/* ... */` comment, as far as a
|
||||
/// backwards scan of at most [`BACKSCAN`] bytes can tell.
|
||||
///
|
||||
/// **Deliberately approximate.** It reads the last `/*` or `*/` before `at`
|
||||
/// and believes it: a `/*` written inside a string or after a `//` fools it,
|
||||
/// and so does a comment whose opener is further back than the budget, in
|
||||
/// which case the answer is "code". Both mis-colour a screen and neither can
|
||||
/// corrupt anything, which is the trade the whole mode is built on.
|
||||
fn inside_block_comment(text: &str, at: u32) -> bool {
|
||||
let at = at as usize;
|
||||
let mut from = at.saturating_sub(BACKSCAN as usize);
|
||||
while from < at && !text.is_char_boundary(from) {
|
||||
from += 1;
|
||||
}
|
||||
let Some(hay) = text.get(from..at) else { return false };
|
||||
match (hay.rfind("/*"), hay.rfind("*/")) {
|
||||
(Some(open), Some(close)) => open > close,
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lex as much of `slice` as lexes, reporting how many bytes that was.
|
||||
///
|
||||
/// The lexer is all-or-nothing (`docs/features/error-recovery/README.md`), and
|
||||
/// a window cut out of the middle of a file ends wherever the viewport ended —
|
||||
/// so an unterminated comment or string at the far edge is the *normal* case
|
||||
/// here, not a broken file. Its error names the line it gave up on, so the
|
||||
/// retry drops that line and everything after it.
|
||||
fn lex(slice: &str) -> (Vec<Token>, u32) {
|
||||
let mut end = slice.len();
|
||||
for _ in 0..SHRINK_ATTEMPTS {
|
||||
let Some(head) = slice.get(..end) else { return (Vec::new(), 0) };
|
||||
match tokenize(head) {
|
||||
Ok(tokens) => return (tokens, end as u32),
|
||||
Err(problem) => match line_start(head, problem.line) {
|
||||
// Line 1 failed: there is nothing left to keep.
|
||||
Some(0) | None => return (Vec::new(), 0),
|
||||
Some(shorter) => end = shorter,
|
||||
},
|
||||
}
|
||||
}
|
||||
(Vec::new(), 0)
|
||||
}
|
||||
|
||||
/// The byte offset of a 1-based line of `text`, or `None` when it has no such
|
||||
/// line. Used only on the failure path, so it walks rather than indexing.
|
||||
fn line_start(text: &str, line: u32) -> Option<usize> {
|
||||
if line <= 1 {
|
||||
return Some(0);
|
||||
}
|
||||
let mut seen = 1;
|
||||
for (at, byte) in text.bytes().enumerate() {
|
||||
if byte == b'\n' {
|
||||
seen += 1;
|
||||
if seen == line {
|
||||
return Some(at + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The block comment the leftovers of a shrunk window open, if they open one.
|
||||
///
|
||||
/// A banner comment crossing the bottom of the viewport is the shape this is
|
||||
/// for: the lexer refused the window because of it, and colouring the rest of
|
||||
/// the window as comment is both what it is and what the *next* window (once
|
||||
/// the user scrolls) will say too.
|
||||
fn trailing_comment(slice: &str, lexed: u32) -> Option<TextRange> {
|
||||
let rest = slice.get(lexed as usize..)?;
|
||||
let open = rest.find("/*")?;
|
||||
// A `/*` that is closed inside the leftovers was not what stopped the
|
||||
// lexer, so this is not the shape above and guessing would be wrong.
|
||||
if rest[open..].contains("*/") {
|
||||
return None;
|
||||
}
|
||||
Some(TextRange::new(lexed + open as u32, lexed + rest.len() as u32))
|
||||
}
|
||||
|
||||
/// Move a token, and the comments hanging off it, from window offsets to
|
||||
/// document offsets.
|
||||
fn rebase(token: &mut Token, by: u32) {
|
||||
token.span = shift(token.span, by);
|
||||
for comment in &mut token.leading {
|
||||
comment.span = shift(comment.span, by);
|
||||
}
|
||||
if let Some(comment) = &mut token.trailing {
|
||||
comment.span = shift(comment.span, by);
|
||||
}
|
||||
}
|
||||
|
||||
fn shift(span: TextRange, by: u32) -> TextRange {
|
||||
TextRange::new(span.start + by, span.end + by)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the two scans
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The keywords that make the identifier after them a declaration, as far as
|
||||
/// the fast path is concerned.
|
||||
///
|
||||
/// A heuristic, and a small one on purpose: it is read backwards from an
|
||||
/// occurrence, not parsed, so a declaration written any other way (a port
|
||||
/// listed in an ANSI header after its direction and type, a `typedef`'s new
|
||||
/// name, an instance name) is simply not found and the request answers
|
||||
/// nothing. Every word here is a real keyword — pinned by a test against
|
||||
/// `vlog_parser::KEYWORDS`, so a typo cannot sit here quietly.
|
||||
const DECLARATORS: [&str; 22] = [
|
||||
"module",
|
||||
"macromodule",
|
||||
"interface",
|
||||
"package",
|
||||
"program",
|
||||
"primitive",
|
||||
"class",
|
||||
"function",
|
||||
"task",
|
||||
"input",
|
||||
"output",
|
||||
"inout",
|
||||
"wire",
|
||||
"reg",
|
||||
"logic",
|
||||
"bit",
|
||||
"integer",
|
||||
"int",
|
||||
"real",
|
||||
"genvar",
|
||||
"parameter",
|
||||
"localparam",
|
||||
];
|
||||
|
||||
/// The identifier `offset` sits in, if it sits in one.
|
||||
pub fn word_at(text: &str, offset: u32) -> Option<TextRange> {
|
||||
let bytes = text.as_bytes();
|
||||
let at = (offset as usize).min(bytes.len());
|
||||
let mut start = at;
|
||||
while start > 0 && is_word(bytes[start - 1]) {
|
||||
start -= 1;
|
||||
}
|
||||
let mut end = at;
|
||||
while end < bytes.len() && is_word(bytes[end]) {
|
||||
end += 1;
|
||||
}
|
||||
// A cursor in whitespace between two words has an empty range, and an
|
||||
// empty name would match everywhere.
|
||||
(start < end).then(|| TextRange::new(start as u32, end as u32))
|
||||
}
|
||||
|
||||
/// Where the name at `offset` looks declared: the first occurrence of it
|
||||
/// preceded by a declaring keyword, or nothing.
|
||||
///
|
||||
/// One linear pass over the buffer, which is what a request on a file nothing
|
||||
/// has indexed costs. The measurement is in the feature README.
|
||||
pub fn definition(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
let name = word_at(&doc.text, offset)?;
|
||||
let name = doc.text.get(name.as_range())?;
|
||||
occurrences(&doc.text, name).find(|at| declares(&doc.text, *at))
|
||||
}
|
||||
|
||||
/// Every occurrence of the name at `offset`, capped at [`REFERENCE_LIMIT`].
|
||||
///
|
||||
/// Occurrences of the *text*, whole-word: this buffer has no scopes, so a
|
||||
/// local `i` in one module and a local `i` in another are one answer. That is
|
||||
/// the honest thing a text scan can say, and it is what the README calls
|
||||
/// checking-light.
|
||||
pub fn references(doc: &Document, offset: u32, include_declaration: bool) -> Vec<TextRange> {
|
||||
let Some(name) = word_at(&doc.text, offset) else { return Vec::new() };
|
||||
let Some(text) = doc.text.get(name.as_range()) else { return Vec::new() };
|
||||
let declaration = (!include_declaration).then(|| definition(doc, offset)).flatten();
|
||||
occurrences(&doc.text, text)
|
||||
.filter(|found| Some(*found) != declaration)
|
||||
.take(REFERENCE_LIMIT)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every whole-word occurrence of `name` in `text`, in order.
|
||||
fn occurrences<'a>(text: &'a str, name: &'a str) -> impl Iterator<Item = TextRange> + 'a {
|
||||
let bytes = text.as_bytes();
|
||||
text.match_indices(name).filter_map(move |(at, _)| {
|
||||
let before = at.checked_sub(1).map(|i| bytes[i]);
|
||||
let after = bytes.get(at + name.len()).copied();
|
||||
let bounded = !before.is_some_and(is_word) && !after.is_some_and(is_word);
|
||||
bounded.then(|| TextRange::new(at as u32, (at + name.len()) as u32))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the word before this occurrence declares it.
|
||||
fn declares(text: &str, occurrence: TextRange) -> bool {
|
||||
let bytes = text.as_bytes();
|
||||
let mut end = occurrence.start as usize;
|
||||
while end > 0 && bytes[end - 1].is_ascii_whitespace() {
|
||||
end -= 1;
|
||||
}
|
||||
let mut start = end;
|
||||
while start > 0 && is_word(bytes[start - 1]) {
|
||||
start -= 1;
|
||||
}
|
||||
text.get(start..end).is_some_and(|word| DECLARATORS.contains(&word))
|
||||
}
|
||||
|
||||
/// Whether a byte can be part of an identifier. `$` is in, for the system
|
||||
/// tasks; the escaped-identifier form (`\name `) is not modelled at all.
|
||||
fn is_word(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::{Position, Range};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A fast-path document over `text`.
|
||||
fn large(text: &str) -> Document {
|
||||
Document::large(Some(PathBuf::from("/rtl/net.v")), text.to_string())
|
||||
}
|
||||
|
||||
fn range(from: u32, to: u32) -> Range {
|
||||
Range {
|
||||
start: Position { line: from, character: 0 },
|
||||
end: Position { line: to, character: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of every token a window produced, in order.
|
||||
fn words(doc: &Document, window: &Window) -> Vec<String> {
|
||||
window
|
||||
.tokens
|
||||
.iter()
|
||||
.filter(|t| t.kind != vlog_parser::token::TokenKind::Eof)
|
||||
.map(|t| doc.text[t.span.as_range()].to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the window
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_window_lexes_its_own_lines_and_reports_document_offsets() {
|
||||
let doc = large("module a;\nwire b;\nwire c;\nendmodule\n");
|
||||
let window = window(&doc, range(1, 2));
|
||||
assert_eq!(words(&doc, &window), ["wire", "b", ";", "wire", "c", ";"]);
|
||||
// The spans are the document's, not the slice's: the first token is
|
||||
// `wire` on line 1, which starts at byte 10.
|
||||
assert_eq!(window.tokens[0].span.start, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_starting_mid_line_is_snapped_back_to_the_line_start() {
|
||||
let doc = large("module a;\nwire b;\n");
|
||||
let mid = Range {
|
||||
start: Position { line: 1, character: 4 },
|
||||
end: Position { line: 1, character: 6 },
|
||||
};
|
||||
assert_eq!(words(&doc, &window(&doc, mid)), ["wire", "b", ";"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_past_the_end_of_the_file_is_empty_and_does_not_panic() {
|
||||
let doc = large("module a;\nendmodule\n");
|
||||
assert!(words(&doc, &window(&doc, range(900, 999))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_opening_inside_a_block_comment_colours_the_tail_and_lexes_the_rest() {
|
||||
let doc = large("/* a\n b\n c */ wire d;\nwire e;\n");
|
||||
// Lines 1..3: the window opens on ` b`, which is inside the comment
|
||||
// opened on line 0, so the tail up to `*/` is a comment span and the
|
||||
// lexer only saw what followed it.
|
||||
let window = window(&doc, range(1, 3));
|
||||
assert_eq!(window.comments.len(), 1);
|
||||
let comment = &doc.text[window.comments[0].as_range()];
|
||||
assert!(comment.ends_with("*/"), "{comment:?}");
|
||||
assert!(comment.starts_with(" b"), "{comment:?}");
|
||||
assert_eq!(words(&doc, &window), ["wire", "d", ";", "wire", "e", ";"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_wholly_inside_a_block_comment_is_one_comment_and_no_tokens() {
|
||||
let mut text = String::from("/* opener\n");
|
||||
for _ in 0..40 {
|
||||
text.push_str(" still a comment\n");
|
||||
}
|
||||
text.push_str("*/\nwire a;\n");
|
||||
let doc = large(&text);
|
||||
let window = window(&doc, range(10, 20));
|
||||
assert!(window.tokens.is_empty());
|
||||
assert_eq!(window.comments.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backward_scan_gives_up_beyond_its_budget_and_assumes_code() {
|
||||
// A block comment opened further back than BACKSCAN: the decision
|
||||
// cannot be made, and the documented answer is "code".
|
||||
let mut text = String::from("/* opener\n");
|
||||
text.push_str(&" filler filler filler filler\n".repeat(4000));
|
||||
assert!(text.len() as u32 > BACKSCAN, "the premise: past the budget");
|
||||
text.push_str("wire a;\n");
|
||||
let doc = large(&text);
|
||||
let last = doc.line_index.line_count() - 2;
|
||||
let window = window(&doc, range(last, last));
|
||||
assert!(window.comments.is_empty(), "no comment was detected");
|
||||
assert_eq!(words(&doc, &window), ["wire", "a", ";"], "it lexed as code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_ending_inside_a_block_comment_keeps_the_lines_that_lex() {
|
||||
let doc = large("wire a;\nwire b;\n/* an unterminated banner\n");
|
||||
let window = window(&doc, range(0, 2));
|
||||
assert_eq!(words(&doc, &window), ["wire", "a", ";", "wire", "b", ";"]);
|
||||
assert_eq!(window.comments.len(), 1, "the banner is coloured as a comment");
|
||||
assert!(doc.text[window.comments[0].as_range()].starts_with("/*"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_ending_inside_a_string_keeps_the_lines_that_lex() {
|
||||
let doc = large("wire a;\n$display(\"unterminated\n");
|
||||
let window = window(&doc, range(0, 1));
|
||||
assert_eq!(words(&doc, &window), ["wire", "a", ";"]);
|
||||
assert!(window.comments.is_empty(), "an unterminated string is not a comment");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_whose_first_line_cannot_lex_answers_nothing_rather_than_guessing() {
|
||||
let doc = large("$display(\"unterminated\nwire a;\n");
|
||||
let window = window(&doc, range(0, 0));
|
||||
assert!(window.tokens.is_empty());
|
||||
assert!(window.comments.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_is_capped_however_much_the_client_asks_for() {
|
||||
// Every line is 8 bytes, so 200_000 lines is 1.6 MB — a client asking
|
||||
// for the whole document must still lex at most MAX_WINDOW of it.
|
||||
let text = "wire a;\n".repeat(200_000);
|
||||
assert!(text.len() as u32 > MAX_WINDOW, "the premise");
|
||||
let doc = large(&text);
|
||||
let window = window(&doc, range(0, doc.line_index.line_count()));
|
||||
let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0);
|
||||
assert!(last <= MAX_WINDOW, "lexed past the cap: {last}");
|
||||
assert!(last > MAX_WINDOW - 64, "and up to it: {last}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_line_longer_than_the_cap_is_cut_rather_than_lexed_whole() {
|
||||
let mut text = String::from("wire ");
|
||||
text.push_str(&"a".repeat(MAX_WINDOW as usize + 1000));
|
||||
text.push_str(";\n");
|
||||
let doc = large(&text);
|
||||
let window = window(&doc, range(0, 0));
|
||||
// It still answers, and it did not read the whole line.
|
||||
let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0);
|
||||
assert!(last <= MAX_WINDOW, "{last}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_buffer_answers_an_empty_window() {
|
||||
let doc = large("");
|
||||
let window = window(&doc, range(0, 10));
|
||||
assert!(window.tokens.is_empty() || words(&doc, &window).is_empty());
|
||||
assert!(window.comments.is_empty());
|
||||
}
|
||||
|
||||
/// QA attack: a buffer of nothing but newlines. Every line is empty, so
|
||||
/// every byte offset the code touches (line starts, line ends, the
|
||||
/// backward scan's window) coincides with several others — the shape most
|
||||
/// likely to trip an off-by-one into an out-of-range slice.
|
||||
#[test]
|
||||
fn a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens() {
|
||||
let doc = large(&"\n".repeat(5_000));
|
||||
for (from, to) in [(0, 1), (0, 5000), (4998, 4999), (2500, 2500)] {
|
||||
let window = window(&doc, range(from, to));
|
||||
// Only the EOF token, which every `tokenize` call ends with even
|
||||
// over blank input — no real token, and no panic getting there.
|
||||
assert!(words(&doc, &window).is_empty(), "nothing to lex: {from}..{to}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA attack: a CRLF netlist. `LineIndex` keeps the `\r` as an ordinary
|
||||
/// byte of its line (`convert.rs`'s own rule), so a window boundary lands
|
||||
/// right before a `\r` rather than a `\n` — this pins that the window
|
||||
/// still lexes the same tokens CRLF or not, and that the trailing `\r` on
|
||||
/// each line does not get coloured as part of the token before it.
|
||||
#[test]
|
||||
fn a_crlf_netlist_windows_the_same_as_its_lf_twin() {
|
||||
let lf = "module m;\r\n wire sig_a;\r\n wire sig_b;\r\nendmodule\r\n";
|
||||
let doc = large(lf);
|
||||
let window = window(&doc, range(1, 2));
|
||||
assert_eq!(words(&doc, &window), ["wire", "sig_a", ";", "wire", "sig_b", ";"]);
|
||||
// No token swallowed the `\r`: every token's text is exactly itself.
|
||||
for token in &window.tokens {
|
||||
let text = &doc.text[token.span.as_range()];
|
||||
assert!(!text.contains('\r'), "a token ate the line ending: {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the shrink helper on its own
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn lex_reports_how_much_of_the_slice_it_used() {
|
||||
let (tokens, used) = lex("wire a;\n");
|
||||
assert!(!tokens.is_empty());
|
||||
assert_eq!(used, 8);
|
||||
let (tokens, used) = lex("wire a;\n/* open");
|
||||
assert!(!tokens.is_empty());
|
||||
assert_eq!(used, 8, "the comment line was dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_start_counts_lines_from_one() {
|
||||
assert_eq!(line_start("a\nb\nc", 1), Some(0));
|
||||
assert_eq!(line_start("a\nb\nc", 2), Some(2));
|
||||
assert_eq!(line_start("a\nb\nc", 3), Some(4));
|
||||
assert_eq!(line_start("a\nb\nc", 4), None);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// definition and references
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
const NETLIST: &str = "module top;\n wire sig_a;\n wire sig_b;\n sub u0 (.a(sig_a), \
|
||||
.b(sig_b));\n assign sig_a = sig_b;\nendmodule\n";
|
||||
|
||||
/// The offset of the `n`-th occurrence of `needle`.
|
||||
fn at(text: &str, needle: &str, n: usize) -> u32 {
|
||||
text.match_indices(needle).nth(n).expect("occurrence").0 as u32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_is_found_by_the_keyword_before_it() {
|
||||
let doc = large(NETLIST);
|
||||
let found = definition(&doc, at(NETLIST, "sig_a", 2)).expect("a declaration");
|
||||
assert_eq!(found.start, at(NETLIST, "sig_a", 0), "the `wire sig_a;` line");
|
||||
assert_eq!(&NETLIST[found.as_range()], "sig_a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_no_keyword_introduces_has_no_definition() {
|
||||
let doc = large(NETLIST);
|
||||
assert!(definition(&doc, at(NETLIST, "u0", 0)).is_none(), "an instance name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_that_is_not_on_a_word_answers_nothing() {
|
||||
let doc = large(NETLIST);
|
||||
let space = NETLIST.find(" wire").expect("indent") as u32;
|
||||
assert!(definition(&doc, space).is_none());
|
||||
assert!(references(&doc, space, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_are_whole_word_and_in_order() {
|
||||
let doc = large(NETLIST);
|
||||
let found = references(&doc, at(NETLIST, "sig_a", 0), true);
|
||||
assert_eq!(found.len(), 3, "declaration, connection, assignment");
|
||||
assert!(found.windows(2).all(|pair| pair[0].start < pair[1].start));
|
||||
// `sig_a` is not found inside `sig_ab`.
|
||||
let doc = large("wire sig_ab;\nwire sig_a;\n");
|
||||
assert_eq!(references(&doc, at(&doc.text, "sig_a", 1), true).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluding_the_declaration_drops_exactly_the_declaration() {
|
||||
let doc = large(NETLIST);
|
||||
let with = references(&doc, at(NETLIST, "sig_a", 1), true);
|
||||
let without = references(&doc, at(NETLIST, "sig_a", 1), false);
|
||||
assert_eq!(without.len(), with.len() - 1);
|
||||
assert!(!without.contains(&with[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reference_list_is_capped() {
|
||||
let text = format!("wire sig;\n{}", "assign x = sig;\n".repeat(REFERENCE_LIMIT + 500));
|
||||
let doc = large(&text);
|
||||
assert_eq!(references(&doc, 5, true).len(), REFERENCE_LIMIT);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the 100 MB probes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A netlist-shaped buffer of about `bytes` bytes.
|
||||
///
|
||||
/// Instantiation lines, which is what a synthesized netlist really is, with
|
||||
/// a declaration and a comment every so often so the scans have something
|
||||
/// to find and the windows have something to colour.
|
||||
fn netlist(bytes: usize) -> String {
|
||||
let mut text = String::with_capacity(bytes + 4096);
|
||||
text.push_str("module netlist_top;\n wire needle;\n");
|
||||
let mut n = 0u64;
|
||||
while text.len() < bytes {
|
||||
text.push_str(&format!(
|
||||
" sky130_fd_sc_hd__inv_2 _{n}_ (.A(net{n}), .Y(net{}));\n",
|
||||
n + 1
|
||||
));
|
||||
if n.is_multiple_of(500) {
|
||||
text.push_str(" /* a banner comment, so the windows are not all code */\n");
|
||||
text.push_str(" wire net_local;\n");
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
// A second declaration at the far end: a scan for it is the worst
|
||||
// case, since the answer is the last thing in the file.
|
||||
text.push_str(" wire tail_needle;\nendmodule\n");
|
||||
text
|
||||
}
|
||||
|
||||
/// **The measurement the feature README quotes.** Ignored by default: it
|
||||
/// builds a 100 MB buffer, which is not something `cargo test` should do
|
||||
/// on every run. Run it as
|
||||
/// `cargo test -p lucisv_server --release -- --ignored --nocapture
|
||||
/// large::tests::the_hundred_megabyte_probes`.
|
||||
///
|
||||
/// The bounds asserted are deliberately loose — an order of magnitude over
|
||||
/// what the numbers actually are on the machine this was written on — so
|
||||
/// the probe fails on a regression in *kind* (someone made the open path
|
||||
/// scan the file twice, someone made the window lex the document) rather
|
||||
/// than on a slow CI box.
|
||||
#[test]
|
||||
#[ignore = "synthesizes a 100 MB buffer; run with --release --ignored --nocapture"]
|
||||
fn the_hundred_megabyte_probes() {
|
||||
use std::time::Instant;
|
||||
let text = netlist(100 * 1024 * 1024);
|
||||
let bytes = text.len();
|
||||
|
||||
let clock = Instant::now();
|
||||
let doc = Document::large(Some(PathBuf::from("/rtl/netlist.v")), text);
|
||||
let open = clock.elapsed();
|
||||
|
||||
let lines = doc.line_index.line_count();
|
||||
let middle = lines / 2;
|
||||
let viewport = Range {
|
||||
start: Position { line: middle, character: 0 },
|
||||
end: Position { line: middle + 60, character: 0 },
|
||||
};
|
||||
// Twice: the first call is where any accidental one-off whole-file
|
||||
// work would hide.
|
||||
let clock = Instant::now();
|
||||
let first = window(&doc, viewport);
|
||||
let first_window = clock.elapsed();
|
||||
let clock = Instant::now();
|
||||
let again = window(&doc, viewport);
|
||||
let second_window = clock.elapsed();
|
||||
assert_eq!(first.tokens.len(), again.tokens.len());
|
||||
assert!(!first.tokens.is_empty(), "the window really did lex something");
|
||||
|
||||
// The worst case for both scans: the name is declared in the *last*
|
||||
// line of the file, so the answer is only found after a whole pass.
|
||||
let tail = doc.text.rfind("tail_needle").expect("the tail declaration") as u32;
|
||||
let clock = Instant::now();
|
||||
let found = definition(&doc, tail);
|
||||
let definition_scan = clock.elapsed();
|
||||
assert!(found.is_some());
|
||||
|
||||
let clock = Instant::now();
|
||||
let refs = references(&doc, tail, true);
|
||||
let reference_scan = clock.elapsed();
|
||||
assert!(!refs.is_empty());
|
||||
|
||||
// And the shape that is worst for the search itself: a short name
|
||||
// that occurs as a *prefix* of a million others, so the whole-word
|
||||
// filter runs on every one of them.
|
||||
let common = doc.text.find("net1)").expect("a net use") as u32;
|
||||
let clock = Instant::now();
|
||||
let many = references(&doc, common, true);
|
||||
let capped_scan = clock.elapsed();
|
||||
|
||||
eprintln!(
|
||||
"100 MB probe: {bytes} bytes, {lines} lines\n \
|
||||
open (line index only): {open:?}\n \
|
||||
semanticTokens/range window (60 lines): {first_window:?} then {second_window:?}\n \
|
||||
definition scan (declared in the last line): {definition_scan:?}\n \
|
||||
references scan (2 hits, whole file): {reference_scan:?}\n \
|
||||
references scan (short name, {} hits among a million prefixes): {capped_scan:?}",
|
||||
many.len()
|
||||
);
|
||||
|
||||
assert!(open.as_millis() < 5_000, "opening cost {open:?}");
|
||||
assert!(first_window.as_millis() < 200, "the first window cost {first_window:?}");
|
||||
assert!(second_window.as_millis() < 200, "the second window cost {second_window:?}");
|
||||
assert!(
|
||||
definition_scan.as_millis() < 1_000,
|
||||
"the definition scan cost {definition_scan:?}"
|
||||
);
|
||||
assert!(reference_scan.as_millis() < 1_000, "the reference scan cost {reference_scan:?}");
|
||||
assert!(capped_scan.as_millis() < 1_000, "the worst-case scan cost {capped_scan:?}");
|
||||
}
|
||||
|
||||
/// What the fast path is worth, measured rather than asserted: the same
|
||||
/// buffer through [`Document::new`] and through [`Document::large`].
|
||||
///
|
||||
/// Ten megabytes rather than a hundred, because the point is the *ratio*
|
||||
/// and because a 100 MB full analysis is minutes and gigabytes — which is
|
||||
/// itself the finding, and is why the threshold exists.
|
||||
#[test]
|
||||
#[ignore = "analyzes a 10 MB buffer in full; run with --release --ignored --nocapture"]
|
||||
fn the_full_pipeline_probe_says_what_the_fast_path_saves() {
|
||||
use std::time::Instant;
|
||||
let text = netlist(10 * 1024 * 1024);
|
||||
let clock = Instant::now();
|
||||
let fast = Document::large(None, text.clone());
|
||||
let fast_open = clock.elapsed();
|
||||
|
||||
let clock = Instant::now();
|
||||
let full = Document::new(None, text, &vlog_semantic::WorkspaceIndex::default());
|
||||
let full_open = clock.elapsed();
|
||||
|
||||
eprintln!(
|
||||
"10 MB open: fast path {fast_open:?} ({} tokens), full pipeline {full_open:?} \
|
||||
({} tokens) — {:.0}x",
|
||||
fast.tokens.len(),
|
||||
full.tokens.len(),
|
||||
full_open.as_secs_f64() / fast_open.as_secs_f64().max(f64::MIN_POSITIVE)
|
||||
);
|
||||
assert!(fast_open < full_open, "the fast path is the fast one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_declarator_is_a_real_keyword() {
|
||||
for word in DECLARATORS {
|
||||
assert!(
|
||||
vlog_parser::KEYWORDS.contains(&word),
|
||||
"{word} is not a keyword the lexer knows"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// **QA finding 1 (2026-08-27), fixed and now a gate.** A single line far
|
||||
/// longer than [`BACKSCAN`], packed with thousands of short tokens rather
|
||||
/// than one long one — a wide bus concatenation or a one-line generated
|
||||
/// port list, both ordinary netlist shapes. `window()` itself only ever
|
||||
/// touches [`MAX_WINDOW`] bytes, so the *lexer* side was always bounded by
|
||||
/// construction. But colouring the window also converts every token's byte
|
||||
/// span to a UTF-16 LSP position (`tokens::flatten`), and that conversion
|
||||
/// used to scan from the **start of the token's line** every time: on an
|
||||
/// ordinary file a few dozen bytes of work, on a window that is all one
|
||||
/// line O(line length) per token, i.e. **O(tokens²)**. Measured at
|
||||
/// 107.8 ms → 439.3 ms → 1.85 s → **7.86 s** across the four sizes below
|
||||
/// (release) — 4x the time for 2x the tokens, the signature of a quadratic
|
||||
/// wall rather than the "bounded, however big the file is" cost the
|
||||
/// feature README promises.
|
||||
///
|
||||
/// `tokens::flatten` now converts through `Positions::walker`
|
||||
/// (`convert.rs`), which measures each line once however many offsets fall
|
||||
/// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for
|
||||
/// 2x, and 596x faster at the top.
|
||||
///
|
||||
/// The bound is wall-clock, loose, and in debug (this test runs in the
|
||||
/// normal suite): ~4x the measured debug cost of the largest size, which
|
||||
/// the quadratic version overshoots by more than two orders of magnitude.
|
||||
/// A regression in *kind* fails it; a slow CI box does not.
|
||||
#[test]
|
||||
fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() {
|
||||
use std::time::Instant;
|
||||
for count in [5_000u32, 10_000, 20_000, 40_000] {
|
||||
// One line: `module m; wire a0,a1,...,last;` — realistic in shape
|
||||
// (a wide declaration), synthetic only in how wide.
|
||||
let mut text = String::from("module m; wire ");
|
||||
for n in 0..count {
|
||||
text.push_str(&format!("a{n},"));
|
||||
}
|
||||
text.push_str("last;\nendmodule\n");
|
||||
let doc = large(&text);
|
||||
let clock = Instant::now();
|
||||
let window = window(&doc, range(0, 1));
|
||||
let lex_elapsed = clock.elapsed();
|
||||
assert!(!window.tokens.is_empty());
|
||||
let clock2 = Instant::now();
|
||||
let data = crate::tokens::semantic_tokens_in_window(&doc, range(0, 1));
|
||||
let colour_elapsed = clock2.elapsed();
|
||||
eprintln!(
|
||||
"{count} tokens, {}-byte line: lex {lex_elapsed:?}, colour {colour_elapsed:?}, \
|
||||
{} tokens answered",
|
||||
text.len(),
|
||||
data.len() / 5
|
||||
);
|
||||
assert!(!data.is_empty(), "the window really did colour something");
|
||||
assert!(
|
||||
colour_elapsed.as_millis() < COLOUR_BUDGET_MS,
|
||||
"colouring {count} tokens on one line cost {colour_elapsed:?} — \
|
||||
the quadratic conversion is back"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The wall-clock ceiling the test above holds the colourer to, in a
|
||||
/// **debug** build: 4.5x the slowest of the four sizes as measured on the
|
||||
/// machine this was written on (77 ms at 40,000 tokens, ±0.5 ms over
|
||||
/// four runs), where the quadratic version this replaced would need tens
|
||||
/// of seconds.
|
||||
const COLOUR_BUDGET_MS: u128 = 350;
|
||||
|
||||
/// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other*
|
||||
/// fast-path consumer of `Positions`: `references`' hits still have to
|
||||
/// become `lsp_types::Location`s (`Server::large_scan`, `server.rs`), one
|
||||
/// `Positions::range` each. `large::references` itself was always linear;
|
||||
/// the wall was entirely in turning up to [`REFERENCE_LIMIT`] hits on one
|
||||
/// gigantic line into positions — 206 ms → 789 ms → 3.15 s → **12.6 s**
|
||||
/// for 100 → 800 hits (release), against a scan of 0.9 → 6.4 ms.
|
||||
///
|
||||
/// `large_scan` now walks the hits with one `Positions::walker`, which
|
||||
/// they are already in ascending order for. This runs at an eighth of the
|
||||
/// original probe's line lengths so it can live in the normal suite; the
|
||||
/// bound is debug wall-clock and ~4x the measured cost, which a return of
|
||||
/// the per-hit rescan overshoots by two orders of magnitude.
|
||||
#[test]
|
||||
fn references_on_one_giant_line_locate_their_hits_in_linear_time() {
|
||||
use std::time::Instant;
|
||||
for width in [100u32, 200, 400, 800] {
|
||||
// One line: `wire sig;` filler `sig` filler `sig` ... — `width`
|
||||
// occurrences of the needle spread over one line, all comfortably
|
||||
// under REFERENCE_LIMIT so the cap is not what is being timed.
|
||||
let mut text = String::from("wire sig;");
|
||||
for _ in 0..width {
|
||||
text.push_str(&" filler_word ".repeat(250));
|
||||
text.push_str("sig");
|
||||
}
|
||||
text.push('\n');
|
||||
let doc = large(&text);
|
||||
let clock = Instant::now();
|
||||
let hits = references(&doc, 5, true);
|
||||
let scan_elapsed = clock.elapsed();
|
||||
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
|
||||
let positions = doc.positions();
|
||||
let clock2 = Instant::now();
|
||||
// Exactly what `Server::large_scan` does with them.
|
||||
let mut walker = positions.walker();
|
||||
for hit in &hits {
|
||||
std::hint::black_box(walker.range(*hit));
|
||||
}
|
||||
let locate_elapsed = clock2.elapsed();
|
||||
eprintln!(
|
||||
"{width} hits on one {}-byte line: scan {scan_elapsed:?}, locate {locate_elapsed:?}",
|
||||
text.len()
|
||||
);
|
||||
assert!(
|
||||
locate_elapsed.as_millis() < LOCATE_BUDGET_MS,
|
||||
"locating {width} hits on one line cost {locate_elapsed:?} — \
|
||||
the per-hit line rescan is back"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The wall-clock ceiling for the locator above, in a **debug** build:
|
||||
/// 4.7x the slowest of the four sizes as measured on the machine this was
|
||||
/// written on (32 ms at 800 hits on a 2.6 MB line, ±0.2 ms over four
|
||||
/// runs).
|
||||
const LOCATE_BUDGET_MS: u128 = 150;
|
||||
}
|
||||
@@ -0,0 +1,761 @@
|
||||
//! `textDocument/codeLens`: how often the workspace instantiates the module
|
||||
//! written on this line.
|
||||
//!
|
||||
//! One lens per module (and per interface — the same AST node) declared in the
|
||||
//! open buffer, sitting on the declaration's own name so the editor draws it
|
||||
//! on the line above the header. It reads **"N instantiations"**, "1
|
||||
//! instantiation", or "no instantiations", and N is the number of
|
||||
//! instantiation *sites* across the whole workspace — the same population
|
||||
//! `callHierarchy/incomingCalls` reports, counted by the same walk
|
||||
//! ([`hierarchy::callers_of_each`]) so the two can never disagree.
|
||||
//!
|
||||
//! **Clicking.** The lens carries `lucisv.showInstantiations`, run through the
|
||||
//! `workspace/executeCommand` this server already serves. The command answers
|
||||
//! with every site as a `Location`, and — for a client that advertised
|
||||
//! `window/showDocument` — the server pushes a request to open the first of
|
||||
//! them, which is what makes the click actually move a cursor. LSP has no
|
||||
//! server-initiated "peek these seven places"; that is a VS Code command, and
|
||||
//! this repo's extension does not declare one. A module with **no**
|
||||
//! instantiations gets a display-only lens instead (an empty `command`
|
||||
//! string, as rust-analyzer ships for the same case): there is nothing to
|
||||
//! open, and a click that led nowhere would be worse than no click.
|
||||
//!
|
||||
//! See `docs/features/code-lens/README.md`.
|
||||
|
||||
use lsp_types::{CodeLens, Command, Location, Uri};
|
||||
use serde_json::Value;
|
||||
|
||||
use vlog_semantic::instantiations;
|
||||
|
||||
use crate::hierarchy;
|
||||
use crate::state::Workspace;
|
||||
|
||||
/// Show every instantiation of a module: `[module-name]`.
|
||||
pub const SHOW_INSTANTIATIONS: &str = "lucisv.showInstantiations";
|
||||
|
||||
/// Every command this module executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![SHOW_INSTANTIATIONS.to_string()]
|
||||
}
|
||||
|
||||
/// One lens per module or interface declared in the open buffer, counting the
|
||||
/// workspace's instantiations of it.
|
||||
///
|
||||
/// `None` — which the handler sends as `null` — for a buffer this server was
|
||||
/// never shown, matching every other request that answers from a `Document`.
|
||||
/// A buffer that declares nothing the parser could name gets an empty list:
|
||||
/// the file was read, and it has no declarations to decorate.
|
||||
pub fn code_lenses(ws: &Workspace, uri: &Uri) -> Option<Vec<CodeLens>> {
|
||||
let doc = ws.document(uri)?;
|
||||
// A declaration the parser could not name — recovered from broken text,
|
||||
// or reached through an error item — has no span to hang a lens on.
|
||||
let decls: Vec<_> = instantiations::declarations(&doc.tree.items)
|
||||
.into_iter()
|
||||
.filter(|decl| !decl.module.name_span.is_empty())
|
||||
.collect();
|
||||
if decls.is_empty() {
|
||||
// Before the workspace walk: a buffer with nothing to decorate must
|
||||
// not read every file in the project to learn that.
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let names: Vec<&str> = decls.iter().map(|decl| decl.module.name.as_str()).collect();
|
||||
let callers = hierarchy::callers_of_each(ws, &names);
|
||||
let positions = doc.positions();
|
||||
Some(
|
||||
decls
|
||||
.iter()
|
||||
.zip(callers)
|
||||
.map(|(decl, calls)| CodeLens {
|
||||
range: positions.range(decl.module.name_span),
|
||||
command: Some(command(&decl.module.name, sites_in(&calls))),
|
||||
data: None,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Run `lucisv.showInstantiations`: every place the workspace instantiates the
|
||||
/// named module, as locations.
|
||||
///
|
||||
/// One location per **site**, not per instantiating module — that is what the
|
||||
/// lens counted, and a caller that asked to see "7 instantiations" wants seven
|
||||
/// places. A name nothing instantiates answers an empty list rather than an
|
||||
/// error: a module waiting to be used is an ordinary state, and it is the
|
||||
/// state whose lens does not click in the first place.
|
||||
pub fn execute(ws: &Workspace, arguments: &[Value]) -> Result<Vec<Location>, String> {
|
||||
let name =
|
||||
arguments.first().and_then(Value::as_str).filter(|name| !name.is_empty()).ok_or_else(
|
||||
|| format!("{SHOW_INSTANTIATIONS} wants a module name as its first argument."),
|
||||
)?;
|
||||
Ok(sites_of(ws, name))
|
||||
}
|
||||
|
||||
/// Every instantiation of `name` in the workspace, one location per site, in
|
||||
/// the order the hierarchy lists its callers.
|
||||
fn sites_of(ws: &Workspace, name: &str) -> Vec<Location> {
|
||||
hierarchy::callers_of_each(ws, &[name])
|
||||
.pop()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.flat_map(|call| {
|
||||
let uri = call.from.uri;
|
||||
call.from_ranges.into_iter().map(move |range| Location { uri: uri.clone(), range })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many sites one name's incoming calls hold. A caller reports every site
|
||||
/// inside it, so the count is the sum and not the number of callers.
|
||||
fn sites_in(calls: &[lsp_types::CallHierarchyIncomingCall]) -> usize {
|
||||
calls.iter().map(|call| call.from_ranges.len()).sum()
|
||||
}
|
||||
|
||||
/// The lens for one module: what it reads, and what clicking it runs.
|
||||
///
|
||||
/// A module nothing instantiates gets a display-only lens — a `Command` whose
|
||||
/// `command` is the empty string, which clients render as plain text. See the
|
||||
/// module comment for why.
|
||||
fn command(name: &str, sites: usize) -> Command {
|
||||
Command {
|
||||
title: title(sites),
|
||||
command: if sites == 0 { String::new() } else { SHOW_INSTANTIATIONS.to_string() },
|
||||
arguments: (sites > 0).then(|| vec![Value::String(name.to_string())]),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the lens reads, in the user's own arithmetic.
|
||||
fn title(sites: usize) -> String {
|
||||
match sites {
|
||||
0 => "no instantiations".to_string(),
|
||||
1 => "1 instantiation".to_string(),
|
||||
many => format!("{many} instantiations"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use lsp_types::CallHierarchyItem;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch workspace root, removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_lens_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("mkdir");
|
||||
}
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// A workspace over `files`, with the first of them opened as a buffer.
|
||||
fn workspace(name: &str, files: &[(&str, &str)]) -> (Tree, Workspace, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
let mut first = None;
|
||||
for (rel, text) in files {
|
||||
let path = tree.write(rel, text);
|
||||
if first.is_none() {
|
||||
first = Some((path, *text));
|
||||
}
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let (path, text) = first.expect("at least one file");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(tree, ws, uri)
|
||||
}
|
||||
|
||||
/// Every lens of a buffer as `(title, command, start line, start column)`.
|
||||
fn shape(lenses: &[CodeLens]) -> Vec<(String, String, u32, u32)> {
|
||||
lenses
|
||||
.iter()
|
||||
.map(|lens| {
|
||||
let command = lens.command.as_ref().expect("every lens carries a command");
|
||||
(
|
||||
command.title.clone(),
|
||||
command.command.clone(),
|
||||
lens.range.start.line,
|
||||
lens.range.start.character,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Just the titles, for the tests that only care what the user reads.
|
||||
fn titles(lenses: &[CodeLens]) -> Vec<String> {
|
||||
lenses
|
||||
.iter()
|
||||
.map(|lens| lens.command.as_ref().map_or(String::new(), |c| c.title.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
const SUB: &str = "module sub (input logic clk);\nendmodule\n";
|
||||
const TOP: &str = "\
|
||||
module top;
|
||||
sub u_a (.clk(1'b0));
|
||||
sub u_b (.clk(1'b1));
|
||||
endmodule
|
||||
";
|
||||
const OTHER: &str = "module other;\n sub u_c (.clk(1'b0));\nendmodule\n";
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the count
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_lens_counts_every_instantiation_in_the_workspace() {
|
||||
// Three sites across two other files, on a declaration in this one.
|
||||
let (_tree, ws, uri) =
|
||||
workspace("count", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("an open buffer");
|
||||
assert_eq!(titles(&lenses), ["3 instantiations"], "two in top.sv, one in o.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_counts_in_the_users_own_arithmetic() {
|
||||
let alone = "module lonely;\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("zero", &[("lonely.sv", alone)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]);
|
||||
|
||||
let one = "module top;\n lonely u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("one", &[("lonely.sv", alone), ("top.sv", one)]);
|
||||
assert_eq!(
|
||||
titles(&code_lenses(&ws, &uri).expect("open")),
|
||||
["1 instantiation"],
|
||||
"not `1 instantiations`"
|
||||
);
|
||||
|
||||
let two = "module top;\n lonely u1 ();\n lonely u2 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("two", &[("lonely.sv", alone), ("top.sv", two)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_is_exactly_what_incoming_calls_would_list() {
|
||||
// The whole contract between this feature and the hierarchy: a user
|
||||
// who reads "3 instantiations" and then opens the call hierarchy must
|
||||
// be shown three sites.
|
||||
let (_tree, ws, uri) =
|
||||
workspace("agree", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(lenses.len(), 1);
|
||||
|
||||
let item = CallHierarchyItem {
|
||||
name: "sub".to_string(),
|
||||
kind: lsp_types::SymbolKind::MODULE,
|
||||
tags: None,
|
||||
detail: None,
|
||||
uri: uri.clone(),
|
||||
range: lenses[0].range,
|
||||
selection_range: lenses[0].range,
|
||||
data: None,
|
||||
};
|
||||
let listed: usize =
|
||||
hierarchy::incoming(&ws, &item).iter().map(|call| call.from_ranges.len()).sum();
|
||||
assert_eq!(titles(&lenses), [format!("{listed} instantiations")]);
|
||||
assert_eq!(listed, 3, "and the number itself is the one we meant");
|
||||
// And the command shows exactly those sites.
|
||||
assert_eq!(execute(&ws, &[Value::String("sub".to_string())]).expect("runs").len(), listed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it() {
|
||||
// The same rule `callHierarchy/incomingCalls` applies: a site with no
|
||||
// enclosing module has no caller to report, so it is nobody's edge.
|
||||
let (_tree, ws, uri) =
|
||||
workspace("filescope", &[("sub.sv", SUB), ("loose.sv", "sub u_loose ();\n")]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["no instantiations"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// which declarations get a lens, and where it sits
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_lens_sits_on_the_declarations_own_name() {
|
||||
// The client draws a lens on the line *above* `range.start`, so the
|
||||
// name span is what puts it over the header and nowhere else.
|
||||
let (_tree, ws, uri) = workspace("span", &[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(
|
||||
shape(&lenses),
|
||||
[("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7)],
|
||||
"column 7 is `sub`, not the `module` keyword"
|
||||
);
|
||||
assert_eq!(lenses[0].range.end.character, 10, "the name only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_is_a_module_declaration_and_gets_its_own_lens() {
|
||||
let bus = "interface bus;\n logic clk;\nendinterface\n";
|
||||
let user = "module top;\n bus u_bus ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("iface", &[("bus.sv", bus), ("top.sv", user)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_module_in_a_file_gets_its_own_lens_in_source_order() {
|
||||
let many = "\
|
||||
module first;
|
||||
endmodule
|
||||
|
||||
module second;
|
||||
endmodule
|
||||
|
||||
module third;
|
||||
endmodule
|
||||
";
|
||||
let uses = "module top;\n third u3 ();\n first u1 ();\n third u3b ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("many", &[("many.sv", many), ("top.sv", uses)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(
|
||||
shape(&lenses),
|
||||
[
|
||||
("1 instantiation".to_string(), SHOW_INSTANTIATIONS.to_string(), 0, 7),
|
||||
("no instantiations".to_string(), String::new(), 3, 7),
|
||||
("2 instantiations".to_string(), SHOW_INSTANTIATIONS.to_string(), 6, 7),
|
||||
],
|
||||
"source order, one per declaration"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_nothing_instantiates_gets_a_lens_that_does_not_click() {
|
||||
let (_tree, ws, uri) =
|
||||
workspace("noclick", &[("lonely.sv", "module lonely;\nendmodule\n")]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
let command = lenses[0].command.as_ref().expect("a command");
|
||||
assert_eq!(command.title, "no instantiations");
|
||||
assert_eq!(command.command, "", "display-only: there is nothing to open");
|
||||
assert_eq!(command.arguments, None, "and nothing to pass");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clickable_lens_carries_the_module_name_as_its_only_argument() {
|
||||
let (_tree, ws, uri) = workspace("args", &[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
let command = lenses[0].command.as_ref().expect("a command");
|
||||
assert_eq!(command.command, SHOW_INSTANTIATIONS);
|
||||
assert_eq!(command.arguments, Some(vec![Value::String("sub".to_string())]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_lens_is_ever_left_for_a_resolve_to_fill_in() {
|
||||
// `resolveProvider: false` is advertised, so a lens without a command
|
||||
// would be a lens the client can never complete.
|
||||
let (_tree, ws, uri) = workspace("complete", &[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert!(lenses.iter().all(|lens| lens.command.is_some() && lens.data.is_none()));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the refusals
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_buffer_this_server_was_never_shown_has_no_lenses_at_all() {
|
||||
let (tree, ws, _) = workspace("closed", &[("sub.sv", SUB)]);
|
||||
let never = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert!(code_lenses(&ws, &never).is_none(), "null, not an empty list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_declares_no_module_gets_an_empty_list() {
|
||||
let (_tree, ws, uri) = workspace("nomodules", &[("p.sv", "package p;\nendpackage\n")]);
|
||||
assert_eq!(code_lenses(&ws, &uri).expect("open"), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic() {
|
||||
let junk = ")))) not verilog ((((\n@@@ endmodule : ;\n";
|
||||
let (_tree, ws, uri) = workspace("junk", &[("junk.sv", junk)]);
|
||||
assert_eq!(
|
||||
code_lenses(&ws, &uri).expect("open"),
|
||||
Vec::new(),
|
||||
"total, whatever it parses to"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_the_parser_could_not_name_gets_no_lens() {
|
||||
// `module ;` recovers into a declaration with an empty name span,
|
||||
// which is a lens with no line to sit on.
|
||||
let broken = "module ;\nendmodule\n\nmodule fine;\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("unnamed", &[("broken.sv", broken)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert!(
|
||||
lenses.iter().all(|lens| lens.range.start.line == 3),
|
||||
"only the named declaration: {lenses:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the command
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_command_answers_one_location_per_site() {
|
||||
let (_tree, ws, _) =
|
||||
workspace("sites", &[("sub.sv", SUB), ("top.sv", TOP), ("o.sv", OTHER)]);
|
||||
let locations = execute(&ws, &[Value::String("sub".to_string())]).expect("runs");
|
||||
let shape: Vec<(String, u32, u32)> = locations
|
||||
.iter()
|
||||
.map(|at| {
|
||||
(
|
||||
at.uri.as_str().rsplit('/').next().unwrap_or("?").to_string(),
|
||||
at.range.start.line,
|
||||
at.range.start.character,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
shape,
|
||||
[
|
||||
("o.sv".to_string(), 1, 2),
|
||||
("top.sv".to_string(), 1, 2),
|
||||
("top.sv".to_string(), 2, 2),
|
||||
],
|
||||
"every site, sorted by file then position"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_answers_nothing_for_a_module_nothing_instantiates() {
|
||||
let (_tree, ws, _) = workspace("nosites", &[("lonely.sv", "module lonely;\nendmodule\n")]);
|
||||
assert_eq!(execute(&ws, &[Value::String("lonely".to_string())]), Ok(Vec::new()));
|
||||
assert_eq!(
|
||||
execute(&ws, &[Value::String("never-heard-of-it".to_string())]),
|
||||
Ok(Vec::new()),
|
||||
"a name the workspace does not declare is not an error either"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_declines_arguments_it_cannot_read() {
|
||||
let (_tree, ws, _) = workspace("badargs", &[("sub.sv", SUB)]);
|
||||
for arguments in [vec![], vec![Value::Null], vec![Value::String(String::new())]] {
|
||||
let message = execute(&ws, &arguments).expect_err("declined");
|
||||
assert!(message.contains("module name"), "{message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_list_is_what_the_server_advertises() {
|
||||
assert_eq!(commands(), vec![SHOW_INSTANTIATIONS]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26): count-honesty shapes the fixture above never
|
||||
// exercises — a multi-instance statement, self-recursion, name
|
||||
// collisions (within one file and across files), generate replication
|
||||
// and an `ifdef`-guarded instantiation. None of these turned out to
|
||||
// disagree with `hierarchy::incoming` — they can't, since `lens.rs` and
|
||||
// `hierarchy::incoming` both bottom out in the same
|
||||
// `hierarchy::callers_of_each` — but the *number itself* is worth
|
||||
// pinning so a future change to what counts as a "site" is visible here
|
||||
// too, not just in `hierarchy.rs`. See QA log in
|
||||
// `docs/features/code-lens/README.md`.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_corpus_counts_agree_with_grep_derived_ground_truth() {
|
||||
// `corpus/common_cells/src/cdc_fifo_gray.sv` declares three modules.
|
||||
// Ground truth by hand, `grep -rnE '\bNAME\b' corpus --include='*.sv'
|
||||
// --include='*.svh'`, read line by line to exclude the declaration
|
||||
// itself and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has
|
||||
// several, e.g. line 56's "In contrast to the cdc_fifo_gray
|
||||
// version..."):
|
||||
// - `cdc_fifo_gray` — one real instantiation,
|
||||
// `common_cells/test/cdc_fifo_tb.sv:49` (`i_dut`).
|
||||
// - `cdc_fifo_gray_src` — one, `cdc_fifo_gray.sv:130`, inside
|
||||
// `cdc_fifo_gray` itself (`_src_clearable` is a different name
|
||||
// and does not match `\bcdc_fifo_gray_src\b`).
|
||||
// - `cdc_fifo_gray_dst` — one, `cdc_fifo_gray.sv:145`, likewise.
|
||||
// Skipped like the other corpus tests when `corpus/` is not checked
|
||||
// out (`tools/corpus_fetch.sh`).
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
|
||||
let Ok(text) = fs::read_to_string(&file) else {
|
||||
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let uri = path_to_uri(&file).expect("uri");
|
||||
ws.set_document(uri.clone(), text);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(
|
||||
titles(&lenses),
|
||||
["1 instantiation", "1 instantiation", "1 instantiation"],
|
||||
"cdc_fifo_gray, cdc_fifo_gray_src, cdc_fifo_gray_dst, in that source order: {lenses:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_multi_instance_statement_is_one_site_not_two() {
|
||||
// `sub u1 (), u2 ();` is ONE `Instantiation` AST node carrying TWO
|
||||
// `Instance` entries — physically two instantiations of `sub` in the
|
||||
// design. This is not a code-lens decision: `hierarchy.rs`'s own
|
||||
// documented assumption ("One `Instantiation` is one call site,
|
||||
// however many instances it declares") already settles it, the same
|
||||
// way `textDocument/references` reports the module name once. Pinned
|
||||
// here too so a change to that policy is visible in both features.
|
||||
let top = "module top;\n sub u1 (), u2 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_multi", &[("sub.sv", SUB), ("top.sv", top)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(titles(&lenses), ["1 instantiation"], "one AST node, not two instances");
|
||||
let locs = execute(&ws, &[Value::String("sub".to_string())]).expect("runs");
|
||||
assert_eq!(locs.len(), 1, "one location for the one site: {locs:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_module_that_instantiates_itself_counts_its_own_instantiation() {
|
||||
// Self-recursion (illegal to elaborate, legal text) is handled the
|
||||
// same way `hierarchy.rs` handles an `a -> b -> a` cycle: each
|
||||
// request answers one hop, so there is nothing here that could ever
|
||||
// recurse or hang.
|
||||
let text = "module m;\n m u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_recursive", &[("m.sv", text)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(titles(&lenses), ["1 instantiation"]);
|
||||
let locs = execute(&ws, &[Value::String("m".to_string())]).expect("runs");
|
||||
assert_eq!(locs.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both() {
|
||||
// The census is by name (documented in this README's Assumptions):
|
||||
// an instantiation of `m` cannot say which of two `module m`
|
||||
// declarations it meant, so both lenses read the workspace-wide
|
||||
// total rather than a partitioned one. Same limitation
|
||||
// `callHierarchy/incomingCalls` already has, for the same reason.
|
||||
let m_a = "module m;\n logic a;\nendmodule\n";
|
||||
let m_b = "module m;\n logic b;\nendmodule\n";
|
||||
let user = "module top;\n m u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri_a) =
|
||||
workspace("qa_collide_a", &[("a/m.sv", m_a), ("b/m.sv", m_b), ("top.sv", user)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri_a).expect("open a/m.sv")), ["1 instantiation"]);
|
||||
|
||||
// Same workspace, opening the OTHER declaration instead: same total.
|
||||
let mut ws_b = Workspace::default();
|
||||
let tree_b = Tree::new("qa_collide_b");
|
||||
tree_b.write("a/m.sv", m_a);
|
||||
let path_b = tree_b.write("b/m.sv", m_b);
|
||||
tree_b.write("top.sv", user);
|
||||
ws_b.open_whole_workspace(vec![tree_b.path.clone()]);
|
||||
let uri_b = path_to_uri(&path_b).expect("uri");
|
||||
ws_b.set_document(uri_b.clone(), m_b.to_string());
|
||||
assert_eq!(
|
||||
titles(&code_lenses(&ws_b, &uri_b).expect("open b/m.sv")),
|
||||
["1 instantiation"],
|
||||
"the other declaration reads the same total, not zero"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count() {
|
||||
// The tolerant parser accepts `module m; endmodule module m;
|
||||
// endmodule` in one file (real SystemVerilog forbids it, but this is
|
||||
// reachable through broken input). The batch in
|
||||
// `hierarchy::callers_of_each` is asked `["m", "m"]` — two indices,
|
||||
// not deduplicated — so this also pins that duplicate names in one
|
||||
// batch do not alias or corrupt each other's answer.
|
||||
let text = "module m;\nendmodule\n\nmodule m;\nendmodule\n";
|
||||
let user = "module top;\n m u1 ();\nendmodule\n";
|
||||
let (_tree, ws, uri) = workspace("qa_dup_same_file", &[("m.sv", text), ("top.sv", user)]);
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
assert_eq!(lenses.len(), 2, "one lens per declaration");
|
||||
assert_eq!(titles(&lenses), ["1 instantiation", "1 instantiation"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_generate_replicated_instantiation_counts_the_written_statement_once() {
|
||||
// `generate for` is not elaborated: the AST has exactly one
|
||||
// `Instantiation` node inside the loop body regardless of the
|
||||
// genvar's range, matching `hierarchy.rs`'s own documented handling
|
||||
// of the identical shape (`incoming_calls_reach_generate_regions_...`
|
||||
// in `hierarchy.rs`). Four elaborated instances at synthesis time,
|
||||
// one textual site here — the lens counts text, not hardware.
|
||||
let sub = "module sub;\nendmodule\n";
|
||||
let top = "\
|
||||
module top;
|
||||
generate
|
||||
for (genvar i = 0; i < 4; i++) begin : g
|
||||
sub u1 ();
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri) = workspace("qa_generate", &[("sub.sv", sub), ("top.sv", top)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["1 instantiation"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_ifdef_guarded_instantiation_counts_both_arms() {
|
||||
// Inherited from `hierarchy.rs`, disclosed there as an Assumption:
|
||||
// the parser does not evaluate `` `ifdef``/`` `else``, so both arms
|
||||
// land as ordinary `Instantiation` items and both are counted, even
|
||||
// though only one is ever really built. Pinned here too since the
|
||||
// lens is a second, more prominent surface for the same policy.
|
||||
let sub = "module sub;\nendmodule\n";
|
||||
let top = "\
|
||||
module top;
|
||||
`ifdef FOO
|
||||
sub u1 ();
|
||||
`endif
|
||||
sub u2 ();
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri) = workspace("qa_ifdef", &[("sub.sv", sub), ("top.sv", top)]);
|
||||
assert_eq!(titles(&code_lenses(&ws, &uri).expect("open")), ["2 instantiations"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the performance claim, measured
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The number the round's Handshake was filed for, measured: what a whole
|
||||
/// file's lenses cost before the edge table (a walk of every in-scope
|
||||
/// file, re-read and re-parsed) and what they cost after (a lookup).
|
||||
///
|
||||
/// `#[ignore]`d like the other measurement probes in this crate — it prints
|
||||
/// a number rather than asserting one, and the assertion that must hold is
|
||||
/// `code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk`
|
||||
/// above. Run with `cargo test -p lucisv_server -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn qa_perf_lens_lookup_against_the_walk_it_replaced() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
|
||||
let Ok(text) = fs::read_to_string(&file) else {
|
||||
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let uri = path_to_uri(&file).expect("uri");
|
||||
ws.set_document(uri.clone(), text);
|
||||
let _ = code_lenses(&ws, &uri);
|
||||
|
||||
let mut lenses = std::time::Duration::ZERO;
|
||||
let mut walk = std::time::Duration::ZERO;
|
||||
for _ in 0..3 {
|
||||
let started = std::time::Instant::now();
|
||||
let _ = code_lenses(&ws, &uri).expect("open");
|
||||
lenses = lenses.max(started.elapsed());
|
||||
// What `callers_of_each` used to begin with, every request.
|
||||
let started = std::time::Instant::now();
|
||||
let _ = ws.sources();
|
||||
walk = walk.max(started.elapsed());
|
||||
}
|
||||
eprintln!(
|
||||
"codeLens over {} files: {lenses:?} for the whole file; one workspace walk \
|
||||
(what the old census re-read on every request) is {walk:?}",
|
||||
ws.index().files().len()
|
||||
);
|
||||
}
|
||||
|
||||
/// What a whole file's lenses cost over the real corpus, against what one
|
||||
/// workspace walk costs.
|
||||
///
|
||||
/// **Superseded this round (incremental-index, 2026-08-27):**
|
||||
/// `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted
|
||||
/// `whole_file < one_name * 2` — that asking about three modules cost about
|
||||
/// what asking about one did, because both were *one walk* of the whole
|
||||
/// workspace. There is no walk any more: the count is a lookup in the
|
||||
/// index's instantiation-edge table, and the only I/O left is reading the
|
||||
/// handful of files that really do instantiate one of the three. Both sides
|
||||
/// of that ratio are now microseconds dominated by a file read each, so the
|
||||
/// ratio pins noise. The property worth pinning is the stronger one this
|
||||
/// round bought: **a whole file's lenses cost a small fraction of one
|
||||
/// workspace walk**, measured here rather than asserted.
|
||||
///
|
||||
/// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`),
|
||||
/// like the other corpus tests. The budget is deliberately loose: a debug
|
||||
/// build on a loaded machine is the worst case this ever runs in, and this
|
||||
/// exists to catch an order-of-magnitude regression — a lens handler that
|
||||
/// went back to re-reading the workspace would fail it by two.
|
||||
#[test]
|
||||
fn code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
// A real file declaring three modules, so the batch has something to
|
||||
// amortize over.
|
||||
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
|
||||
let Ok(text) = fs::read_to_string(&file) else {
|
||||
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let uri = path_to_uri(&file).expect("uri");
|
||||
ws.set_document(uri.clone(), text);
|
||||
|
||||
// Warm, then the worst of three, for the whole file and for one name;
|
||||
// and the best of three for the walk it used to be, so the comparison
|
||||
// is stacked against the claim rather than for it.
|
||||
let _ = code_lenses(&ws, &uri);
|
||||
let mut whole_file = std::time::Duration::ZERO;
|
||||
let mut one_name = std::time::Duration::ZERO;
|
||||
let mut walk = std::time::Duration::MAX;
|
||||
let mut count = 0;
|
||||
for _ in 0..3 {
|
||||
let started = std::time::Instant::now();
|
||||
let lenses = code_lenses(&ws, &uri).expect("open");
|
||||
whole_file = whole_file.max(started.elapsed());
|
||||
count = lenses.len();
|
||||
let started = std::time::Instant::now();
|
||||
let _ = sites_of(&ws, "cdc_fifo_gray");
|
||||
one_name = one_name.max(started.elapsed());
|
||||
let started = std::time::Instant::now();
|
||||
let _ = ws.sources();
|
||||
walk = walk.min(started.elapsed());
|
||||
}
|
||||
eprintln!(
|
||||
"corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \
|
||||
(one name alone: {one_name:?}; one workspace walk: {walk:?})",
|
||||
ws.index().files().len(),
|
||||
);
|
||||
assert!(count >= 3, "the file declares three modules: {count}");
|
||||
assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}");
|
||||
assert!(
|
||||
whole_file * 10 < walk,
|
||||
"the lens is a lookup, not a walk: {count} names cost {whole_file:?} against \
|
||||
{walk:?} for one walk of the workspace"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,912 @@
|
||||
//! `textDocument/linkedEditingRange`: a closing label edits with the name it
|
||||
//! repeats.
|
||||
//!
|
||||
//! SystemVerilog writes a declaration's name twice whenever it closes with a
|
||||
//! label — `module m ... endmodule : m`, `function f ... endfunction : f`,
|
||||
//! `begin : blk ... end : blk`. Linked editing is the protocol's answer to
|
||||
//! exactly that shape: the server hands back the set of ranges holding the
|
||||
//! same name, and the editor applies every keystroke to all of them, so the
|
||||
//! two halves cannot drift apart while the user types.
|
||||
//!
|
||||
//! **The pair is a node, never a text match.** Every construct served below
|
||||
//! records both spans on one AST node (`name_span` and `end_label_span`), so
|
||||
//! the answer is a lookup and not a search. That is what makes
|
||||
//! `begin : x begin : x ... end : x end : x` — four byte-identical names —
|
||||
//! resolve to the *syntactic* partner rather than to the nearest one.
|
||||
//!
|
||||
//! **Two refusals, both `null`.** A closing label is optional in SV, so a bare
|
||||
//! `endmodule` has nothing to co-edit and gets no ranges: this feature never
|
||||
//! offers to create a label. And a *mismatched* label
|
||||
//! (`module m ... endmodule : wrong`) is declined too, because the spec
|
||||
//! requires the linked ranges to contain identical text — linking them would
|
||||
//! silently rewrite one half into the other on the user's next keystroke,
|
||||
//! which is an edit nobody asked for. Rules and the constructs the tree cannot
|
||||
//! reach: `docs/features/linked-editing/README.md`.
|
||||
|
||||
use lsp_types::LinkedEditingRanges;
|
||||
use vlog_parser::ast::{
|
||||
ClassDecl, ClockingDecl, FunctionDecl, GenBlock, GenElse, GenIf, Item, ItemKind, Module, Stmt,
|
||||
StmtKind, TaskDecl,
|
||||
};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// What a client may type into a linked range and keep the link.
|
||||
///
|
||||
/// Sent rather than left to the client's own language word pattern: an SV
|
||||
/// identifier admits `$` after its first character (IEEE 1800 §5.6), and an
|
||||
/// editor's default word pattern for an unknown language id does not — so a
|
||||
/// user typing `foo$bar` would watch the link drop halfway. The pattern is
|
||||
/// anchored at both ends and deliberately says nothing about escaped
|
||||
/// identifiers, which [`is_simple_identifier`] declines outright.
|
||||
const WORD_PATTERN: &str = "^[A-Za-z_][A-Za-z0-9_$]*$";
|
||||
|
||||
/// The header name and the closing label that repeats it, when the cursor is
|
||||
/// on either of them.
|
||||
///
|
||||
/// `None` — which the handler sends as `null` — for every other position, for
|
||||
/// a construct that wrote no closing label, and for the two shapes that must
|
||||
/// not be linked: a label that does not match its header, and a name that is
|
||||
/// not a plain identifier.
|
||||
pub fn linked_editing_ranges(doc: &Document, offset: u32) -> Option<LinkedEditingRanges> {
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
let pair = pairs.into_iter().find(|pair| pair.covers(offset))?;
|
||||
if !pair.is_linkable(&doc.text) {
|
||||
return None;
|
||||
}
|
||||
let positions = doc.positions();
|
||||
Some(LinkedEditingRanges {
|
||||
ranges: vec![positions.range(pair.open), positions.range(pair.close)],
|
||||
word_pattern: Some(WORD_PATTERN.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
/// One construct's two name occurrences, in source order.
|
||||
struct Pair {
|
||||
/// The name in the header: `m` of `module m`, `blk` of `begin : blk`.
|
||||
open: TextRange,
|
||||
/// The same name after the closer's `:`.
|
||||
close: TextRange,
|
||||
}
|
||||
|
||||
impl Pair {
|
||||
/// Whether the cursor is on either name.
|
||||
///
|
||||
/// One byte past the end counts, as it does for
|
||||
/// [`crate::pairs::highlights`]: an editor leaves the caret after the
|
||||
/// character just typed, and a link that switched off at `m|` would be
|
||||
/// gone exactly while the user is renaming. Two label occurrences are
|
||||
/// always separated by at least a keyword, so the extra byte can never
|
||||
/// claim a neighbouring name.
|
||||
fn covers(&self, offset: u32) -> bool {
|
||||
let touches = |span: TextRange| offset >= span.start && offset <= span.end;
|
||||
touches(self.open) || touches(self.close)
|
||||
}
|
||||
|
||||
/// Whether these two ranges may be edited as one.
|
||||
///
|
||||
/// Both conditions are the protocol's: the ranges must hold identical
|
||||
/// text, and what the user types into them must stay describable by
|
||||
/// [`WORD_PATTERN`].
|
||||
fn is_linkable(&self, text: &str) -> bool {
|
||||
let (Some(open), Some(close)) =
|
||||
(text.get(self.open.as_range()), text.get(self.close.as_range()))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
open == close && is_simple_identifier(open)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a name is a plain SV identifier — the charset [`WORD_PATTERN`]
|
||||
/// describes.
|
||||
///
|
||||
/// This is what excludes an escaped identifier (`\my$odd.name `), whose extent
|
||||
/// depends on a trailing space that no word pattern can express. Rather than
|
||||
/// send a pattern a client could use to corrupt the escape, such a pair is
|
||||
/// simply not offered.
|
||||
fn is_simple_identifier(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
match chars.next() {
|
||||
Some(first) if first == '_' || first.is_ascii_alphabetic() => {}
|
||||
_ => return false,
|
||||
}
|
||||
chars.all(|c| c == '_' || c == '$' || c.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
/// Push a pair when the construct wrote both halves. An absent closing label
|
||||
/// is the common case and means there is nothing to link.
|
||||
fn push(open: Option<TextRange>, close: Option<TextRange>, out: &mut Vec<Pair>) {
|
||||
if let (Some(open), Some(close)) = (open, close) {
|
||||
if !open.is_empty() && !close.is_empty() {
|
||||
out.push(Pair { open, close });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn items_pairs(items: &[Item], out: &mut Vec<Pair>) {
|
||||
for item in items {
|
||||
item_pairs(item, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => module_pairs(m, out),
|
||||
ItemKind::Package { name_span, end_label_span, items, .. } => {
|
||||
push(Some(*name_span), *end_label_span, out);
|
||||
items_pairs(items, out);
|
||||
}
|
||||
ItemKind::Class(c) => class_pairs(c, out),
|
||||
ItemKind::Function(f) => function_pairs(f, out),
|
||||
ItemKind::Task(t) => task_pairs(t, out),
|
||||
ItemKind::Clocking(c) => clocking_pairs(c, out),
|
||||
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
|
||||
ItemKind::GenIf(g) => gen_if_pairs(g, out),
|
||||
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
for arm in &g.items {
|
||||
gen_block_pairs(&arm.body, out);
|
||||
}
|
||||
}
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
stmt_pairs(stmt, out);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn module_pairs(m: &Module, out: &mut Vec<Pair>) {
|
||||
push(Some(m.name_span), m.end_label_span, out);
|
||||
items_pairs(&m.items, out);
|
||||
}
|
||||
|
||||
fn class_pairs(c: &ClassDecl, out: &mut Vec<Pair>) {
|
||||
push(Some(c.name_span), c.end_label_span, out);
|
||||
items_pairs(&c.items, out);
|
||||
}
|
||||
|
||||
fn function_pairs(f: &FunctionDecl, out: &mut Vec<Pair>) {
|
||||
push(Some(f.name_span), f.end_label_span, out);
|
||||
stmts_pairs(&f.stmts, out);
|
||||
}
|
||||
|
||||
fn task_pairs(t: &TaskDecl, out: &mut Vec<Pair>) {
|
||||
push(Some(t.name_span), t.end_label_span, out);
|
||||
stmts_pairs(&t.stmts, out);
|
||||
}
|
||||
|
||||
/// `clocking cb @(posedge clk); ... endclocking : cb`. The anonymous
|
||||
/// `default clocking @(...)` form has no name at all, so it pairs nothing.
|
||||
fn clocking_pairs(c: &ClockingDecl, out: &mut Vec<Pair>) {
|
||||
push(c.name.as_ref().map(|n| n.span), c.end_label_span, out);
|
||||
}
|
||||
|
||||
fn gen_if_pairs(gen_if: &GenIf, out: &mut Vec<Pair>) {
|
||||
gen_block_pairs(&gen_if.then, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
gen_block_pairs(&nested.then, out);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
gen_block_pairs(block, out);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_block_pairs(block: &GenBlock, out: &mut Vec<Pair>) {
|
||||
push(block.label_span, block.end_label_span, out);
|
||||
items_pairs(&block.items, out);
|
||||
}
|
||||
|
||||
fn stmts_pairs(list: &[Stmt], out: &mut Vec<Pair>) {
|
||||
for stmt in list {
|
||||
stmt_pairs(stmt, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement half of the walk.
|
||||
///
|
||||
/// The recursion is bounded by the parser's own nesting limit
|
||||
/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it
|
||||
/// built.
|
||||
fn stmt_pairs(stmt: &Stmt, out: &mut Vec<Pair>) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { label_span, end_label_span, stmts, .. }
|
||||
| StmtKind::ForkJoin { label_span, end_label_span, stmts, .. } => {
|
||||
push(*label_span, *end_label_span, out);
|
||||
stmts_pairs(stmts, out);
|
||||
}
|
||||
// `blk : begin ... end : blk` (IEEE 1800 §9.3.5): the name is written
|
||||
// before the keyword, so the parser puts it on this node and leaves
|
||||
// the block's own label empty. Still one syntactic pair — the LRM
|
||||
// requires the end label to name this statement — but only when the
|
||||
// block wrote no label of its own. Writing both is illegal, and the
|
||||
// block's own pair has already been pushed by the recursion below.
|
||||
StmtKind::Labeled { name_span, stmt: inner, .. } => {
|
||||
if let Some(close) = prefix_labelled_end(inner) {
|
||||
push(Some(*name_span), Some(close), out);
|
||||
}
|
||||
stmt_pairs(inner, out);
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
stmt_pairs(then, out);
|
||||
if let Some(els) = els.as_deref() {
|
||||
stmt_pairs(els, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for item in items {
|
||||
stmt_pairs(&item.stmt, out);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => stmt_pairs(body, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
stmt_pairs(inner, out)
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
if let Some(then) = then.as_deref() {
|
||||
stmt_pairs(then, out);
|
||||
}
|
||||
if let Some(els) = els.as_deref() {
|
||||
stmt_pairs(els, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The closing label of a block named *before* its keyword, or `None` when the
|
||||
/// statement is not such a block.
|
||||
fn prefix_labelled_end(stmt: &Stmt) -> Option<TextRange> {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { label: None, end_label_span, .. }
|
||||
| StmtKind::ForkJoin { label: None, end_label_span, .. } => *end_label_span,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
fn doc_of(text: &str) -> Document {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
/// The byte offset of `needle`'s first occurrence.
|
||||
fn at(text: &str, needle: &str) -> u32 {
|
||||
text.find(needle).expect("needle present") as u32
|
||||
}
|
||||
|
||||
/// The byte offset just past `prefix` — how a fixture points at a name
|
||||
/// whose own spelling occurs earlier in the text (`m` of `module m`).
|
||||
fn at_after(text: &str, prefix: &str) -> u32 {
|
||||
at(text, prefix) + prefix.len() as u32
|
||||
}
|
||||
|
||||
/// The byte offset just past the *last* `prefix`. Every fixture below
|
||||
/// writes its closing label as the file's last `": "`, so this is where
|
||||
/// that label starts.
|
||||
fn at_last_after(text: &str, prefix: &str) -> u32 {
|
||||
text.rfind(prefix).expect("needle present") as u32 + prefix.len() as u32
|
||||
}
|
||||
|
||||
/// The answer's ranges as `(line, start character, end character)`, which
|
||||
/// is enough to say which occurrence each one is.
|
||||
fn linked(text: &str, offset: u32) -> Option<Vec<(u32, u32, u32)>> {
|
||||
let doc = doc_of(text);
|
||||
let answer = linked_editing_ranges(&doc, offset)?;
|
||||
assert_eq!(
|
||||
answer.word_pattern.as_deref(),
|
||||
Some(WORD_PATTERN),
|
||||
"every answer carries the SV word pattern"
|
||||
);
|
||||
Some(
|
||||
answer
|
||||
.ranges
|
||||
.iter()
|
||||
.map(|r| (r.start.line, r.start.character, r.end.character))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// every construct that ships
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn every_labeled_construct_links_its_two_names() {
|
||||
// Each fixture writes its name twice and nowhere else, and its closing
|
||||
// label is the last `": "` in the text.
|
||||
let cases = [
|
||||
("module m;\nendmodule : m\n", "module ", "module"),
|
||||
("macromodule m;\nendmodule : m\n", "macromodule ", "macromodule"),
|
||||
("interface bus_if;\nendinterface : bus_if\n", "interface ", "interface"),
|
||||
("package p;\nendpackage : p\n", "package ", "package"),
|
||||
("class c;\nendclass : c\n", "class ", "class"),
|
||||
("module m;\n function f;\n endfunction : f\nendmodule\n", "function ", "function"),
|
||||
("module m;\n task t;\n endtask : t\nendmodule\n", "task ", "task"),
|
||||
(
|
||||
"module m;\n initial begin : blk\n end : blk\nendmodule\n",
|
||||
"begin : ",
|
||||
"named begin",
|
||||
),
|
||||
("module m;\n initial fork : frk\n join : frk\nendmodule\n", "fork : ", "named fork"),
|
||||
(
|
||||
concat!(
|
||||
"module m;\n",
|
||||
" generate\n",
|
||||
" for (genvar i = 0; i < 2; i++) begin : g\n",
|
||||
" wire w;\n",
|
||||
" end : g\n",
|
||||
" endgenerate\n",
|
||||
"endmodule\n",
|
||||
),
|
||||
"begin : ",
|
||||
"generate block",
|
||||
),
|
||||
(
|
||||
"interface i;\n clocking cb @(posedge clk);\n endclocking : cb\nendinterface\n",
|
||||
"clocking ",
|
||||
"clocking",
|
||||
),
|
||||
(
|
||||
"module m;\n initial pre : begin\n end : pre\nendmodule\n",
|
||||
"initial ",
|
||||
"prefix-labelled begin",
|
||||
),
|
||||
];
|
||||
for (text, header, what) in cases {
|
||||
let from_label = linked(text, at_last_after(text, ": "))
|
||||
.unwrap_or_else(|| panic!("{what}: the closing label answered nothing at all"));
|
||||
assert_eq!(from_label.len(), 2, "{what}: exactly two ranges");
|
||||
let from_header = linked(text, at_after(text, header))
|
||||
.unwrap_or_else(|| panic!("{what}: the header name answered nothing"));
|
||||
assert_eq!(from_label, from_header, "{what}: both directions answer the same pair");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// where the cursor is
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_cursor_may_sit_anywhere_in_either_name() {
|
||||
let text = "module wide;\nendmodule : wide\n";
|
||||
let header = at_after(text, "module ");
|
||||
let label = at_last_after(text, ": ");
|
||||
let expected = linked(text, header).expect("the header answers");
|
||||
assert_eq!(expected, vec![(0, 7, 11), (1, 12, 16)]);
|
||||
for (offset, what) in [
|
||||
(header, "header start"),
|
||||
(header + 2, "header middle"),
|
||||
(header + 4, "header end, one past the last byte"),
|
||||
(label, "label start"),
|
||||
(label + 2, "label middle"),
|
||||
(label + 4, "label end, one past the last byte"),
|
||||
] {
|
||||
assert_eq!(linked(text, offset).as_ref(), Some(&expected), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_beside_the_names_answers_nothing() {
|
||||
let text = "module m;\nendmodule : m\n";
|
||||
assert!(linked(text, 0).is_none(), "the `module` keyword itself");
|
||||
assert!(linked(text, at(text, " m;")).is_none(), "the space before the name");
|
||||
assert!(linked(text, at(text, ";") + 1).is_none(), "past the semicolon");
|
||||
assert!(linked(text, at(text, "endmodule")).is_none(), "the closing keyword");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_past_the_end_of_the_file_answers_nothing() {
|
||||
let text = "module m;\nendmodule : m\n";
|
||||
assert!(linked(text, text.len() as u32).is_none());
|
||||
assert!(linked(text, text.len() as u32 + 1_000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_buffer_answers_nothing() {
|
||||
assert!(linked("", 0).is_none());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the two refusals
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_unlabeled_closer_links_nothing() {
|
||||
// The label is optional in SV, and its absence is not an invitation to
|
||||
// create one: there is no second range, so there is no answer.
|
||||
for (text, header) in [
|
||||
("module m;\nendmodule\n", "module "),
|
||||
("package p;\nendpackage\n", "package "),
|
||||
("class c;\nendclass\n", "class "),
|
||||
("module m;\n function f;\n endfunction\nendmodule\n", "function "),
|
||||
("module m;\n task t;\n endtask\nendmodule\n", "task "),
|
||||
("module m;\n initial begin : blk\n end\nendmodule\n", "begin : "),
|
||||
] {
|
||||
assert!(linked(text, at_after(text, header)).is_none(), "{text:?} must link nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mismatched_label_links_nothing() {
|
||||
// Broken code. Linking the two would rewrite one half into the other
|
||||
// on the next keystroke — an edit the user never asked for — and the
|
||||
// spec requires the ranges to hold identical text anyway.
|
||||
let text = "module m;\nendmodule : wrong\n";
|
||||
assert!(linked(text, at_after(text, "module ")).is_none(), "from the header");
|
||||
assert!(linked(text, at(text, "wrong")).is_none(), "and from the label");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_label_differing_only_in_case_links_nothing() {
|
||||
let text = "module Data;\nendmodule : data\n";
|
||||
assert!(linked(text, at(text, "Data")).is_none());
|
||||
assert!(linked(text, at(text, "data")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_identifier_links_nothing() {
|
||||
// `\odd.name ` is an identifier whose extent depends on a trailing
|
||||
// space, which no word pattern can describe. Both halves matching does
|
||||
// not make it safe to hand a client.
|
||||
let text = "module \\odd.name ;\nendmodule : \\odd.name \n";
|
||||
let doc = doc_of(text);
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
assert_eq!(pairs.len(), 1, "premise: the tree really did record the pair");
|
||||
assert!(linked(text, at(text, "\\odd.name")).is_none(), "from the header");
|
||||
assert!(
|
||||
linked(text, text.rfind("\\odd.name").expect("label") as u32).is_none(),
|
||||
"and back"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_simple_identifier_accepts_exactly_the_word_pattern() {
|
||||
for good in ["m", "_x", "a1", "foo$bar", "A_b$9", "_"] {
|
||||
assert!(is_simple_identifier(good), "{good} is a plain SV identifier");
|
||||
}
|
||||
for bad in ["", "1a", "$x", "\\odd.name", "a b", "a.b", "é"] {
|
||||
assert!(!is_simple_identifier(bad), "{bad:?} is not");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// nesting — the pair must be the syntactic one
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn nested_blocks_answer_their_own_pair() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" initial begin : outer\n",
|
||||
" begin : inner\n",
|
||||
" x = 1;\n",
|
||||
" end : inner\n",
|
||||
" end : outer\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let outer = linked(text, at(text, "outer")).expect("the outer header answers");
|
||||
assert_eq!(outer, vec![(1, 18, 23), (5, 8, 13)], "line 1 header, line 5 label");
|
||||
let inner = linked(text, at(text, "inner")).expect("the inner header answers");
|
||||
assert_eq!(inner, vec![(2, 12, 17), (4, 10, 15)], "line 2 header, line 4 label");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_names_at_different_nesting_pair_syntactically() {
|
||||
// The evil fixture: four byte-identical names, two pairs. A
|
||||
// nearest-same-text rule would pair the outer header with the *inner*
|
||||
// label, because that one is nearer. The pair comes off the AST node,
|
||||
// so it cannot.
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" initial begin : x\n",
|
||||
" begin : x\n",
|
||||
" y = 1;\n",
|
||||
" end : x\n",
|
||||
" end : x\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let outer_header = at_after(text, "begin : ");
|
||||
let inner_header =
|
||||
text.match_indices("begin : ").nth(1).expect("the inner block").0 as u32 + 8;
|
||||
let outer = linked(text, outer_header).expect("the outer header answers");
|
||||
assert_eq!(outer, vec![(1, 18, 19), (5, 8, 9)], "outer header pairs with the OUTER end");
|
||||
let inner = linked(text, inner_header).expect("the inner header answers");
|
||||
assert_eq!(inner, vec![(2, 12, 13), (4, 10, 11)], "inner header pairs with the INNER end");
|
||||
assert_ne!(outer, inner);
|
||||
// And from each closing label, back to the same two pairs.
|
||||
let inner_label = text.match_indices("end : ").next().expect("the inner end").0 as u32 + 6;
|
||||
let outer_label = at_last_after(text, "end : ");
|
||||
assert_eq!(linked(text, inner_label), Some(inner));
|
||||
assert_eq!(linked(text, outer_label), Some(outer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_and_the_function_inside_it_are_separate_pairs() {
|
||||
// The function is deliberately named `m` too.
|
||||
let text = "module m;\n function m;\n endfunction : m\nendmodule : m\n";
|
||||
let module = linked(text, at_after(text, "module ")).expect("the module header answers");
|
||||
assert_eq!(module, vec![(0, 7, 8), (3, 12, 13)], "module header, endmodule label");
|
||||
let function =
|
||||
linked(text, at_after(text, "function ")).expect("the function header answers");
|
||||
assert_eq!(function, vec![(1, 11, 12), (2, 16, 17)], "function header, endfunction label");
|
||||
assert_ne!(module, function);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_method_pairs_inside_its_class() {
|
||||
let text = "class c;\n function void f();\n endfunction : f\nendclass : c\n";
|
||||
let class = linked(text, at_after(text, "class ")).expect("the class answers");
|
||||
assert_eq!(class, vec![(0, 6, 7), (3, 11, 12)]);
|
||||
let method = linked(text, at(text, "f()")).expect("the method answers");
|
||||
assert_eq!(method, vec![(1, 16, 17), (2, 16, 17)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_block_inside_a_generate_for_pairs() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" generate\n",
|
||||
" for (genvar i = 0; i < 2; i++) begin : g\n",
|
||||
" initial begin : inner\n",
|
||||
" end : inner\n",
|
||||
" end : g\n",
|
||||
" endgenerate\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let gen = linked(text, at(text, "g\n")).expect("the generate label answers");
|
||||
assert_eq!(gen, vec![(2, 43, 44), (5, 10, 11)]);
|
||||
let inner = linked(text, at(text, "inner")).expect("the inner block answers");
|
||||
assert_eq!(inner, vec![(3, 22, 27), (4, 12, 17)]);
|
||||
assert_ne!(gen, inner);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// UTF-16 positions
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_multibyte_comment_before_the_name_does_not_shift_it() {
|
||||
// SV identifiers are ASCII, but everything around them need not be.
|
||||
// The characters are counted in UTF-16 units, so `é` (2 bytes, 1 unit)
|
||||
// and `🎉` (4 bytes, 2 units) must not move the name's column.
|
||||
let text = "// café 🎉\nmodule m;\nendmodule : m\n";
|
||||
let ranges = linked(text, at_after(text, "module ")).expect("the header answers");
|
||||
assert_eq!(ranges, vec![(1, 7, 8), (2, 12, 13)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multibyte_comment_on_the_same_line_keeps_the_columns_honest() {
|
||||
let text = "module m; // 🎉 party\nendmodule : m // café\n";
|
||||
let ranges = linked(text, at_last_after(text, ": ")).expect("the label answers");
|
||||
assert_eq!(ranges, vec![(0, 7, 8), (1, 12, 13)]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// buffers that do not parse
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_lex_answers_nothing() {
|
||||
let text = "module m;\n wire a; /* unterminated\n";
|
||||
let doc = doc_of(text);
|
||||
assert!(doc.tokens.is_empty(), "premise: the lexer gave up");
|
||||
assert!(linked_editing_ranges(&doc, at_after(text, "module ")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_typed_construct_answers_nothing_rather_than_guessing() {
|
||||
let text = "module m;\n initial begin : blk\nendmodule\n";
|
||||
assert!(linked(text, at(text, "blk")).is_none(), "no closing label was written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pair_written_after_a_broken_item_still_answers() {
|
||||
// Error recovery keeps the items it could parse, so a mistake early in
|
||||
// the file must not un-link everything below it.
|
||||
let text = "module a;\n @@@ ;\nendmodule\nmodule b;\nendmodule : b\n";
|
||||
let ranges = linked(text, at_after(text, "module b")).expect("the second module answers");
|
||||
assert_eq!(ranges.len(), 2);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the answer's own shape
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_two_ranges_hold_identical_text_and_never_overlap() {
|
||||
let text = "module top;\n initial begin : blk\n end : blk\nendmodule : top\n";
|
||||
let doc = doc_of(text);
|
||||
for offset in [at(text, "top") + 1, at(text, "blk") + 1] {
|
||||
let answer = linked_editing_ranges(&doc, offset).expect("a pair");
|
||||
assert_eq!(answer.ranges.len(), 2);
|
||||
let (first, second) = (answer.ranges[0], answer.ranges[1]);
|
||||
assert!(
|
||||
(first.end.line, first.end.character) < (second.start.line, second.start.character),
|
||||
"the header comes first and the two do not overlap: {answer:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
first.end.character - first.start.character,
|
||||
second.end.character - second.start.character,
|
||||
"identical length"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26) — the prefix-label gate, and the ranges' exact bytes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every offset in `0..=text.len()` answers without panicking, and every
|
||||
/// `Some` answer holds two identical-text, non-overlapping ranges. The
|
||||
/// blanket check the targeted tests below narrow in on one fixture at a
|
||||
/// time — kept here because a tolerant-parser fixture is exactly the kind
|
||||
/// of input where a hand-picked offset can miss what a sweep finds.
|
||||
fn assert_total_and_sane(text: &str) {
|
||||
let doc = doc_of(text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let Some(answer) = linked_editing_ranges(&doc, offset) else { continue };
|
||||
assert_eq!(answer.ranges.len(), 2, "{text:?} at {offset}: {answer:?}");
|
||||
assert_eq!(
|
||||
answer.word_pattern.as_deref(),
|
||||
Some(WORD_PATTERN),
|
||||
"{text:?} at {offset}: word pattern missing"
|
||||
);
|
||||
let (a, b) = (answer.ranges[0], answer.ranges[1]);
|
||||
let (before, after) =
|
||||
if (a.start.line, a.start.character) <= (b.start.line, b.start.character) {
|
||||
(a, b)
|
||||
} else {
|
||||
(b, a)
|
||||
};
|
||||
assert!(
|
||||
(before.end.line, before.end.character)
|
||||
<= (after.start.line, after.start.character),
|
||||
"{text:?} at {offset}: ranges overlap: {answer:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_named_both_ways_answers_only_the_blocks_own_pair() {
|
||||
// `x : begin : y ... end : y` is illegal SV (IEEE 1800 §9.3.5: a block
|
||||
// is named one way or the other), but the tolerant parser accepts it
|
||||
// — the block wrote its own label, so `Labeled`'s prefix-label gate
|
||||
// (`prefix_labelled_end`, only fires when the block wrote no label of
|
||||
// its own) must stay silent and the block's own (y, y) pair, not a
|
||||
// fabricated (x, y), must be what answers.
|
||||
let text = "module m;\n initial x : begin : y\n z = 1;\n end : y\nendmodule\n";
|
||||
assert_total_and_sane(text);
|
||||
let y_pair = linked(text, at(text, "y")).expect("the block's own label pairs");
|
||||
assert_eq!(y_pair.len(), 2);
|
||||
assert_eq!(linked(text, text.rfind('y').expect("closing y") as u32), Some(y_pair));
|
||||
// `x` is not part of any pair: the prefix label was correctly not
|
||||
// linked to anything.
|
||||
assert!(linked(text, at(text, "x")).is_none(), "the unused prefix label links nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched() {
|
||||
// `x : begin ... end : y` — the block wrote no label of its own, so
|
||||
// the prefix-label gate does fire and pushes (x, y). The two names
|
||||
// differ, so this must still answer null, the same as any other
|
||||
// mismatch — the gate firing is not itself a promise of a match.
|
||||
let text = "module m;\n initial x : begin\n z = 1;\n end : y\nendmodule\n";
|
||||
assert_total_and_sane(text);
|
||||
assert!(linked(text, at(text, "x")).is_none(), "mismatched prefix pair: from x");
|
||||
assert!(linked(text, at(text, "y")).is_none(), "mismatched prefix pair: from y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_second_end_label_after_the_block_already_closed_is_inert() {
|
||||
// Two `end : x` for one `begin : x`. The first one closes the block;
|
||||
// the second is leftover tokens the item-level recovery has to make
|
||||
// sense of on its own. Whatever it becomes, it must not create a
|
||||
// second, wrong pairing, and it must not make the walk panic.
|
||||
let text = "module m;\n initial begin : x\n z = 1;\n end : x\n end : x\nendmodule\n";
|
||||
assert_total_and_sane(text);
|
||||
let doc = doc_of(text);
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
assert_eq!(pairs.len(), 1, "the stray `end : x` must not mint a second pair");
|
||||
// The pair that does exist closes on the FIRST `end : x`, not the
|
||||
// second — the leftover tokens answer nothing at all.
|
||||
let first_end = text.find("end : x").expect("first end");
|
||||
let second_end = text.rfind("end : x").expect("second end");
|
||||
assert_ne!(first_end, second_end);
|
||||
assert!(
|
||||
linked(text, second_end as u32 + 6).is_none(),
|
||||
"the leftover end : x links nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_and_unclosed_labeled_constructs_never_panic() {
|
||||
for text in [
|
||||
"module m;\n initial begin : blk\n z = 1;\nendmodule\n", // `end` missing
|
||||
"module m;\n initial begin : blk\n z = 1;\n", // no closer at all, EOF
|
||||
"module m;\n initial begin : \n end : \nendmodule\n", // label written, no name
|
||||
"module m;\n initial begin :\n end\nendmodule\n", // colon, no name, no close label
|
||||
] {
|
||||
assert_total_and_sane(text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_closing_labels_never_bleed_into_each_other() {
|
||||
// `endfunction : f` immediately followed by `endmodule : m` on the
|
||||
// next line: the "name spans never touch" claim, checked at the exact
|
||||
// boundary a lexer could in principle blur.
|
||||
let text = "module m;\n function f;\n endfunction : f\nendmodule : m\n";
|
||||
assert_total_and_sane(text);
|
||||
let f = linked(text, at(text, "f;")).expect("the function pairs");
|
||||
let m = linked(text, at_after(text, "module ")).expect("the module pairs");
|
||||
assert_ne!(f, m);
|
||||
}
|
||||
|
||||
/// The ranges cover exactly the identifier's bytes — never the `:`, never
|
||||
/// the surrounding whitespace or a comment written between them. An
|
||||
/// off-by-one here would let a client's keystroke land on the colon.
|
||||
#[test]
|
||||
fn ranges_cover_exactly_the_identifier_never_the_colon_or_comment() {
|
||||
let cases: [(&str, &str, &str); 3] = [
|
||||
("module m;\nendmodule : /*c*/ m\n", "module ", "m"),
|
||||
("module m;\n initial begin:x\n end:x\nendmodule\n", "begin:", "x"),
|
||||
("module m;\n initial begin :\n x\n end :\n x\nendmodule\n", "begin :\n ", "x"),
|
||||
];
|
||||
for (text, header_prefix, want) in cases {
|
||||
let doc = doc_of(text);
|
||||
let answer = linked_editing_ranges(&doc, at_after(text, header_prefix))
|
||||
.unwrap_or_else(|| panic!("{text:?}: the header answers"));
|
||||
let positions = doc.positions();
|
||||
// Decode each `Range` back to a byte span via the same
|
||||
// `Positions::offset` the server itself uses to turn a client
|
||||
// position into an offset, and check it covers exactly the name
|
||||
// — not the colon, not a space, not the comment beside it.
|
||||
for range in &answer.ranges {
|
||||
let start = positions.offset(range.start) as usize;
|
||||
let end = positions.offset(range.end) as usize;
|
||||
assert_eq!(&text[start..end], want, "{text:?}: range {range:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// corpus sweep — real RTL, every offset, machine-checked invariants
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every offset of a handful of real corpus files that write closing
|
||||
/// labels: totality (no panic), and every `Some` answer's two ranges hold
|
||||
/// identical text and do not overlap. Skipped when `corpus/` is not
|
||||
/// checked out, like every other corpus test in this crate.
|
||||
#[test]
|
||||
fn a_corpus_sweep_of_labeled_constructs_is_total_and_sane() {
|
||||
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let files = [
|
||||
"common_cells/src/lzc.sv",
|
||||
"common_cells/src/rr_arb_tree.sv",
|
||||
"common_cells/src/popcount.sv",
|
||||
"common_cells/src/cdc_reset_ctrlr.sv",
|
||||
"common_cells/src/deprecated/rrarbiter.sv",
|
||||
"common_cells/src/deprecated/prioarbiter.sv",
|
||||
"common_cells/src/stream_fifo_optimal_wrap.sv",
|
||||
"common_cells/src/stream_throttle.sv",
|
||||
"ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv",
|
||||
"ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_monitor.sv",
|
||||
"opentitan/hw/ip/uart/dv/env/seq_lib/uart_base_vseq.sv",
|
||||
];
|
||||
let mut files_checked = 0;
|
||||
let mut pairs_found = 0;
|
||||
for name in files {
|
||||
let path = corpus.join(name);
|
||||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||||
eprintln!("{} not checked out — skipping", path.display());
|
||||
continue;
|
||||
};
|
||||
assert!(
|
||||
text.contains("end") && text.contains(':'),
|
||||
"{}: premise, this file should write a closing label",
|
||||
path.display()
|
||||
);
|
||||
let doc = doc_of(&text);
|
||||
let mut file_pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut file_pairs);
|
||||
pairs_found += file_pairs.len();
|
||||
let positions = doc.positions();
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let Some(answer) = linked_editing_ranges(&doc, offset) else { continue };
|
||||
assert_eq!(answer.ranges.len(), 2, "{}: {answer:?}", path.display());
|
||||
let (a, b) = (answer.ranges[0], answer.ranges[1]);
|
||||
let a_text =
|
||||
&text[positions.offset(a.start) as usize..positions.offset(a.end) as usize];
|
||||
let b_text =
|
||||
&text[positions.offset(b.start) as usize..positions.offset(b.end) as usize];
|
||||
assert_eq!(
|
||||
a_text,
|
||||
b_text,
|
||||
"{}: at {offset}, ranges hold different text",
|
||||
path.display()
|
||||
);
|
||||
assert!(
|
||||
is_simple_identifier(a_text),
|
||||
"{}: at {offset}, {a_text:?} is not a plain identifier",
|
||||
path.display()
|
||||
);
|
||||
assert!(
|
||||
(a.end.line, a.end.character) <= (b.start.line, b.start.character)
|
||||
|| (b.end.line, b.end.character) <= (a.start.line, a.start.character),
|
||||
"{}: at {offset}, ranges overlap: {answer:?}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
files_checked += 1;
|
||||
}
|
||||
assert!(files_checked > 5, "the corpus really is checked out: {files_checked} files");
|
||||
assert!(
|
||||
pairs_found > 10,
|
||||
"these files really do write closing labels: {pairs_found} pairs"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing() {
|
||||
let text = "module m;\n initial begin : blk\n end : blk\nendmodule\n";
|
||||
for (offset, what) in [
|
||||
(at(text, ": blk"), "the colon before the header's `blk`"),
|
||||
(at(text, ": blk") + 1, "the space after that colon"),
|
||||
(at(text, " end"), "the indentation before `end`, between the two names"),
|
||||
] {
|
||||
// A position strictly on the colon or on whitespace — never on a
|
||||
// letter of `blk` itself — answers nothing, even with `blk`
|
||||
// close by on both sides.
|
||||
assert!(linked(text, offset).is_none(), "{what}: {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_of_a_whole_file_finds_every_construct_once() {
|
||||
let text = concat!(
|
||||
"package p;\n",
|
||||
"endpackage : p\n",
|
||||
"module m;\n",
|
||||
" function f;\n",
|
||||
" endfunction : f\n",
|
||||
" task t;\n",
|
||||
" endtask : t\n",
|
||||
" initial begin : blk\n",
|
||||
" end : blk\n",
|
||||
"endmodule : m\n",
|
||||
);
|
||||
let doc = doc_of(text);
|
||||
let mut pairs = Vec::new();
|
||||
items_pairs(&doc.tree.items, &mut pairs);
|
||||
assert_eq!(pairs.len(), 5, "package, module, function, task, named begin");
|
||||
// And every one of them is reachable from either of its own names.
|
||||
for pair in &pairs {
|
||||
assert!(linked_editing_ranges(&doc, pair.open.start).is_some());
|
||||
assert!(linked_editing_ranges(&doc, pair.close.start).is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,17 +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 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> {
|
||||
let text = ws.text_of(path)?;
|
||||
Some(LineIndex::new(&text).line_col(offset).0)
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
return Some(doc.line_index.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,29 +10,41 @@ mod candidates;
|
||||
mod code_action;
|
||||
mod completion;
|
||||
mod convert;
|
||||
mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod file_ops;
|
||||
mod folding;
|
||||
mod format;
|
||||
mod hierarchy;
|
||||
mod hover;
|
||||
mod includes;
|
||||
mod index_cache;
|
||||
mod inlay;
|
||||
mod inline;
|
||||
mod instantiations;
|
||||
mod large;
|
||||
mod lens;
|
||||
mod linked;
|
||||
mod lint;
|
||||
mod locate;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
#[cfg(test)]
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod selection;
|
||||
mod server;
|
||||
mod settings;
|
||||
mod signature;
|
||||
mod state;
|
||||
mod symbols;
|
||||
mod sync;
|
||||
mod templates;
|
||||
mod tokens;
|
||||
mod type_def;
|
||||
mod type_hierarchy;
|
||||
mod uri;
|
||||
mod watch;
|
||||
|
||||
@@ -42,20 +54,62 @@ use std::path::PathBuf;
|
||||
use lsp_server::Connection;
|
||||
use lsp_types::{
|
||||
CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability,
|
||||
CompletionOptions, DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability,
|
||||
InitializeParams, InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind,
|
||||
RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
|
||||
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions,
|
||||
CodeLensOptions, CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities,
|
||||
DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions,
|
||||
FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
|
||||
InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind,
|
||||
RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions,
|
||||
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
|
||||
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
|
||||
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
|
||||
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
|
||||
};
|
||||
|
||||
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()?;
|
||||
// Read before the typed decode, because `lsp-types` 0.97's client
|
||||
// capabilities have no field for it and drop it on the floor — see
|
||||
// `ranges_formatting_support`.
|
||||
let ranges_formatting = ranges_formatting_support(¶ms);
|
||||
// Read from the raw params for the same reason, and because it is not a
|
||||
// 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();
|
||||
@@ -63,14 +117,56 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let abilities = ClientAbilities {
|
||||
snippets: snippet_support(¶ms),
|
||||
file_watching: watch::dynamic_registration(¶ms),
|
||||
apply_edit: apply_edit_support(¶ms),
|
||||
pull_diagnostics: pull_diagnostics_support(¶ms),
|
||||
work_done_progress: work_done_progress_support(¶ms),
|
||||
code_lens_refresh: code_lens_refresh_support(¶ms),
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
};
|
||||
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
Server::new(connection, roots, abilities).run()?;
|
||||
// The message loop parses every buffer it is handed, so it does not run
|
||||
// on the main thread: that stack is whatever the OS and `ulimit -s` left
|
||||
// it, and the parser's nesting limit only turns over-deep input into a
|
||||
// diagnostic above `PARSE_STACK_SIZE` (below it the overflow aborts the
|
||||
// whole server, taking the editor session with it). Nothing else here
|
||||
// parses — `lsp-server`'s reader and writer threads move JSON, and the
|
||||
// forwarder in `Server::queue` moves messages.
|
||||
std::thread::Builder::new()
|
||||
.name("lucisv-main".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.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.
|
||||
@@ -79,10 +175,54 @@ fn capabilities() -> ServerCapabilities {
|
||||
// The protocol default, and what the conversion in `convert.rs`
|
||||
// implements. Stated rather than left implicit.
|
||||
position_encoding: Some(PositionEncodingKind::UTF16),
|
||||
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
|
||||
// Incremental sync: a keystroke costs one range, not the whole file.
|
||||
// Spelled out as options rather than a bare kind because a bare kind
|
||||
// says nothing about open/close or save, and clients fill that in
|
||||
// themselves — this states the same defaults a bare kind resolved to,
|
||||
// so nothing but `change` moves. `includeText: false` keeps a save
|
||||
// from re-sending a buffer the server already tracks edit by edit;
|
||||
// the `didSave` handler still honours text if a client sends it.
|
||||
text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
|
||||
open_close: Some(true),
|
||||
change: Some(TextDocumentSyncKind::INCREMENTAL),
|
||||
// The plain `willSave` notification carries nothing this server
|
||||
// can act on, so it is left unadvertised; `willSaveWaitUntil` is
|
||||
// the format-on-save hook, for the editors that have no
|
||||
// format-on-save of their own. It answers `null` unless
|
||||
// `lucisv.formatOnSave` is on — see
|
||||
// `docs/features/will-save-wait-until/README.md`.
|
||||
will_save: None,
|
||||
will_save_wait_until: Some(true),
|
||||
save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
|
||||
include_text: Some(false),
|
||||
})),
|
||||
})),
|
||||
document_formatting_provider: Some(OneOf::Left(true)),
|
||||
document_range_formatting_provider: Some(OneOf::Left(true)),
|
||||
// Two trigger characters, and only two. A newline re-indents the line
|
||||
// it opened; a `;` lays out the statement it ended, through the range
|
||||
// engine. Not `}` — SV closes its blocks with the *word* `end`, and
|
||||
// re-triggering on letters would run this on half of every identifier.
|
||||
// Advertised unconditionally: on-type formatting only fires where the
|
||||
// client's own `editor.formatOnType` is on, which is off by default,
|
||||
// so the user has already opted in by the time a request arrives. See
|
||||
// `docs/features/on-type-formatting/README.md`.
|
||||
document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
|
||||
first_trigger_character: on_type::NEWLINE.to_string(),
|
||||
more_trigger_character: Some(vec![on_type::SEMICOLON.to_string()]),
|
||||
}),
|
||||
definition_provider: Some(OneOf::Left(true)),
|
||||
// The same jump one token to the left: from a name to where its type
|
||||
// is declared. `Simple(true)` rather than a registration — there is
|
||||
// nothing to scope it to that `definitionProvider` is not already
|
||||
// scoped to. See `docs/features/type-definition/README.md`.
|
||||
type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
|
||||
// SV's closing labels, edited as one name: `module m` and
|
||||
// `endmodule : m` change together. `Simple(true)` rather than a
|
||||
// registration — there is nothing to scope it to, and the handler
|
||||
// declines every position that is not one of the two names. See
|
||||
// `docs/features/linked-editing/README.md`.
|
||||
linked_editing_range_provider: Some(LinkedEditingRangeServerCapabilities::Simple(true)),
|
||||
references_provider: Some(OneOf::Left(true)),
|
||||
// `` `include`` lines, underlined and ctrl-clickable. Every link is
|
||||
// returned with its target already resolved, so there is nothing for
|
||||
@@ -125,11 +265,19 @@ fn capabilities() -> ServerCapabilities {
|
||||
})),
|
||||
// The port refactorings. `lucisv.addPort` needs a declaration typed by
|
||||
// the user, which no code action can carry, and a Vim user has no
|
||||
// lightbulb at all — so all three are commands as well.
|
||||
// lightbulb at all — so all three are commands as well. The code
|
||||
// lens's own jump joins them: a lens carries a `Command`, and this is
|
||||
// where a command has to be declared to be runnable.
|
||||
execute_command_provider: Some(ExecuteCommandOptions {
|
||||
commands: ports::commands(),
|
||||
commands: commands(),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
}),
|
||||
// "N instantiations" over every module and interface declaration in
|
||||
// the buffer, counted across the workspace. Every lens is returned
|
||||
// complete — title, command and arguments — so there is nothing for
|
||||
// `codeLens/resolve` to do, which is said out loud rather than left
|
||||
// unset. See `docs/features/code-lens/README.md`.
|
||||
code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(false) }),
|
||||
// Module hinting. No trigger characters: an identifier being typed is
|
||||
// what asks for these, and the handler declines every position that is
|
||||
// not a module item, so an unprompted request costs a token scan.
|
||||
@@ -172,6 +320,43 @@ fn capabilities() -> ServerCapabilities {
|
||||
// sends the request after opting into `ProposedFeatures`, so an
|
||||
// extension older than this server simply never asks.
|
||||
inline_completion_provider: Some(OneOf::Left(true)),
|
||||
// Expand-selection. Nothing to configure: the chain is computed from
|
||||
// the buffer alone, and every position is answered.
|
||||
selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
|
||||
// Pull diagnostics (3.17), served from the same parse+lint pass the
|
||||
// push model publishes. `inter_file_dependencies` because a save
|
||||
// rebuilds the workspace index and *that* changes what other files
|
||||
// report; `workspace_diagnostics` because `workspace/diagnostic` is
|
||||
// answered — over the open buffers, which is the only scope this
|
||||
// server has ever diagnosed.
|
||||
diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
|
||||
identifier: Some(diagnostics::SOURCE.to_string()),
|
||||
inter_file_dependencies: true,
|
||||
workspace_diagnostics: true,
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
})),
|
||||
// File operations (3.16): renaming a header rewrites the
|
||||
// `` `include``s that resolve to it, and a rename or a delete nudges
|
||||
// the index without waiting for the watcher round-trip. Advertised
|
||||
// unconditionally — unlike the watchers, nothing here is
|
||||
// server-initiated, so a client that cannot send these requests simply
|
||||
// never sends them and the capability costs it nothing. See
|
||||
// `docs/features/file-operations/README.md`.
|
||||
workspace: Some(WorkspaceServerCapabilities {
|
||||
// Workspace folders, added and removed mid-session. Both halves
|
||||
// are needed and neither implies the other: `supported` says the
|
||||
// server understands a multi-folder workspace at all, and
|
||||
// `changeNotifications` is what makes the client *send*
|
||||
// `didChangeWorkspaceFolders`. `Left(true)` rather than an id —
|
||||
// the string form exists so the registration can later be undone
|
||||
// by name, and this server never unregisters it. See
|
||||
// `docs/features/folders-and-config/README.md`.
|
||||
workspace_folders: Some(WorkspaceFoldersServerCapabilities {
|
||||
supported: Some(true),
|
||||
change_notifications: Some(OneOf::Left(true)),
|
||||
}),
|
||||
file_operations: Some(file_ops::file_operations()),
|
||||
}),
|
||||
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
|
||||
SemanticTokensOptions {
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
@@ -179,14 +364,62 @@ fn capabilities() -> ServerCapabilities {
|
||||
token_types: tokens::token_types(),
|
||||
token_modifiers: tokens::token_modifiers(),
|
||||
},
|
||||
range: None,
|
||||
full: Some(SemanticTokensFullOptions::Bool(true)),
|
||||
// The visible lines, for the first paint of a large file:
|
||||
// the same tokenizer, filtered, and re-encoded from the
|
||||
// start of the document so the answer stands on its own.
|
||||
range: Some(true),
|
||||
// `delta: true` rather than a bare `full: true`, so a client
|
||||
// that has an answer already asks what changed instead of
|
||||
// re-fetching the file's whole token set on every keystroke.
|
||||
// `full` itself stays served — the enum's `Delta` variant is
|
||||
// the full capability plus deltas, not a replacement.
|
||||
full: Some(SemanticTokensFullOptions::Delta { delta: Some(true) }),
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command this server executes: the three port refactorings, and the
|
||||
/// jump the code lens hangs off.
|
||||
fn commands() -> Vec<String> {
|
||||
let mut commands = ports::commands();
|
||||
commands.extend(lens::commands());
|
||||
commands
|
||||
}
|
||||
|
||||
/// The `initialize` result exactly as it goes on the wire.
|
||||
///
|
||||
/// Two capabilities are written in here rather than in [`capabilities`],
|
||||
/// because `lsp-types` 0.97 cannot spell either:
|
||||
///
|
||||
/// * **`typeHierarchyProvider`** — the crate models type hierarchy on the
|
||||
/// *client* side only, so `ServerCapabilities` has no field for it, and
|
||||
/// `experimental` is a different key that no client reads for this.
|
||||
/// * **`documentRangeFormattingProvider`** widened to
|
||||
/// `{ "rangesSupport": true }` when `ranges_formatting` — the crate's
|
||||
/// `DocumentRangeFormattingOptions` carries only `workDoneProgress`. This is
|
||||
/// the spec's own `boolean | DocumentRangeFormattingOptions` union, so the
|
||||
/// object form is legal for any client; it is sent only to a client that
|
||||
/// asked because the bare `true` is the shape no client can misread, and a
|
||||
/// client that did not ask will never send the request anyway. See
|
||||
/// `docs/features/lsp-318-extras/README.md`.
|
||||
///
|
||||
/// Both are the same JSON a field would have produced.
|
||||
fn initialize_value(ranges_formatting: bool) -> Result<serde_json::Value, serde_json::Error> {
|
||||
let mut value = serde_json::to_value(initialize_result())?;
|
||||
if let Some(caps) = value.get_mut("capabilities").and_then(serde_json::Value::as_object_mut) {
|
||||
caps.insert("typeHierarchyProvider".to_string(), serde_json::Value::Bool(true));
|
||||
if ranges_formatting {
|
||||
caps.insert(
|
||||
"documentRangeFormattingProvider".to_string(),
|
||||
serde_json::json!({ "rangesSupport": true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn initialize_result() -> lsp_types::InitializeResult {
|
||||
lsp_types::InitializeResult {
|
||||
capabilities: capabilities(),
|
||||
@@ -200,6 +433,44 @@ fn initialize_result() -> lsp_types::InitializeResult {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the client can send `textDocument/rangesFormatting` (LSP 3.18),
|
||||
/// read from the **raw** `initialize` params.
|
||||
///
|
||||
/// It has to be the raw JSON: `lsp-types` 0.97 aliases
|
||||
/// `DocumentRangeFormattingClientCapabilities` to the plain dynamic-registration
|
||||
/// struct, which has no `rangesSupport` field and no place to keep an unknown
|
||||
/// one, so by the time the params are an `InitializeParams` the flag is gone.
|
||||
/// Anything that is not literally `true` at
|
||||
/// `capabilities.textDocument.rangeFormatting.rangesSupport` — absent, `false`,
|
||||
/// a string, a client whose params do not parse at all — means no, which is
|
||||
/// exactly the answer that leaves that client's capability where it was.
|
||||
fn ranges_formatting_support(params: &serde_json::Value) -> bool {
|
||||
params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true
|
||||
}
|
||||
|
||||
/// The folder the client set aside for this workspace's server state —
|
||||
/// `initializationOptions.storagePath`, which the VS Code extension fills in
|
||||
/// with `context.storageUri`.
|
||||
///
|
||||
/// The persistent index cache goes here when there is one: it is
|
||||
/// per-workspace, the editor cleans it up when the workspace is forgotten,
|
||||
/// and it needs no guess about where this platform keeps caches. A client
|
||||
/// that sends nothing — every client but ours, and ours before this — leaves
|
||||
/// the OS cache directory to decide
|
||||
/// (`docs/features/index-persistence/README.md`). A blank value counts as
|
||||
/// unset, the same reading `lucisv.serverPath` gives a blank setting.
|
||||
fn storage_path(params: &serde_json::Value) -> Option<PathBuf> {
|
||||
let path = params["initializationOptions"]["storagePath"].as_str()?;
|
||||
(!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
|
||||
@@ -216,6 +487,114 @@ fn snippet_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
/// result — which is what every client got before this was read, and is the
|
||||
/// only thing left to try for one that cannot be pushed an edit.
|
||||
fn apply_edit_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.apply_edit)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client lets the *server* cancel a semantic-tokens request —
|
||||
/// `textDocument.semanticTokens.serverCancelSupport`.
|
||||
///
|
||||
/// The large-file fast path declines `semanticTokens/full`, and this decides
|
||||
/// with which error code: `ServerCancelled` for a client that says it
|
||||
/// understands one (the spec restricts that code to requests "that explicitly
|
||||
/// support being server cancellable", and this capability is how a client
|
||||
/// says so), `ContentModified` for one that does not. Both leave
|
||||
/// `vscode-languageclient` throwing a `CancellationError`, which is what keeps
|
||||
/// the range provider alive — see
|
||||
/// `docs/features/large-file-mode/README.md`.
|
||||
fn token_server_cancel_support(params: &InitializeParams) -> bool {
|
||||
params.capabilities.text_document.as_ref().is_some_and(|text_document| {
|
||||
text_document
|
||||
.semantic_tokens
|
||||
.as_ref()
|
||||
.is_some_and(|tokens| tokens.server_cancel_support == Some(true))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the client pulls diagnostics (LSP 3.17).
|
||||
///
|
||||
/// Sending the capability at all is what says so; its two fields are about
|
||||
/// dynamic registration and related documents, neither of which this server
|
||||
/// uses. A client that says nothing keeps the push model unchanged.
|
||||
fn pull_diagnostics_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.is_some_and(|text_document| text_document.diagnostic.is_some())
|
||||
}
|
||||
|
||||
/// Whether the client renders server-initiated work-done progress.
|
||||
///
|
||||
/// The spec forbids a server from creating progress at all without this, so a
|
||||
/// client that said nothing is sent no `window/workDoneProgress/create` and no
|
||||
/// `$/progress` — the workspace rescan is silent for it, exactly as it was
|
||||
/// before this was read.
|
||||
fn work_done_progress_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.window
|
||||
.as_ref()
|
||||
.and_then(|window| window.work_done_progress)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can be asked to re-request its code lenses.
|
||||
///
|
||||
/// `workspace/codeLens/refresh` is server-initiated, so the spec makes this
|
||||
/// capability the gate. A client that said nothing keeps whatever counts it
|
||||
/// last asked for until something else makes it ask again — which is what
|
||||
/// every client got before code lenses existed at all.
|
||||
fn code_lens_refresh_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.code_lens.as_ref())
|
||||
.and_then(|code_lens| code_lens.refresh_support)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client opens a document the server asks it to.
|
||||
///
|
||||
/// This is what makes the instantiation lens actually navigate: an
|
||||
/// `executeCommand` result cannot move a cursor, so the jump is a pushed
|
||||
/// `window/showDocument`. A client that did not advertise it still gets the
|
||||
/// sites back as the command's result.
|
||||
fn show_document_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.window
|
||||
.as_ref()
|
||||
.and_then(|window| window.show_document.as_ref())
|
||||
.is_some_and(|show_document| show_document.support)
|
||||
}
|
||||
|
||||
/// Whether the client answers `workspace/configuration`.
|
||||
///
|
||||
/// The pull half of the settings model: a client that says so is asked for
|
||||
/// the `lucisv` section at startup and again whenever it sends an empty
|
||||
/// `didChangeConfiguration`. A client that said nothing is only ever pushed
|
||||
/// settings, exactly as before.
|
||||
fn configuration_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.configuration)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The directories to index: the client's workspace folders, or the
|
||||
/// deprecated single root when that is all it sent.
|
||||
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
|
||||
@@ -233,12 +612,76 @@ 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();
|
||||
assert!(caps.document_formatting_provider.is_some());
|
||||
assert!(caps.document_range_formatting_provider.is_some());
|
||||
assert!(caps.definition_provider.is_some());
|
||||
assert!(caps.type_definition_provider.is_some());
|
||||
assert!(caps.linked_editing_range_provider.is_some());
|
||||
assert!(caps.references_provider.is_some());
|
||||
assert!(caps.document_link_provider.is_some());
|
||||
assert!(caps.document_highlight_provider.is_some());
|
||||
@@ -255,6 +698,336 @@ mod tests {
|
||||
assert!(caps.inlay_hint_provider.is_some());
|
||||
assert!(caps.call_hierarchy_provider.is_some());
|
||||
assert!(caps.inline_completion_provider.is_some());
|
||||
assert!(caps.selection_range_provider.is_some());
|
||||
assert!(caps.diagnostic_provider.is_some());
|
||||
assert!(caps.code_lens_provider.is_some());
|
||||
assert!(caps.document_on_type_formatting_provider.is_some());
|
||||
assert!(caps.workspace.is_some(), "the file operations live here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_operations_reach_the_wire_under_workspace() {
|
||||
// A client sends `willRenameFiles` only where the *server's* filters
|
||||
// say so, and it looks for them at this exact key — a capability
|
||||
// nested one level wrong is a capability that is never exercised.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
let operations = &value["capabilities"]["workspace"]["fileOperations"];
|
||||
assert_eq!(
|
||||
operations["willRename"]["filters"][0]["pattern"]["glob"],
|
||||
serde_json::json!(watch::SOURCE_GLOB),
|
||||
"{value:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
operations["willRename"]["filters"][1]["pattern"]["matches"],
|
||||
serde_json::json!("folder"),
|
||||
"a folder rename moves every include that reached into it"
|
||||
);
|
||||
assert_eq!(operations["didRename"]["filters"].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(operations["didDelete"]["filters"].as_array().map(Vec::len), Some(1));
|
||||
// The three this server does not answer are absent, not empty: a
|
||||
// filter list a server cannot serve is a request it will be sent.
|
||||
for absent in ["willCreate", "didCreate", "willDelete"] {
|
||||
assert_eq!(operations[absent], serde_json::Value::Null, "{absent} is not answered");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_folders_are_supported_and_their_changes_are_asked_for() {
|
||||
// Two separate statements, and a client reads them separately:
|
||||
// without `supported` it may not treat this as a multi-folder server
|
||||
// at all, and without `changeNotifications` it never sends
|
||||
// `didChangeWorkspaceFolders` however well that is handled.
|
||||
let folders = capabilities()
|
||||
.workspace
|
||||
.expect("the workspace section")
|
||||
.workspace_folders
|
||||
.expect("workspace folders");
|
||||
assert_eq!(folders.supported, Some(true));
|
||||
assert_eq!(folders.change_notifications, Some(OneOf::Left(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_folder_capability_reaches_the_wire_at_the_key_a_client_reads() {
|
||||
// Nested one level wrong, or serialized as the string form of
|
||||
// `changeNotifications`, and the notification simply never arrives.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["workspace"]["workspaceFolders"],
|
||||
serde_json::json!({ "supported": true, "changeNotifications": true }),
|
||||
"{value:#?}"
|
||||
);
|
||||
// And the neighbour under the same key is untouched.
|
||||
assert!(value["capabilities"]["workspace"]["fileOperations"].is_object(), "{value:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configuration_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
|
||||
assert!(!configuration_support(&InitializeParams::default()), "silence means push-only");
|
||||
|
||||
let saying = |configuration: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities {
|
||||
configuration,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(configuration_support(&saying(Some(true))));
|
||||
assert!(!configuration_support(&saying(Some(false))));
|
||||
assert!(!configuration_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_type_hierarchy_is_advertised_even_though_lsp_types_cannot_spell_it() {
|
||||
// `ServerCapabilities` has no `type_hierarchy_provider` field in
|
||||
// lsp-types 0.97 — the crate models type hierarchy on the client side
|
||||
// only — so the capability is written into the serialized object. A
|
||||
// client keys entirely off this key: without it the three requests are
|
||||
// never sent, however well they are implemented.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["typeHierarchyProvider"],
|
||||
serde_json::json!(true),
|
||||
"{value:#?}"
|
||||
);
|
||||
// And the rest of the object is untouched by the insertion.
|
||||
assert_eq!(value["capabilities"]["callHierarchyProvider"], serde_json::json!(true));
|
||||
assert_eq!(value["serverInfo"]["name"], serde_json::json!("lucisv-server"));
|
||||
}
|
||||
|
||||
// QA (2026-08-26): the spot checks above name two fields; this pins the
|
||||
// whole object instead. `initialize_result()` and `capabilities()` are
|
||||
// untouched by this round (confirmed against `24e8eab`), so the only way
|
||||
// the insertion could disturb anything is the one `caps.insert` call
|
||||
// itself — this proves that byte-for-byte rather than by inspection: pull
|
||||
// the one inserted key back out and what remains must equal the plain,
|
||||
// uninserted serialization exactly. A future round that lets the
|
||||
// insertion clobber an existing key, or that adds a field to
|
||||
// `ServerCapabilities` under the same JSON name, fails this immediately.
|
||||
#[test]
|
||||
fn the_json_insertion_disturbs_nothing_else_in_the_initialize_result() {
|
||||
let mut with_insertion = initialize_value(false).expect("the initialize result serializes");
|
||||
let plain = serde_json::to_value(initialize_result()).expect("serializes on its own too");
|
||||
let caps =
|
||||
with_insertion["capabilities"].as_object_mut().expect("capabilities is a JSON object");
|
||||
assert_eq!(
|
||||
caps.remove("typeHierarchyProvider"),
|
||||
Some(serde_json::json!(true)),
|
||||
"the one key the insertion is supposed to add"
|
||||
);
|
||||
assert_eq!(
|
||||
with_insertion, plain,
|
||||
"removing the inserted key must restore exactly what capabilities() \
|
||||
and initialize_result() produce on their own, key for key, value for value"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `rangesFormatting` (LSP 3.18) — the capability, on both wire shapes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// `initialize` params carrying whatever a client said about
|
||||
/// `rangesSupport`, as raw JSON — which is the only place it survives.
|
||||
fn client_saying(ranges_support: serde_json::Value) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"processId": null,
|
||||
"capabilities": {
|
||||
"textDocument": { "rangeFormatting": { "rangesSupport": ranges_support } }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_formatting_support_is_read_from_the_raw_params_and_only_when_literally_true() {
|
||||
assert!(ranges_formatting_support(&client_saying(serde_json::json!(true))));
|
||||
assert!(!ranges_formatting_support(&client_saying(serde_json::json!(false))));
|
||||
// Junk in that slot is not a yes. A client that means it sends `true`.
|
||||
assert!(!ranges_formatting_support(&client_saying(serde_json::json!("yes"))));
|
||||
assert!(!ranges_formatting_support(&client_saying(serde_json::Value::Null)));
|
||||
// The 3.17 client: the key is not there at all.
|
||||
assert!(!ranges_formatting_support(&serde_json::json!({ "capabilities": {} })));
|
||||
// And params that are not even an object — `Value::index` answers
|
||||
// `Null` rather than panicking, which is the whole reason this is a
|
||||
// JSON read and not a typed one.
|
||||
assert!(!ranges_formatting_support(&serde_json::json!("nonsense")));
|
||||
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
|
||||
// must see the same byte on the wire. A bare `true` is the shape no
|
||||
// client can misread, and one that never advertised `rangesSupport`
|
||||
// will never send the request however it is advertised.
|
||||
let value = initialize_value(false).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["documentRangeFormattingProvider"],
|
||||
serde_json::json!(true),
|
||||
"{value:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_asked_sees_the_options_object_with_ranges_support() {
|
||||
// `documentRangeFormattingProvider` is `boolean |
|
||||
// DocumentRangeFormattingOptions` in the spec, and `rangesSupport` is
|
||||
// a field on the options arm — so widening the bool to the object is
|
||||
// how the spec says to answer, and it is the only way
|
||||
// `vscode-languageclient` will register its multi-range provider.
|
||||
let value = initialize_value(true).expect("the initialize result serializes");
|
||||
assert_eq!(
|
||||
value["capabilities"]["documentRangeFormattingProvider"],
|
||||
serde_json::json!({ "rangesSupport": true }),
|
||||
"{value:#?}"
|
||||
);
|
||||
// Single-range formatting is still advertised by that same key — the
|
||||
// object is not an *extra* capability, it is the same one saying more.
|
||||
assert!(
|
||||
value["capabilities"]["documentRangeFormattingProvider"].is_object(),
|
||||
"and never a second key: {value:#?}"
|
||||
);
|
||||
assert_eq!(value["capabilities"]["documentRangeFormattingProvider"]["rangesSupport"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_the_range_capability_disturbs_nothing_else_in_the_initialize_result() {
|
||||
// The same proof `the_json_insertion_disturbs_nothing_else...` gives
|
||||
// for `typeHierarchyProvider`, for the second inserted key: the two
|
||||
// results must differ at exactly one key and be equal everywhere else.
|
||||
let mut gated = initialize_value(true).expect("serializes");
|
||||
let plain = initialize_value(false).expect("serializes");
|
||||
let caps = gated["capabilities"].as_object_mut().expect("capabilities is a JSON object");
|
||||
assert_eq!(
|
||||
caps.insert("documentRangeFormattingProvider".to_string(), serde_json::json!(true)),
|
||||
Some(serde_json::json!({ "rangesSupport": true })),
|
||||
"the one key the widening is supposed to replace"
|
||||
);
|
||||
assert_eq!(
|
||||
gated, plain,
|
||||
"putting the bare `true` back must restore the ungated result exactly"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else() {
|
||||
// The trigger set is the feature: a client sends this request on every
|
||||
// one of these characters and on no other, so what is listed here is
|
||||
// exactly what `on_type::on_type_formatting` knows how to answer. `}`
|
||||
// is deliberately absent — SV closes its blocks with the word `end`.
|
||||
let options = capabilities().document_on_type_formatting_provider.expect("advertised");
|
||||
assert_eq!(options.first_trigger_character, "\n");
|
||||
assert_eq!(options.more_trigger_character, Some(vec![";".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_semantic_token_capability_asks_for_ranges_and_for_deltas() {
|
||||
// A client keys entirely off this: it sends `full/delta` only where
|
||||
// `full.delta` is `true`, and `range` only where `range` is.
|
||||
let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(options)) =
|
||||
capabilities().semantic_tokens_provider
|
||||
else {
|
||||
panic!("the options form, not a registration");
|
||||
};
|
||||
assert_eq!(options.range, Some(true));
|
||||
assert_eq!(options.full, Some(SemanticTokensFullOptions::Delta { delta: Some(true) }));
|
||||
assert_eq!(options.legend.token_types.len(), 14, "the legend is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sync_options_ask_for_the_save_hook_and_not_the_notification() {
|
||||
let Some(TextDocumentSyncCapability::Options(options)) = capabilities().text_document_sync
|
||||
else {
|
||||
panic!("the options form, not a bare kind");
|
||||
};
|
||||
assert_eq!(options.change, Some(TextDocumentSyncKind::INCREMENTAL));
|
||||
assert_eq!(options.will_save_wait_until, Some(true), "the format-on-save hook is answered");
|
||||
assert_eq!(options.will_save, None, "the plain notification has nothing for us");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_diagnostic_options_say_what_this_server_actually_does() {
|
||||
let Some(DiagnosticServerCapabilities::Options(options)) =
|
||||
capabilities().diagnostic_provider
|
||||
else {
|
||||
panic!("plain options, not a dynamic registration");
|
||||
};
|
||||
assert_eq!(options.identifier.as_deref(), Some(diagnostics::SOURCE), "same tag as a push");
|
||||
assert!(options.inter_file_dependencies, "a save changes other files' diagnostics");
|
||||
assert!(options.workspace_diagnostics, "`workspace/diagnostic` is answered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_edit_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities};
|
||||
assert!(!apply_edit_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |apply_edit: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities { apply_edit, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(apply_edit_support(&saying(Some(true))));
|
||||
assert!(!apply_edit_support(&saying(Some(false))));
|
||||
assert!(!apply_edit_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_done_progress_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{ClientCapabilities, WindowClientCapabilities};
|
||||
assert!(!work_done_progress_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |work_done_progress: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
window: Some(WindowClientCapabilities { work_done_progress, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(work_done_progress_support(&saying(Some(true))));
|
||||
assert!(!work_done_progress_support(&saying(Some(false))));
|
||||
assert!(!work_done_progress_support(&saying(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_sent_the_diagnostic_capability_at_all_is_a_pulling_client() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, DiagnosticClientCapabilities, TextDocumentClientCapabilities,
|
||||
};
|
||||
assert!(!pull_diagnostics_support(&InitializeParams::default()), "silence means push");
|
||||
|
||||
let pulling = InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
text_document: Some(TextDocumentClientCapabilities {
|
||||
// Both fields left unset: sending the capability is the
|
||||
// whole of the statement, and neither field is about
|
||||
// whether the client pulls.
|
||||
diagnostic: Some(DiagnosticClientCapabilities::default()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(pull_diagnostics_support(&pulling));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -359,7 +1132,12 @@ mod tests {
|
||||
#[test]
|
||||
fn every_advertised_command_is_one_the_server_runs() {
|
||||
let options = capabilities().execute_command_provider.expect("commands");
|
||||
assert_eq!(options.commands, ports::commands());
|
||||
assert_eq!(options.commands, commands());
|
||||
// Both halves of the list, so neither can go missing quietly: a lens
|
||||
// whose command is not advertised is a lens no client will run.
|
||||
for command in ports::commands().iter().chain(lens::commands().iter()) {
|
||||
assert!(options.commands.contains(command), "{command} is not advertised");
|
||||
}
|
||||
assert!(
|
||||
options.commands.iter().all(|c| c.starts_with("lucisv.")),
|
||||
"{:?}",
|
||||
@@ -367,6 +1145,55 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_lenses_resolve_nothing_because_every_lens_is_complete() {
|
||||
let options = capabilities().code_lens_provider.expect("code lenses");
|
||||
assert_eq!(options.resolve_provider, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_lens_refresh_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, CodeLensWorkspaceClientCapabilities, WorkspaceClientCapabilities,
|
||||
};
|
||||
assert!(!code_lens_refresh_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |refresh_support: Option<bool>| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
workspace: Some(WorkspaceClientCapabilities {
|
||||
code_lens: Some(CodeLensWorkspaceClientCapabilities { refresh_support }),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(code_lens_refresh_support(&saying(Some(true))));
|
||||
assert!(!code_lens_refresh_support(&saying(Some(false))));
|
||||
assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_document_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, ShowDocumentClientCapabilities, WindowClientCapabilities,
|
||||
};
|
||||
assert!(!show_document_support(&InitializeParams::default()), "silence means no");
|
||||
|
||||
let saying = |support: bool| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
window: Some(WindowClientCapabilities {
|
||||
show_document: Some(ShowDocumentClientCapabilities { support }),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(show_document_support(&saying(true)));
|
||||
assert!(!show_document_support(&saying(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_is_advertised_because_that_is_what_convert_implements() {
|
||||
assert_eq!(capabilities().position_encoding, Some(PositionEncodingKind::UTF16));
|
||||
|
||||
+923
-37
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -307,10 +307,34 @@ fn opener_rule(text: &str) -> Option<(usize, &'static Rule)> {
|
||||
}
|
||||
|
||||
/// The closer keyword `text` is, as a `'static` string from the table.
|
||||
fn closer_keyword(text: &str) -> Option<&'static str> {
|
||||
pub(crate) fn closer_keyword(text: &str) -> Option<&'static str> {
|
||||
RULES.iter().flat_map(|r| r.close).copied().find(|c| *c == text)
|
||||
}
|
||||
|
||||
/// The keywords that close the scope the token at `i` opens, or `None` when it
|
||||
/// opens none.
|
||||
///
|
||||
/// [`analyze`]'s own two questions — "is this an opener?" and "does it really
|
||||
/// open here?" — asked as one, so the on-type indent model counts nesting off
|
||||
/// exactly the scopes the matcher matches. The [`RULES`] table and
|
||||
/// [`opens_a_scope`]'s exception list must have one reader's answer, not two:
|
||||
/// an `extern function f();` that opened a scope for one of them and not the
|
||||
/// other would leave the two disagreeing about every line below it.
|
||||
///
|
||||
/// The caller still owns the prototype flag ([`starts_a_prototype`]), because
|
||||
/// that one spans tokens and only a running scan can carry it.
|
||||
pub(crate) fn opens_scope_at(tokens: &[Token], i: usize) -> Option<&'static [&'static str]> {
|
||||
let text = tokens.get(i)?.text.as_str();
|
||||
let (_, rule) = opener_rule(text)?;
|
||||
opens_a_scope(tokens, i).then_some(rule.close)
|
||||
}
|
||||
|
||||
/// Whether a keyword turns the rest of its statement into a declaration with
|
||||
/// no body — see [`PROTOTYPE_STARTERS`]. Cleared at the next `;`.
|
||||
pub(crate) fn starts_a_prototype(text: &str) -> bool {
|
||||
PROTOTYPE_STARTERS.contains(&text)
|
||||
}
|
||||
|
||||
/// The opener a closer belongs to, for "`end` has no matching `begin`".
|
||||
fn opener_of(closer: &str) -> &'static str {
|
||||
RULES.iter().find(|r| r.close.contains(&closer)).map_or("", |r| r.open)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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| {
|
||||
@@ -75,15 +78,15 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
|
||||
|
||||
/// Run one of the three commands, or say why it cannot run.
|
||||
///
|
||||
/// The answer is the `WorkspaceEdit` the client is expected to apply (through
|
||||
/// `workspace/applyEdit`, which the server does not push: an editor that asked
|
||||
/// for the command owns the edit) plus the engine's warnings.
|
||||
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
|
||||
/// it reaches the editor is `server.rs`'s business: it is pushed as a
|
||||
/// `workspace/applyEdit` request, or — for a client that cannot be pushed one
|
||||
/// — returned as the command's result (`docs/features/apply-edit/README.md`).
|
||||
pub fn execute(
|
||||
ws: &Workspace,
|
||||
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())?;
|
||||
@@ -92,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 => {
|
||||
@@ -108,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.")),
|
||||
@@ -120,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),
|
||||
@@ -243,7 +266,7 @@ mod tests {
|
||||
let sub = tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let top_uri = path_to_uri(&top).expect("uri");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(top_uri.clone(), TOP.to_string());
|
||||
@@ -322,7 +345,7 @@ mod tests {
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", text);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let arguments = vec![
|
||||
@@ -356,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.
|
||||
@@ -122,7 +141,7 @@ mod tests {
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TOP);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
(ws, uri)
|
||||
@@ -194,7 +213,7 @@ mod tests {
|
||||
let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n";
|
||||
let file = tree.write("m.sv", text);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&file).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
|
||||
@@ -206,13 +225,624 @@ 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");
|
||||
tree.write("sub.sv", SUB);
|
||||
let top_path = tree.write("top.sv", "module top;\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
// The buffer instantiates `sub`; the file on disk does not.
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), TOP.to_string());
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
//! `textDocument/selectionRange` — expand-selection.
|
||||
//!
|
||||
//! No new analysis: everything the chain is built from is already computed for
|
||||
//! something else. The token stream gives the innermost step, the tolerant
|
||||
//! parse's item and statement spans give the middle ones, and `pairs::analyze`
|
||||
//! — the rainbow's own matcher — gives the scopes a broken parse would
|
||||
//! otherwise lose. The four sources are thrown into one list of byte ranges
|
||||
//! that cover the cursor, and the chain is whatever nests. See
|
||||
//! `docs/features/selection-range/README.md`.
|
||||
|
||||
use lsp_types::{Position, SelectionRange};
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::pairs::analyze;
|
||||
use crate::state::{first_token_reaching, Document};
|
||||
|
||||
/// One chain per requested position, in the order they were asked for.
|
||||
///
|
||||
/// Each chain runs innermost first, every step strictly containing the one
|
||||
/// before it and the last one being the whole file. A position that resolves
|
||||
/// to nothing else — an empty buffer, a file that does not lex — still gets
|
||||
/// that last step, because the protocol wants exactly one answer per position.
|
||||
pub fn selection_ranges(doc: &Document, positions: &[Position]) -> Vec<SelectionRange> {
|
||||
let converter = doc.positions();
|
||||
positions.iter().map(|position| chain(doc, converter.offset(*position))).collect()
|
||||
}
|
||||
|
||||
/// The chain for one byte offset.
|
||||
fn chain(doc: &Document, offset: u32) -> SelectionRange {
|
||||
let positions = doc.positions();
|
||||
let mut range: Option<SelectionRange> = None;
|
||||
// Widest first, so each step is built already holding its parent.
|
||||
for span in nested(enclosing(doc, offset)).into_iter().rev() {
|
||||
range = Some(SelectionRange { range: positions.range(span), parent: range.map(Box::new) });
|
||||
}
|
||||
range.unwrap_or_else(|| SelectionRange { range: positions.whole_document(), parent: None })
|
||||
}
|
||||
|
||||
/// Every byte range this server can name that covers `offset`, from every
|
||||
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
|
||||
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
|
||||
let mut spans = Vec::new();
|
||||
// The first token that reaches `offset` is the first that can cover it,
|
||||
// and — because the tokens after it all start no earlier — the only one
|
||||
// the sweep this replaced could ever have returned. Note that `covers`
|
||||
// takes `span.end` inclusively, so this is deliberately *not*
|
||||
// `Document::token_at`: at a byte two adjacent tokens share, the sweep
|
||||
// answered with the earlier one and so does this.
|
||||
if let Some(token) = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|token| covers(token.span, offset))
|
||||
{
|
||||
spans.push(token.span);
|
||||
}
|
||||
items(&doc.tree.items, offset, &mut spans);
|
||||
// The scopes the AST does not model — an unclosed `begin` inside an
|
||||
// otherwise fine module, a `case` in a file that only half parsed — still
|
||||
// match over the token stream, and a user expanding a selection there is
|
||||
// exactly the user whose file is mid-edit.
|
||||
for pair in analyze(&doc.tokens).pairs {
|
||||
let span = TextRange::new(pair.open.start, pair.close.end);
|
||||
if covers(span, offset) {
|
||||
spans.push(span);
|
||||
}
|
||||
}
|
||||
spans.push(TextRange::new(0, doc.text.len() as u32));
|
||||
spans
|
||||
}
|
||||
|
||||
/// The subsequence that really nests, smallest first.
|
||||
///
|
||||
/// Two ranges that both cover the cursor need not contain one another — an
|
||||
/// item span and a scope pair can overlap when a parse went wrong — and LSP
|
||||
/// requires every step to contain its child. So the list is walked smallest
|
||||
/// first and a range is kept only when it strictly contains what was kept
|
||||
/// before it; that also drops the duplicates the four sources produce for the
|
||||
/// same construct.
|
||||
fn nested(mut spans: Vec<TextRange>) -> Vec<TextRange> {
|
||||
// A zero-width step selects nothing, which is not a step a user can see.
|
||||
spans.retain(|span| !span.is_empty());
|
||||
spans.sort_by_key(|span| (span.len(), span.start));
|
||||
let mut out: Vec<TextRange> = Vec::new();
|
||||
for span in spans {
|
||||
let keep = match out.last() {
|
||||
Some(inner) => {
|
||||
span.start <= inner.start && span.end >= inner.end && span.len() > inner.len()
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if keep {
|
||||
out.push(span);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a span covers an offset. The end is **included**: a cursor sitting
|
||||
/// just after a word is still on that word, which is where an expand-selection
|
||||
/// keystroke is most often pressed.
|
||||
fn covers(span: TextRange, offset: u32) -> bool {
|
||||
span.start <= offset && offset <= span.end
|
||||
}
|
||||
|
||||
/// The spans of every item that covers `offset`, descending only into the one
|
||||
/// that does — the walk is per-keystroke, and a whole-file walk would visit
|
||||
/// thousands of nodes to report a handful.
|
||||
fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
|
||||
for item in list {
|
||||
if !covers(item.span, offset) {
|
||||
continue;
|
||||
}
|
||||
out.push(item.span);
|
||||
match &item.kind {
|
||||
ItemKind::Module(module) => items(&module.items, offset, out),
|
||||
ItemKind::Class(class) => items(&class.items, offset, out),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
|
||||
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
if covers(case_item.span, offset) {
|
||||
out.push(case_item.span);
|
||||
gen_block(&case_item.body, offset, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
statement(stmt, offset, out)
|
||||
}
|
||||
ItemKind::Function(decl) => statements(&decl.stmts, offset, out),
|
||||
ItemKind::Task(decl) => statements(&decl.stmts, offset, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate `if`, its `else if` ladder and its final `else`.
|
||||
fn gen_if_blocks(gen_if: &GenIf, offset: u32, out: &mut Vec<TextRange>) {
|
||||
gen_block(&gen_if.then, offset, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
gen_block(&nested.then, offset, out);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
gen_block(block, offset, out);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_block(block: &GenBlock, offset: u32, out: &mut Vec<TextRange>) {
|
||||
if !covers(block.span, offset) {
|
||||
return;
|
||||
}
|
||||
out.push(block.span);
|
||||
items(&block.items, offset, out);
|
||||
}
|
||||
|
||||
fn statements(list: &[Stmt], offset: u32, out: &mut Vec<TextRange>) {
|
||||
for stmt in list {
|
||||
statement(stmt, offset, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The spans of `stmt` and of every statement inside it that covers `offset`.
|
||||
///
|
||||
/// The recursion is bounded by the parser's own nesting limit
|
||||
/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it
|
||||
/// built.
|
||||
fn statement(stmt: &Stmt, offset: u32, out: &mut Vec<TextRange>) {
|
||||
if !covers(stmt.span, offset) {
|
||||
return;
|
||||
}
|
||||
out.push(stmt.span);
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
|
||||
statements(stmts, offset, out)
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
statement(then, offset, out);
|
||||
if let Some(els) = els {
|
||||
statement(els, offset, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for case_item in items {
|
||||
if covers(case_item.span, offset) {
|
||||
out.push(case_item.span);
|
||||
statement(&case_item.stmt, offset, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::Labeled { stmt: inner, .. } => statement(inner, offset, out),
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => statement(body, offset, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
statement(inner, offset, out)
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
if let Some(then) = then {
|
||||
statement(then, offset, out);
|
||||
}
|
||||
if let Some(els) = els {
|
||||
statement(els, offset, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::Range;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
fn doc_of(text: &str) -> Document {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
/// The innermost step of a chain used to come from a sweep of the whole
|
||||
/// token vector; it now comes from a binary search. `covers` takes
|
||||
/// `span.end` inclusively, so at a byte two adjacent tokens share the
|
||||
/// sweep answered with the earlier of the two — this pins that the search
|
||||
/// answers with the earlier one too, at every byte of a buffer written to
|
||||
/// have plenty of them.
|
||||
#[test]
|
||||
fn the_innermost_step_is_the_token_the_sweep_returned_at_every_offset() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let doc = doc_of(&text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc.tokens.iter().find(|token| covers(token.span, offset));
|
||||
let searched = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|token| covers(token.span, offset));
|
||||
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The chain for the first occurrence of `needle`, as the source text of
|
||||
/// each step, innermost first.
|
||||
fn steps(text: &str, needle: &str) -> Vec<String> {
|
||||
let doc = doc_of(text);
|
||||
let offset = text.find(needle).expect("the needle is in the text") as u32;
|
||||
let position = doc.positions().position(offset);
|
||||
let chains = selection_ranges(&doc, &[position]);
|
||||
assert_eq!(chains.len(), 1, "one chain per position");
|
||||
let mut out = Vec::new();
|
||||
let mut step = Some(&chains[0]);
|
||||
let positions = doc.positions();
|
||||
while let Some(current) = step {
|
||||
let start = positions.offset(current.range.start) as usize;
|
||||
let end = positions.offset(current.range.end) as usize;
|
||||
out.push(text[start..end].to_string());
|
||||
step = current.parent.as_deref();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every step of a chain, as `(start, end)` byte offsets.
|
||||
fn spans(doc: &Document, offset: u32) -> Vec<(u32, u32)> {
|
||||
let position = doc.positions().position(offset);
|
||||
let chains = selection_ranges(doc, &[position]);
|
||||
let positions = doc.positions();
|
||||
let mut out = Vec::new();
|
||||
let mut step = chains.first();
|
||||
while let Some(current) = step {
|
||||
out.push((positions.offset(current.range.start), positions.offset(current.range.end)));
|
||||
step = current.parent.as_deref();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_chain_runs_from_the_token_out_to_the_whole_file() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let steps = steps(text, "wire");
|
||||
assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}");
|
||||
assert_eq!(steps.last().map(String::as_str), Some(text), "the whole file closes it");
|
||||
assert!(steps.contains(&"wire a;".to_string()), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_expands_through_its_block_and_its_process() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" initial begin\n",
|
||||
" if (a) begin\n",
|
||||
" x = 1;\n",
|
||||
" end\n",
|
||||
" end\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let steps = steps(text, "x = 1");
|
||||
assert_eq!(steps.first().map(String::as_str), Some("x"));
|
||||
assert!(steps.iter().any(|s| s == "x = 1;"), "the statement: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("if (a) begin")), "the if: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("initial begin")), "the process: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("module m;")), "the module: {steps:?}");
|
||||
assert_eq!(steps.last().map(String::as_str), Some(text));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_step_strictly_contains_the_one_before_it() {
|
||||
// The protocol's own requirement, and the thing the four sources of
|
||||
// ranges could most easily break.
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" always_comb begin\n",
|
||||
" case (sel)\n",
|
||||
" 2'd0: y = a;\n",
|
||||
" default: y = b;\n",
|
||||
" endcase\n",
|
||||
" end\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let doc = doc_of(text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let spans = spans(&doc, offset);
|
||||
assert!(!spans.is_empty(), "every position gets a chain, at {offset}");
|
||||
for pair in spans.windows(2) {
|
||||
let (inner, outer) = (pair[0], pair[1]);
|
||||
assert!(
|
||||
outer.0 <= inner.0 && outer.1 >= inner.1 && outer != inner,
|
||||
"at {offset}: {outer:?} must strictly contain {inner:?} — {spans:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
spans.last(),
|
||||
Some(&(0, text.len() as u32)),
|
||||
"the file closes every chain, at {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_item_is_a_step_of_its_own() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" always_comb begin\n",
|
||||
" case (sel)\n",
|
||||
" 2'd0: y = a;\n",
|
||||
" endcase\n",
|
||||
" end\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let steps = steps(text, "y = a");
|
||||
assert!(steps.iter().any(|s| s == "2'd0: y = a;"), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("case (sel)")), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_block_is_a_step_of_its_own() {
|
||||
let text = concat!(
|
||||
"module m;\n",
|
||||
" generate\n",
|
||||
" if (A) begin : g\n",
|
||||
" wire a;\n",
|
||||
" end\n",
|
||||
" endgenerate\n",
|
||||
"endmodule\n",
|
||||
);
|
||||
let steps = steps(text, "wire a");
|
||||
assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("begin : g")), "the block: {steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("generate")), "the region: {steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_positions_are_answered_position_for_position() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let positions = doc.positions();
|
||||
let at = |needle: &str| positions.position(text.find(needle).expect("needle") as u32);
|
||||
let asked = vec![at("endmodule"), at("wire"), at("module")];
|
||||
let chains = selection_ranges(&doc, &asked);
|
||||
assert_eq!(chains.len(), 3);
|
||||
for (chain, position) in chains.iter().zip(&asked) {
|
||||
assert!(
|
||||
chain.range.start <= *position && *position <= chain.range.end,
|
||||
"each answer is about its own position: {chain:?} vs {position:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_positions_asked_means_no_chains_answered() {
|
||||
let doc = doc_of("module m;\nendmodule\n");
|
||||
assert!(selection_ranges(&doc, &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_still_answers_one_degenerate_chain() {
|
||||
let doc = doc_of("");
|
||||
let chains = selection_ranges(&doc, &[Position { line: 0, character: 0 }]);
|
||||
assert_eq!(chains.len(), 1);
|
||||
assert_eq!(chains[0].range.start, chains[0].range.end, "there is nothing to select");
|
||||
assert!(chains[0].parent.is_none(), "and nothing to expand to");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_still_answers_the_file_range() {
|
||||
// `Document::new` leaves `tokens` empty and the tree an error leaf, so
|
||||
// this is the path where every source but the last one gives nothing.
|
||||
let text = "module m;\n wire a; /* unterminated\n";
|
||||
let doc = doc_of(text);
|
||||
assert!(doc.tokens.is_empty(), "the premise");
|
||||
let spans = spans(&doc, 12);
|
||||
assert_eq!(spans.last(), Some(&(0, text.len() as u32)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_scope_still_expands_through_what_did_close() {
|
||||
// The mid-edit shape: the `begin` never closes, so the AST cannot
|
||||
// offer the statement — the module's own pair still can.
|
||||
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let offset = text.find("x = 1").expect("needle") as u32;
|
||||
let spans = spans(&doc, offset);
|
||||
assert!(spans.len() >= 2, "at least the token and the file: {spans:?}");
|
||||
assert_eq!(spans.last(), Some(&(0, text.len() as u32)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_past_the_end_of_the_file_clamps_into_it() {
|
||||
let text = "module m;\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let chains = selection_ranges(&doc, &[Position { line: 99, character: 99 }]);
|
||||
assert_eq!(chains.len(), 1);
|
||||
assert_eq!(chains[0].range.end, doc.positions().whole_document().end);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multibyte_line_keeps_the_columns_in_utf16() {
|
||||
// The chain is computed in bytes and answered in UTF-16 units; an
|
||||
// off-by-one here would select the wrong text in the editor only.
|
||||
let text = "module m;\n // é 🎉\n wire a;\nendmodule\n";
|
||||
let steps = steps(text, "wire");
|
||||
assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_drops_a_range_that_does_not_contain_what_came_before() {
|
||||
// The guard for the overlapping-sources case: two ranges that both
|
||||
// cover the cursor but nest in neither direction. The wider-but-not-
|
||||
// enclosing one must be dropped, never emitted as a parent.
|
||||
let spans = vec![
|
||||
TextRange::new(4, 6),
|
||||
TextRange::new(0, 8),
|
||||
TextRange::new(5, 20), // covers 5, contains neither of the above
|
||||
TextRange::new(0, 30),
|
||||
];
|
||||
let kept = nested(spans);
|
||||
assert_eq!(
|
||||
kept.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(),
|
||||
vec![(4, 6), (0, 8), (0, 30)]
|
||||
);
|
||||
}
|
||||
|
||||
/// The strict-nesting invariant, on the real corpus rather than
|
||||
/// hand-written snippets. `every_step_strictly_contains_the_one_before_it`
|
||||
/// above proves the invariant on files this crate's author wrote to
|
||||
/// exercise it; a corpus file was written by nobody thinking about this
|
||||
/// walk at all, and is exactly what turns up a construct the four
|
||||
/// sources disagree about. Skipped when `corpus/` is not checked out,
|
||||
/// like every other corpus test in this crate.
|
||||
#[test]
|
||||
fn every_step_strictly_nests_over_the_real_corpus() {
|
||||
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let extensions = ["sv", "v", "svh", "vh"];
|
||||
let mut files_checked = 0;
|
||||
let mut positions_checked = 0;
|
||||
for entry in walk(&corpus) {
|
||||
let Some(ext) = entry.extension().and_then(|e| e.to_str()) else { continue };
|
||||
if !extensions.contains(&ext) {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(&entry) else { continue };
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
files_checked += 1;
|
||||
let doc = Document::new(Some(entry.clone()), text.clone(), &WorkspaceIndex::default());
|
||||
let converter = doc.positions();
|
||||
// A handful of evenly spaced offsets per file, not every byte:
|
||||
// the corpus is 800+ files, and the per-offset invariant is
|
||||
// already proven exhaustively on small files above. This is
|
||||
// about *coverage of real syntax*, not exhaustiveness per file.
|
||||
let len = text.len() as u32;
|
||||
let stride = (len / 7).max(1);
|
||||
let mut offset = 0;
|
||||
while offset <= len {
|
||||
positions_checked += 1;
|
||||
let position = converter.position(offset);
|
||||
let chains = selection_ranges(&doc, &[position]);
|
||||
assert_eq!(chains.len(), 1, "{}: offset {offset}", entry.display());
|
||||
let mut step = Some(&chains[0]);
|
||||
let mut previous: Option<Range> = None;
|
||||
while let Some(current) = step {
|
||||
if let Some(inner) = previous {
|
||||
let widens = current.range.start <= inner.start
|
||||
&& current.range.end >= inner.end
|
||||
&& current.range != inner;
|
||||
assert!(
|
||||
widens,
|
||||
"{}: offset {offset}: {:?} does not strictly contain {:?}",
|
||||
entry.display(),
|
||||
current.range,
|
||||
inner
|
||||
);
|
||||
}
|
||||
previous = Some(current.range);
|
||||
step = current.parent.as_deref();
|
||||
}
|
||||
let whole = converter.whole_document();
|
||||
assert_eq!(
|
||||
previous,
|
||||
Some(whole),
|
||||
"{}: offset {offset}: the file must close every chain",
|
||||
entry.display()
|
||||
);
|
||||
offset += stride;
|
||||
}
|
||||
}
|
||||
assert!(files_checked > 100, "the corpus really is checked out: {files_checked} files");
|
||||
eprintln!("selection ranges: {files_checked} files, {positions_checked} positions, no panics, every step strictly nested");
|
||||
}
|
||||
|
||||
/// Every regular file under `dir`, recursively — no filtering by anything
|
||||
/// but extension, which the caller does. Errors reading a directory are
|
||||
/// treated as "nothing here" rather than failing the whole sweep: a
|
||||
/// symlink loop or a permission-denied subtree in a third-party corpus
|
||||
/// checkout should not take the QA test down with it.
|
||||
fn walk(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
out.extend(walk(&path));
|
||||
} else {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_drops_duplicates_and_empty_ranges() {
|
||||
let spans = vec![
|
||||
TextRange::new(3, 3),
|
||||
TextRange::new(2, 9),
|
||||
TextRange::new(2, 9),
|
||||
TextRange::new(0, 9),
|
||||
];
|
||||
let kept = nested(spans);
|
||||
assert_eq!(kept.iter().map(|s| (s.start, s.end)).collect::<Vec<_>>(), vec![(2, 9), (0, 9)]);
|
||||
}
|
||||
}
|
||||
+7862
-95
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`.
|
||||
//! The `lucisv.*` settings a client pushes over `workspace/didChangeConfiguration`
|
||||
//! — or answers when the server pulls them with `workspace/configuration`.
|
||||
//!
|
||||
//! These are the editor's copy of what `lucisv.toml` carries — the same keys, so
|
||||
//! a user with no config file in the tree can still say "indent 4" from their
|
||||
@@ -27,10 +28,71 @@ use serde_json::Value;
|
||||
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
|
||||
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
|
||||
|
||||
/// `lucisv.index.maxFileSize`'s default: 1 MiB. A source file bigger than this
|
||||
/// is almost always a generated netlist or a dumped trace, which costs minutes
|
||||
/// to index and answers nothing a user asked. `0` means no cap; see
|
||||
/// `docs/features/indexing-ux/README.md`.
|
||||
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;
|
||||
|
||||
/// `lucisv.largeFile.threshold`'s default: 4 MiB. A buffer bigger than this is
|
||||
/// opened on the fast path — line index only, no lex, no parse, no index — and
|
||||
/// coloured a viewport at a time. `0` turns the fast path off, so every buffer
|
||||
/// is analyzed in full however big it is; see
|
||||
/// `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
|
||||
/// worth optimising for, and in it the files a user is working with are the
|
||||
/// ones beside the file they opened; walking every workspace folder to answer
|
||||
/// a question about one folder is minutes of work nobody asked for. See
|
||||
/// `docs/features/index-scope/README.md` for what the narrow scope costs,
|
||||
/// which is cross-folder answers until the scope reaches the other folder.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum IndexScope {
|
||||
/// The open buffers' own folders, each raised
|
||||
/// [`ClientSettings::index_scope_depth`] levels, walked.
|
||||
#[default]
|
||||
Folder,
|
||||
/// Every workspace folder, walked whole — what the server did before
|
||||
/// 2026-08-27, and what a user with a small project or a big machine can
|
||||
/// ask for back.
|
||||
Workspace,
|
||||
}
|
||||
|
||||
/// The configuration section these settings live in — the key a push nests
|
||||
/// them under, and the `section` a pull asks for. One constant, because the
|
||||
/// two must name the same thing or the pull would answer settings the parser
|
||||
/// then looks for somewhere else.
|
||||
pub const SECTION: &str = "lucisv";
|
||||
|
||||
/// The `lucisv.*` settings in force, after validation. Every field is "no
|
||||
/// opinion" until a client says otherwise, which is exactly what an unset
|
||||
/// VS Code setting means.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
/// VS Code setting means — except the two whose own default is not silence
|
||||
/// (`index.maxFileSize`, `index.logFiles`), which resolve to it here so no
|
||||
/// use site has to remember what "unset" meant. See the hand-written
|
||||
/// [`Default`] below.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientSettings {
|
||||
/// `lucisv.lineLength`.
|
||||
pub line_length: Option<usize>,
|
||||
@@ -46,6 +108,85 @@ 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
|
||||
/// own already runs `textDocument/formatting` on save, and a server that
|
||||
/// also formatted would format twice. See
|
||||
/// `docs/features/will-save-wait-until/README.md`.
|
||||
pub format_on_save: bool,
|
||||
/// `lucisv.index.maxFileSize`: the largest *walked* file, in bytes, that
|
||||
/// the workspace index will read. `0` is no cap. An open buffer is
|
||||
/// indexed whatever its size — the user opened it deliberately. Defaults
|
||||
/// to [`DEFAULT_MAX_FILE_SIZE`] rather than to 0, so a plain
|
||||
/// `ClientSettings::default()` is the capped behaviour the server ships
|
||||
/// with.
|
||||
pub max_file_size: u64,
|
||||
/// `lucisv.index.logFiles`: whether each file the index reads is named in
|
||||
/// a `window/logMessage`, and each oversized one in a skip line. On
|
||||
/// unless a client says otherwise — the Output panel it lands in is
|
||||
/// hidden until somebody opens it.
|
||||
pub log_files: bool,
|
||||
/// `lucisv.index.scope`: whether the walk covers the open files' folders
|
||||
/// or every workspace folder. Defaults to [`IndexScope::Folder`], which
|
||||
/// is a narrower index than the server built before 2026-08-27 — see
|
||||
/// `docs/features/index-scope/README.md`.
|
||||
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` 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.
|
||||
/// On unless a client says otherwise — a half-finished scan that has to
|
||||
/// start again from zero is the thing this exists to prevent. Off means
|
||||
/// off in both directions: nothing is read and nothing is written
|
||||
/// (`docs/features/index-persistence/README.md`).
|
||||
pub index_persist: bool,
|
||||
/// `lucisv.index.cachePath`: where that store lives, absolute or relative
|
||||
/// to the first workspace root. Empty means "unset", and then the
|
||||
/// editor's own storage folder — or this platform's cache directory —
|
||||
/// decides; see `index_cache::cache_dir` for the ladder.
|
||||
pub index_cache_path: Option<String>,
|
||||
/// `lucisv.largeFile.threshold`: the size in bytes above which an **open
|
||||
/// buffer** is served by the fast path instead of being analyzed. `0`
|
||||
/// disables the fast path. Unlike `index.maxFileSize`, which is about
|
||||
/// files on disk that nobody asked for, this one is about the file on
|
||||
/// screen — see `docs/features/large-file-mode/README.md`.
|
||||
pub large_file_threshold: u64,
|
||||
}
|
||||
|
||||
/// The settings a client that said nothing is treated as having asked for.
|
||||
///
|
||||
/// Hand-written because two of them do not default to silence: the size cap
|
||||
/// is on at 1 MiB and the file log is on. Every other field is its type's own
|
||||
/// zero, exactly as the derive produced.
|
||||
impl Default for ClientSettings {
|
||||
fn default() -> ClientSettings {
|
||||
ClientSettings {
|
||||
line_length: None,
|
||||
indent: None,
|
||||
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: DEFAULT_SCOPE_DEPTH,
|
||||
index_persist: true,
|
||||
index_cache_path: None,
|
||||
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
|
||||
@@ -63,13 +204,101 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// `synchronize.configurationSection: 'lucisv'` produces. A payload without
|
||||
// the section (including the `{"settings": null}` a client sends when it
|
||||
// syncs no section at all) means "no opinion about anything".
|
||||
let Some(lucisv) = settings.get("lucisv") else { return ClientSettings::default() };
|
||||
let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() };
|
||||
// `lucisv.index.maxFileSize` is a dotted id, and both doors nest it: VS
|
||||
// Code's settings model turns every segment into an object, so the section
|
||||
// arrives as `{"index": {"maxFileSize": …}}`. An `index` that is missing —
|
||||
// or is not an object at all — leaves both of its keys at their defaults,
|
||||
// which is what `Value::get` on a non-object already returns.
|
||||
let index = lucisv.get("index");
|
||||
// `lucisv.largeFile.threshold` nests exactly as `index.*` does, for the
|
||||
// same reason: VS Code turns every dotted segment into an object.
|
||||
let large_file = lucisv.get("largeFile");
|
||||
ClientSettings {
|
||||
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
|
||||
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
|
||||
exclude: strings(lucisv.get("exclude")),
|
||||
filelist: path(lucisv.get("filelist")),
|
||||
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.
|
||||
format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false),
|
||||
// The safe direction for these two is the shipped default, not zero:
|
||||
// a wrong-typed cap that read as `0` would index the netlist the
|
||||
// setting exists to skip.
|
||||
max_file_size: count(index.and_then(|i| i.get("maxFileSize")))
|
||||
.unwrap_or(DEFAULT_MAX_FILE_SIZE),
|
||||
log_files: flag(index.and_then(|i| i.get("logFiles"))).unwrap_or(true),
|
||||
// An unreadable scope leaves the narrow default standing, for the
|
||||
// same reason a junk cap leaves the cap on: the direction that
|
||||
// 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(),
|
||||
// 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
|
||||
// a cache that is on can only ever cost a file's parse, because every
|
||||
// hit is verified against the file's own bytes.
|
||||
index_persist: flag(index.and_then(|i| i.get("persist"))).unwrap_or(true),
|
||||
index_cache_path: path(index.and_then(|i| i.get("cachePath"))),
|
||||
// The safe direction again: a wrong-typed threshold leaves the fast
|
||||
// path armed at its default. A junk value that read as `0` would turn
|
||||
// it off, and the first 100 MB netlist opened after that would hang
|
||||
// the editor for minutes — which is the whole thing this exists to
|
||||
// prevent.
|
||||
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
|
||||
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
|
||||
}
|
||||
}
|
||||
|
||||
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
|
||||
/// case and all — because the enum in `package.json` is what a settings UI
|
||||
/// offers, and forgiving `"Workspace"` here would make a typo mean something
|
||||
/// on one client and nothing on another.
|
||||
fn scope(value: Option<&Value>) -> Option<IndexScope> {
|
||||
match value?.as_str()? {
|
||||
"folder" => Some(IndexScope::Folder),
|
||||
"workspace" => Some(IndexScope::Workspace),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one `workspace/configuration` answer — the *contents* of the `lucisv`
|
||||
/// section, since that is what the server asked for by name.
|
||||
///
|
||||
/// Deliberately the same parser as a push, reached by wrapping the section
|
||||
/// back into the shape a push arrives in. Two entry points, one set of rules:
|
||||
/// a range, a type or a default that drifted between the pull and the push
|
||||
/// paths would be a setting that means one thing in VS Code and another in
|
||||
/// Neovim. `null` — the answer the spec requires when a client cannot provide
|
||||
/// the section — parses as "no opinion about anything", which is exactly the
|
||||
/// defaults.
|
||||
pub fn from_section(section: &Value) -> ClientSettings {
|
||||
from_payload(&Value::Object([(SECTION.to_string(), section.clone())].into_iter().collect()))
|
||||
}
|
||||
|
||||
/// Whether a `didChangeConfiguration` payload carries nothing at all.
|
||||
///
|
||||
/// The 3.17 model: a client that knows the server pulls sends the
|
||||
/// notification as a bare "something changed, ask me for what you need" —
|
||||
/// `{"settings": null}` is what `vscode-languageclient` sends once no legacy
|
||||
/// `synchronize.configurationSection` is configured, and `{}` is the same
|
||||
/// statement written differently. Both are a *trigger*, not a settings
|
||||
/// payload, so the server pulls rather than resetting everything to its
|
||||
/// default. A payload with any key in it is a real push and is applied as it
|
||||
/// always was, whether or not our section is among those keys.
|
||||
pub fn says_nothing(settings: &Value) -> bool {
|
||||
match settings {
|
||||
Value::Null => true,
|
||||
Value::Object(map) => map.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +330,16 @@ fn bounded(value: Option<&Value>, range: RangeInclusive<u64>) -> Option<usize> {
|
||||
range.contains(&number).then_some(number as usize)
|
||||
}
|
||||
|
||||
/// A JSON count — any unsigned integer, `0` included — or nothing.
|
||||
///
|
||||
/// Unbounded on purpose: there is no size a cap may not take, and a cap larger
|
||||
/// than any file on disk is the same as no cap at all. `as_u64` still rejects
|
||||
/// the negatives, the fractions, the strings and the booleans, exactly as
|
||||
/// [`bounded`] does.
|
||||
fn count(value: Option<&Value>) -> Option<u64> {
|
||||
value?.as_u64()
|
||||
}
|
||||
|
||||
/// Every string in a JSON array, or an empty list for anything else. Entries
|
||||
/// that are not strings are dropped rather than stringified: a number in an
|
||||
/// exclude list is a mistake, and guessing what it meant would hide it.
|
||||
@@ -132,11 +371,176 @@ mod tests {
|
||||
"indent": indent,
|
||||
"exclude": exclude,
|
||||
"filelist": "",
|
||||
"inlineTemplates": true
|
||||
"inlineTemplates": true,
|
||||
"inlineInstantiation": true,
|
||||
"formatOnSave": false,
|
||||
"index": {
|
||||
"maxFileSize": 1048576, "logFiles": true,
|
||||
"scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off() {
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).max_file_size, DEFAULT_MAX_FILE_SIZE);
|
||||
assert_eq!(DEFAULT_MAX_FILE_SIZE, 1_048_576, "1 MiB, as the setting's description says");
|
||||
// The whole sub-section missing is the same as the key missing.
|
||||
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).max_file_size, 1_048_576);
|
||||
let off = settings(json!({ "lucisv": { "index": { "maxFileSize": 0 } } }));
|
||||
assert_eq!(off.max_file_size, 0, "0 is the client asking for no cap at all");
|
||||
let raised = settings(json!({ "lucisv": { "index": { "maxFileSize": 20_000_000 } } }));
|
||||
assert_eq!(raised.max_file_size, 20_000_000, "and there is no upper bound");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_typed_size_cap_leaves_the_default_standing() {
|
||||
// The safe direction is the shipped cap: reading junk as `0` would
|
||||
// turn the cap *off*, which is the failure the setting exists to
|
||||
// prevent.
|
||||
for bad in
|
||||
[json!("1048576"), json!(-1), json!(1.5), json!(true), json!(null), json!([1048576])]
|
||||
{
|
||||
let found = settings(json!({ "lucisv": { "index": { "maxFileSize": bad } } }));
|
||||
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "maxFileSize {bad} is ignored");
|
||||
}
|
||||
// An `index` that is not an object at all is the same as no `index`.
|
||||
for bad in [json!(null), json!(7), json!("index"), json!([])] {
|
||||
let found = settings(json!({ "lucisv": { "index": bad } }));
|
||||
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, DEFAULT_SCOPE_DEPTH, "and its scopeDepth");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_log_is_on_until_a_client_turns_it_off() {
|
||||
assert!(settings(json!({ "lucisv": {} })).log_files, "absence is on");
|
||||
assert!(
|
||||
settings(json!({ "lucisv": { "index": {} } })).log_files,
|
||||
"and so is an empty section"
|
||||
);
|
||||
assert!(settings(json!({ "lucisv": { "index": { "logFiles": true } } })).log_files);
|
||||
assert!(!settings(json!({ "lucisv": { "index": { "logFiles": false } } })).log_files);
|
||||
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
|
||||
let found = settings(json!({ "lucisv": { "index": { "logFiles": bad } } }));
|
||||
assert!(found.log_files, "logFiles {bad} must be ignored");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_settings_come_through_the_pull_door_too() {
|
||||
// `from_section` is the same parser, and these were the first nested
|
||||
// keys to go through it — a section that lost the nesting on the way
|
||||
// would silently un-cap every pulling client.
|
||||
let section = json!({
|
||||
"index": {
|
||||
"maxFileSize": 4096, "logFiles": false,
|
||||
"scope": "workspace", "scopeDepth": 2,
|
||||
"persist": false, "cachePath": "/tmp/store"
|
||||
}
|
||||
});
|
||||
let pulled = from_section(§ion);
|
||||
assert_eq!(pulled.max_file_size, 4096);
|
||||
assert!(!pulled.log_files);
|
||||
assert_eq!(pulled.index_scope, IndexScope::Workspace);
|
||||
assert_eq!(pulled.index_scope_depth, 2);
|
||||
assert!(!pulled.index_persist);
|
||||
assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store"));
|
||||
assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_cache_is_on_until_a_client_turns_it_off() {
|
||||
// Same shape as the file log, and the same direction for junk: the
|
||||
// setting that costs a user work if it is guessed wrong is "off", so
|
||||
// anything unreadable leaves it on.
|
||||
assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on");
|
||||
assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one");
|
||||
assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist);
|
||||
assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist);
|
||||
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
|
||||
let found = settings(json!({ "lucisv": { "index": { "persist": bad } } }));
|
||||
assert!(found.index_persist, "persist {bad} must be ignored");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_path_is_unset_until_a_client_names_one() {
|
||||
// The empty string is `lucisv.index.cachePath`'s own default and means
|
||||
// "you decide", exactly as it does for `lucisv.filelist` — not "the
|
||||
// directory named by the empty path".
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None);
|
||||
assert_eq!(
|
||||
settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path,
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } }))
|
||||
.index_cache_path
|
||||
.as_deref(),
|
||||
Some(".cache/lucisv")
|
||||
);
|
||||
for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] {
|
||||
let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } }));
|
||||
assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() {
|
||||
// The default is the narrow one, and it is what silence, an empty
|
||||
// sub-section and a missing `index` all resolve to.
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).index_scope, IndexScope::Folder);
|
||||
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope, IndexScope::Folder);
|
||||
assert_eq!(IndexScope::default(), IndexScope::Folder, "and the enum agrees");
|
||||
let wide = settings(json!({ "lucisv": { "index": { "scope": "workspace" } } }));
|
||||
assert_eq!(wide.index_scope, IndexScope::Workspace, "the migration setting");
|
||||
let narrow = settings(json!({ "lucisv": { "index": { "scope": "folder" } } }));
|
||||
assert_eq!(narrow.index_scope, IndexScope::Folder, "spelled out, same thing");
|
||||
// Anything else is junk, and junk leaves the *narrow* default: a
|
||||
// misparse must never buy a whole-workspace scan silently.
|
||||
for bad in
|
||||
[json!("Workspace"), json!("all"), json!(""), json!(2), json!(true), json!(["folder"])]
|
||||
{
|
||||
let found = settings(json!({ "lucisv": { "index": { "scope": bad } } }));
|
||||
assert_eq!(found.index_scope, IndexScope::Folder, "scope {bad} must be ignored");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
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.
|
||||
let absurd = settings(json!({ "lucisv": { "index": { "scopeDepth": 9999 } } }));
|
||||
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, DEFAULT_SCOPE_DEPTH,
|
||||
"scopeDepth {bad} must be ignored"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_is_taken_when_it_names_something() {
|
||||
let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } }));
|
||||
@@ -160,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"
|
||||
);
|
||||
}
|
||||
@@ -189,6 +628,37 @@ 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);
|
||||
assert!(!settings(json!({ "lucisv": { "formatOnSave": false } })).format_on_save);
|
||||
// Absence is off: the hook runs on every save of every buffer, and a
|
||||
// server that formatted uninvited would fight the editor's own
|
||||
// format-on-save.
|
||||
assert!(!settings(json!({ "lucisv": {} })).format_on_save, "and so is its absence");
|
||||
for bad in [json!("true"), json!(1), json!(null), json!([true]), json!({ "on": true })] {
|
||||
let found = settings(json!({ "lucisv": { "formatOnSave": bad } }));
|
||||
assert!(!found.format_on_save, "formatOnSave {bad} must be ignored");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_populated_payload_is_read_whole() {
|
||||
let found = settings(vscode_payload(json!(120), json!(4), json!(["vendor", "*_gen.sv"])));
|
||||
@@ -253,6 +723,72 @@ mod tests {
|
||||
assert_eq!(found.exclude, vec!["ok".to_string(), "fine".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_section_is_read_by_exactly_the_same_rules_as_a_pushed_one() {
|
||||
// The whole point of `from_section`: the pull answers the section's
|
||||
// contents, the push nests them one level deeper, and every rule
|
||||
// about ranges, types and defaults must be the one set of rules.
|
||||
let section = json!({
|
||||
"lineLength": 120, "indent": 4, "exclude": ["vendor"],
|
||||
"filelist": "rtl/files.f", "inlineTemplates": false, "formatOnSave": true
|
||||
});
|
||||
assert_eq!(from_section(§ion), settings(json!({ "lucisv": section })));
|
||||
// ...including the rejections.
|
||||
let junk = json!({ "indent": "4", "lineLength": 4000, "exclude": "vendor" });
|
||||
assert_eq!(from_section(&junk), settings(json!({ "lucisv": junk })));
|
||||
assert_eq!(from_section(&junk), ClientSettings::default(), "and they are rejections");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_pull_answer_is_the_defaults_rather_than_an_error() {
|
||||
// A client that cannot provide the section must answer `null`, per
|
||||
// spec — and one that answers something absurd instead must cost the
|
||||
// user no more than one that answered nothing.
|
||||
for answer in [
|
||||
json!(null),
|
||||
json!({}),
|
||||
json!("lucisv"),
|
||||
json!(7),
|
||||
json!([1, 2]),
|
||||
json!({ "lucisv": { "indent": 4 } }),
|
||||
] {
|
||||
assert_eq!(
|
||||
from_section(&answer),
|
||||
ClientSettings::default(),
|
||||
"the answer {answer} must resolve to the defaults"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_push_is_a_pull_signal_and_a_populated_one_is_not() {
|
||||
// `{"settings": null}` is what a modern `vscode-languageclient`
|
||||
// sends: "something changed, ask me". Applying it as a payload would
|
||||
// silently reset every setting the user had pulled.
|
||||
assert!(says_nothing(&json!(null)));
|
||||
assert!(says_nothing(&json!({})));
|
||||
assert!(!says_nothing(&json!({ "lucisv": { "indent": 4 } })));
|
||||
// A legacy push that syncs some *other* server's section is still a
|
||||
// push: it carries a payload, and this server's answer to it — no
|
||||
// opinion about anything — is what it has always been.
|
||||
assert!(!says_nothing(&json!({ "someOtherServer": { "indent": 4 } })));
|
||||
// Neither an array nor a scalar is the client saying "ask me"; both
|
||||
// are junk, and junk goes down the push path where `from_payload`
|
||||
// drops it.
|
||||
assert!(!says_nothing(&json!([])));
|
||||
assert!(!says_nothing(&json!("")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_section_constant_is_the_key_the_parser_reads() {
|
||||
// The pull asks for `SECTION` by name and the push nests under it. A
|
||||
// constant that drifted from the parser would make every pulled
|
||||
// setting silently invisible.
|
||||
let found = from_payload(&json!({ SECTION: { "indent": 4 } }));
|
||||
assert_eq!(found.indent, Some(4));
|
||||
assert_eq!(SECTION, "lucisv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_accepted_ranges_are_the_ones_lucisv_toml_accepts() {
|
||||
// The bounds above are copied from `lucisv_core::config`, which exports
|
||||
|
||||
@@ -321,7 +321,7 @@ endmodule
|
||||
tree.write("sub.sv", SUB);
|
||||
let path = tree.write("top.sv", top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
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;
|
||||
@@ -456,7 +456,7 @@ endmodule
|
||||
let top = "module top;\n bare #(\n";
|
||||
let path = tree.write("top.sv", top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
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.len() as u32 - 1;
|
||||
|
||||
+4657
-83
File diff suppressed because it is too large.
Load diff
@@ -179,7 +179,7 @@ mod tests {
|
||||
.expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
|
||||
let hits = workspace_symbols(&ws, "alpha");
|
||||
let names: Vec<_> = hits.iter().map(|h| h.name.as_str()).collect();
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
//! Applying a `didChange`'s edits to a buffer.
|
||||
//!
|
||||
//! With `TextDocumentSyncKind::INCREMENTAL` the client stops sending the whole
|
||||
//! file on every keystroke and sends the ranges it touched instead. The server
|
||||
//! is then the only holder of the buffer's text, so this module is the one
|
||||
//! place a wrong offset silently rewrites what the user is looking at — hence
|
||||
//! a pure function, a second implementation to cross-check it against, and no
|
||||
//! slicing that can panic. The exact clamping rules are in
|
||||
//! `docs/features/incremental-sync/README.md`.
|
||||
|
||||
use lsp_types::TextDocumentContentChangeEvent;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::convert::Positions;
|
||||
|
||||
/// Apply one `didChange`'s content changes to a buffer, in the order the
|
||||
/// client sent them, and return the buffer that results.
|
||||
///
|
||||
/// A change with no range replaces the whole document — what a full-sync
|
||||
/// client sends, and what still works if one arrives mid-batch.
|
||||
pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
let mut text = text.to_string();
|
||||
for change in changes {
|
||||
let Some(range) = change.range else {
|
||||
// The whole document. This also resets the state that the ranges
|
||||
// after it in the same batch are positioned against.
|
||||
text.clone_from(&change.text);
|
||||
continue;
|
||||
};
|
||||
// A fresh line table per change: each range is positioned against the
|
||||
// document as the *previous* changes in this batch left it. That is
|
||||
// O(changes × file) per notification, which at Verilog file sizes is
|
||||
// microseconds and buys a function with no incremental state to get
|
||||
// out of step.
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
let start = positions.offset(range.start) as usize;
|
||||
// A range that runs backwards is a client desync. Reading it as an
|
||||
// insertion at `start` is the one interpretation that deletes nothing:
|
||||
// we have no resync mechanism, so the safe direction is to keep text.
|
||||
let end = (positions.offset(range.end) as usize).max(start);
|
||||
let (Some(before), Some(after)) = (text.get(..start), text.get(end..)) else {
|
||||
// Unreachable: `Positions::offset` only ever returns character
|
||||
// boundaries. Written as a skip rather than a slice because the
|
||||
// slice would panic, and a panic here takes the buffer with it.
|
||||
continue;
|
||||
};
|
||||
text = format!("{before}{}{after}", change.text);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::{Position, Range};
|
||||
|
||||
fn pos(line: u32, character: u32) -> Position {
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
/// A ranged change, the way a client sends one.
|
||||
fn edit(
|
||||
start: (u32, u32),
|
||||
end: (u32, u32),
|
||||
text: &str,
|
||||
) -> lsp_types::TextDocumentContentChangeEvent {
|
||||
TextDocumentContentChangeEvent {
|
||||
range: Some(Range { start: pos(start.0, start.1), end: pos(end.0, end.1) }),
|
||||
range_length: None,
|
||||
text: text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A rangeless change: the whole buffer, as a full-sync client sends it.
|
||||
fn whole(text: &str) -> TextDocumentContentChangeEvent {
|
||||
TextDocumentContentChangeEvent { range: None, range_length: None, text: text.to_string() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_lands_where_the_range_is_empty() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 8), (1, 8), "b")]);
|
||||
assert_eq!(after, "module m;\n wire ab;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_removes_exactly_the_range() {
|
||||
let text = "module m;\n wire aaa;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 7), (1, 10), "")]);
|
||||
assert_eq!(after, "module m;\n wire ;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replace_swaps_the_range_for_the_text() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let after = apply_changes(text, &[edit((1, 2), (1, 6), "logic")]);
|
||||
assert_eq!(after, "module m;\n logic a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_range_collapses_the_lines_it_spans() {
|
||||
let text = "a\nb\nc\n";
|
||||
let after = apply_changes(text, &[edit((0, 1), (2, 0), "X")]);
|
||||
assert_eq!(after, "aXc\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_changes_see_what_the_earlier_ones_did() {
|
||||
// The batch a real editor sends for "type `wire w;` on a new line",
|
||||
// split into three: each range is against the state after the last.
|
||||
let text = "module m;\nendmodule\n";
|
||||
let after = apply_changes(
|
||||
text,
|
||||
&[
|
||||
edit((1, 0), (1, 0), "\n"), // open a line
|
||||
edit((1, 0), (1, 0), " wire "), // the keyword
|
||||
edit((1, 7), (1, 7), "w;"), // the name
|
||||
],
|
||||
);
|
||||
assert_eq!(after, "module m;\n wire w;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_range_positioned_against_the_original_text_would_be_wrong() {
|
||||
// The regression this whole module exists to prevent: if the line
|
||||
// table were built once, the second range below would land on the old
|
||||
// line 1 and the result would differ.
|
||||
let text = "aaa\nbbb\n";
|
||||
let after = apply_changes(text, &[edit((0, 0), (0, 0), "x\n"), edit((1, 1), (1, 2), "Z")]);
|
||||
assert_eq!(after, "x\naZa\nbbb\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_byte_character_is_one_utf16_unit_to_the_edit_too() {
|
||||
let text = "// é ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 5), (0, 7), "no")]);
|
||||
assert_eq!(after, "// é no\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_astral_character_takes_two_units_and_is_never_split() {
|
||||
// `🎉` is 2 UTF-16 units. A boundary on its low half rounds forward
|
||||
// past the whole character, so no edit can ever cut it in half.
|
||||
let text = "// 🎉 ok\n";
|
||||
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 5), "X")]), "// X ok\n");
|
||||
// Start inside the pair: the emoji survives, the edit begins after it.
|
||||
assert_eq!(apply_changes(text, &[edit((0, 4), (0, 6), "X")]), "// 🎉Xok\n");
|
||||
// End inside the pair: rounds forward, so the emoji goes with it.
|
||||
assert_eq!(apply_changes(text, &[edit((0, 3), (0, 4), "X")]), "// X ok\n");
|
||||
for change in [edit((0, 4), (0, 4), "!"), edit((0, 4), (0, 5), "!")] {
|
||||
let out = apply_changes(text, &[change]);
|
||||
assert!(out.is_char_boundary(out.len()), "still valid UTF-8: {out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_after_an_emoji_counts_from_the_right_column() {
|
||||
let text = "// 🎉 wire a;\n";
|
||||
// "wire" starts at UTF-16 unit 6: `/`,`/`,` `,🎉(2),` `.
|
||||
let after = apply_changes(text, &[edit((0, 6), (0, 10), "logic")]);
|
||||
assert_eq!(after, "// 🎉 logic a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_ends_survive_an_edit_on_the_line() {
|
||||
let text = "module m;\r\n wire a;\r\nendmodule\r\n";
|
||||
let after = apply_changes(text, &[edit((1, 7), (1, 8), "bb")]);
|
||||
assert_eq!(after, "module m;\r\n wire bb;\r\nendmodule\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_line_can_be_joined_to_the_next() {
|
||||
let text = "ab\r\ncd\r\n";
|
||||
let after = apply_changes(text, &[edit((0, 2), (1, 0), "")]);
|
||||
assert_eq!(after, "abcd\r\n", "the whole `\\r\\n` goes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_at_the_start_of_the_document() {
|
||||
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 0), "// ")]), "// wire a;\n");
|
||||
assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 4), "logic")]), "logic a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_at_end_of_file() {
|
||||
// The empty last line a trailing newline opens.
|
||||
assert_eq!(apply_changes("a\n", &[edit((1, 0), (1, 0), "b\n")]), "a\nb\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_insert_at_the_end_of_a_last_line_with_no_trailing_newline() {
|
||||
assert_eq!(apply_changes("endmodule", &[edit((0, 9), (0, 9), "\n")]), "endmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_into_an_empty_document() {
|
||||
assert_eq!(apply_changes("", &[edit((0, 0), (0, 0), "module m;")]), "module m;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rangeless_change_replaces_the_whole_document() {
|
||||
assert_eq!(apply_changes("old\n", &[whole("new\n")]), "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_of_several_rangeless_changes_wins() {
|
||||
// What the full-sync handler did before this feature, unchanged.
|
||||
assert_eq!(apply_changes("old\n", &[whole("a\n"), whole("b\n"), whole("c\n")]), "c\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rangeless_change_resets_what_the_next_range_is_against() {
|
||||
let after = apply_changes("anything\n", &[whole("abc\ndef\n"), edit((1, 1), (1, 2), "X")]);
|
||||
assert_eq!(after, "abc\ndXf\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_changes_is_the_buffer_unchanged() {
|
||||
assert_eq!(apply_changes("wire a;\n", &[]), "wire a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_past_the_end_clamps_to_the_end_of_the_document() {
|
||||
let text = "a\nb\n";
|
||||
assert_eq!(apply_changes(text, &[edit((99, 0), (99, 5), "X")]), "a\nb\nX");
|
||||
// And a range that *starts* in the document and ends past it.
|
||||
assert_eq!(apply_changes(text, &[edit((1, 0), (99, 0), "X")]), "a\nX");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_past_the_end_of_a_line_clamps_to_its_content() {
|
||||
assert_eq!(apply_changes("ab\ncd\n", &[edit((0, 99), (0, 99), "!")]), "ab!\ncd\n");
|
||||
assert_eq!(apply_changes("ab\r\ncd\r\n", &[edit((0, 99), (0, 99), "!")]), "ab!\r\ncd\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_that_runs_backwards_deletes_nothing() {
|
||||
// Clamping `end` up to `start` turns a desynced range into a pure
|
||||
// insertion — the only reading that cannot lose the user's text.
|
||||
assert_eq!(apply_changes("abcdef\n", &[edit((0, 4), (0, 1), "X")]), "abcdXef\n");
|
||||
assert_eq!(apply_changes("ab\ncd\n", &[edit((1, 1), (0, 0), "X")]), "ab\ncXd\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// randomized cross-check against a second implementation
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A fixed-seed linear congruential generator — deterministic randomness
|
||||
/// with no dependency. The constants are Knuth's MMIX.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// The same rules, implemented a second way: a flat `Vec<char>` with the
|
||||
/// line starts scanned out of it, rather than byte offsets off a
|
||||
/// `LineIndex`. Sharing no code with `apply_changes` is the point.
|
||||
fn reference_apply(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
let mut text = text.to_string();
|
||||
for change in changes {
|
||||
let Some(range) = change.range else {
|
||||
text.clone_from(&change.text);
|
||||
continue;
|
||||
};
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let start = reference_index(&chars, range.start);
|
||||
let end = reference_index(&chars, range.end).max(start);
|
||||
let mut out: String = chars[..start].iter().collect();
|
||||
out.push_str(&change.text);
|
||||
out.extend(chars[end..].iter());
|
||||
text = out;
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The index into `chars` that a position names: lines are `\n`-
|
||||
/// terminated, one `\r` before that terminator is not content, a
|
||||
/// character past a line's content clamps to it, a line past the last
|
||||
/// clamps to the end of the text, and a character landing inside a
|
||||
/// surrogate pair rounds forward past the whole character.
|
||||
fn reference_index(chars: &[char], position: Position) -> usize {
|
||||
let mut starts = vec![0usize];
|
||||
for (i, c) in chars.iter().enumerate() {
|
||||
if *c == '\n' {
|
||||
starts.push(i + 1);
|
||||
}
|
||||
}
|
||||
let Some(&start) = starts.get(position.line as usize) else {
|
||||
return chars.len();
|
||||
};
|
||||
// The line's content ends before its `\n`, and before one `\r`.
|
||||
let mut end = match starts.get(position.line as usize + 1) {
|
||||
Some(&next) => next - 1,
|
||||
None => chars.len(),
|
||||
};
|
||||
if end > start && chars[end - 1] == '\r' {
|
||||
end -= 1;
|
||||
}
|
||||
let mut units = 0u32;
|
||||
let mut at = start;
|
||||
while at < end && units < position.character {
|
||||
units += chars[at].len_utf16() as u32;
|
||||
at += 1;
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// A random document over an alphabet that mixes every width and both
|
||||
/// line endings — including a bare `\r`, which is an ordinary character.
|
||||
fn random_text(rng: &mut Lcg) -> String {
|
||||
const ALPHABET: [&str; 8] = ["a", "b", " ", ";", "\n", "\r\n", "é", "🎉"];
|
||||
let len = rng.below(24);
|
||||
(0..len).map(|_| ALPHABET[rng.below(8) as usize]).collect()
|
||||
}
|
||||
|
||||
/// A random change: mostly ranged, occasionally a whole-document reset,
|
||||
/// with positions that are often — but deliberately not always — inside
|
||||
/// the document.
|
||||
fn random_change(rng: &mut Lcg, text: &str) -> TextDocumentContentChangeEvent {
|
||||
if rng.below(10) == 0 {
|
||||
return whole(&random_text(rng));
|
||||
}
|
||||
let lines = text.matches('\n').count() as u32 + 1;
|
||||
let position = |rng: &mut Lcg| Position {
|
||||
line: rng.below(u64::from(lines) + 2) as u32,
|
||||
character: rng.below(12) as u32,
|
||||
};
|
||||
let (first, second) = (position(rng), position(rng));
|
||||
TextDocumentContentChangeEvent {
|
||||
range: Some(Range { start: first, end: second }),
|
||||
range_length: None,
|
||||
text: random_text(rng),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_edit_sequences_agree_with_the_reference_model() {
|
||||
let mut rng = Lcg(0x5EED_1CE5);
|
||||
let mut ranged = 0usize;
|
||||
for case in 0..400 {
|
||||
let text = random_text(&mut rng);
|
||||
let mut changes = Vec::new();
|
||||
let mut running = text.clone();
|
||||
for _ in 0..rng.below(5) + 1 {
|
||||
let change = random_change(&mut rng, &running);
|
||||
ranged += usize::from(change.range.is_some());
|
||||
// The next range is against the state this one leaves.
|
||||
running = apply_changes(&running, std::slice::from_ref(&change));
|
||||
changes.push(change);
|
||||
}
|
||||
let ours = apply_changes(&text, &changes);
|
||||
assert_eq!(ours, reference_apply(&text, &changes), "case {case}, from {text:?}");
|
||||
assert_eq!(ours, running, "case {case}: one batch equals the changes one at a time");
|
||||
}
|
||||
assert!(ranged > 500, "the cases must be mostly ranged edits, got {ranged}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA additions (2026-08-26) — see docs/features/incremental-sync/README.md
|
||||
// QA log for the full writeup of each of these.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_deletion_starting_at_the_low_surrogate_index_preserves_the_character() {
|
||||
// Character 4 is the low half of `🎉`'s pair (the emoji starts at 3,
|
||||
// ends at 5). A *start* boundary landing there rounds forward past
|
||||
// the whole character, so the emoji is excluded from — and survives
|
||||
// — a deletion that begins mid-pair.
|
||||
let text = "// 🎉 ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 4), (0, 6), "")]);
|
||||
assert_eq!(after, "// 🎉ok\n", "the emoji stays, only the trailing space is deleted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character() {
|
||||
// Symmetric case: an *end* boundary on the low half also rounds
|
||||
// forward, but here that means the deletion is widened to swallow
|
||||
// the whole character rather than stopping short of it.
|
||||
let text = "// 🎉 ok\n";
|
||||
let after = apply_changes(text, &[edit((0, 3), (0, 4), "")]);
|
||||
assert_eq!(after, "// ok\n", "the whole emoji is gone, both flanking spaces remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_split_across_two_changes_in_one_batch_reorders_the_bytes() {
|
||||
// QA finding (docs/features/incremental-sync/README.md QA log,
|
||||
// 2026-08-26): pinning present, *surprising* behavior rather than
|
||||
// asserting it is correct. `convert.rs::line_content_end` treats a
|
||||
// trailing bare `\r` as "not content" whether or not a `\n` will
|
||||
// follow it, so a second change in the same batch that targets "end
|
||||
// of line" after a first change appended a lone `\r` lands *before*
|
||||
// that `\r`, not after it. A client that split one `\r\n` insertion
|
||||
// into two ranged changes this way would get `\n\r`, not `\r\n`. No
|
||||
// real editor's diff algorithm is known to do this, and no panic or
|
||||
// data loss occurs — but if this test's expected string ever needs
|
||||
// to change to `"ab\r\n"`, that is a deliberate fix to
|
||||
// `Positions::offset`/`line_content_end`, not an accidental one.
|
||||
let text = "ab";
|
||||
let after = apply_changes(text, &[edit((0, 2), (0, 2), "\r"), edit((0, 2), (0, 2), "\n")]);
|
||||
assert_eq!(after, "ab\n\r", "known edge case: see the comment above");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_covering_the_final_newline_removes_exactly_it() {
|
||||
let text = "a\nb\n";
|
||||
let after = apply_changes(text, &[edit((1, 1), (2, 0), "")]);
|
||||
assert_eq!(after, "a\nb", "the trailing newline is gone, nothing else is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_width_inserts_at_the_same_position_compose_in_batch_order() {
|
||||
// Not a bug: per protocol, each change is positioned against what the
|
||||
// previous ones in the batch left, so two inserts naming the same
|
||||
// literal position land with the *second* one first — a client that
|
||||
// wants "12" must advance the second insert's position past the
|
||||
// first's text, exactly as it would need to for a non-zero-width
|
||||
// range. Pinned so a future refactor cannot silently change the
|
||||
// batch's ordering semantics.
|
||||
let text = "x";
|
||||
let after = apply_changes(text, &[edit((0, 0), (0, 0), "1"), edit((0, 0), (0, 0), "2")]);
|
||||
assert_eq!(after, "21x");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -8,7 +8,7 @@
|
||||
//! module asks it to say what it sees. See
|
||||
//! `docs/features/file-watching/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::notification::{DidChangeWatchedFiles, Notification as _};
|
||||
use lsp_types::{
|
||||
@@ -112,7 +112,36 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
|
||||
.any(|path| watched(&path, filelist))
|
||||
}
|
||||
|
||||
fn watched(path: &Path, filelist: Option<&Path>) -> bool {
|
||||
/// The one file an event named, when it named exactly one and that one is not
|
||||
/// the filelist.
|
||||
///
|
||||
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
|
||||
/// checkout fills this list, and a list of one is the case a single file's
|
||||
/// contribution can be replaced in place. The filelist is excluded because a
|
||||
/// change to it moves the whole scope, which is a rebuild by definition. An
|
||||
/// event naming the same path twice — a client is free to send `Changed` and
|
||||
/// `Created` for one file — is still one file.
|
||||
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
|
||||
let mut named: Vec<PathBuf> = changes
|
||||
.iter()
|
||||
.filter_map(|change| uri_to_path(&change.uri))
|
||||
.filter(|path| watched(path, filelist))
|
||||
.collect();
|
||||
named.sort();
|
||||
named.dedup();
|
||||
match named.as_slice() {
|
||||
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether one path is something the index reads: a source file, or the
|
||||
/// filelist that decides which source files there are.
|
||||
///
|
||||
/// Public since 2026-08-27 for `file_ops.rs`: `didRenameFiles`/`didDeleteFiles`
|
||||
/// nudge the index for exactly the paths a watcher event would, and two copies
|
||||
/// of that test would drift.
|
||||
pub fn watched(path: &Path, filelist: Option<&Path>) -> bool {
|
||||
if filelist == Some(path) {
|
||||
return true;
|
||||
}
|
||||
|
||||
+3263
-21
File diff suppressed because it is too large.
Load diff
@@ -77,6 +77,11 @@ impl From<VerificationError> for FormatError {
|
||||
/// The output is only returned if it re-lexes to the same token stream as the
|
||||
/// input (comments included) and formatting it again is a fixed point;
|
||||
/// otherwise the caller gets an error and must leave the original text alone.
|
||||
///
|
||||
/// Parses `source` (twice, for verification), so call this only on a thread
|
||||
/// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one
|
||||
/// lets sufficiently nested input abort the process instead of returning
|
||||
/// `Err` (see `docs/features/recursion-limit/README.md`).
|
||||
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
let output = format_once(source, config).map_err(FormatError::Source)?;
|
||||
verify_equivalence(source, &output)?;
|
||||
@@ -93,6 +98,9 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
|
||||
/// formatter output, and both checks are global. Convergence is checked by
|
||||
/// replaying the same per-item decisions against the output — see
|
||||
/// `docs/features/range-formatting/README.md`.
|
||||
///
|
||||
/// Same stack requirement as [`format_source`]: needs a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
|
||||
pub fn format_range(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
@@ -405,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);
|
||||
}
|
||||
@@ -824,6 +839,63 @@ 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.
|
||||
@@ -1533,6 +1605,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));
|
||||
@@ -1568,6 +1643,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(" "));
|
||||
@@ -1601,7 +1679,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("#"));
|
||||
@@ -1872,9 +1950,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(" ") });
|
||||
@@ -1973,7 +2065,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));
|
||||
@@ -2161,6 +2253,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 } => {
|
||||
@@ -2175,15 +2271,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2312,10 +2418,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)
|
||||
@@ -2323,13 +2436,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)])])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2417,6 +2536,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);
|
||||
}
|
||||
@@ -2461,17 +2586,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 (")];
|
||||
@@ -2503,7 +2632,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")];
|
||||
@@ -2524,7 +2654,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 } => {
|
||||
@@ -2581,16 +2712,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 {
|
||||
@@ -2652,9 +2785,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
|
||||
@@ -2692,9 +2829,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()
|
||||
@@ -2736,16 +2873,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));
|
||||
}
|
||||
@@ -2866,25 +3014,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) => {
|
||||
@@ -3044,6 +3183,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.
|
||||
@@ -3094,3 +3241,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
|
||||
@@ -194,3 +194,52 @@ module m
|
||||
import c::u;
|
||||
#(parameter int W = 8) (input clk_i);
|
||||
endmodule
|
||||
====
|
||||
# a direction-less first ANSI port: the normal spelling of an interface port
|
||||
module m(bus_if bus,input logic clk);endmodule
|
||||
----
|
||||
module m (bus_if bus, input logic clk);
|
||||
endmodule
|
||||
====
|
||||
# the same port with a modport, and alone in the list
|
||||
module m( bus_if.mp bus );endmodule
|
||||
----
|
||||
module m (bus_if.mp bus);
|
||||
endmodule
|
||||
====
|
||||
# a package-scoped type as the first port
|
||||
module m(my_pkg::state_t s,output logic q);endmodule
|
||||
----
|
||||
module m (my_pkg::state_t s, output logic q);
|
||||
endmodule
|
||||
====
|
||||
# an interface header takes the same list
|
||||
interface i(bus_if.mp bus,input logic clk);endinterface
|
||||
----
|
||||
interface i (bus_if.mp bus, input logic clk);
|
||||
endinterface
|
||||
====
|
||||
# a typed first port with packed dimensions and a parameterized one
|
||||
module m(word_t [3:0] d,item #(A, B) req,input a);endmodule
|
||||
----
|
||||
module m (word_t [3:0] d, item #(A, B) req, input a);
|
||||
endmodule
|
||||
====
|
||||
# a direction-less first port in a list too wide for one line
|
||||
module wide_module_name_here(bus_if.mp bus_interface_port,my_pkg::state_t current_state_in,input logic clock_signal,output logic [31:0] result_word_out);endmodule
|
||||
----
|
||||
module wide_module_name_here (
|
||||
bus_if.mp bus_interface_port,
|
||||
my_pkg::state_t current_state_in,
|
||||
input logic clock_signal,
|
||||
output logic [31:0] result_word_out
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# a name-only non-ANSI list is untouched by the disambiguation
|
||||
module m(a,b);input a;output b;endmodule
|
||||
----
|
||||
module m (a, b);
|
||||
input a;
|
||||
output b;
|
||||
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,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
|
||||
@@ -7,13 +7,15 @@
|
||||
//! the formatter at all.
|
||||
|
||||
use vlog_formatter::{format_source, Config, FormatError};
|
||||
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH};
|
||||
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH, PARSE_STACK_SIZE};
|
||||
|
||||
/// Formatting the deepest legal tree peaks around 4 MiB of stack in an
|
||||
/// unoptimized build, more than a default test thread's 2 MiB.
|
||||
/// 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 two limits need.
|
||||
fn format_deep(source: String) -> Result<String, FormatError> {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || format_source(&source, &Config::default()))
|
||||
.expect("spawn formatter thread")
|
||||
.join()
|
||||
@@ -68,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,232 @@ 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",
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
@@ -300,12 +300,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 +533,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 +560,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 +630,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 +680,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 +807,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 +1018,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 +1229,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 +1455,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>),
|
||||
|
||||
@@ -22,7 +22,7 @@ pub enum DefineKind {
|
||||
}
|
||||
|
||||
/// One `` `define`` or `` `undef`` directive, as written.
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Define {
|
||||
/// Whether this entry defines the name or undefines it.
|
||||
pub kind: DefineKind,
|
||||
@@ -48,12 +48,24 @@ pub struct Define {
|
||||
///
|
||||
/// Redefinition is legal Verilog, so a name can have several definitions; they
|
||||
/// are all kept and [`DefineTable::latest`] picks the last one.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct DefineTable {
|
||||
entries: Vec<Define>,
|
||||
}
|
||||
|
||||
impl DefineTable {
|
||||
/// A table from entries that are already known, in source order.
|
||||
///
|
||||
/// The inverse of [`DefineTable::entries`], for the one caller that has a
|
||||
/// file's directives without the file's tokens: the workspace index's
|
||||
/// persistent cache, which stores what a parse found and restores it
|
||||
/// (`docs/features/index-persistence/README.md`). Nothing is re-derived
|
||||
/// here — `collect_defines` is still the only thing that *reads* a table
|
||||
/// out of a file.
|
||||
pub fn from_entries(entries: Vec<Define>) -> DefineTable {
|
||||
DefineTable { entries }
|
||||
}
|
||||
|
||||
/// Every recorded directive, `` `undef``s included, in source order.
|
||||
pub fn entries(&self) -> &[Define] {
|
||||
&self.entries
|
||||
|
||||
@@ -14,7 +14,7 @@ pub mod token;
|
||||
|
||||
pub use lexer::{tokenize, LexError};
|
||||
pub use line_index::LineIndex;
|
||||
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError};
|
||||
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError, PARSE_STACK_SIZE};
|
||||
pub use span::TextRange;
|
||||
pub use token::KEYWORDS;
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
+2066
-149
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()
|
||||
|
||||
@@ -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,8 +595,10 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -712,6 +720,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 +824,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 +875,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);
|
||||
}
|
||||
|
||||
@@ -902,14 +902,24 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_typed_port_list_is_refused_as_a_parse_failure() {
|
||||
// The disclosed `vlog_parser` gap: an interface-typed ANSI port
|
||||
// (`iface_bus.mst bus`) stops the header from parsing, so no module
|
||||
// is produced at all. The refusal must name the real cause.
|
||||
fn an_interface_typed_port_list_is_planned_like_any_other() {
|
||||
// Was the disclosed `vlog_parser` gap: an interface-typed ANSI port
|
||||
// (`iface_bus.mst bus`) as the first, direction-less element stopped
|
||||
// the header from parsing, so no module was produced at all and the
|
||||
// refusal had to name the real cause. `docs/features/ansi-first-port`
|
||||
// closed it, so the plan is now the ordinary one — an interface port
|
||||
// has no direction, and its type is the interface (with its modport)
|
||||
// exactly as written.
|
||||
let text = "module m (iface_bus.mst bus, input logic clk);\nendmodule\n";
|
||||
let message = instantiation_plan("m", text, None).expect_err("the parser gap");
|
||||
assert!(message.contains("does not parse"), "{message}");
|
||||
assert!(message.contains("line"), "{message}");
|
||||
let plan = plan(text, "m");
|
||||
assert_eq!(plan.ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["bus", "clk"]);
|
||||
assert_eq!(plan.ports[0].dir, "");
|
||||
assert_eq!(plan.ports[0].ty, "iface_bus.mst");
|
||||
assert_eq!(plan.ports[1].dir, "input");
|
||||
assert_eq!(plan.ports[1].ty, "logic");
|
||||
let skeleton = plan.render(&Layout::default());
|
||||
assert!(skeleton.contains(".bus("), "{skeleton}");
|
||||
assert!(parses(&skeleton), "{skeleton}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -318,6 +318,61 @@ fn a_port_renames_inside_the_connection_lists_of_other_files() {
|
||||
assert!(after.contains(".rst(1'b1)"), "the other connection is untouched: {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_renames_from_the_declaration_it_types_in_another_file() {
|
||||
// Overlay promotion (`docs/features/overlay-promotion/README.md`) made
|
||||
// this reachable: an unqualified type name nothing in the using file
|
||||
// binds is now an external candidate the workspace answers, so the two
|
||||
// halves of the rename are one symbol instead of two unrelated words.
|
||||
// The interface is written in the body rather than in the header, which
|
||||
// is the shape this test has always pinned. The header spelling reaches
|
||||
// the same reference since `docs/features/ansi-first-port/README.md`, and
|
||||
// is asserted below as its own arm.
|
||||
let iface = "interface bus_if;\nendinterface\n";
|
||||
let top = "module top;\n virtual bus_if vif;\n bus_if other ();\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
|
||||
|
||||
let edit = rename(&files, &path("top.sv"), at(top, "virtual", "bus_if"), "fabric_if")
|
||||
.expect("renames");
|
||||
assert!(apply(iface, &edit, &path("bus_if.sv")).contains("interface fabric_if;"));
|
||||
let after = apply(top, &edit, &path("top.sv"));
|
||||
assert!(after.contains("virtual fabric_if vif;"), "{after}");
|
||||
assert!(after.contains("fabric_if other ()"), "the instantiation too: {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_renames_through_a_direction_less_ansi_port() {
|
||||
// The header spelling of the same rename, which needed
|
||||
// `docs/features/ansi-first-port/README.md` to parse at all: the port is
|
||||
// first and carries no direction, and its modport travels with the type.
|
||||
let iface = "interface bus_if;\n modport mp (input a);\nendinterface\n";
|
||||
let top = "module top (bus_if.mp bus, input logic clk);\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
|
||||
|
||||
let edit =
|
||||
rename(&files, &path("top.sv"), at(top, "top ", "bus_if"), "fabric_if").expect("renames");
|
||||
assert!(apply(iface, &edit, &path("bus_if.sv")).contains("interface fabric_if;"));
|
||||
let after = apply(top, &edit, &path("top.sv"));
|
||||
assert!(after.contains("module top (fabric_if.mp bus,"), "{after}");
|
||||
}
|
||||
|
||||
#[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";
|
||||
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());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// refusals
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -375,6 +430,24 @@ fn an_unresolved_name_is_refused_rather_than_guessed() {
|
||||
assert!(message.contains("not resolved"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_value_position_typo_never_reaches_an_unrelated_same_named_module() {
|
||||
// The regression the overlay-promotion round shipped and this round took
|
||||
// back (QA finding 1, 2026-08-26). `typo_name` on an assignment's LHS is a
|
||||
// plain expression identifier — `Target::Lexical` via `ExprKind::Ident`,
|
||||
// not a type window — so it is never given the bare-name path that would
|
||||
// make it an external candidate. Without that, `locate` takes the
|
||||
// `NotFound` arm and refuses, instead of rewriting an unrelated file's
|
||||
// module declaration on nothing but a name collision.
|
||||
let unrelated = "module typo_name;\nendmodule\n";
|
||||
let top = "module top;\n assign typo_name = 1'b1;\nendmodule\n";
|
||||
let files = workspace(&[("typo_name.sv", unrelated), ("top.sv", top)]);
|
||||
|
||||
let message = rename(&files, &path("top.sv"), at(top, "assign", "typo_name"), "fixed_name")
|
||||
.expect_err("a value-position typo must not be renamable across files");
|
||||
assert!(message.contains("not resolved to any declaration"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_outside_the_indexed_files_is_refused() {
|
||||
let text = "module m;\n import other_pkg::*;\n wire w = FROM_ELSEWHERE;\nendmodule\n";
|
||||
|
||||
@@ -22,6 +22,14 @@ pub(crate) struct Pending {
|
||||
pub(crate) enum Target {
|
||||
/// The lexical chain from `scope` outward, imports included.
|
||||
Lexical,
|
||||
/// A name written where a **type** goes — the user-defined type of a
|
||||
/// declaration, a port, a parameter, a return type, a `virtual` interface
|
||||
/// property. Looked up exactly like [`Target::Lexical`], but a miss also
|
||||
/// carries the bare name to the workspace, because that is how a
|
||||
/// cross-file `interface`, `class` or `typedef` is spelled. Every type
|
||||
/// position reaches this through [`Binder::bind_data_type`]; an
|
||||
/// identifier in a *value* position never does.
|
||||
Type,
|
||||
/// A package name: the `p` of `import p::x`. Only a package can be
|
||||
/// imported, so this stays narrower than [`Target::Unit`].
|
||||
Package,
|
||||
@@ -134,6 +142,7 @@ impl<'a> Binder<'a> {
|
||||
kind,
|
||||
name_span,
|
||||
decl_span,
|
||||
detail_span: None,
|
||||
scope,
|
||||
child_scope: None,
|
||||
});
|
||||
@@ -299,7 +308,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);
|
||||
@@ -493,6 +504,27 @@ impl<'a> Binder<'a> {
|
||||
ScopeKind::Function | ScopeKind::Task => SymbolKind::TfArg,
|
||||
_ => SymbolKind::Port,
|
||||
};
|
||||
// A non-ANSI port's body declaration (`input signed [31:0] data_in;`)
|
||||
// completes a port the header only named (`data_in,`). `declare`
|
||||
// below attaches it as a reference to that header symbol — and here,
|
||||
// the whole declaration's span is recorded on the symbol as where its
|
||||
// direction, type and width are written. First writer wins, so a
|
||||
// header that names a port twice is the linter's to complain about
|
||||
// and this stays deterministic.
|
||||
//
|
||||
// An old-style task or function argument (`task t(a);` finished by
|
||||
// `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.
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
|
||||
}
|
||||
|
||||
@@ -967,6 +999,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);
|
||||
}
|
||||
@@ -997,6 +1031,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)
|
||||
}
|
||||
@@ -1046,6 +1084,11 @@ impl<'a> Binder<'a> {
|
||||
TimingControl::Event(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 { .. }) => {}
|
||||
@@ -1219,8 +1262,16 @@ impl<'a> Binder<'a> {
|
||||
self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string()));
|
||||
}
|
||||
None => {
|
||||
let ns = crate::scan::name_span(self.src, window, &ty.name);
|
||||
self.use_name(scope, &ty.name, ns, Target::Lexical);
|
||||
// `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 ns = crate::scan::name_span(self.src, window, name);
|
||||
self.use_name(scope, name, ns, Target::Type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Finding class declarations in a parse tree — one walk, two readers.
|
||||
//!
|
||||
//! `type_hierarchy.rs` wants every class in a file so it can build a hierarchy
|
||||
//! item for the one the cursor names; the workspace index wants the same walk
|
||||
//! so it can record who extends whom as it builds
|
||||
//! (`docs/features/incremental-index/README.md`). One walk here, so the census
|
||||
//! the index holds and the declaration the hierarchy shows can never disagree.
|
||||
//!
|
||||
//! **Lifted from `lucisv_server::type_hierarchy` on 2026-08-27**, unchanged by
|
||||
//! the move.
|
||||
|
||||
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
/// One class declaration: the node, and the extent of the whole
|
||||
/// `class ... endclass` it was written as.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Decl<'a> {
|
||||
/// The declaration node, for its name and its `extends` clause.
|
||||
pub class: &'a ClassDecl,
|
||||
/// Code extent of the declaration, attributes included — what a type
|
||||
/// hierarchy item's `range` is.
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
/// Every class declaration in `items`, wherever a class may be written: at file
|
||||
/// scope, inside a `package`, inside a `module`, and nested inside another
|
||||
/// class.
|
||||
pub fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
|
||||
let mut out = Vec::new();
|
||||
collect(items, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The base class one declaration names, as written — `None` when the header
|
||||
/// has no `extends`.
|
||||
///
|
||||
/// The name is the bare base: `extends base #(8)` reads `base`, because the
|
||||
/// parser keeps the parameter overrides on their own field, so a parameterized
|
||||
/// base needs no unwrapping here.
|
||||
pub fn extends_name(class: &ClassDecl) -> Option<&str> {
|
||||
class.extends.as_ref().map(|extends| extends.name.as_str())
|
||||
}
|
||||
|
||||
fn collect<'a>(items: &'a [Item], out: &mut Vec<Decl<'a>>) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Class(class) => {
|
||||
out.push(Decl { class, span: item.span });
|
||||
collect(&class.items, out);
|
||||
}
|
||||
ItemKind::Package { items, .. } => collect(items, out),
|
||||
ItemKind::Module(module) => collect(&module.items, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
/// Every class name a file declares, in walk order, with its base.
|
||||
fn declared(text: &str) -> Vec<(String, String)> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
declarations(&tree.items)
|
||||
.iter()
|
||||
.map(|decl| {
|
||||
(decl.class.name.clone(), extends_name(decl.class).unwrap_or("-").to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_is_found_wherever_it_may_be_written() {
|
||||
let text = "\
|
||||
class top extends base;
|
||||
class nested extends top;
|
||||
endclass
|
||||
endclass
|
||||
|
||||
package p;
|
||||
class in_pkg extends top;
|
||||
endclass
|
||||
endpackage
|
||||
|
||||
module m;
|
||||
class in_mod;
|
||||
endclass
|
||||
endmodule
|
||||
";
|
||||
assert_eq!(
|
||||
declared(text),
|
||||
[
|
||||
("top".to_string(), "base".to_string()),
|
||||
("nested".to_string(), "top".to_string()),
|
||||
("in_pkg".to_string(), "top".to_string()),
|
||||
("in_mod".to_string(), "-".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameterized_base_names_the_bare_class() {
|
||||
assert_eq!(
|
||||
declared("class d extends b #(8);\nendclass\n"),
|
||||
[("d".to_string(), "b".to_string())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declarations_extent_contains_its_own_name() {
|
||||
let text = "class first;\nendclass\n\nclass second;\nendclass\n";
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let decls = declarations(&tree.items);
|
||||
assert_eq!(decls.len(), 2);
|
||||
for decl in &decls {
|
||||
assert!(decl.span.start <= decl.class.name_span.start);
|
||||
assert!(decl.class.name_span.end <= decl.span.end);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,574 @@
|
||||
//! [`FileFacts`] as one line of text: the format the index cache stores a
|
||||
//! parse's result in, and reads it back from.
|
||||
//!
|
||||
//! Hand-rolled, because the alternative is a serialization dependency in a
|
||||
//! crate that has one dependency and it is the parser. The shape is the one
|
||||
//! `lucisv_core::cache` established for the formatter's store — tab-separated
|
||||
//! fields on one line, so a torn write is a line without a newline and a
|
||||
//! record that does not parse is a record that is dropped — with lists
|
||||
//! length-prefixed rather than nested, so reading a record is one pass over a
|
||||
//! flat token stream and nothing is ambiguous.
|
||||
//!
|
||||
//! **Anything that changes what a record holds, or how it is written, bumps
|
||||
//! [`FACTS_FORMAT`].** A record written by another format is not read at all;
|
||||
//! see `docs/features/index-persistence/README.md` for why the cache would
|
||||
//! rather redo the work than guess.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::defines::{Define, DefineKind, DefineTable};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::model::SymbolKind;
|
||||
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 = 5;
|
||||
|
||||
impl FileFacts {
|
||||
/// These facts as one line's worth of fields, tab-separated.
|
||||
///
|
||||
/// `None` for a path that cannot be written on a line of text — not UTF-8,
|
||||
/// or holding a tab or a newline. Such a file is simply never cached, the
|
||||
/// same answer `lucisv_core::cache` gives for the same shape of path.
|
||||
/// Every *other* string a record holds is escaped instead, because a macro
|
||||
/// body really can contain a tab.
|
||||
pub fn encode(&self) -> Option<String> {
|
||||
let path = self.path.to_str()?;
|
||||
let mut out = Writer::default();
|
||||
out.text(path);
|
||||
out.tag("D", self.defines.entries().len());
|
||||
for define in self.defines.entries() {
|
||||
out.define(define);
|
||||
}
|
||||
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 {
|
||||
out.text(unit);
|
||||
out.decl(decl);
|
||||
}
|
||||
out.tag("I", self.instantiations.len());
|
||||
for (module, site) in &self.instantiations {
|
||||
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 {
|
||||
out.text(base);
|
||||
out.site(subclass);
|
||||
}
|
||||
out.tag("R", self.references.len());
|
||||
for reference in &self.references {
|
||||
out.reference(reference);
|
||||
}
|
||||
Some(out.out)
|
||||
}
|
||||
|
||||
/// The facts a record describes, or `None` for anything that is not
|
||||
/// exactly one whole record of this format.
|
||||
///
|
||||
/// Strict on purpose, in both directions: a field missing, a number that
|
||||
/// does not parse, a kind this version has no name for, a count that
|
||||
/// outruns the line, **or a field left over at the end** all mean the same
|
||||
/// thing — this is not a record this version wrote, so nothing is taken
|
||||
/// from it. A dropped record costs one file's parse; a half-read one would
|
||||
/// cost correctness.
|
||||
pub fn decode(line: &str) -> Option<FileFacts> {
|
||||
let mut input = Reader::new(line);
|
||||
let path = PathBuf::from(input.text()?);
|
||||
let mut defines = Vec::new();
|
||||
for _ in 0..input.tag("D")? {
|
||||
defines.push(input.define()?);
|
||||
}
|
||||
let mut units = Vec::new();
|
||||
for _ in 0..input.tag("U")? {
|
||||
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")? {
|
||||
members.push((input.text()?, input.decl()?));
|
||||
}
|
||||
let mut instantiations = Vec::new();
|
||||
for _ in 0..input.tag("I")? {
|
||||
let module = input.text()?;
|
||||
let owner = input.site()?;
|
||||
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")? {
|
||||
subclasses.push((input.text()?, input.site()?));
|
||||
}
|
||||
let mut references = Vec::new();
|
||||
for _ in 0..input.tag("R")? {
|
||||
references.push(input.reference()?);
|
||||
}
|
||||
if !input.done() {
|
||||
return None;
|
||||
}
|
||||
Some(FileFacts {
|
||||
path,
|
||||
defines: DefineTable::from_entries(defines),
|
||||
units,
|
||||
members,
|
||||
instantiations,
|
||||
subclasses,
|
||||
references,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The path a record is for, without decoding the rest of it.
|
||||
///
|
||||
/// A store keyed by path has to read this out of every record it holds, and
|
||||
/// only ever decodes the handful it is asked for — so the cheap half of the
|
||||
/// format is public separately from [`FileFacts::decode`]. `None` for a record
|
||||
/// whose first field is not a readable path, which is a record that would not
|
||||
/// decode either.
|
||||
pub fn record_path(record: &str) -> Option<PathBuf> {
|
||||
let field = record.split('\t').next()?;
|
||||
Some(PathBuf::from(unescape(field)?))
|
||||
}
|
||||
|
||||
/// A record under construction: fields pushed in order, separated by tabs.
|
||||
#[derive(Default)]
|
||||
struct Writer {
|
||||
out: String,
|
||||
/// Whether a field has been written yet, so the separator goes *between*
|
||||
/// fields — asked of a flag rather than of `out.is_empty()`, which would
|
||||
/// be wrong for a first field that is itself empty.
|
||||
written: bool,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// One string field, escaped.
|
||||
fn text(&mut self, text: &str) {
|
||||
self.field();
|
||||
for ch in text.chars() {
|
||||
match ch {
|
||||
'\\' => self.out.push_str("\\\\"),
|
||||
'\t' => self.out.push_str("\\t"),
|
||||
'\n' => self.out.push_str("\\n"),
|
||||
'\r' => self.out.push_str("\\r"),
|
||||
_ => self.out.push(ch),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One number field.
|
||||
fn num(&mut self, n: u32) {
|
||||
self.field();
|
||||
self.out.push_str(&n.to_string());
|
||||
}
|
||||
|
||||
/// A list's marker and its length — the length prefix that makes the
|
||||
/// stream flat and still unambiguous.
|
||||
fn tag(&mut self, tag: &str, len: usize) {
|
||||
self.field();
|
||||
self.out.push_str(tag);
|
||||
self.num(len as u32);
|
||||
}
|
||||
|
||||
fn range(&mut self, range: TextRange) {
|
||||
self.num(range.start);
|
||||
self.num(range.end);
|
||||
}
|
||||
|
||||
fn decl(&mut self, decl: &Decl) {
|
||||
self.text(&decl.name);
|
||||
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
|
||||
// written before it is discarded whole rather than read field-shifted
|
||||
// by two (`docs/features/port-detail-spans/README.md`).
|
||||
match decl.detail_span {
|
||||
Some(span) => self.range(span),
|
||||
None => {
|
||||
self.num(0);
|
||||
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));
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
self.text(&site.name);
|
||||
self.range(site.name_span);
|
||||
self.range(site.span);
|
||||
}
|
||||
|
||||
fn define(&mut self, define: &Define) {
|
||||
self.field();
|
||||
self.out.push(match define.kind {
|
||||
DefineKind::Define => 'd',
|
||||
DefineKind::Undef => 'u',
|
||||
});
|
||||
self.text(&define.name);
|
||||
match &define.params {
|
||||
// A macro with no parameter list at all is not a macro with an
|
||||
// empty one — `` `define A x`` against `` `define A() x`` — so the
|
||||
// two cannot share a spelling.
|
||||
None => {
|
||||
self.field();
|
||||
self.out.push('-');
|
||||
}
|
||||
Some(params) => {
|
||||
self.num(params.len() as u32);
|
||||
for param in params {
|
||||
self.text(param);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.text(&define.body);
|
||||
self.range(define.span);
|
||||
self.range(define.name_span);
|
||||
}
|
||||
|
||||
fn reference(&mut self, reference: &ReferenceFact) {
|
||||
match reference {
|
||||
ReferenceFact::Local { definition, occurrence } => {
|
||||
self.field();
|
||||
self.out.push('l');
|
||||
self.range(*definition);
|
||||
self.range(*occurrence);
|
||||
}
|
||||
ReferenceFact::External { name, paths, occurrence } => {
|
||||
self.field();
|
||||
self.out.push('e');
|
||||
self.text(name);
|
||||
self.num(paths.len() as u32);
|
||||
for path in paths {
|
||||
self.text(path);
|
||||
}
|
||||
self.range(*occurrence);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The separator before every field but the first.
|
||||
fn field(&mut self) {
|
||||
if self.written {
|
||||
self.out.push('\t');
|
||||
}
|
||||
self.written = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// A record being read, one field at a time.
|
||||
struct Reader<'a> {
|
||||
fields: Vec<&'a str>,
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn new(line: &'a str) -> Reader<'a> {
|
||||
Reader { fields: line.split('\t').collect(), at: 0 }
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
let field = self.fields.get(self.at)?;
|
||||
self.at += 1;
|
||||
Some(field)
|
||||
}
|
||||
|
||||
/// Whether every field has been read — the check that makes a record with
|
||||
/// something extra on the end invalid rather than merely surprising.
|
||||
fn done(&self) -> bool {
|
||||
self.at == self.fields.len()
|
||||
}
|
||||
|
||||
fn text(&mut self) -> Option<String> {
|
||||
unescape(self.next()?)
|
||||
}
|
||||
|
||||
fn num(&mut self) -> Option<u32> {
|
||||
self.next()?.parse().ok()
|
||||
}
|
||||
|
||||
fn range(&mut self) -> Option<TextRange> {
|
||||
Some(TextRange::new(self.num()?, self.num()?))
|
||||
}
|
||||
|
||||
/// A list's length, once its marker has been confirmed. The marker is what
|
||||
/// turns a misaligned read into a dropped record instead of a plausible
|
||||
/// one.
|
||||
fn tag(&mut self, tag: &str) -> Option<usize> {
|
||||
if self.next()? != tag {
|
||||
return None;
|
||||
}
|
||||
Some(self.num()? as usize)
|
||||
}
|
||||
|
||||
fn decl(&mut self) -> Option<Decl> {
|
||||
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));
|
||||
// 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()?;
|
||||
// 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 })
|
||||
}
|
||||
|
||||
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> {
|
||||
Some(DeclSite { name: self.text()?, name_span: self.range()?, span: self.range()? })
|
||||
}
|
||||
|
||||
fn define(&mut self) -> Option<Define> {
|
||||
let kind = match self.next()? {
|
||||
"d" => DefineKind::Define,
|
||||
"u" => DefineKind::Undef,
|
||||
_ => return None,
|
||||
};
|
||||
let name = self.text()?;
|
||||
let params = match self.next()? {
|
||||
"-" => None,
|
||||
count => {
|
||||
let count: u32 = count.parse().ok()?;
|
||||
let mut params = Vec::new();
|
||||
for _ in 0..count {
|
||||
params.push(self.text()?);
|
||||
}
|
||||
Some(params)
|
||||
}
|
||||
};
|
||||
Some(Define {
|
||||
kind,
|
||||
name,
|
||||
params,
|
||||
body: self.text()?,
|
||||
span: self.range()?,
|
||||
name_span: self.range()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn reference(&mut self) -> Option<ReferenceFact> {
|
||||
match self.next()? {
|
||||
"l" => {
|
||||
Some(ReferenceFact::Local { definition: self.range()?, occurrence: self.range()? })
|
||||
}
|
||||
"e" => {
|
||||
let name = 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()? })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One escaped string field, back as it was written. `None` for an escape
|
||||
/// this format does not write, which is a record it did not write either.
|
||||
fn unescape(field: &str) -> Option<String> {
|
||||
let mut out = String::with_capacity(field.len());
|
||||
let mut chars = field.chars();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch != '\\' {
|
||||
out.push(ch);
|
||||
continue;
|
||||
}
|
||||
out.push(match chars.next()? {
|
||||
'\\' => '\\',
|
||||
't' => '\t',
|
||||
'n' => '\n',
|
||||
'r' => '\r',
|
||||
_ => return None,
|
||||
});
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A [`SymbolKind`]'s name in a record. Written out rather than numbered, so
|
||||
/// a variant inserted in the middle of the enum cannot silently turn one kind
|
||||
/// into another — and a name this version does not know drops the record.
|
||||
fn kind_name(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Module => "module",
|
||||
SymbolKind::Package => "package",
|
||||
SymbolKind::Port => "port",
|
||||
SymbolKind::Net => "net",
|
||||
SymbolKind::Var => "var",
|
||||
SymbolKind::Param => "param",
|
||||
SymbolKind::Genvar => "genvar",
|
||||
SymbolKind::Typedef => "typedef",
|
||||
SymbolKind::EnumVariant => "enumvariant",
|
||||
SymbolKind::Function => "function",
|
||||
SymbolKind::Task => "task",
|
||||
SymbolKind::TfArg => "tfarg",
|
||||
SymbolKind::Instance => "instance",
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "structmember",
|
||||
SymbolKind::Class => "class",
|
||||
}
|
||||
}
|
||||
|
||||
/// The inverse of [`kind_name`], total in the other direction: anything else
|
||||
/// is not a kind this version writes.
|
||||
fn kind_of(name: &str) -> Option<SymbolKind> {
|
||||
Some(match name {
|
||||
"module" => SymbolKind::Module,
|
||||
"package" => SymbolKind::Package,
|
||||
"port" => SymbolKind::Port,
|
||||
"net" => SymbolKind::Net,
|
||||
"var" => SymbolKind::Var,
|
||||
"param" => SymbolKind::Param,
|
||||
"genvar" => SymbolKind::Genvar,
|
||||
"typedef" => SymbolKind::Typedef,
|
||||
"enumvariant" => SymbolKind::EnumVariant,
|
||||
"function" => SymbolKind::Function,
|
||||
"task" => SymbolKind::Task,
|
||||
"tfarg" => SymbolKind::TfArg,
|
||||
"instance" => SymbolKind::Instance,
|
||||
"block" => SymbolKind::Block,
|
||||
"structmember" => SymbolKind::StructMember,
|
||||
"class" => SymbolKind::Class,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every kind round-trips, and the two directions are inverses. If a
|
||||
/// variant is added to `SymbolKind` this fails to compile in `kind_name`
|
||||
/// first, which is the point of writing both matches out.
|
||||
#[test]
|
||||
fn every_symbol_kind_has_a_name_and_only_its_own() {
|
||||
let kinds = [
|
||||
SymbolKind::Module,
|
||||
SymbolKind::Package,
|
||||
SymbolKind::Port,
|
||||
SymbolKind::Net,
|
||||
SymbolKind::Var,
|
||||
SymbolKind::Param,
|
||||
SymbolKind::Genvar,
|
||||
SymbolKind::Typedef,
|
||||
SymbolKind::EnumVariant,
|
||||
SymbolKind::Function,
|
||||
SymbolKind::Task,
|
||||
SymbolKind::TfArg,
|
||||
SymbolKind::Instance,
|
||||
SymbolKind::Block,
|
||||
SymbolKind::StructMember,
|
||||
SymbolKind::Class,
|
||||
];
|
||||
let mut names: Vec<&str> = kinds.iter().map(|k| kind_name(*k)).collect();
|
||||
for kind in kinds {
|
||||
assert_eq!(kind_of(kind_name(kind)), Some(kind));
|
||||
}
|
||||
names.sort_unstable();
|
||||
let before = names.len();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), before, "two kinds share a name: {names:?}");
|
||||
assert_eq!(kind_of("Module"), None, "the names are exact");
|
||||
assert_eq!(kind_of(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_escape_survives_a_round_trip() {
|
||||
for text in ["", "plain", "a\tb", "a\nb", "a\\b", "a\\\\tb", "\r\n", "\\", "üñî"] {
|
||||
let mut out = Writer::default();
|
||||
out.text(text);
|
||||
let field = out.out;
|
||||
assert_eq!(unescape(&field).as_deref(), Some(text), "{text:?}");
|
||||
assert!(!field.contains('\t'), "a field never holds a raw tab: {field:?}");
|
||||
assert!(!field.contains('\n'), "nor a newline: {field:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escape_this_format_does_not_write_is_not_read() {
|
||||
assert_eq!(unescape("a\\qb"), None);
|
||||
assert_eq!(unescape("trailing\\"), None);
|
||||
}
|
||||
}
|
||||
+9
@@ -11,6 +11,13 @@
|
||||
//! Gate primitives are not instantiations here: `and (q, a, b)` is an
|
||||
//! [`ItemKind::GateInstantiation`], names no module, and is nobody's edge in
|
||||
//! the hierarchy.
|
||||
//!
|
||||
//! **Lifted from `lucisv_server` on 2026-08-27** so the workspace index can
|
||||
//! record instantiation edges as it builds
|
||||
//! (`docs/features/incremental-index/README.md`). The walk is the census —
|
||||
//! what counts as one instantiation site — and a second copy of it in the
|
||||
//! index would have been free to drift from the one the call hierarchy uses.
|
||||
//! The code is unchanged by the move.
|
||||
|
||||
use vlog_parser::ast::{GenBlock, GenElse, Instantiation, Item, ItemKind, Module};
|
||||
use vlog_parser::TextRange;
|
||||
@@ -19,6 +26,7 @@ use vlog_parser::TextRange;
|
||||
/// `module ... endmodule` it was written as.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Decl<'a> {
|
||||
/// The declaration node, for its name and its own items.
|
||||
pub module: &'a Module,
|
||||
/// Code extent of the declaration, attributes included — what a call
|
||||
/// hierarchy item's `range` is.
|
||||
@@ -27,6 +35,7 @@ pub struct Decl<'a> {
|
||||
|
||||
/// One module instantiation, and the module whose body it sits in.
|
||||
pub struct Site<'a> {
|
||||
/// The instantiation node: the module it names, and its connections.
|
||||
pub inst: &'a Instantiation,
|
||||
/// The innermost module the instantiation is written inside. `None` for
|
||||
/// one written at file scope — illegal SystemVerilog, and reachable
|
||||
@@ -17,18 +17,24 @@
|
||||
//! the simplifications taken.
|
||||
|
||||
mod bind;
|
||||
pub mod classes;
|
||||
mod facts;
|
||||
pub mod instantiations;
|
||||
mod model;
|
||||
mod resolve;
|
||||
mod scan;
|
||||
mod workspace;
|
||||
|
||||
pub use facts::{record_path, FACTS_FORMAT};
|
||||
pub use model::{
|
||||
DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol,
|
||||
SymbolId, SymbolKind,
|
||||
};
|
||||
pub use workspace::{
|
||||
resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId, IndexCounts,
|
||||
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;
|
||||
@@ -43,6 +49,16 @@ pub struct Semantics {
|
||||
references: Vec<Reference>,
|
||||
/// symbol → indices into `references`, in source order.
|
||||
uses: HashMap<SymbolId, Vec<usize>>,
|
||||
/// Non-empty declaration-name spans, sorted by start for cursor lookup.
|
||||
symbol_positions: Vec<(TextRange, SymbolId)>,
|
||||
/// Non-empty reference-name spans, sorted by start for cursor lookup.
|
||||
reference_positions: Vec<(TextRange, ReferenceId)>,
|
||||
/// Every symbol id, sorted by the name it declares, ties in declaration
|
||||
/// order — so looking a name up is a binary search rather than a walk of
|
||||
/// every symbol. A side table rather than a `HashMap<String, _>` because
|
||||
/// this way `Semantics` does not carry a second copy of every name it
|
||||
/// already holds, and it is cloned per document.
|
||||
by_name: Vec<SymbolId>,
|
||||
}
|
||||
|
||||
/// Build the symbol table for one parsed file. `src` must be the text the
|
||||
@@ -74,7 +90,26 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
||||
uses.entry(id).or_default().push(i);
|
||||
}
|
||||
}
|
||||
Semantics { scopes, symbols, references, uses }
|
||||
let mut symbol_positions: Vec<(TextRange, SymbolId)> = symbols
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, symbol)| !symbol.name_span.is_empty())
|
||||
.map(|(i, symbol)| (symbol.name_span, SymbolId(i as u32)))
|
||||
.collect();
|
||||
symbol_positions.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
let mut reference_positions: Vec<(TextRange, ReferenceId)> = references
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, reference)| !reference.name_span.is_empty())
|
||||
.map(|(i, reference)| (reference.name_span, ReferenceId(i as u32)))
|
||||
.collect();
|
||||
reference_positions.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
// A *stable* sort by name, so symbols sharing a name keep the order they
|
||||
// were declared in — the order a caller filtering `symbols()` by name
|
||||
// would have seen, which is what makes swapping the two an identity.
|
||||
let mut by_name: Vec<SymbolId> = (0..symbols.len() as u32).map(SymbolId).collect();
|
||||
by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name));
|
||||
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name }
|
||||
}
|
||||
|
||||
/// Point every import at the package it names, when this file declares it.
|
||||
@@ -122,24 +157,34 @@ impl Semantics {
|
||||
self.symbols.get(id.0 as usize)
|
||||
}
|
||||
|
||||
/// Every declaration that spells `name`, in declaration order — the same
|
||||
/// symbols, in the same order, that filtering [`Semantics::symbols`] by
|
||||
/// name yields, without walking the ones that cannot match.
|
||||
pub fn symbols_named(&self, name: &str) -> impl Iterator<Item = SymbolId> + '_ {
|
||||
// Two binary searches over the name-sorted side table: the first name
|
||||
// that is not less than the one asked for, then the first one past it.
|
||||
let spelling = |id: &SymbolId| self.symbol(*id).map_or("", |symbol| symbol.name.as_str());
|
||||
let start = self.by_name.partition_point(|id| spelling(id) < name);
|
||||
let rest = self.by_name.get(start..).unwrap_or(&[]);
|
||||
let end = rest.partition_point(|id| spelling(id) == name);
|
||||
rest.get(..end).unwrap_or(&[]).iter().copied()
|
||||
}
|
||||
|
||||
/// The declaration whose *name* covers `offset` — a cursor sitting on a
|
||||
/// declared name, not anywhere in its declaration.
|
||||
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
|
||||
self.symbols.iter().position(|s| s.name_span.contains(offset)).map(|i| SymbolId(i as u32))
|
||||
position_at(&self.symbol_positions, offset)
|
||||
}
|
||||
|
||||
/// The use whose name covers `offset`.
|
||||
pub fn reference_at(&self, offset: u32) -> Option<&Reference> {
|
||||
self.references.iter().find(|r| r.name_span.contains(offset))
|
||||
self.reference_id_at(offset).and_then(|id| self.reference(id))
|
||||
}
|
||||
|
||||
/// The id of the use whose name covers `offset` — the key the workspace
|
||||
/// index's overlay uses.
|
||||
pub fn reference_id_at(&self, offset: u32) -> Option<ReferenceId> {
|
||||
self.references
|
||||
.iter()
|
||||
.position(|r| r.name_span.contains(offset))
|
||||
.map(|i| ReferenceId(i as u32))
|
||||
position_at(&self.reference_positions, offset)
|
||||
}
|
||||
|
||||
/// One use by id.
|
||||
@@ -211,3 +256,10 @@ impl Semantics {
|
||||
self.scopes.first().map_or(TextRange::empty(0), |s| s.span)
|
||||
}
|
||||
}
|
||||
|
||||
/// The source span covering `offset` in a non-overlapping, start-sorted table.
|
||||
fn position_at<Id: Copy>(positions: &[(TextRange, Id)], offset: u32) -> Option<Id> {
|
||||
let after = positions.partition_point(|(span, _)| span.start <= offset);
|
||||
let (span, id) = positions.get(after.checked_sub(1)?)?;
|
||||
span.contains(offset).then_some(*id)
|
||||
}
|
||||
@@ -57,6 +57,13 @@ pub struct Symbol {
|
||||
/// Byte range of the construct that owns the name (the whole `module`,
|
||||
/// the whole declarator, the whole port declaration).
|
||||
pub decl_span: TextRange,
|
||||
/// Where the *complete* declaration is written, when that is not
|
||||
/// `decl_span`: a non-ANSI port's header names it and a body `input
|
||||
/// signed [31:0] data_in;` finishes it, so hover and go-to-definition
|
||||
/// point here — the line that carries the direction, the type and the
|
||||
/// 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 scope the name is bound in.
|
||||
pub scope: ScopeId,
|
||||
/// The scope this declaration opens, for the kinds that open one
|
||||
@@ -71,20 +78,30 @@ pub enum Resolution {
|
||||
Resolved(SymbolId),
|
||||
/// Nothing in this file binds it, but a named external unit could: a
|
||||
/// package imported with `import p::*` / `import p::x`, a package written
|
||||
/// as `p::x`, or a module instantiated but declared in another file.
|
||||
/// `paths` names those units — a path containing `::` is a package path,
|
||||
/// a bare name is a module, package or class name. The workspace index
|
||||
/// (TODO.md §6) is what finishes these.
|
||||
/// as `p::x`, a module instantiated but declared in another file, or an
|
||||
/// unqualified **type** name — an `interface`, a package-less `class` —
|
||||
/// that only a file-scope declaration somewhere else can be. `paths` names
|
||||
/// those units — a path containing `::` is a package path, a bare name is a
|
||||
/// module, package or class name — in the order they are tried, the use's
|
||||
/// own name last. The workspace index (TODO.md §6) is what finishes these.
|
||||
ExternalCandidate { paths: Vec<String> },
|
||||
/// A use inside a class that nothing lexical binds, where the class's
|
||||
/// `extends` could: `base` is the base-class path as written
|
||||
/// (`uvm_component`, `pkg::base`), and `paths` are any import paths the
|
||||
/// lexical walk collected — either could supply the name. Nothing chases
|
||||
/// `base`, in this file or out of it; a future hover/index round can,
|
||||
/// without this crate pretending it did inheritance resolution. See
|
||||
/// `docs/features/class-semantics/README.md`.
|
||||
/// (`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`.
|
||||
InheritedCandidate { base: String, paths: Vec<String> },
|
||||
/// Nothing in this file binds it and no external unit could.
|
||||
/// 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
|
||||
/// `this.x`/`super.x` with no class or base to blame, or a plain
|
||||
/// value-position identifier with no import in scope. An unqualified miss
|
||||
/// in a **type** position is never this — the workspace's unit table could
|
||||
/// hold it — so that one is an `ExternalCandidate` carrying its own name.
|
||||
NotFound,
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Reso
|
||||
// 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),
|
||||
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::Unit => unit(scopes, symbols, p.scope, &p.name),
|
||||
@@ -36,7 +37,18 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Reso
|
||||
/// class whose header says `extends` becomes an inheritance candidate — the
|
||||
/// base (which this crate never chases, in this file or out of it) could
|
||||
/// supply the name, and so could any import path collected on the way out.
|
||||
fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
///
|
||||
/// `promote` is set for [`Target::Type`] only. A **type** name nothing here
|
||||
/// binds is exactly how a file-scope `interface`, a package-less `class` or a
|
||||
/// cross-file `typedef` is written (`bus_if bus;`, `my_cls h;`), so its miss
|
||||
/// ends carrying the **bare name** as its last path — last, so an import that
|
||||
/// could supply the name still wins — and the workspace's unit table, the only
|
||||
/// layer that can say, gets asked. A [`Target::Lexical`] miss is an identifier
|
||||
/// in a *value* position: a name a `` `define`` would have produced, a typo, a
|
||||
/// signal declared somewhere this crate does not model. Nothing about it says
|
||||
/// "file-scope declaration", so it is not swept through the unit table, where a
|
||||
/// mere name collision would make `rename` rewrite an unrelated file.
|
||||
fn lexical(scopes: &[Scope], from: ScopeId, name: &str, promote: bool) -> Resolution {
|
||||
let mut external = Vec::new();
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
@@ -66,6 +78,9 @@ fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
if promote {
|
||||
external.push(name.to_string());
|
||||
}
|
||||
miss(scopes, from, external, false)
|
||||
}
|
||||
|
||||
@@ -197,7 +212,10 @@ fn super_member(scopes: &[Scope], from: ScopeId) -> Resolution {
|
||||
/// nearest extends-carrying enclosing class's base could supply the name
|
||||
/// (the LRM even puts it ahead of the enclosing scopes this walk already
|
||||
/// searched — the deliberate inexactness the same README argues), so it
|
||||
/// becomes `InheritedCandidate`.
|
||||
/// becomes `InheritedCandidate` — which keeps its base and its paths both,
|
||||
/// because either could be the answer and nothing here picks between them.
|
||||
/// A miss with nothing to name at all — no import in scope, no bare name
|
||||
/// because the use was not a type — is `NotFound`.
|
||||
fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: bool) -> Resolution {
|
||||
if unit_lookup {
|
||||
return Resolution::ExternalCandidate { paths: external };
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -206,7 +206,10 @@ endclass
|
||||
let expect = Resolution::InheritedCandidate { base: "uvm_object".into(), paths: Vec::new() };
|
||||
assert_eq!(resolution_at(&s, nth(src, "super.new", 0) + 6), expect);
|
||||
assert_eq!(resolution_at(&s, nth(src, "super.whatever", 0) + 6), expect);
|
||||
// A plain call that misses the whole lexical chain blames the base too.
|
||||
// A plain call that misses the whole lexical chain blames the base too,
|
||||
// and carries no path: a callee is a value position, and the promotion
|
||||
// (`docs/features/overlay-promotion/README.md`) fires on type positions
|
||||
// only, so nothing sweeps `set_name` through the workspace's unit table.
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "set_name", 0)),
|
||||
Resolution::InheritedCandidate { base: "uvm_object".into(), paths: Vec::new() }
|
||||
@@ -229,6 +232,8 @@ endclass
|
||||
match resolution_at(&s, nth(src, "UVM_LOW", 0)) {
|
||||
Resolution::InheritedCandidate { base, paths } => {
|
||||
assert_eq!(base, "uvm_component");
|
||||
// The imports in walk order, and nothing else: a call argument
|
||||
// is a value position, so the bare name is not appended.
|
||||
assert_eq!(paths, vec!["uvm_pkg::*".to_string()]);
|
||||
}
|
||||
other => panic!("expected an inherited candidate, got {other:?}"),
|
||||
@@ -618,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
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -720,7 +759,11 @@ fn inherited_candidates_are_not_the_workspace_overlays_business() {
|
||||
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.
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let id = s.reference_id_at(nth(sources[1].1, "held = 1", 0)).expect("an id");
|
||||
assert!(overlay.get(id).is_none(), "the overlay holds external candidates only");
|
||||
assert!(overlay.get(id).is_none(), "a name the workspace cannot answer is not in the overlay");
|
||||
}
|
||||
@@ -49,7 +49,7 @@ impl Totals {
|
||||
let pct = |n: usize| 100.0 * n as f64 / self.references.max(1) as f64;
|
||||
println!(
|
||||
"{label}: {} files, {} symbols, {} references — {:.1}% resolved in-file, \
|
||||
{:.1}% external candidates, {:.1}% inherited candidates, {:.1}% unresolved, \
|
||||
{:.1}% external candidates, {:.1}% inherited candidates, {:.2}% unresolved ({}), \
|
||||
{} names unplaced",
|
||||
self.files,
|
||||
self.symbols,
|
||||
@@ -58,6 +58,7 @@ impl Totals {
|
||||
pct(self.external),
|
||||
pct(self.inherited),
|
||||
pct(self.unresolved()),
|
||||
self.unresolved(),
|
||||
self.unplaced,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Deeply nested input against the stack the parse actually runs on.
|
||||
//!
|
||||
//! `vlog_parser` turns nesting past `MAX_NESTING_DEPTH` into an ordinary
|
||||
//! diagnostic, but only above `PARSE_STACK_SIZE`: reaching level 64 costs
|
||||
//! stack, and a thread too small to hold it overflows before the guard ever
|
||||
//! fires — an abort, not a `Result`. These tests run the whole indexing
|
||||
//! pipeline (tokenize → tolerant parse → `analyze` → facts) on exactly that
|
||||
//! stack, so they fail if either half of the contract is cut.
|
||||
//!
|
||||
//! Reported 2026-08-28: 500 nested `begin`/`end` through `FileFacts::of`
|
||||
//! aborted the process on a default 2 MiB test thread.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
|
||||
|
||||
/// Run `f` on the stack every production parse site is given — the CLI's
|
||||
/// worker thread and rayon pool, the language server's message loop. Not a
|
||||
/// generous number picked for the test: the constant itself, so shrinking
|
||||
/// the guarantee below what the depth limit needs fails here.
|
||||
fn on_parse_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(f)
|
||||
.expect("spawn a parse-sized thread")
|
||||
.join()
|
||||
.expect("the parse thread died")
|
||||
}
|
||||
|
||||
/// The index one file's facts build, read off on the same stack.
|
||||
fn index_of(src: String) -> WorkspaceIndex {
|
||||
on_parse_stack(move || {
|
||||
let mut builder = IndexBuilder::new();
|
||||
builder.add_facts(FileFacts::of(PathBuf::from("/w/deep.sv"), &src));
|
||||
builder.finish()
|
||||
})
|
||||
}
|
||||
|
||||
/// `n` nested `begin`/`end` inside an `initial`, in a module.
|
||||
fn nested_begins(n: usize) -> String {
|
||||
format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
)
|
||||
}
|
||||
|
||||
/// Every block-structured shape that nests, at a depth far past the limit.
|
||||
/// Each is `(name, source)`; the innermost body is a statement or an item, so
|
||||
/// the shape is what real generated code would produce, not a bare skeleton.
|
||||
fn deep_block_shapes(n: usize) -> Vec<(&'static str, String)> {
|
||||
let stmt = |open: &str, close: &str| {
|
||||
format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
open.repeat(n),
|
||||
close.repeat(n)
|
||||
)
|
||||
};
|
||||
vec![
|
||||
("begin/end", nested_begins(n)),
|
||||
("if/begin", stmt("if (c) begin\n", "end\n")),
|
||||
("fork/join", stmt("fork\n", "join\n")),
|
||||
("case/endcase", stmt("case (s)\n1: ", "endcase\n")),
|
||||
("foreach", stmt("foreach (a[j])\n", "")),
|
||||
("while", stmt("while (c)\n", "")),
|
||||
("for", stmt("for (int i = 0; i < 4; i++)\n", "")),
|
||||
(
|
||||
"else-if chain",
|
||||
format!(
|
||||
"module m;\ninitial\n{}x <= 0;\nendmodule\n",
|
||||
"if (c) x <= 1; else\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"generate if",
|
||||
format!(
|
||||
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
|
||||
"if (1) begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"generate for",
|
||||
format!(
|
||||
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
|
||||
"for (i = 0; i < 2; i = i + 1) begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"nested modules",
|
||||
format!("{}wire w;\n{}", "module m;\n".repeat(n), "endmodule\n".repeat(n)),
|
||||
),
|
||||
(
|
||||
// Not legal SystemVerilog at all — a `task` cannot open inside a
|
||||
// task body — so this errors early rather than on depth. It is
|
||||
// here because "errors early" is a claim about the stack too.
|
||||
"nested tasks",
|
||||
format!(
|
||||
"module m;\n{}x = 1;\n{}endmodule\n",
|
||||
"task t;\n".repeat(n),
|
||||
"endtask\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"nested functions",
|
||||
format!(
|
||||
"module m;\n{}f = 1;\n{}endmodule\n",
|
||||
"function int f;\n".repeat(n),
|
||||
"endfunction\n".repeat(n)
|
||||
),
|
||||
),
|
||||
("nested parens", {
|
||||
format!("module m;\nassign x = {}1{};\nendmodule\n", "(".repeat(n), ")".repeat(n))
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_hundred_nested_blocks_are_indexed_not_aborted() {
|
||||
// The reported repro, verbatim in shape. The depth limit rejects the
|
||||
// `initial` block, tolerant recovery turns it into an error leaf, and the
|
||||
// module around it is still a fact — a graceful result, not a dead
|
||||
// process.
|
||||
let index = index_of(nested_begins(500));
|
||||
assert_eq!(index.files().len(), 1);
|
||||
assert_eq!(index.units("m").len(), 1, "the module survives the unparsable body");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_block_shape_can_abort_the_parse_stack() {
|
||||
// 400 levels is far past `MAX_NESTING_DEPTH` for every family, so each of
|
||||
// these either errors on depth or errors earlier; what is asserted is
|
||||
// that the pipeline *returns* on the guaranteed stack. A regression here
|
||||
// is a SIGABRT, so the assertion below is secondary — reaching it is the
|
||||
// test.
|
||||
for (name, src) in deep_block_shapes(400) {
|
||||
let index = index_of(src);
|
||||
assert_eq!(index.files().len(), 1, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_just_under_the_limit_still_yields_its_facts() {
|
||||
// Legal depth, so nothing is rejected and the whole 64-level tree is
|
||||
// parsed, analyzed and walked on this stack — the expensive direction,
|
||||
// and the one a smaller stack fails first.
|
||||
let index = index_of(nested_begins(vlog_parser::parser::MAX_NESTING_DEPTH as usize - 6));
|
||||
assert_eq!(index.units("m").len(), 1, "a legally deep file is indexed like any other");
|
||||
}
|
||||
@@ -211,7 +211,10 @@ endmodule
|
||||
let in_loop = s.reference_at(nth(src, "assign w = i", 0) + 11).expect("the use in the body");
|
||||
assert_eq!(in_loop.resolved(), Some(genvar));
|
||||
|
||||
// Outside the loop the genvar is gone.
|
||||
// Outside the loop the genvar is gone, and a bare `i` in an expression is
|
||||
// a value position: nothing in scope names it and nothing offers it to the
|
||||
// workspace, so it stays `NotFound` (a one-letter name is exactly the kind
|
||||
// of coincidence a unit-table sweep must not chase).
|
||||
let outside = s.reference_at(nth(src, "assign top_i = i", 0) + 15).expect("the use outside");
|
||||
assert_eq!(outside.resolution, Resolution::NotFound);
|
||||
|
||||
@@ -299,7 +302,9 @@ endmodule
|
||||
let s = sem(src);
|
||||
|
||||
// Only the wildcard could supply this name; the explicit import names
|
||||
// something else, so it is not offered to the workspace index.
|
||||
// something else, so it is not offered to the workspace index. No bare
|
||||
// name either: the promotion is for type positions, and this is a value
|
||||
// (`docs/features/overlay-promotion/README.md`).
|
||||
let some = s.reference_at(nth(src, "SOMETHING", 0)).expect("the use");
|
||||
assert_eq!(
|
||||
some.resolution,
|
||||
@@ -505,6 +510,92 @@ endmodule
|
||||
assert_eq!(body.resolved(), Some(a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ansi_port_records_where_its_body_declaration_completes_it() {
|
||||
let src = "\
|
||||
module m (a, b);
|
||||
input [7:0] a;
|
||||
output b;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let a = symbol_named(&s, "a");
|
||||
let detail = a.detail_span.expect("the body declaration's span");
|
||||
assert!(
|
||||
src[detail.start as usize..detail.end as usize].starts_with("input [7:0] a"),
|
||||
"the detail site covers the body declaration: {:?}",
|
||||
&src[detail.start as usize..detail.end as usize]
|
||||
);
|
||||
// ...while the name stays in the header.
|
||||
assert_eq!(&src[a.name_span.start as usize..a.name_span.end as usize], "a");
|
||||
assert!(a.name_span.start < detail.start);
|
||||
|
||||
// An ANSI port is complete where it is named: no detail site.
|
||||
let ansi = sem("module m (input wire clk);\nendmodule\n");
|
||||
assert_eq!(symbol_named(&ansi, "clk").detail_span, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_style_task_argument_records_its_body_declaration_too() {
|
||||
// `task t(a);` names the argument and `input [7:0] a;` finishes it —
|
||||
// the same shape a non-ANSI module port has, merged by the same
|
||||
// `declare`, so it carries the same detail site (QA, PDS-3).
|
||||
let src = "\
|
||||
module m;
|
||||
task t(a);
|
||||
input [7:0] a;
|
||||
$display(a);
|
||||
endtask
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let a = symbol_named(&s, "a");
|
||||
assert_eq!(a.kind, SymbolKind::TfArg);
|
||||
let detail = a.detail_span.expect("the body declaration's span");
|
||||
assert_eq!(&src[detail.start as usize..detail.end as usize], "input [7:0] a;");
|
||||
assert!(a.name_span.start < detail.start, "the name stays in the header");
|
||||
|
||||
// An argument complete where it is named has no detail site, as before.
|
||||
let ansi = sem("module m;\n task t(input [7:0] a);\n endtask\nendmodule\n");
|
||||
assert_eq!(symbol_named(&ansi, "a").detail_span, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn looking_a_name_up_answers_exactly_what_scanning_every_symbol_would() {
|
||||
// The name-keyed lookup exists so a caller never walks the whole symbol
|
||||
// table to find the declarations spelling one name. It is only a
|
||||
// substitution if it answers the same symbols in the same order — and the
|
||||
// order is what decides the tie when one buffer holds two declarations of
|
||||
// one name, as a mid-edit buffer does.
|
||||
// One scope never binds a name twice (`bind::declare`), so two
|
||||
// declarations of one name means two scopes — a buffer holding an old
|
||||
// module and its half-written replacement, which is the tie
|
||||
// `hover::live_symbol` has to break.
|
||||
let src = "\
|
||||
module m (input wire dup);
|
||||
wire other;
|
||||
endmodule
|
||||
module n (input wire [7:0] dup);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for name in ["dup", "other", "m", "n", "absent"] {
|
||||
let scanned: Vec<SymbolId> = s
|
||||
.symbols()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, sym)| sym.name == name)
|
||||
.map(|(i, _)| SymbolId(i as u32))
|
||||
.collect();
|
||||
let looked_up: Vec<SymbolId> = s.symbols_named(name).collect();
|
||||
assert_eq!(looked_up, scanned, "the two answers must agree for {name}");
|
||||
}
|
||||
// The one that matters: two `dup`s, and the first is the earlier one.
|
||||
let dups: Vec<SymbolId> = s.symbols_named("dup").collect();
|
||||
assert_eq!(dups.len(), 2, "{dups:?}");
|
||||
assert!(dups[0].0 < dups[1].0, "declaration order, so the first match is the first written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_name_resolves_only_its_head() {
|
||||
let src = "\
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,406 @@
|
||||
# ansi-first-port
|
||||
|
||||
## Goal
|
||||
|
||||
An ANSI module header whose **first** port carries no direction did not parse:
|
||||
`module m (bus_if bus, input logic clk);` became an `Error` item, and so did
|
||||
`module m (bus_if.mp bus);` and `module m (my_pkg::state_t s);`. IEEE 1800
|
||||
§23.2.2.2 makes the direction optional on every ANSI port including the first
|
||||
(it defaults to `inout`, and to whatever the previous port wrote for a
|
||||
continuation port), and for an *interface* port there is no direction to write
|
||||
at all — `bus_if bus` is the only spelling there is. This round closes that
|
||||
gap: the port list is classified ANSI-or-not by what follows the first
|
||||
identifier rather than by the identifier alone, and an interface port may name
|
||||
its modport. It was filed as Handshake request 2 of
|
||||
`docs/features/type-definition/README.md`, whose interface-port tests had to
|
||||
write the port *second* to have anything to test.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A first port spelled `ident ident` is a type and a name, never two
|
||||
non-ANSI port names.** SystemVerilog has no port list in which two
|
||||
identifiers stand side by side without a separator, so the pair is
|
||||
unambiguous. The non-ANSI list is exactly the case where the first
|
||||
identifier is followed by `,` or `)`, and that is what the disambiguation
|
||||
tests for — through the same lookahead (`at_typed_declarator`) that already
|
||||
decides `pkg::my_t x` from `x[i] = 1` everywhere else in the parser.
|
||||
- **A `.` after an identifier is a member access everywhere except a port
|
||||
header.** That is why `bus_if.mp bus` is recognized in `parse_ansi_port` and
|
||||
not in `parse_opt_data_type`: making the general type parser accept a dotted
|
||||
name would change how an identifier is read in expression and declaration
|
||||
positions, which is far more than this gap asks for. `virtual bus_if.mp v;`
|
||||
(a modport-qualified *virtual interface*, legal per §25.9) is therefore
|
||||
still not parsed — see Status.
|
||||
- **A modport belongs in the type name, glued.** `DataType::name` already
|
||||
carries `pkg::state_t` glued, and every consumer prints or scans that one
|
||||
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.
|
||||
- **`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
|
||||
them; deliberately out of scope (Status).
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Changed in `vlog_parser` (`crates/vlog_parser/src/parser.rs`):**
|
||||
|
||||
- `parse_port_list`'s ANSI/non-ANSI classification now also answers "ANSI" for
|
||||
a leading `Ident` that begins a typed declarator (`at_typed_declarator`,
|
||||
which already looks past a `pkg::` chain, a `#( ... )` override and packed
|
||||
dimensions) or a modport-qualified port (`at_modport_port`). Every other
|
||||
input classifies exactly as before — a macro token is `TokenKind::Directive`
|
||||
and never `Ident`, and a name followed by `,`/`)` is still a non-ANSI list.
|
||||
- `parse_ansi_port` takes `bus_if.mp` as the port's type via the new
|
||||
`at_modport_port` / `parse_modport_port_type` pair.
|
||||
- **No AST change.** The new shapes are ordinary `AnsiPort`s with
|
||||
`dir: None` — the value a non-first direction-less port has always carried —
|
||||
so `PortList`, `AnsiPort` and `DataType` are byte-identical to what
|
||||
downstream already handles. `AnsiPort::ty.name` is the one field that can
|
||||
now contain a `.`.
|
||||
|
||||
**Changed in `vlog_semantic` (`crates/vlog_semantic/src/bind.rs`):**
|
||||
|
||||
- `bind_data_type`'s unqualified arm binds the half of the type name before a
|
||||
`.` (`bus_if` of `bus_if.mp`) as `Target::Type`, instead of using the glued
|
||||
string as a name. The ANSI-port call site (`bind_module`, `bind.rs:393`) is
|
||||
unchanged: the type window is still "start of the port → start of its name",
|
||||
which is exactly right for a port that writes no direction.
|
||||
|
||||
**Changed in `lucisv_server` (`crates/lucisv_server/src/type_def.rs`):**
|
||||
|
||||
- `type_span` matches a site's type name by the half before its `.` as well as
|
||||
by its last `::` segment, so the cursor on a modport-qualified port reaches
|
||||
the interface. See that feature's work log.
|
||||
|
||||
**Consumed, unchanged:** `vlog_formatter` prints `AnsiPort` through
|
||||
`ansi_port_cells`/`data_type`, which write `ty.name` verbatim — a glued
|
||||
modport round-trips with no formatter change. `vlog_refactor`'s
|
||||
`instantiate::ansi_ports` reads the port's *source text* between its start and
|
||||
its name, so it reports `iface_bus.mst` as the type with no change either.
|
||||
|
||||
**Requested of other modules:** nothing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Reproduce all three shapes as `Error` items before changing anything.
|
||||
- [x] `parse_port_list`: classify a leading `ident ident` / `ident :: ident
|
||||
ident` / `ident . ident ident` as ANSI.
|
||||
- [x] `parse_ansi_port`: the modport-qualified interface port.
|
||||
- [x] `bind_data_type`: bind the interface half of a dotted type name.
|
||||
- [x] `type_def::type_span`: match it back.
|
||||
- [x] 9 parser tests, 7 formatter table cases, 1 semantic binding test, 2
|
||||
server tests, 2 refactor tests (one flipped, one new).
|
||||
- [x] Corpus before/after: identical, with every file's formatted output
|
||||
byte-identical (below).
|
||||
- [x] Handshake 2 struck in `docs/features/type-definition/README.md`; the
|
||||
stale annotation in `TODO.md` §9c corrected.
|
||||
- [ ] **Not done, deliberately: `module m (interface bus);`** — the generic
|
||||
interface port (IEEE 1800 §25.3), whose type is the `interface` keyword
|
||||
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.
|
||||
- [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
|
||||
what this gap was about.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **Reproduced first, and the filed report was accurate to the token.** A
|
||||
throwaway `parse_source_tolerant` harness (removed after use) gave, for the
|
||||
three shapes: `expected ")" (found "bus")`, `expected ")" (found ".")`,
|
||||
`expected ")" (found "::")` — each producing two `Error` items, the header
|
||||
and the orphaned `endmodule`. It also turned up two facts the report did not
|
||||
state and the fix had to account for: `my_pkg::state_t s` already parsed in
|
||||
a *non-first* position (`at_typed_declarator` walks `::` chains), while
|
||||
`bus_if.mp bus` parsed in **no** position at all — so the modport is a
|
||||
second, independent gap that merely looked like part of the first.
|
||||
- **The disambiguation is a lookahead, not a new grammar.** `parse_port_list`
|
||||
classified the list from its first token: a direction keyword, a type
|
||||
keyword or a net keyword meant ANSI, anything else meant a non-ANSI name
|
||||
list. The fix adds one clause — a leading `Ident` that `at_typed_declarator`
|
||||
says still leaves an identifier for the declarator name. That predicate
|
||||
already exists and is already the parser's answer to "type-then-name or
|
||||
something else", including past `pkg::`, `#( ... )` and packed dimensions;
|
||||
reusing it means the header list cannot drift out of step with how a body
|
||||
declaration is read. The complement is exactly the non-ANSI list: after the
|
||||
first name comes a `,` or a `)`, neither of which is an identifier.
|
||||
- **The modport is glued into the type name, and only in a port header.**
|
||||
`interface_port_header ::= interface_identifier [ . modport_identifier ]` is
|
||||
a port production, not a data-type production, and after an identifier
|
||||
anywhere else a `.` opens a member access — so `at_modport_port` /
|
||||
`parse_modport_port_type` sit in `parse_ansi_port`, four tokens of lookahead
|
||||
wide (`ident . ident ident`), and `parse_opt_data_type` is untouched. Gluing
|
||||
follows the `pkg::state_t` precedent, which is what kept the AST, the
|
||||
formatter and `vlog_refactor` out of this change entirely.
|
||||
- **`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.
|
||||
- **`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
|
||||
`bus_if`, the match failed and the jump answered nothing. One line: match by
|
||||
the half before the `.` too, alongside the existing "last `::` segment"
|
||||
rule.
|
||||
- **No AST change, which was the point.** The brief asked whether `AnsiPort`
|
||||
already models absence of direction — it does (`dir: Option<String>`), and
|
||||
every continuation port (`input a, b`) has carried `dir: None` since the
|
||||
beginning. So the new shapes produce AST that every existing consumer was
|
||||
already written for, and the whole downstream cost of this round was two
|
||||
match widenings (one in `vlog_semantic`, one in `lucisv_server`) that exist
|
||||
only because of the modport dot.
|
||||
- **Snapshot churn: none.** `crates/vlog_formatter/tests/snapshots/` is
|
||||
untouched, and `git diff --stat` shows no fixture file changed. No
|
||||
previously-refused fixture started formatting, so there was nothing to
|
||||
justify.
|
||||
- **Corpus: identical, which is itself the finding.** Baseline (HEAD 0e740d7,
|
||||
the change stashed) and after: `813/820 (99.1%)`, 11 ok-unchanged, 802
|
||||
would-reformat, 7 parse-error, 0 verification-error, 0 crash — and the two
|
||||
TSVs are byte-identical, path for path, message for message. To prove the
|
||||
stronger property the TSV does not carry, every corpus file was formatted to
|
||||
stdout and hashed on both sides: all 820 hashes identical. So the passing
|
||||
set is a (trivially strict) superset, no file's output moved by a byte, and
|
||||
the safety net never fired. The reason nothing was gained is that this
|
||||
corpus contains no direction-less first port at all — had it contained one,
|
||||
that file would have been a `parse-error` row before and a formatted one
|
||||
after; the 7 that remain are the known macro-bracketed covergroup, the
|
||||
`` ` ``-number lex error and friends, unchanged. `vlog_semantic`'s corpus
|
||||
acceptance run agrees from the other side: 860 files, 561 modules, 94685
|
||||
references, 88.8% of external candidates answered — identical to three
|
||||
decimal places before and after, so no previously-`Error` module header
|
||||
joined the index either.
|
||||
- **Tests.** `vlog_parser` +9 (`parser.rs` tests module): the three shapes,
|
||||
each alone and mixed with directed ports in both orders; an `interface`
|
||||
header taking the same list; a typed first port with packed dimensions and
|
||||
a parameterized one; the non-ANSI list pinned by name *and* by comma flags,
|
||||
plus the one-name list; `module m ();` and `module m;`; the `input a, b`
|
||||
direction carry-over; a macro-produced list, an escaped name and a comment
|
||||
before the comma, all three still non-ANSI because the clause fires only on
|
||||
a `TokenKind::Ident`; and recovery on two genuinely broken headers plus a
|
||||
never-closed one through `parse_source_tolerant`.
|
||||
`vlog_formatter` +7 table cases in `tests/cases/module_headers.cases`
|
||||
(each is an idempotency and equivalence assertion too — `format_source`
|
||||
verifies both, and the harness re-formats the expected output).
|
||||
`vlog_semantic` +1 (`tests/workspace.rs`):
|
||||
`a_direction_less_first_ansi_port_binds_its_interface_type_cross_file`,
|
||||
both spellings, cross-file through the unit table, plus an assertion that
|
||||
the port declarations themselves survived.
|
||||
`lucisv_server` +2 and one flipped (`type_def.rs`, now 47).
|
||||
`vlog_refactor`: `an_interface_typed_port_list_is_refused_as_a_parse_failure`
|
||||
→ `an_interface_typed_port_list_is_planned_like_any_other` (it asserted the
|
||||
gap; it now asserts the plan, the rendered skeleton and that the skeleton
|
||||
parses), and +1 rename test through a direction-less first port.
|
||||
- **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
|
||||
--workspace`: 0 warnings. `cargo test --workspace`: green (0 failed
|
||||
anywhere; `vlog_parser` 214, `lucisv_server` 873). `cargo test -p
|
||||
vlog_formatter`: green, all 8 targets, no snapshot churn.
|
||||
`tools/corpus_check.sh` before and after: identical, exit 0 both times.
|
||||
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`. No `git commit`, no `git push`; `docs/site/` untouched.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent
|
||||
|
||||
**Gates, re-run independently — all matched the dev's claim exactly.**
|
||||
`cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace`:
|
||||
0 warnings. `cargo test --workspace`: green, `vlog_parser` 214 passed,
|
||||
`lucisv_server` 873 passed / 4 ignored (the 4 ignored are pre-existing in
|
||||
`lucisv_server::{hierarchy,includes,inlay}`, unrelated to this round).
|
||||
`cargo test -p vlog_formatter --all-targets`: green, 7 test binaries run
|
||||
(`lib`, `cases`, `deep_nesting`, `fences`, `fixtures`, `ranges`,
|
||||
`verification`) — the work log's "all 8 targets" is one over the actual
|
||||
binary count; cosmetic, not a gate failure. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**Corpus proof — reproduced independently, not taken on the dev's word.**
|
||||
Built release binaries at the working tree and at a `git worktree add` of
|
||||
`0e740d7` (the round's parent commit) so the working tree was never stashed.
|
||||
`tools/corpus_check.sh corpus`: `813/820 (99.1%)` on both binaries, and the
|
||||
two TSVs are byte-identical (`diff` exit 0) — this also matches the dev's own
|
||||
`corpus-check-results.tsv` left in the tree byte-for-byte. Then, independent
|
||||
of the TSV, every one of the 820 corpus files was formatted with `--stdout`
|
||||
and SHA-256 hashed under both binaries: **all 820 hashes identical.** This is
|
||||
the round's central safety claim and it now has two independent
|
||||
confirmations (the dev's and this one), not one.
|
||||
|
||||
**A. Classification-boundary sweep** (`vlog_parser::parse_source_tolerant`,
|
||||
current tree vs. the `0e740d7` worktree, diffed on `{diagnostics, debug AST}`):
|
||||
|
||||
| shape | verdict |
|
||||
|---|---|
|
||||
| `module m (a, b);` | unaffected, byte-identical AST (non-ANSI, untouched) |
|
||||
| `module m (a);` | unaffected, byte-identical AST |
|
||||
| `module m (mytype a);` | now ANSI, `ty.name="mytype"` — correct |
|
||||
| `module m (a[3:0] b);` | now ANSI, packed dim consumed correctly |
|
||||
| `module m (a #(8) b);` | now ANSI, `#(...)` consumed correctly |
|
||||
| `module m (a.b);` (3-token, closes) | **unaffected** — `at_modport_port` needs a 4th `Ident` after the dotted name and correctly does not fire on `)`; still the same `expected ")" (found ".")` error both sides |
|
||||
| `module m (a.b.c d);` (5-token) | **unaffected** — the lookahead is exactly 4 tokens wide (`ident . ident ident`), a longer dotted chain does not match `at_modport_port`, so this still errors identically both sides (an underdocumented but correctly-failing edge, not a misfire) |
|
||||
| `module m (bus_if.mp bus, foo.bar baz);` (modport non-first) | now parses — confirms the work log's claim that `at_modport_port` fires per-port in `parse_ansi_port`, not just at list-classification, so any `ident.ident` port anywhere in an ANSI list now parses, not only `bus_if.mp` specifically |
|
||||
| `module m (my_pkg::t.mp bus);` (`pkg::type` + modport dot) | **unaffected, fails safe** — neither `at_typed_declarator` nor `at_modport_port` fires (the `::`-chain walk stops before a bare `.`), so this still reports `expected ")" (found "::")` on both sides. Not filed, not tested by the dev, but does not misfire — worth a line in Assumptions if this shape is ever revisited |
|
||||
| directive before first port, then a direction-less port (`` `ifdef FOO `endif bus_if bus, input logic clk); ``) | parses correctly — `take_list_directives` already peels the directive off before the ANSI/non-ANSI decision reads the next token, independent of this round's change |
|
||||
|
||||
**No misfire found in either direction**: nothing that used to be a non-ANSI
|
||||
list started parsing as ANSI, and no shape swallowed characters it should not
|
||||
have.
|
||||
|
||||
**B. Formatter round-trip.** All boundary and headline shapes above were run
|
||||
through `format_source` (`vlog_formatter::format_source`); every one that
|
||||
parses returned `Ok` (i.e. both `verify_equivalence` and `verify_convergence`
|
||||
passed internally — the safety net never fired). The three headline shapes'
|
||||
formatted output matches `module_headers.cases` byte-for-byte. `module m (a,
|
||||
b); input a; output b; endmodule` and `module m (a); input a; endmodule`
|
||||
(non-ANSI) format byte-identically between the `0e740d7` binary and the
|
||||
working-tree binary. No real corpus file with an old-style bare-name port list
|
||||
was found to spot-check against (consistent with the dev's note that this
|
||||
corpus has no such file) — the in-memory comparison above is the substitute.
|
||||
|
||||
**C. `bind_data_type` / `type_span` modport handling — attacked, holds.**
|
||||
Added one test, `renaming_the_modport_half_of_a_port_type_is_refused` in
|
||||
`crates/vlog_refactor/tests/rename.rs` (kept; passes; +1 to `vlog_refactor`'s
|
||||
rename suite, 52 total): a rename request positioned on the `mp` of `bus_if.mp
|
||||
bus` is refused (`rename()` returns `Err`) rather than silently renaming the
|
||||
interface or corrupting the modport spelling — confirming `ItemKind::Modport`
|
||||
being an unbound leaf actually protects the rename path, not just the
|
||||
go-to-type-definition path. Renaming `bus_if` itself through the same port
|
||||
still renames correctly (already covered by the dev's
|
||||
`an_interface_renames_through_a_direction_less_ansi_port`).
|
||||
|
||||
**D. Error recovery — two diagnostic-drift findings, not corruption.**
|
||||
Severity: low. The claim "error recovery unchanged" holds for the two
|
||||
specific fixtures the dev pinned (`module m (input, );` — confirmed
|
||||
byte-identical diagnostics and AST both sides) but **does not hold** for one
|
||||
of the exact shapes named in this round's own attack brief:
|
||||
|
||||
- `module m (foo bar` (never closes, no `endmodule`) — file:
|
||||
`crates/vlog_parser/src/parser.rs`, the `ansi` lookahead added at the
|
||||
`parse_port_list` classification site (~line 2415) plus `parse_ansi_port`
|
||||
(~line 2494). Baseline: `expected ")" (found "bar")` at line 1 col 15.
|
||||
Current: `expected ")" (found "<eof>")` at line 2 col 1. Cause: `foo bar` is
|
||||
now recognized as a typed declarator (`at_typed_declarator` fires), so the
|
||||
parser commits to consuming it as one `AnsiPort` and only then looks for the
|
||||
next `,`/`)`, which is past EOF instead of at the second identifier.
|
||||
- `module m (bus_if bus;` and `module m (bus_if bus\nendmodule\n)` — same
|
||||
cause: baseline reports the error at the second identifier (`bus`, since it
|
||||
reads `bus_if` alone as a non-ANSI name and then chokes on a second
|
||||
identifier); current reports it at the token *after* the successfully
|
||||
parsed `bus_if bus` port (`;` or `endmodule` respectively). The dev's own
|
||||
test (`a_broken_header_still_reports_its_own_token`) only asserts
|
||||
`!diags.is_empty()` for the never-closed case, not a specific position, so
|
||||
this drift does not contradict any committed test — it contradicts the
|
||||
QA-brief's framing of "same error positions/recovery as baseline", which is
|
||||
not literally true for any genuinely-broken header that happens to start
|
||||
with two adjacent identifiers.
|
||||
- In every case checked, the file still ends up as a single `Error(RawText)`
|
||||
item over the same span with the same raw text on both sides — no partial
|
||||
output, no corruption, invariant #1 holds. This is a diagnostic-quality
|
||||
regression at worst (arguably the new position is more precise, since it
|
||||
points at the actual unexpected token rather than the first token past a
|
||||
guessed name), not a safety issue. No fix applied; recorded for the lead's
|
||||
judgment on whether the work log's phrasing needs softening.
|
||||
|
||||
**E. Fuzz-ish sweep.** 50 corpus files with an ANSI first port whose leading
|
||||
direction keyword (`input`/`output`/`inout`) was stripped, re-parsed through
|
||||
`parse_source_tolerant` under `catch_unwind`: **0 panics**. 23 re-parsed
|
||||
clean (the stripped port had a real type after the keyword, e.g. `input logic
|
||||
clk` → `logic clk`, and the new classification correctly reads it as a
|
||||
direction-less typed port). 27 still report a parse error (the stripped port
|
||||
was just `input a` → bare `a`, which correctly falls back to non-ANSI
|
||||
classification and then fails on the *next* port's leading keyword with a
|
||||
sensible `expected identifier (found "input")` — fails safe, not a crash, not
|
||||
a silent misparse).
|
||||
|
||||
**F. The three left-open items.** `module m (a[3], b);` is pinned by
|
||||
`a_broken_header_still_reports_its_own_token`, confirmed unchanged (matches
|
||||
the dev's specific pinning claim — this is the only one of the three the dev
|
||||
actually claimed a test for). `module m (interface bus);` (generic interface
|
||||
port) and `virtual bus_if.mp v;` (modport-qualified virtual interface
|
||||
declaration) are **not** pinned by any test anywhere in the diff, but both
|
||||
were confirmed byte-identical (diagnostics + AST) between `0e740d7` and the
|
||||
working tree by the same harness as section A. Recommendation, not a blocker:
|
||||
a one-line regression test for each would close the gap between "verified
|
||||
today" and "protected going forward," since neither has a test to catch a
|
||||
future regression.
|
||||
|
||||
**G. CLAUDE.md compliance.** `crates/vlog_formatter/src/verify.rs`: `git diff
|
||||
--stat` shows no change — invariant #4 correctly not triggered (no
|
||||
normalization was widened, so no masked-corruption attack tests were owed).
|
||||
`unwrap()`/`expect()`/`panic!`: the only three `panic!`s added are inside
|
||||
`crates/vlog_parser/src/parser.rs`'s `#[cfg(test)] mod tests` (test-helper
|
||||
`ansi_ports`/list-shape assertions) — permitted, not library-path code.
|
||||
`at_modport_port` and `parse_modport_port_type` both have doc comments.
|
||||
`docs/features/ansi-first-port/README.md` has each required section exactly
|
||||
once, in the required order. The `type-definition` feature's Handshake 2 is
|
||||
struck with `~~...~~` and a "Delivered 2026-08-26" annotation, matching this
|
||||
repo's existing struck-handshake convention. `docs/site/` was not touched.
|
||||
|
||||
**Not independently verifiable:** the work log's `vlog_semantic` corpus
|
||||
figure ("860 files, 561 modules, 94685 references, 88.8%... identical to
|
||||
three decimal places before and after") has no corresponding script under
|
||||
`tools/` and no committed test that reproduces it — unlike the
|
||||
`vlog_formatter` corpus proof (section above), which was fully reproduced.
|
||||
Not flagged as a defect (the two headline corpus proofs this round rests on
|
||||
are independently confirmed), just noted as an unverifiable secondary claim.
|
||||
|
||||
**Fix made:** added
|
||||
`renaming_the_modport_half_of_a_port_type_is_refused` to
|
||||
`crates/vlog_refactor/tests/rename.rs` (section C above). No other changes to
|
||||
the diff under review.
|
||||
|
||||
**Verdict: committable as-is.** No hard-invariant violation found (no
|
||||
corruption, comments-preservation and idempotency untouched, `verify.rs`
|
||||
untouched). One low-severity, non-blocking finding (D: diagnostic-position
|
||||
drift on genuinely-broken headers, which the lead may want reflected in the
|
||||
work log's phrasing) and two documentation/test-coverage gaps (the
|
||||
unpinned left-open items in F, and the unreproducible semantic-corpus figure)
|
||||
are recorded for follow-up, not for blocking this round.
|
||||
|
||||
## Review
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. For the highest-invariant-risk crate in the repo, this round set
|
||||
the standard: reproduction before any fix (which surfaced that the
|
||||
modport shape was a second, independent gap), a classification clause
|
||||
built on the parser's own existing lookahead rather than a new
|
||||
recognizer, no AST change, and the corpus proof taken past the TSV to
|
||||
all 820 formatted-output hashes — which QA then re-established
|
||||
independently through a worktree build rather than trusting it. The
|
||||
boundary AST-diff harness and the 50-file direction-stripping sweep are
|
||||
exactly the adversarial coverage a parser change needs.
|
||||
|
||||
Rulings on QA's three notes. The diagnostic-position shift on broken
|
||||
two-identifier headers is accepted: the parser committing further
|
||||
before failing is inherent to recognizing the new legal prefix, no
|
||||
Error item's span or text moved, and better commitment usually means
|
||||
better messages. The two unpinned left-open items are now pinned — I
|
||||
added `the_two_shapes_left_open_by_ansi_first_port_still_refuse` to the
|
||||
parser suite so a future round changes them on purpose. The
|
||||
unreproducible vlog_semantic corpus figure is a fair point filed
|
||||
against that README's tooling, not this round; the workspace harness
|
||||
tests remain the executable check. QA's modport-rename refusal test
|
||||
closes the one write-path question the match-widenings raised.
|
||||
Accepted as shipped.
|
||||
@@ -0,0 +1,215 @@
|
||||
# apply-edit
|
||||
|
||||
## Goal
|
||||
|
||||
Make the three port commands actually edit something in a stock editor.
|
||||
`workspace/executeCommand` used to answer with the `WorkspaceEdit` that
|
||||
`ports::execute` computed, as the request's *result*. The protocol defines no
|
||||
such thing: an `executeCommand` result is `any | null`, and a client applies
|
||||
what a server **pushes** at it with `workspace/applyEdit`.
|
||||
`vscode-languageclient` (which `editors/vscode/extension.js` uses unmodified)
|
||||
drops the result on the floor, and so does Neovim's built-in client — so
|
||||
`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked *as
|
||||
commands* did nothing at all in every stock client. (The code-action path was
|
||||
never affected: a code action carries its edit inline.) This round pushes the
|
||||
edit, answers `null`, and reads the one client response the server can no
|
||||
longer ignore.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`workspace.applyEdit` is the gate.** A client that advertised it gets the
|
||||
push and a `null` result. A client that did not gets exactly the old
|
||||
behavior — the edit as the result — because for that one it is the only
|
||||
thing that could ever work, and a silent no-op is worse than a
|
||||
non-standard answer that some caller may yet read. Both VS Code and Neovim
|
||||
advertise it; `editors/vscode/smoke.js` sends `capabilities: {}` and so
|
||||
takes the fallback, which is why it still passes untouched.
|
||||
- **The push goes out before the command's own response.** The loop sends a
|
||||
request's response when the handler returns, and the handler sends the
|
||||
`applyEdit` request during it. The protocol allows a server to make a
|
||||
request at any time, and a client that waited for the command result before
|
||||
applying the edit would deadlock against any server that does this — VS
|
||||
Code and Neovim both apply immediately. Stated here because it is the
|
||||
ordering a reader would otherwise wonder about.
|
||||
- **A refusal is worth a popup.** `ApplyWorkspaceEditResponse.applied: false`
|
||||
means the user ran a command, watched nothing happen, and has no other way
|
||||
to find out why. It is shown as an ERROR naming the command, plus the
|
||||
client's own `failureReason` when it sent one. Success says nothing.
|
||||
- **A response that does not parse is a refusal.** Nothing was seen to be
|
||||
applied, so the honest thing is to say so rather than assume the best.
|
||||
- **Watcher (un)registration answers stay ignored.** Their ids are never in
|
||||
the pending map, so they fall straight through the new handler — including
|
||||
an error response, which is what a client that refuses to watch sends. The
|
||||
behavior `docs/features/file-watching/README.md` documents is unchanged.
|
||||
- **No retry, no timeout.** A client that never answers leaves one entry in
|
||||
the pending map for the life of the session; three port commands per
|
||||
session is not a leak worth a timer, and the server has no timers by
|
||||
design.
|
||||
- **The `report_scope(warnings)` behavior is unchanged** — the engine's
|
||||
warnings are still surfaced exactly as before, whichever delivery path the
|
||||
edit takes.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains `apply_edit: bool` and derives `Default`, so a test
|
||||
can name only the ability it cares about. `main.rs` fills it from
|
||||
`InitializeParams.capabilities.workspace.apply_edit`.
|
||||
- `Server` gains `applying: HashMap<RequestId, String>` — the outstanding
|
||||
`workspace/applyEdit` requests, each remembering the command that asked.
|
||||
- `Server::send_request` now **returns** the `RequestId` it sent on. The
|
||||
watcher registration ignores it, exactly as it ignores the answer.
|
||||
- `run`'s `Message::Response(_) => {}` becomes `self.response(response)`.
|
||||
- `ExecuteCommand` goes through the new `Server::deliver`.
|
||||
|
||||
### `ports`
|
||||
|
||||
`ports::execute`'s signature is unchanged; only the doc comment's claim that
|
||||
"the server does not push `workspace/applyEdit`" is now false, and is
|
||||
rewritten. No engine behavior changed.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
**No extension change.** `vscode-languageclient` applies `workspace/applyEdit`
|
||||
requests itself; `extension.js` has no custom `executeCommand` handling and
|
||||
needs none. Verified by reading, not assumed.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `workspace.applyEdit` read into `ClientAbilities` at initialize
|
||||
- [x] `Server::deliver`: push the edit with a `label`, answer `null`
|
||||
- [x] `Server::response`: match answers to outstanding requests, report a
|
||||
refusal as an ERROR naming the command
|
||||
- [x] Return-the-edit fallback kept for a client that cannot apply
|
||||
- [x] Tests: pushed-and-null, fallback-returns-the-edit, refusal reported,
|
||||
success silent, duplicate/unknown answer ignored, watcher answer still
|
||||
ignored
|
||||
- [ ] Not done, deliberately: no `$/progress` or timeout on an unanswered
|
||||
`applyEdit` — see Assumptions.
|
||||
- [ ] Not done, deliberately: `WorkspaceEdit` still carries plain `changes`
|
||||
(no `documentChanges`, no snippet edits). That is TODO §9c's item, and
|
||||
it would improve `addPort` cursor placement.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9a
|
||||
|
||||
- **`deliver` is a method on `Server`, not a free function**, because it has
|
||||
to both send a request and remember its id; splitting it would have meant
|
||||
returning a request for the caller to send, which is a shape with one user.
|
||||
- **`send_request` returning the id** was the smallest change that let the
|
||||
applyEdit path record it. The two watcher call sites ignore the value; a
|
||||
`RequestId` is not `#[must_use]`, so this stays silent.
|
||||
- **The pending map is keyed by `RequestId`, not by command**, so two
|
||||
commands in flight cannot be confused and a duplicate answer to a spent id
|
||||
does nothing. Pinned by
|
||||
`an_edit_the_editor_applied_is_said_nothing_about`'s second half.
|
||||
- **The `label`** is `lucisv: <command>` — it is what an editor shows on its
|
||||
undo stack, so it names the thing the user would want to undo.
|
||||
- Files touched: `crates/lucisv_server/src/server.rs`,
|
||||
`crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`, and
|
||||
`ports.rs`'s stale doc comment (it claimed the server does not push
|
||||
`workspace/applyEdit`). `editors/vscode/extension.js` was read and
|
||||
deliberately left alone.
|
||||
|
||||
**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings),
|
||||
`cargo test --workspace`, `node editors/vscode/smoke.js` — all clean. 5 new
|
||||
unit tests in `server.rs` (plus the watcher-answer guard), 1 in `main.rs`, and
|
||||
one e2e session (`a_command_pushes_its_edit_to_a_client_that_can_apply_one`)
|
||||
that pushes the edit at a real binary and answers it as an editor would.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent, §9a
|
||||
|
||||
**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`,
|
||||
`cargo clippy --all-targets --workspace` (zero warnings, forced a rebuild by
|
||||
touching the changed files first so the check was not answered from a stale
|
||||
cache), `cargo test --workspace` (3 full runs, no failures), `node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server` (exit 0) — all reproduced
|
||||
independently.
|
||||
|
||||
**Read the diff against the README's claims,** file:line references against
|
||||
the working tree as it stood before this QA pass:
|
||||
|
||||
- `server.rs`'s `ExecuteCommand` handler (around what is now line 304) calls
|
||||
`self.report_scope(warnings)` unconditionally in the `Ok` arm, before
|
||||
`self.deliver(...)` branches on the ability — confirmed **both** the push
|
||||
and the fallback path surface engine warnings identically.
|
||||
- **RequestId collision, checked and ruled out.** `applying` and the watcher
|
||||
(un)registration ids are both minted by the same `send_request`, whose
|
||||
counter (`self.request_ids`) is a single monotonically increasing `u32`
|
||||
shared across every call site — two ids can never collide, so a watcher
|
||||
answer can never land in `applying` and vice versa. This is structural,
|
||||
not incidental: there is exactly one counter to break for a collision to
|
||||
become possible.
|
||||
- `ports.rs`'s doc comment rewrite matches the new behavior; no engine
|
||||
behavior changed there, confirmed by reading `execute`'s body (untouched
|
||||
except the comment).
|
||||
|
||||
**Attacked the response-routing path** (`server.rs::response`, the
|
||||
`ApplyWorkspaceEditResponse` deserialization). The existing tests covered
|
||||
`Ok(applied: true)`, `Ok(applied: false, failureReason)`, a duplicate answer,
|
||||
and a watcher answer — but not the two cases the doc comment explicitly
|
||||
claims to handle: a response payload that is `Ok` JSON but does not
|
||||
deserialize as `ApplyWorkspaceEditResponse` at all, and a JSON-RPC-level
|
||||
`Err` response (a client that rejects the request outright rather than
|
||||
answering it). Added both as tests in `server.rs`:
|
||||
|
||||
- `a_malformed_apply_edit_answer_is_reported_as_a_refusal` — answers with
|
||||
`{"notApplied": "whatever"}` (no `applied` field, which is required with no
|
||||
default in `lsp_types::ApplyWorkspaceEditResponse`); asserts one ERROR
|
||||
naming the command, not a panic and not silence.
|
||||
- `a_response_with_a_jsonrpc_error_is_reported_too` — uses
|
||||
`Response::new_err` directly; asserts the `error.message` reaches the
|
||||
shown text.
|
||||
|
||||
Both pass. Confirms the "a response that does not parse is a refusal"
|
||||
assumption is real code, not just a comment.
|
||||
|
||||
**Found and fixed one self-inflicted test bug while adding the above:** the
|
||||
first draft of `a_malformed_apply_edit_answer_is_reported_as_a_refusal` named
|
||||
its tree `propagating("malformed", ...)`, which collides with the *existing*
|
||||
`Tree::new("malformed")` in
|
||||
`a_malformed_watched_files_notification_is_dropped` — both resolve to the
|
||||
same `std::env::temp_dir()` path (keyed only by pid + name), so running the
|
||||
suite in parallel raced the two tests' filesystem setup and made
|
||||
`ports::execute` fail to find `sub.sv` (`server.rs`, originally around line
|
||||
1417 in this session's numbering). Not a server bug — a QA-test-authoring
|
||||
bug. Renamed to `"malformedapplyedit"`; reran the full `lucisv_server` suite
|
||||
three times back to back with no failures. Worth a general note for future
|
||||
dev/QA agents: `Tree::new`'s temp path is name-keyed, not test-keyed, so a
|
||||
tree name must be checked for uniqueness across the whole crate, not just
|
||||
the tests being added.
|
||||
|
||||
**Capability reading:** `apply_edit_support` reads
|
||||
`params.capabilities.workspace.as_ref().and_then(|w| w.apply_edit)` —
|
||||
verified this cannot panic on `InitializeParams::default()` or any partial
|
||||
capability object; already covered by
|
||||
`apply_edit_support_is_read_from_the_clients_own_capabilities`, re-ran it
|
||||
directly.
|
||||
|
||||
**CLAUDE.md compliance:** grepped the new/changed lines in `server.rs`,
|
||||
`main.rs`, `ports.rs` for `.unwrap()`, `.expect()`, `panic!` outside
|
||||
`#[cfg(test)]` — none found. Public items added (`ClientAbilities::apply_edit`)
|
||||
carry doc comments. README has all seven required sections; TODO.md's
|
||||
checkbox is checked with the item text unchanged and a `→` pointer added.
|
||||
|
||||
**Verdict: no blocking findings.** The two new attack tests and the
|
||||
tree-name-collision fix are the only changes made to this feature's code.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full
|
||||
workspace suite/smoke.js myself, all clean. The design is right: the gate is
|
||||
the client's own `workspace.apply_edit` capability, the fallback is exactly
|
||||
the old behavior for exactly the clients the old behavior could serve, and
|
||||
the pending-map keyed by the one shared id counter makes response routing
|
||||
collision-free by construction (QA verified the same). The `deliver`
|
||||
doc comment's deadlock note is a good catch worth keeping. The no-timeout
|
||||
decision is accepted: three commands per session cannot leak meaningfully,
|
||||
and the server has no timers by design. `ports.rs`'s previously-false doc
|
||||
comment is now true. Accepted as shipped.
|
||||
@@ -0,0 +1,533 @@
|
||||
# cancel-request
|
||||
|
||||
## Goal
|
||||
|
||||
`$/cancelRequest` is the client's way of saying "drop that one, the user has
|
||||
moved on" — sent constantly by real editors, which cancel the completion,
|
||||
hover and inlay-hint requests of the previous keystroke on every new one.
|
||||
Until now the notification fell through `Server::notification`'s `_ => {}` arm
|
||||
and the request was computed and answered anyway. This round answers a
|
||||
cancelled request with the protocol's own `RequestCancelled` (-32800) instead
|
||||
of computing it, whenever the cancel reaches the loop in time — which, on a
|
||||
single-threaded server, means *while the request is still queued*. The gain is
|
||||
not correctness (an ignored cancel is legal) but work not done: on a slow
|
||||
rescan or a large-file format, the queue behind the busy handler is exactly
|
||||
where a stale completion request sits, and answering it costs nothing (TODO.md
|
||||
§9b, the last item of that section).
|
||||
|
||||
## What "in time" can mean on a one-message-at-a-time loop
|
||||
|
||||
Everything about this feature follows from one fact: **the client sends the
|
||||
request and its cancel down one ordered channel**, and the server handles one
|
||||
message at a time. Read strictly one message per iteration, a cancel is always
|
||||
too late — by the time `C(R)` is dequeued, `R` was dequeued, computed and
|
||||
answered an iteration ago. Cancellation only becomes reachable when the loop
|
||||
looks at *more than one message at a time*: while a handler runs, the client
|
||||
keeps sending, so the backlog waiting behind it can hold `[R1, C(R1), R2]` —
|
||||
and R1 can be answered `RequestCancelled` for free.
|
||||
|
||||
So `run()` now works in bursts:
|
||||
|
||||
1. block for the next message, as before;
|
||||
2. take everything already queued behind it, without blocking, into one FIFO
|
||||
(the blocked-for message first);
|
||||
3. scan that whole burst for `$/cancelRequest` notifications and collect the
|
||||
ids that name a request **in the same burst**;
|
||||
4. handle the burst strictly in arrival order — a cancelled request answered
|
||||
`RequestCancelled` without dispatch, every other message exactly as before.
|
||||
|
||||
Step 3 is what keeps the cancelled set from being state: it is built per burst
|
||||
and dropped with it.
|
||||
|
||||
### The transport does not queue — so we do
|
||||
|
||||
The first attempt used `connection.receiver.try_recv()` for step 2 and
|
||||
cancelled **nothing** over a real pipe. The reason is worth writing down,
|
||||
because it is invisible from the API:
|
||||
|
||||
> `lsp-server` 0.10's stdio transport wires its reader, writer and dropper
|
||||
> threads with **`crossbeam_channel::bounded(0)`** — rendezvous channels with
|
||||
> no capacity at all (`stdio.rs`). Its reader thread parks *inside* `send`
|
||||
> holding one message until the loop takes it. A client's backlog therefore
|
||||
> never sits on `connection.receiver`: it sits in the OS pipe, one message
|
||||
> deep from where we stand, and `try_recv` right after a `recv` loses a
|
||||
> microsecond-scale race with the reader thread essentially every time.
|
||||
|
||||
`Server::queue()` fixes this with the smallest thing that can: one forwarder
|
||||
thread that blocks on `connection.receiver` and pushes onto an unbounded
|
||||
`std::sync::mpsc` queue that `run()` owns. The backlog then accumulates where
|
||||
we can see it, and step 2 is a plain `try_recv` loop. The thread touches no
|
||||
server state, moves messages and nothing else, and is std-only — no new
|
||||
dependency.
|
||||
|
||||
The forwarder **stops at the `shutdown` request and never reads past it**.
|
||||
`Connection::handle_shutdown` answers the request and then reads the `exit`
|
||||
notification off the *connection* itself; a forwarder that kept going would
|
||||
take that `exit` first, and `handle_shutdown` would block for its full
|
||||
thirty-second timeout and then return a protocol error. Stopping there also
|
||||
means nothing after a shutdown is ever queued, which is exactly the protocol's
|
||||
own rule.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Cancellation is best-effort, and the spec says so.** LSP allows a server
|
||||
to ignore a cancel it cannot honour; the only hard requirement is that every
|
||||
request gets exactly one response. Both are held here: a cancel that misses
|
||||
its window leaves the request answered normally.
|
||||
- **A cancel arriving in a *later* burst than its request is dropped.** By
|
||||
then the request has been answered — there is nothing left to cancel, and
|
||||
remembering the id would be a set that grows for the life of the session.
|
||||
This is the single rule that keeps this feature stateless.
|
||||
- **A cancel in the same burst but dequeued *before* its request still
|
||||
cancels it.** The burst is scanned as a whole before any of it runs, so
|
||||
ordering within the burst does not matter. (A real client never sends the
|
||||
cancel first; a transport is free to make it look that way.)
|
||||
- **A cancel for a request the server never received is dropped** where it is
|
||||
read, for the same reason.
|
||||
- **Cancelling one request twice is harmless.** The id is removed from the
|
||||
cancelled set as it is used, so a second cancel finds nothing — and it could
|
||||
not touch a later request even if ids were reused, because the set never
|
||||
outlives its burst.
|
||||
- **`shutdown` is never cancellable.** `handle_shutdown` runs before the
|
||||
cancelled set is consulted, so a cancel naming the shutdown id cannot stop
|
||||
the server from shutting down. The spec's "a server should still answer a
|
||||
cancelled request" reading is the safe one here: a client that cannot shut
|
||||
its server down leaks a process.
|
||||
- **Notifications are never cancelled.** They carry no id and get no
|
||||
response; `$/cancelRequest` names request ids only. A `didChange` queued
|
||||
ahead of a cancelled request is still applied — the state a *later* request
|
||||
is answered against must not depend on which requests were dropped.
|
||||
- **Order inside a burst is the invariant, not an implementation detail.**
|
||||
A `didChange` the client sent before a completion request must be in effect
|
||||
when that completion is answered, exactly as it would be one message at a
|
||||
time. Pinned by
|
||||
`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`.
|
||||
- **Both id forms are read.** `CancelParams.id` is
|
||||
`NumberOrString`; a numeric id becomes `RequestId::from(i32)` and a string
|
||||
id `RequestId::from(String)`. The string `"8"` is not the number `8` —
|
||||
`RequestId` keeps them apart and so does the cancel, which is the only
|
||||
behaviour that can be right when a client uses both forms.
|
||||
- **A cancel whose params do not parse is dropped**, on the same reasoning as
|
||||
every other malformed notification: there is no id to act on and no id to
|
||||
answer on.
|
||||
- **The cancelled response carries a message.** `-32800` plus
|
||||
`"lucisv: request cancelled by the client"`. Clients do not show it — the
|
||||
code is what they read — but a log with the text in it is easier to read
|
||||
than a log with a number in it.
|
||||
- **Nothing already *running* is cancelled.** There is one thread; a format,
|
||||
a rescan or a rename that has started runs to completion. The work-done
|
||||
progress bar still advertises `cancellable: false`, which stays true.
|
||||
- **The queue is unbounded.** Backpressure on the pipe used to be the reader
|
||||
thread's rendezvous; now a burst is buffered in memory instead. For an LSP
|
||||
client that is bounded by what an editor sends between two of our handler
|
||||
calls — kilobytes. A client that floods a server faster than it can read
|
||||
would grow this queue, and would equally have grown the pipe before.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `lucisv_server::server` (this feature's own module)
|
||||
|
||||
- `Server::run` no longer receives-and-dispatches inline. It builds the queue,
|
||||
blocks on it, and hands each burst to `process_batch`. Behaviour for a
|
||||
client that never cancels is identical, message for message.
|
||||
- **New private items:** `Server::queue()` (the forwarder),
|
||||
`Server::process_batch(Vec<Message>) -> Result<bool, …>` (the burst
|
||||
handler; `true` means the client shut us down), and the free functions
|
||||
`burst`, `is_shutdown`, `cancelled_in`, `cancelled_id`, `cancelled_response`.
|
||||
- `Server::request`, `Server::notification` and `Server::response` are
|
||||
**unchanged**. `$/cancelRequest` never reaches `notification()`; it is
|
||||
consumed in the burst handler, which is the only place that can act on one.
|
||||
- No field was added to `Server`. Cancellation state lives for the length of
|
||||
one burst and no longer.
|
||||
|
||||
### `lsp-server`
|
||||
|
||||
- Consumed, not changed: `Connection.receiver` is now `clone()`d (crossbeam
|
||||
receivers are `Clone`), and `handle_shutdown` is called exactly where it was
|
||||
— the forwarder's stop rule is what keeps its `exit` read working.
|
||||
- The rendezvous-channel finding above is a property of version `=0.10.0`,
|
||||
which the workspace pins. A future bump should re-read `stdio.rs`: if the
|
||||
transport ever queues, `Server::queue` becomes redundant rather than wrong.
|
||||
|
||||
### Every other crate, and `editors/vscode`
|
||||
|
||||
**Untouched.** No engine crate knows this happened, and no client capability
|
||||
gates it — `$/cancelRequest` is unconditional in the protocol, advertised by
|
||||
nobody and sent by everybody. `smoke.js` passes unchanged (run as a gate).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `run()` restructured into blocking receive → burst drain → burst handler
|
||||
- [x] Forwarder thread so the backlog is observable at all (the rendezvous
|
||||
finding), stopping at `shutdown` so `handle_shutdown` keeps its `exit`
|
||||
- [x] Cancelled ids collected per burst, matched against that burst's own
|
||||
requests, dropped otherwise
|
||||
- [x] Cancelled requests answered `-32800` without dispatch; the cancels
|
||||
themselves consumed
|
||||
- [x] `shutdown` honoured before any cancel is consulted
|
||||
- [x] Arrival order preserved across the whole burst (notifications included)
|
||||
- [x] Numeric and string cancel ids; malformed cancels dropped
|
||||
- [x] Tests: 10 unit in `server.rs` (through the `Session` harness, driving
|
||||
the real `process_batch`), 1 e2e over the wire
|
||||
- [x] TODO.md §9b checkbox; loop description in
|
||||
`docs/features/lucisv-server/README.md`
|
||||
- [ ] **Not done, deliberately:** no cancellation of work in flight. That
|
||||
needs a worker pool and cancellation tokens threaded through the engine
|
||||
— TODO.md §6's explicit non-goal for as long as per-file recompute stays
|
||||
in the millisecond range.
|
||||
- [ ] **Not done, deliberately:** no `ContentModified` (-32801) for requests
|
||||
invalidated by a `didChange` queued behind them. It is the neighbouring
|
||||
idea and a real option now that the loop can see a burst, but the spec
|
||||
warns that an answer computed against slightly older text is usually
|
||||
still useful — and the client, not the server, is the one that knows.
|
||||
Filed here, not built.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent (§9b, `$/cancelRequest`)
|
||||
|
||||
- Read `CLAUDE.md`, `docs/features/lucisv-server/README.md`, TODO.md §9b and
|
||||
the whole of `server.rs`'s loop before touching anything.
|
||||
- **Verified the lead's design against the code, and found one thing that
|
||||
invalidated its second step.** The plan said to drain `connection.receiver`
|
||||
non-blockingly with `try_iter`/`try_recv`. Written that way, the e2e flood
|
||||
cancelled **zero** of five requests, reproducibly. `lsp-server` 0.10's
|
||||
`stdio.rs` uses `bounded(0)` rendezvous channels throughout: there is no
|
||||
queue on that receiver to drain, ever. The rest of the design — burst FIFO,
|
||||
batch-wide cancel scan, drop-if-not-in-batch, order preserved, shutdown
|
||||
never cancellable — is unchanged and implemented as written.
|
||||
- **Fix: one forwarder thread** (`Server::queue`) onto a `std::sync::mpsc`
|
||||
queue, so the backlog accumulates somewhere observable. Std-only, no new
|
||||
dependency, no shared state, ~12 lines. Considered and rejected: a timed
|
||||
drain window (`recv_timeout(1ms)`), which would tax *every* message with a
|
||||
millisecond of latency and still be a race; and handling shutdown ourselves
|
||||
to free the forwarder, which would duplicate `handle_shutdown`'s protocol
|
||||
for no gain.
|
||||
- **The forwarder's stop-at-shutdown rule was found by reading
|
||||
`handle_shutdown`, not by a failing test**: it reads `exit` off the
|
||||
connection itself, so an eager forwarder would have stolen it and turned
|
||||
every shutdown into a 30-second timeout followed by a protocol error. The
|
||||
rule is asserted by `a_shutdown_is_honoured_however_it_is_cancelled` and by
|
||||
the e2e session, which shuts down through the same flood.
|
||||
- Tests: 10 unit tests in `server.rs`, driving the real `process_batch`
|
||||
through a new `Session::batch` helper (the harness otherwise bypasses the
|
||||
loop entirely), plus `Session::answers()` for reading responses off the
|
||||
client end. One e2e test running the real binary and the real `run()`.
|
||||
- **The e2e test asserts what is deterministic, and says why.** Three
|
||||
iterations were needed to get there: with cheap requests, *how many* cancels
|
||||
land in the same burst as their request is a scheduling race, and demanding
|
||||
all five failed roughly one full-suite run in four (the suite runs 38
|
||||
server processes in parallel). The final shape floods twenty
|
||||
`textDocument/formatting` requests over a 300-line buffer — enough work per
|
||||
message that the forwarder is never starved — and asserts the properties
|
||||
that must hold on any schedule: exactly one response per request, `-32800`
|
||||
only ever on an id the client actually cancelled, a correct formatted answer
|
||||
on every other id, at least one honoured cancel (the wire path works), and
|
||||
a clean shutdown. Measured under a deliberate 24-way overload: worst case
|
||||
two of five honoured, never zero.
|
||||
- Also corrected two now-stale comments about cancellation being absent
|
||||
entirely — the module header of `server.rs`, `begin_indexing`'s note on
|
||||
`cancellable: false`, and the matching line in the progress e2e test. The
|
||||
bar's `false` stays correct: what has *started* still runs to completion.
|
||||
- Gates, all clean: `cargo fmt --all -- --check`, `cargo clippy --all-targets`
|
||||
(no warnings), `cargo test --workspace` (34 suites green; `lucisv_server`
|
||||
702 unit + 38 e2e), `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` → OK. The e2e suite was re-run ten consecutive
|
||||
times looking for flake: ten passes.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent (§9b, `$/cancelRequest`)
|
||||
|
||||
**Verdict: committable as-is.** No corruption, no protocol violation, no
|
||||
reproducible flake found. Four gaps in test coverage for the highest-risk
|
||||
part of the change (the forwarder thread) were found and closed directly;
|
||||
one theoretical (not reproduced) flake risk in the e2e flood is recorded
|
||||
below with a reasoned trade-off, not "fixed," because the fixes available
|
||||
would weaken the property the test exists to prove.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets`
|
||||
clean, no warnings. `cargo test --workspace`: every suite green, including
|
||||
`lucisv_server` at 706 unit (was 702 pre-QA; +4 added below) + 38 e2e.
|
||||
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` →
|
||||
OK. `cargo test -p lucisv_server --test e2e` run five more times standalone,
|
||||
before the QA-added tests and five more times after: **10/10 green**, no
|
||||
flake observed in the flood test or anywhere else in the suite.
|
||||
|
||||
**1. Forwarder shutdown hand-off — verified clean, by reading
|
||||
`lsp-server` 0.10's actual source, not the dev's summary.**
|
||||
|
||||
- Read `~/.cargo/registry/.../lsp-server-0.10.0/src/stdio.rs`,
|
||||
`src/lib.rs` (`Connection::handle_shutdown`, `Connection::memory`) and
|
||||
`src/msg.rs` (`Request::is_shutdown`, `Notification::is_exit`,
|
||||
`Response`'s `#[serde(flatten)]` encoding). Confirms the README's claim:
|
||||
the stdio reader thread parks inside a `bounded(0)` `send` until taken,
|
||||
so a client's backlog really does live in the OS pipe and not on
|
||||
`connection.receiver`.
|
||||
- (a) **Method-name detection, and the notification case.** `is_shutdown`
|
||||
(`crates/lucisv_server/src/server.rs:1119`) matches
|
||||
`Message::Request { method == "shutdown" }` only — the same test
|
||||
`lsp-server`'s own `Request::is_shutdown` (msg.rs:233) uses. A
|
||||
**notification** shaped like `{"method":"shutdown"}` fails the match
|
||||
(wrong enum variant), so the forwarder does not stop for it; it is
|
||||
forwarded like any other message and falls through `notification()`'s
|
||||
`_ => {}` arm, doing nothing. This was asserted by nothing before QA —
|
||||
added `is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`
|
||||
(server.rs:3574). A malformed shutdown-*request* (e.g. non-null params)
|
||||
is not a distinct case: neither `is_shutdown` nor `handle_shutdown`
|
||||
parses params, only the method name, so there is nothing to be
|
||||
malformed.
|
||||
- (b) **The stolen-message / deadlock window.** Traced the forwarder
|
||||
(`Server::queue`, server.rs:209-233): it checks `is_shutdown` on the
|
||||
message **after** receiving it but **before** issuing its next `recv()`,
|
||||
and breaks its loop without calling `recv()` again when that check is
|
||||
true. `handle_shutdown` (lsp-server lib.rs:348) is only reached by
|
||||
`process_batch` for a request already sitting in the batch Vec — i.e.
|
||||
after the forwarder that produced it has already returned from its last
|
||||
`sender.send`. Because the forwarder's own break happens strictly before
|
||||
any further receive, there is no window where both the forwarder and
|
||||
`handle_shutdown` are calling `recv`/`recv_timeout` on the same
|
||||
crossbeam channel at once — no steal, no deadlock. Added
|
||||
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`
|
||||
(server.rs:3632), which sends a real shutdown request + exit notification
|
||||
through a `Connection::memory()` pair, calls the real `Server::queue()`,
|
||||
and asserts (i) the shutdown is the last thing the forwarder ever
|
||||
forwards even after 50ms of extra opportunity to misbehave, and (ii) the
|
||||
`exit` is still sitting, unread, directly on `connection.receiver` —
|
||||
exactly where `handle_shutdown` looks for it. This is the one test in
|
||||
the whole suite that exercises the real `queue()` method without going
|
||||
through a subprocess.
|
||||
- (c) **Messages already forwarded ahead of a shutdown in the same
|
||||
batch.** Because the forwarder always stops immediately after
|
||||
forwarding the message it detects as shutdown, shutdown is provably
|
||||
always the *last* message that forwarder instance ever produces — there
|
||||
is no way for a message to be forwarded *after* shutdown by the same
|
||||
producer, and there is only ever one producer (next point). So the
|
||||
scenario "a request forwarded after shutdown gets silently dropped" is
|
||||
not reachable through this code path. Nothing found here; the design
|
||||
note in the feature README (lines 63-69) undersells this a little by
|
||||
only mentioning the *thirty-second timeout* consequence of an eager
|
||||
forwarder — the actual structural guarantee (shutdown is always last)
|
||||
is worth knowing but the doc isn't wrong, just less complete than it
|
||||
could be. Not fixed (doc-only, not a code finding, and rewriting
|
||||
someone else's README section is not QA's job per CLAUDE.md).
|
||||
|
||||
**2. Message loss/reordering — verified clean.**
|
||||
|
||||
- Exactly one producer: `Server::queue` is called exactly once, from
|
||||
`Server::run` (server.rs:185), which is itself called exactly once, from
|
||||
`main.rs:76`. No respawn path exists.
|
||||
- Single channel used throughout: `run`'s blocking head-of-burst read and
|
||||
`burst`'s non-blocking drain (server.rs:1126) both operate on the same
|
||||
`std::sync::mpsc::Receiver` returned by `queue()` — never a mix of the
|
||||
mpsc and `connection.receiver` on the consuming side. (`connection.receiver`
|
||||
itself is only ever touched by the forwarder's `source` handle and by
|
||||
`handle_shutdown`, never by `run`/`burst`/`process_batch`.)
|
||||
- Exactly-once processing: `burst` pushes the blocking-received `first`
|
||||
plus everything `try_recv` drains, with no filtering or dedup step in
|
||||
between — the FIFO in equals the FIFO out. Added
|
||||
`burst_collects_everything_already_queued_in_arrival_order`
|
||||
(server.rs:3602) directly against a fresh
|
||||
`std::sync::mpsc` channel (no `Server` involved), pinning arrival order
|
||||
for `[first, second, third]`. Previously `burst` had zero direct test
|
||||
coverage — every existing cancel test drives `process_batch` through
|
||||
`Session::batch`, bypassing `burst` entirely, so this was a real gap in
|
||||
a change the assignment calls "the highest-risk this repo's server has
|
||||
taken."
|
||||
|
||||
**3. `exit` handling / zombie-thread check — verified clean.**
|
||||
|
||||
- `talk()` (e2e.rs:66-79) and the progress-e2e session's own `finish()`
|
||||
(e2e.rs:1978-1985) both call `child.wait()` and assert
|
||||
`status.success()` — a hung forwarder or a process that doesn't
|
||||
terminate would hang or fail these, and none did across 10 e2e runs.
|
||||
This is a real check, not a rubber stamp: `child.wait()` blocks until
|
||||
the OS reports the process gone, so a genuinely undead forwarder thread
|
||||
(blocked on stdin, holding the process open) would show up as a test
|
||||
timeout, not a silent pass.
|
||||
- The forwarder thread is detached (`let _ = ... .spawn(...)`), never
|
||||
joined. This is fine for process exit: after `shutdown`+`exit`, the
|
||||
forwarder has *already* stopped itself (point 1b) well before `run()`
|
||||
returns, so by the time `main()` returns there is no thread left
|
||||
blocked on I/O that could hold the process open. In the one edge case
|
||||
where a client disconnects without ever sending `shutdown` (broken
|
||||
pipe), the forwarder's own `source.recv()` errors, it drops its `sender`
|
||||
and exits, closing the mpsc and unblocking `run()`'s own `recv()` the
|
||||
same way `self.connection.receiver.recv()` used to unblock pre-diff —
|
||||
behaviorally identical to the old direct-receive loop for that case.
|
||||
Not a new finding; equivalent to prior behavior.
|
||||
|
||||
**4. Cancellation semantics matrix — re-verified independently, assertions
|
||||
read (not just names), all pass; one gap closed.**
|
||||
|
||||
Read every assertion, not just the test name, for: same-burst
|
||||
cancel-after (`a_request_cancelled_in_the_same_burst_is_answered_cancelled`),
|
||||
cancel-before (`a_cancel_dequeued_before_its_request_still_cancels_it`),
|
||||
partial-batch cancel (`a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone`),
|
||||
orphan/late drop with the id-reuse proof
|
||||
(`a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot`),
|
||||
notification-ordering
|
||||
(`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`),
|
||||
notifications-uncancellable (`a_cancel_never_cancels_a_notification`),
|
||||
shutdown-uncancellable (`a_shutdown_is_honoured_however_it_is_cancelled`),
|
||||
double cancel (`cancelling_one_request_twice_answers_it_once`), int-vs-string
|
||||
ids including the `"8"` vs `8` case (`a_cancel_id_may_be_a_number_or_a_string`),
|
||||
and malformed params (`a_malformed_cancel_is_dropped_rather_than_guessed_at`).
|
||||
Every one asserts what its name claims; none was a false-positive
|
||||
(no-op) test. All pass, independently re-run.
|
||||
|
||||
**Gap found and closed:** no test covered a cancel naming a
|
||||
**server-initiated** id (the `lucisv-0`/`lucisv-index-N`/`lucisv-watched-files-N`
|
||||
namespace from `Server::send_request`, server.rs:949). Traced it: `cancelled_in`
|
||||
(server.rs:1141) only ever matches a cancel against ids of `Message::Request`
|
||||
entries *received in the same batch* — a server-initiated id only ever
|
||||
appears on the wire as a `Message::Response` coming back from the client,
|
||||
a different match arm in `process_batch` entirely, never consulted against
|
||||
`cancelled`. So interference is not possible by construction. Added
|
||||
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
|
||||
(server.rs:3682) to pin this rather than leave it as an inference:
|
||||
it calls the real `send_request`, gets back `lucisv-0`, sends a cancel
|
||||
naming it alongside an ordinary client request, asserts the client request
|
||||
is untouched, and then answers the server-initiated request successfully
|
||||
to prove routing was never disturbed.
|
||||
|
||||
**5. `-32800` on the wire — verified, one assertion added.**
|
||||
|
||||
`cancelled_response` (server.rs:1171) uses
|
||||
`lsp_server::ErrorCode::RequestCanceled as i32`, which is `-32800` in
|
||||
`msg.rs:128` — matches spec. `Response`'s `#[serde(flatten, with =
|
||||
"ResponseResult")]` (lsp-server msg.rs:87-98) serializes to exactly one of
|
||||
`result`/`error`, never both — confirmed by reading the encoding, and by
|
||||
the e2e flood's existing `answer.get("result").is_none()` on a real wire
|
||||
response (e2e.rs:3141). Id-type preservation (int in → int in response) is
|
||||
implicitly covered by the flood test's own matching: it filters
|
||||
`messages.iter().filter(|m| m["id"] == id)` against a Rust `u32`, which
|
||||
would find nothing if the id had round-tripped as a string, and the test
|
||||
asserts exactly one match per id. **Gap found and closed:** nothing
|
||||
asserted that the error carried a non-empty `message` string, only that
|
||||
`code` was right and `result` was absent. Added that assertion in-line at
|
||||
e2e.rs (next to the `result`-absence check in
|
||||
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each`).
|
||||
|
||||
**6. The e2e flood's honesty — one theoretical, unreproduced flake risk,
|
||||
documented rather than "fixed."**
|
||||
|
||||
Read the whole test (e2e.rs:3079-3168). The `honoured > 0` assertion
|
||||
(e2e.rs:3160) is the one the
|
||||
task flagged as suspicious, correctly. Reasoning:
|
||||
|
||||
- The forwarder thread and the main loop's request handling run
|
||||
concurrently on real OS threads. While the main thread is inside a
|
||||
synchronous `self.request(...)` call (formatting), the forwarder can
|
||||
keep draining the reader thread's rendezvous handoffs into the mpsc
|
||||
queue in parallel — this concurrency, not any timer, is what makes a
|
||||
multi-message burst likely.
|
||||
- It is **not mathematically impossible** for every burst to end up size
|
||||
1: a scheduler that always preempts the forwarder thread and lets the
|
||||
main thread fully drain-and-reblock before the next message is
|
||||
forwarded would produce zero cancellations, every time, for any finite
|
||||
request count. No such interleaving was produced in 10 standalone e2e
|
||||
runs plus one full `cargo test --workspace` run (which itself runs the
|
||||
e2e binary), so it is not a *practical* risk today, but "never observed"
|
||||
is exactly the "≠ impossible" the task named.
|
||||
- **Why not fixed:** the two available code fixes both make the test
|
||||
worse. Relaxing `honoured > 0` to `honoured >= 0` (i.e., deleting the
|
||||
assertion) would stop the test from ever proving the cancellation path
|
||||
works over the real wire at all — the one thing this e2e test exists to
|
||||
check per its own doc comment. Adding a synchronization point (e.g. a
|
||||
test-only delay hook) to force a burst would add production-code
|
||||
surface *purely for a test's benefit*, which the "simplicity first"
|
||||
section of `CLAUDE.md` weighs against, for a risk that is theoretical
|
||||
and has a fallback: a failure here is a flake in one non-gating-by-flake
|
||||
test, not a correctness bug (the request would still be answered
|
||||
correctly once instead of cancelled — see point 4's stateless-drop
|
||||
behavior — so no invariant breaks, only the "never zero" assertion
|
||||
would).
|
||||
- **Recommendation:** accept the residual risk as-is. If it is ever
|
||||
observed to flake in CI, the fix is almost certainly to widen the
|
||||
buffer/request count further (the dev already tuned this once, from a
|
||||
~1-in-4 flake rate with cheap requests down to zero observed in 10+ runs
|
||||
with 300 lines / 20 requests) rather than to touch the assertion itself.
|
||||
|
||||
**7. CLAUDE.md compliance — verified clean.**
|
||||
|
||||
- No bare `std::thread::spawn` (which panics on OS resource exhaustion).
|
||||
The forwarder uses `std::thread::Builder::new().spawn(...)`
|
||||
(server.rs:215), which returns `io::Result`, and the error is
|
||||
deliberately discarded with `let _ =` plus a comment explaining the
|
||||
fallback (the mpsc sender is dropped, so `run()`'s `recv()` fails and
|
||||
the loop ends cleanly instead of hanging) — no panic path introduced.
|
||||
This is in `main`-path server setup, which CLAUDE.md's "Tests and
|
||||
`main.rs` argument handling may use them" carve-out does not literally
|
||||
name, but the *effect* is a `Result`-returning call whose error is
|
||||
handled without panicking or unwrapping — no rule is broken; there is
|
||||
no `unwrap`/`expect`/`panic!` in this path at all.
|
||||
- All `.expect(...)`/`.unwrap()` calls introduced by the diff (checked
|
||||
with `git diff | grep`) are inside `mod tests` (`Session::batch`,
|
||||
`symbol_names`, `outcomes`, and the shutdown test's `sender.send(...)`)
|
||||
— allowed.
|
||||
- New free functions and the new `Server` methods all carry one-line-plus
|
||||
doc comments explaining what/why, consistent with the surrounding file's
|
||||
density; none of the new items are `pub`, so the strict "public items"
|
||||
rule doesn't even apply, but the dev exceeded it anyway.
|
||||
- `docs/features/cancel-request/README.md`: each of the seven required
|
||||
sections (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log,
|
||||
Review) appears **exactly once** (checked with `grep -n "^## "`); one
|
||||
extra explanatory section between Goal and Assumptions is additional,
|
||||
not a duplicate, and the template doesn't forbid it.
|
||||
- `TODO.md`: the §9b item's original text
|
||||
("**`$/cancelRequest`** — the loop handles requests sequentially and
|
||||
ignores cancellation; at minimum answer already-cancelled queued
|
||||
requests with `RequestCancelled`.") is byte-for-byte intact; only the
|
||||
checkbox flipped and a `→`-prefixed summary line was appended below it,
|
||||
which is the same pattern used by the 9 other completed items already
|
||||
in the file (`grep -c` confirms 10 occurrences total including this
|
||||
one) — not a one-off deviation.
|
||||
- `docs/features/lucisv-server/README.md` was also touched by this
|
||||
change. That file is the umbrella index every feature registers itself
|
||||
in (the method-dispatch table and the Status/TODO checklist both list
|
||||
every other feature the same way), so this is the expected cross-file
|
||||
touch the Handshakes section describes, not scope creep.
|
||||
|
||||
**Tests added this round (4 unit + 1 e2e assertion, all in the files
|
||||
already under review, no new files):**
|
||||
`is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`,
|
||||
`burst_collects_everything_already_queued_in_arrival_order`,
|
||||
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`,
|
||||
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
|
||||
(all in `crates/lucisv_server/src/server.rs`), plus a `message`-field
|
||||
assertion added to
|
||||
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each` in
|
||||
`crates/lucisv_server/tests/e2e.rs`. `lucisv_server` unit count moved from
|
||||
702 to 706; e2e stayed at 38 (one test grew an assertion, none added).
|
||||
|
||||
**Fixes made:** none beyond the test additions above — no corruption, no
|
||||
mishandled message, no dropped request found anywhere in the diff.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
plus two extra e2e passes (flood test green in every run I and QA made —
|
||||
twelve consecutive between us), clean. The dev's deviation from my brief
|
||||
was the right kind: my burst-drain design assumed a queue that lsp-server's
|
||||
rendezvous channels do not provide, the dev proved that over a real pipe
|
||||
(0/5 honoured) before changing anything, and the forwarder it added is
|
||||
the minimal honest fix — one thread, no shared state, stopping at
|
||||
shutdown for a reason it can cite from lsp-server's own source. QA then
|
||||
re-derived the shutdown hand-off from the vendored code rather than the
|
||||
work log, which is exactly the adversarial re-check this workflow exists
|
||||
for, and closed the four real gaps (the shutdown-shaped notification,
|
||||
bare `burst` coverage, the forwarder hand-off under a real Connection,
|
||||
and the server-id-namespace cancel).
|
||||
|
||||
The stateless cancelled-set design — a cancel matters only beside its
|
||||
request in one burst, everything else dropped on sight — is the reason
|
||||
this feature cannot leak or misfire across sessions, and shutdown
|
||||
sitting before the cancel check closes the one hole a hostile client
|
||||
could poke. On the flood test's `honoured > 0` assertion: QA is right
|
||||
that a pathological scheduler could in principle defeat it and right not
|
||||
to weaken it; the property is the point of the test, the risk is
|
||||
unreproduced in twelve runs, and if CI ever trips it the QA log already
|
||||
contains the analysis. This completes §9b. Accepted as shipped.
|
||||
@@ -0,0 +1,290 @@
|
||||
# change-debounce
|
||||
|
||||
## Goal
|
||||
|
||||
Stop paying a full reanalysis for every keystroke. Before this round each
|
||||
`textDocument/didChange` notification ran `set_document` immediately — lex,
|
||||
parse, `analyze`, `resolve_external`, lint, publish — so a burst of ten
|
||||
keystrokes cost ten of everything and nine of those answers were thrown away
|
||||
before anyone could read them. A `didChange` now only records the buffer's new
|
||||
text as *dirty*; the analysis runs at the first moment anything actually needs
|
||||
it: the next request, the next non-`didChange` notification, or a 150 ms
|
||||
quiet-period timer in the message loop. The buffer's **text** is still exactly
|
||||
current after every notification — only the analysis of it is deferred — so
|
||||
nothing that reads `didChange` results out of order can see a stale buffer.
|
||||
On a 10 000-line file one deferred keystroke saves 31 ms of work
|
||||
(`docs/perf/README.md`); a ten-keystroke burst saves nine of them.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A client sends a burst, not a single change.** Typing produces
|
||||
notifications faster than 150 ms apart; the debounce only pays off while
|
||||
that is true, and costs at most 150 ms of latency when it is not.
|
||||
- **150 ms is short enough not to be felt and long enough to coalesce a
|
||||
burst.** It is the same order as the debounce every mainstream language
|
||||
server uses. It is a constant (`CHANGE_DEBOUNCE` in `server.rs`), not a
|
||||
setting: a knob here would be one more thing to get wrong, and no user has
|
||||
asked for one (`TODO.md` §7, "no option explosion").
|
||||
- **Diagnostics are the one answer nobody requests.** A pushing client never
|
||||
asks for them, so waiting for "the next request" alone would leave a file
|
||||
undiagnosed indefinitely for a user who types and then stops. That is the
|
||||
whole reason the timer exists, rather than flushing only on demand.
|
||||
- **A flush is cheap to trigger from anywhere.** `flush_dirty` returns
|
||||
immediately when nothing is dirty, so the calls at the top of `request` and
|
||||
`notification` cost a `Vec::is_empty` on every message.
|
||||
- **Order within a burst does not matter, order across buffers does.** Dirty
|
||||
buffers are flushed oldest-first (`mark_dirty` replaces an entry in place
|
||||
rather than moving it to the back), so the sequence of `publish` calls a
|
||||
client sees for two edited files is the order they were first edited in.
|
||||
- **Losing an unanalyzed change with its buffer is correct.** `didClose`
|
||||
drops the buffer's pending text: there is nothing left to flush it into,
|
||||
and the client is not looking at the file any more. The drop happens at the
|
||||
*top* of `notification`, ahead of the universal flush — doing it in the
|
||||
`didClose` arm is too late, because the flush has already run by then (QA,
|
||||
CD-1). Closing one buffer says nothing about the others, so every other
|
||||
dirty buffer flushes on that same notification exactly as before.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Amends `docs/features/incremental-sync/README.md`'s pinned invariant.**
|
||||
That round promised "one `didChange` = one `set_document` = one generation
|
||||
bump, however many ranges". The promise is now: **one *flush* is one
|
||||
`set_document`, one generation bump and one `publish` per dirty buffer** —
|
||||
however many ranges *and however many notifications* were coalesced into it.
|
||||
Everything the old promise protected still holds: the generation counter
|
||||
(which is `docs/features/pull-diagnostics/README.md`'s whole `resultId`)
|
||||
never moves twice for work that happened once, and never fails to move for
|
||||
a buffer whose text changed. `incremental-sync`'s own test,
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`, still passes
|
||||
unchanged, because the test helper flushes after each notification — which
|
||||
is exactly the quiet-period timer firing.
|
||||
- **Observable consequence, pinned in `crates/lucisv_server/tests/e2e.rs`**
|
||||
(`incremental_changes_are_advertised_and_applied_over_the_wire`):
|
||||
**intermediate diagnostics states are no longer published**. Two changes
|
||||
arriving back to back — the first breaking a line, the second finishing it
|
||||
— used to produce three publishes (open, broken, fixed) and now produce two
|
||||
(open, composed). Every state that *is* published is a state the buffer
|
||||
really passed through; there are simply fewer of them. That test asserted
|
||||
the old count and now asserts the new one, with the reason written beside
|
||||
it.
|
||||
- **Consumes `sync::apply_changes` unchanged.** Ranged changes are composed
|
||||
against the newest text the server holds, which while a buffer is dirty is
|
||||
the *pending* text, not the last analyzed one. `Server::notification` looks
|
||||
in `dirty` before `workspace.document`. Nothing in `sync.rs` moved.
|
||||
- **Consumes `lsp_server`'s queue as a `std::sync::mpsc` receiver.** The
|
||||
timer is `Receiver::recv_timeout` on the queue `cancel-request` already
|
||||
introduced (`docs/features/cancel-request/README.md`); no thread and no
|
||||
timer object was added. A `Disconnected` receiver ends the loop exactly as
|
||||
the old `while let Ok(..)` did.
|
||||
- **Promises every request still sees the client's own changes.** The flush
|
||||
at the top of `Server::request` runs before dispatch, so a request answered
|
||||
after a `didChange` is answered from that change's analysis — the order
|
||||
contract the loop always had. The large-file fast path is behind that
|
||||
flush, not in front of it.
|
||||
- **No protocol change, no settings change, no index change.** The
|
||||
capabilities advertised at `initialize` are byte-identical.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `dirty: Vec<(Uri, String)>` on `Server` — newest text per buffer, in
|
||||
first-dirtied order.
|
||||
- [x] `mark_dirty` replaces in place, so a burst does not reorder buffers.
|
||||
- [x] `flush_dirty` — one `set_document` + one `publish` per dirty buffer.
|
||||
- [x] `didChange` composes ranges against the pending text when there is one.
|
||||
- [x] Flush on every request, before dispatch.
|
||||
- [x] Flush on every notification that is not a `didChange`.
|
||||
- [x] `CHANGE_DEBOUNCE` (150 ms) quiet-period flush in `run`, via
|
||||
`recv_timeout`, only while something is dirty.
|
||||
- [x] `didClose` drops the buffer's pending change — before the flush, so the
|
||||
drop is real (QA, CD-1), pinned by
|
||||
`closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`.
|
||||
- [x] Test: a burst is one reparse
|
||||
(`a_burst_of_changes_coalesces_into_one_reparse`).
|
||||
- [x] Server tests drive one notification at a time, so the test helper
|
||||
`change()` flushes — documented there as the timer firing.
|
||||
- [x] e2e: the publish count and the reason for it.
|
||||
- [ ] Not done: a flush for a *long* burst that never pauses (a paste-and-hold
|
||||
or a client replaying a file's history sends changes closer together
|
||||
than 150 ms forever). Today such a burst is analyzed when it ends or
|
||||
when the next request arrives. A "flush after N pending changes"
|
||||
backstop is the obvious answer if anyone ever reports it; it is not
|
||||
written because no client behaves that way and an untested backstop is
|
||||
worse than none.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev.** Implemented as part of the LSP performance round
|
||||
(plan: "Improve LSP performance + hover accuracy", part A1).
|
||||
|
||||
- The deferral is a `Vec`, not a `HashMap`: it holds one entry per *dirty*
|
||||
buffer, which is one in practice and two while a user alt-tabs. A linear
|
||||
scan of that is cheaper than hashing a `Uri`, and the `Vec` gives the flush
|
||||
order for free.
|
||||
- Deferred **analysis only, never text**. The alternative — deferring
|
||||
`apply_changes` too and keeping a queue of unapplied changes — was
|
||||
rejected: every reader of `Document::text` would then need to know about
|
||||
the queue, and the ones that forgot would be silently wrong. Composing the
|
||||
text eagerly keeps the pending state to exactly one `String` that only
|
||||
`didChange` and `flush_dirty` know about.
|
||||
- The flush points were chosen to be exhaustive rather than clever: *every*
|
||||
request and *every* notification except the one being deferred. Anything
|
||||
that needs analysis is downstream of one of those two, so there is no
|
||||
handler that has to remember to flush for itself.
|
||||
- `run` only arms the timeout while something is dirty, so an idle server
|
||||
still blocks in `recv()` and wakes for nothing.
|
||||
- The server unit tests drive notifications one at a time through a helper
|
||||
rather than through the loop, so no burst ever forms and nothing would
|
||||
flush them; the helper flushes explicitly, which is the timer's behavior.
|
||||
Three tests that hand-rolled a `didChange` notification were moved onto
|
||||
that helper.
|
||||
|
||||
**2026-08-28 — dev (QA fix).**
|
||||
|
||||
- **CD-1 — fixed.** The `didClose` arm's `dirty.retain` was dead code: the
|
||||
universal flush at the top of `notification` had already drained `dirty`
|
||||
through `std::mem::take` by the time the arm ran, so a buffer closed
|
||||
mid-edit paid a full `Document::new` and published its real diagnostics one
|
||||
line before the close cleared them. The retain moved to the top of
|
||||
`notification`, *ahead* of the flush, guarded on the method name; the arm's
|
||||
comment now says where the drop happened instead of pretending to do it.
|
||||
- The uri has to be read without consuming the notification, since
|
||||
`extract` takes it by value and the arm below still needs it. That is a
|
||||
four-line `closing_uri` beside `extract`, deserializing a clone of the
|
||||
params — a `didClose`'s params are a single uri, so the clone is not
|
||||
worth avoiding with a peek into the raw `Value`. `None` (params that do
|
||||
not parse) drops nothing, which is exactly what the arm below already
|
||||
does with the same params.
|
||||
- The "flush on every notification but `didChange`" rule is unchanged: the
|
||||
flush still runs for `didClose`, and every *other* dirty buffer still
|
||||
goes through it. What changed is only that the closing buffer is no
|
||||
longer in `dirty` when it does.
|
||||
- Pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`
|
||||
(`server.rs`): two buffers dirtied with text that would diagnose, one
|
||||
closed with no request in between; the generation bumps exactly once (the
|
||||
buffer still open), the closed buffer gets exactly one publish and it is
|
||||
the clearing one, and the other buffer's pending edit is published as
|
||||
usual. Verified the test fails on the pre-fix code — `left: 5, right: 4`
|
||||
on the generation assertion — before keeping it.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** Gates run and green: `cargo fmt --check`,
|
||||
`cargo clippy --all-targets --workspace -- -D warnings`, `cargo test
|
||||
--workspace` (0 failed everywhere; `lucisv_server`: 1179 passed, 19 ignored
|
||||
perf tests), `cargo test -p vlog_formatter` (114 passed). All findings below
|
||||
were reproduced with temporary `#[test]`s added to `server.rs`, run, and then
|
||||
removed once confirmed — none are left in the tree.
|
||||
|
||||
- **Finding CD-1 (medium — contradicts a checked-off invariant, wastes work,
|
||||
does not corrupt anything).** `didClose` does **not** actually drop a
|
||||
buffer's pending dirty change before analyzing it. `Server::notification`
|
||||
(`server.rs:1247`) flushes unconditionally for any non-`didChange` method
|
||||
(`server.rs:1253`, `if method != DidChangeTextDocument::METHOD { self
|
||||
.flush_dirty(); }`) — and `didClose` is such a method. That flush runs
|
||||
*before* the `match` statement even reaches the `DidCloseTextDocument::
|
||||
METHOD` arm (`server.rs:1407`), so by the time `self.dirty.retain(|(pending,
|
||||
_)| *pending != uri)` executes (`server.rs:1413`), `flush_dirty` has already
|
||||
drained `self.dirty` via `std::mem::take` — the retain is a no-op in the
|
||||
normal flow. Net effect: closing a buffer that was mid-edit costs one full,
|
||||
wasted reparse + `publish` of the real (about-to-be-discarded) diagnostics,
|
||||
immediately followed by the close handler's own `send_diagnostics(uri,
|
||||
Vec::new())` clearing them — **two** publishes instead of the zero extra
|
||||
ones the design claims. This directly contradicts both the checked-off
|
||||
status-line "`[x]` `didClose` drops the buffer's pending change" and the
|
||||
code comment beside the (dead) retain: "there is nothing left to flush it
|
||||
into" — there is, and it does get flushed.
|
||||
- Repro (temporary test, `server.rs`, removed after confirming): open a
|
||||
clean buffer (`module m;\nendmodule\n`), drain the open publish, note
|
||||
`generation`, send one `didChange` to `module m;\n wire ;\nendmodule\n`
|
||||
(introduces a parse error, buffer stays dirty — `generation` provably
|
||||
unchanged, `dirty` non-empty), then send `didClose` with **no** request
|
||||
in between (`session.notify`, which calls `Server::notification`
|
||||
directly, exactly the production path — no manual flush helper
|
||||
involved). Observed: `generation` bumps by exactly one during the
|
||||
`didClose` call (`2` → `3`), and `session.published()` returns **2**
|
||||
messages: one carrying the real parse-error diagnostic
|
||||
(`"expected identifier (found \";\")"`), then one with `diagnostics: []`.
|
||||
- Not a data-corruption bug — the client ends up with the correct final
|
||||
state (empty diagnostics for a closed file) — but it is a real,
|
||||
reproducible functional gap in exactly the case the debounce is supposed
|
||||
to help most: a user who edits and then immediately closes a buffer pays
|
||||
the full analysis cost the feature exists to avoid, silently. Left
|
||||
unfixed (not small/unambiguous — the right fix wants a decision about
|
||||
whether the top-of-`notification` flush should special-case `didClose`,
|
||||
or whether `didClose` should remove its own `dirty` entry *before* that
|
||||
flush runs, which touches the "flush on every notification but
|
||||
`didChange`" rule this round explicitly checked off).
|
||||
|
||||
- **Attack angles from the brief, checked and clean:**
|
||||
- *An un-flushed edge, generally.* Every request and every non-`didChange`
|
||||
notification flushes at its own top (`server.rs:1253` for notifications,
|
||||
the equivalent at the top of `request`), so the only genuinely
|
||||
un-flushed state is "nothing has asked for analysis yet" — which is
|
||||
exactly what the quiet-period timer exists to bound at 150 ms, and the
|
||||
documented, un-checked TODO item (a burst that never pauses) is real but
|
||||
already honestly disclosed, not silently missing.
|
||||
- *`didChange` on a file the client never opened.* `mark_dirty` does not
|
||||
require a prior `didOpen`, and neither did the pre-debounce
|
||||
`set_document` call it replaces — `flush_dirty`'s `set_document` creates
|
||||
the buffer exactly as before. No new behavior here.
|
||||
- *`didChange` racing `didSave`.* `didSave` is not `didChange`, so it
|
||||
flushes first (`server.rs:1253`) — a save's reindex always sees the
|
||||
latest edited text analyzed, never a stale buffer racing a fresh disk
|
||||
scan.
|
||||
- *Version-number ordering.* The server does not track LSP version numbers
|
||||
at all (`publishDiagnostics`'s own `version` field is hard-coded `None`
|
||||
at `server.rs:1848`, unchanged by this round) — nothing new to get out of
|
||||
order.
|
||||
- *Pending vs. analyzed text observed inconsistent by a request.* Cannot
|
||||
happen: `request` flushes before dispatch (`server.rs`'s `fn request`),
|
||||
so a request is always answered from the analysis of whatever is
|
||||
currently held, dirty or not.
|
||||
- *The `e2e.rs` publish-count change (3 → 2).* Confirmed the buffer
|
||||
genuinely passed through both published states and no diagnostic was
|
||||
lost: traced `incremental_changes_are_advertised_and_applied_over_the_wire`
|
||||
— the two `didChange` notifications and the `textDocument/formatting`
|
||||
request all arrive in one write to the mock transport, so the request's
|
||||
own top-of-`request` flush (or the burst's internal ordering) coalesces
|
||||
both notifications into the one flush that produces publish #2; publish
|
||||
#1 is the clean `didOpen`. The removed middle publish (the transiently
|
||||
*broken* half-edited state) was never a state a real, unhurried client
|
||||
would see anyway — it is the debounce's whole point.
|
||||
- *`a_burst_of_changes_coalesces_into_one_reparse`.* Re-derived by hand:
|
||||
`generation` provably does not move across the two-notification burst,
|
||||
then moves by exactly one at the first request after it, and `dirty` is
|
||||
empty afterward — matches the claimed semantics exactly.
|
||||
|
||||
- **Perf claims (A1's "before/after" in `docs/perf/README.md`).** Arithmetic
|
||||
over already-measured numbers, not a separate measurement — reviewed there,
|
||||
no finding.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted. Gates re-run independently of both agents:
|
||||
`cargo fmt --check` clean, `cargo clippy --all-targets --workspace -D
|
||||
warnings` silent, `cargo test --workspace` green.
|
||||
|
||||
The shape is right. Deferring analysis while applying text immediately is the
|
||||
standard split, and flushing before every request and before every
|
||||
non-`didChange` notification means no handler ever reads a stale buffer —
|
||||
today's correctness guarantee is preserved exactly, and only keystroke-storm
|
||||
reparses are coalesced. The quiet-period timer in `run()` matters as much as
|
||||
the coalescing: diagnostics are the one answer a client never asks for, so a
|
||||
burst that ends in silence still gets drawn.
|
||||
|
||||
QA's CD-1 was a real finding and correctly diagnosed: the universal flush ran
|
||||
*before* the `didClose` arm, so the arm's `retain` was dead and a buffer
|
||||
closed mid-burst paid a full `Document::new` and published diagnostics for a
|
||||
file the user had stopped looking at, only to clear them a line later. The
|
||||
fix drops the pending text ahead of the flush rather than special-casing the
|
||||
flush, which keeps "every other dirty buffer still flushes" true by
|
||||
construction. The dev verified the pinning test fails on pre-fix code before
|
||||
keeping it; that is the right standard.
|
||||
|
||||
The one honest cost is recorded in `docs/perf/README.md` and is not hidden: a
|
||||
keystroke with *nothing* following it now publishes at 164 ms rather than one
|
||||
flush, because it waits out the 150 ms quiet period. Any request flushes
|
||||
early, so a real editor sees 4.35 ms / 37.6 ms instead — but the regression
|
||||
is real for a client that asks for nothing, and the number is written down
|
||||
rather than argued away.
|
||||
|
||||
@@ -5,11 +5,18 @@
|
||||
Automate the checks and the release. Every push to master runs the three
|
||||
checks CLAUDE.md requires (fmt, clippy, test) on Gitea Actions; every tag
|
||||
`vX.Y.Z` builds the full cross-platform artifact set (Apple Silicon +
|
||||
x86_64 macOS, static-musl and RHEL 8-compatible Linux, Windows — both
|
||||
binaries each — plus the `.vsix` and `SHA256SUMS`) and publishes a Gitea
|
||||
release whose notes are the CHANGELOG section for that version. The point
|
||||
is that a release is one `git tag` + `git push` and cannot ship without
|
||||
green checks, matching versions, and written notes.
|
||||
x86_64 macOS, static-musl x86-64/ARM64 and RHEL 8-compatible Linux,
|
||||
Windows — both binaries each — plus the seven `.vsix` packages and
|
||||
`SHA256SUMS`) and publishes a Gitea release whose notes are the CHANGELOG
|
||||
section for that version. **Published assets are the seven `.vsix` packages
|
||||
only** (since 2026-08-27, owner decision): the extension is the product a
|
||||
release delivers, every package is checked by name before publishing, and
|
||||
the loose binaries — still built and audited, since the packages embed
|
||||
them — stay unpublished; a standalone binary is
|
||||
`cargo build --release` for whoever wants one
|
||||
(docs/features/editor-platform-vsix). The point is that a release is one
|
||||
`git tag` + `git push` and cannot ship without green checks, matching
|
||||
versions, written notes, and all seven packages.
|
||||
|
||||
## Assumptions
|
||||
|
||||
@@ -38,8 +45,20 @@ green checks, matching versions, and written notes.
|
||||
## Handshakes
|
||||
|
||||
- Consumes `tools/release.sh --cross` unchanged: artifact names
|
||||
(`lucisv[-server]-<version>-<triple>[.exe]`, `lucisv-<version>.vsix`,
|
||||
(`lucisv[-server]-<version>-<triple>[.exe]`,
|
||||
`lucisv-<version>[-<vsce-target>].vsix`, `lucisv-<version>-all.vsix`,
|
||||
`SHA256SUMS`) and the version-from-binary convention.
|
||||
`tools/prune_release_assets.sh` depends on those `.vsix` names exactly —
|
||||
it checks all **seven** by name and filters `SHA256SUMS` down to `.vsix`
|
||||
lines before publishing. A package added, renamed or dropped in
|
||||
`release.sh` must be reflected in that script's suffix list, or the
|
||||
release fails naming the file it could not find
|
||||
(docs/features/editor-platform-vsix).
|
||||
- The workflow's steps are one-liners calling `tools/` scripts, so every
|
||||
release step is runnable by hand on a developer machine and testable
|
||||
without pushing a tag. `prune_release_assets.sh` in particular is safe to
|
||||
re-run: a second run over an already-pruned directory finds the same seven
|
||||
packages and verifies them again.
|
||||
- Consumes `CHANGELOG.md`'s heading convention: `## <version> — <date>`;
|
||||
`tools/release_notes.sh` keys on the second word of `## ` headings.
|
||||
- `tools/publish_release.sh` expects the GitHub-compatible CI environment
|
||||
@@ -68,6 +87,18 @@ green checks, matching versions, and written notes.
|
||||
automates what RELEASING.md documented as manual; Linux/Windows binaries
|
||||
remain audited, never executed (no such machine in the loop, and no
|
||||
container runtime on the runner).
|
||||
- [x] Publish `.vsix` packages only (2026-08-27): after the audit, the
|
||||
workflow asserts all seven packages exist by name, filters `SHA256SUMS`
|
||||
down to them (keeping the audited hashes), re-verifies it, and deletes
|
||||
the loose binaries from `dist/` so `publish_release.sh` attaches only
|
||||
the packages. Prune logic tested locally against a real `--cross`
|
||||
`dist/`, with a negative control (one package removed → the step fails
|
||||
naming it).
|
||||
- [x] That logic lives in `tools/prune_release_assets.sh` (2026-08-27), not
|
||||
inline in the workflow: every release step is a one-line call into
|
||||
`tools/`, so it can be run and negative-controlled on a developer machine
|
||||
without pushing a tag. The seventh (all-platforms) package joined the
|
||||
must-exist list at the same time.
|
||||
- [ ] A second runner on a non-macOS host, if native-built (rather than
|
||||
cross-built) Linux artifacts are ever wanted.
|
||||
|
||||
@@ -92,6 +123,69 @@ green checks, matching versions, and written notes.
|
||||
rejected: no container runtime exists on the runner Mac, and installing
|
||||
a VM stack is an owner decision, not a CI increment.
|
||||
|
||||
- 2026-08-27 — lead. Owner decision: the release page ships the six
|
||||
`.vsix` packages only (each platform package a must, checked by name;
|
||||
the universal fallback included), no loose binaries — the platform
|
||||
packages embed them, and an experienced user builds standalone binaries
|
||||
with cargo. Implemented as a "Keep only the extension packages" step in
|
||||
`release.yml` between the artifact audit and the notes extraction: the
|
||||
audit still sees (and gates on) the loose binaries, then the step
|
||||
filters `SHA256SUMS` to `.vsix` lines — the published hashes are the
|
||||
audited ones, not recomputed — deletes everything else from `dist/`,
|
||||
and re-runs `shasum -c`. `publish_release.sh` is untouched: it attaches
|
||||
whatever `dist/` holds. Tested against the real 0.10.0 `--cross` dist
|
||||
(six packages verify, correct survivors) and negative-controlled (one
|
||||
package removed → fails naming `lucisv-0.10.0-linux-arm64.vsix`). Docs
|
||||
trued up: RELEASING.md (publishing + CI sections), top-level README
|
||||
(Editor setup and Install-and-releases sections now lead with the
|
||||
platform package and say binaries are build-your-own), and this README's
|
||||
Goal/Handshakes/Status.
|
||||
|
||||
- 2026-08-27 — dev (all-platforms package round). Two changes here, both
|
||||
in service of the seventh `.vsix` (`docs/features/editor-platform-vsix`):
|
||||
|
||||
- **The inline "Keep only the extension packages" step became
|
||||
`tools/prune_release_assets.sh <dist-dir> <version>`.** Same logic,
|
||||
same order — check every package by name, filter `SHA256SUMS` to its
|
||||
`.vsix` lines rather than recompute, delete everything else, re-verify
|
||||
with `shasum -c` — now in a script with a usage header like its
|
||||
siblings, so `release.yml` is back to one-line steps and the step is
|
||||
testable without a tag. It grew the `-all` suffix and argument
|
||||
validation (`[ $# -eq 2 ]`, missing dir, missing `SHA256SUMS` → exit 2,
|
||||
matching `publish_release.sh`'s convention); a missing package is still
|
||||
exit 1 naming the file.
|
||||
- **`release.yml`**: the step body is now
|
||||
`tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"`, and the
|
||||
header comment says seven packages. Nothing else in the workflow moved;
|
||||
the prune still sits between the artifact audit and the notes
|
||||
extraction, so the audit keeps gating on the loose binaries before they
|
||||
are deleted.
|
||||
|
||||
**Verified**, from the real repo path, against the real `dist/` from a
|
||||
`tools/release.sh --cross` run of 0.10.1 (copies only — `dist/` itself was
|
||||
left intact for the lead, since the script deletes files):
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `bash -n tools/prune_release_assets.sh` | clean |
|
||||
| positive: a 20-file `dist/` copy | exit 0, 8 survivors (7 `.vsix` + `SHA256SUMS`), `SHA256SUMS` down to 7 lines, all 7 verify `OK` |
|
||||
| negative: `lucisv-0.10.1-all.vsix` removed | exit 1, `missing lucisv-0.10.1-all.vsix`, **and nothing deleted** — all 19 remaining files still there, because the name check runs before any destructive step |
|
||||
| negative: wrong version argument (`0.10.0`) | exit 1, `missing lucisv-0.10.0.vsix`, nothing deleted |
|
||||
| negative: one argument / missing dir / dir without `SHA256SUMS` | exit 2 each, with the usage or the specific reason |
|
||||
| re-run over an already-pruned directory | exit 0, same 7 packages verify again — a CI job re-run is safe |
|
||||
| `python3 -c yaml.safe_load` on `release.yml` | parses; the six step names unchanged |
|
||||
|
||||
The negative controls were run on copies in the session scratchpad, but
|
||||
the script itself and every `release.sh` run were driven from
|
||||
`/Users/guoliangchen/repo/verilogrustformatter` — `vsce` collects zero
|
||||
files under the scratchpad's UUID path
|
||||
(`docs/features/editor-packaging` QA Finding 2).
|
||||
|
||||
Not verified: the workflow has not been run on the Gitea runner in this
|
||||
round — no tag was pushed (and pushing one is the lead's call). The step
|
||||
is a one-line invocation of a script proven by hand on the same machine
|
||||
the runner is, which is as close as this gets without cutting a release.
|
||||
|
||||
## QA log
|
||||
|
||||
_(no QA round — infrastructure, verified by the live v0.7.1 run; see work log)_
|
||||
|
||||
@@ -48,10 +48,14 @@ the deviations are stated where they happen.
|
||||
`Resolution::InheritedCandidate { base, paths }` — `base` is the extends
|
||||
path as written (`uvm_component`, `pkg::base`), `paths` are the import
|
||||
paths the lexical walk collected on the way out (both could supply the
|
||||
name; recording both is the honest answer). Nothing chases `base`, in
|
||||
name; recording both is the honest answer), **plus, since 2026-08-26, the
|
||||
use's own name last** (`docs/features/overlay-promotion/README.md`), so a
|
||||
cross-file `interface` or class written as the type of a member of a UVM
|
||||
class reaches the workspace's unit table. Nothing chases `base`, in
|
||||
this file or out of it: a future hover/index round can, without this
|
||||
crate pretending it did inheritance resolution. The fallback applies to
|
||||
*member* uses only — a **unit-name** miss (a `p::x` head, an
|
||||
crate pretending it did inheritance resolution. The overlay may now answer
|
||||
such a reference from `paths` — it never rewrites it, and `base` stays.
|
||||
The fallback applies to *member* uses only — a **unit-name** miss (a `p::x` head, an
|
||||
`extends`/`implements` base) stays `ExternalCandidate` even inside an
|
||||
extending class, because a base class supplies members, not package or
|
||||
class names (QA-found, lead-ruled; pinned by
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,592 @@
|
||||
# code-lens
|
||||
|
||||
## Goal
|
||||
|
||||
`textDocument/codeLens` puts one line of true, computed information above
|
||||
every module and interface declaration in the open buffer: **"N
|
||||
instantiations"** — how many times the whole workspace instantiates that
|
||||
module — with "1 instantiation" and "no instantiations" spelled the way a
|
||||
person would. It is the single most Verilog-shaped thing a lens can say: a
|
||||
module's fan-in is the number an RTL engineer actually wants when they open a
|
||||
file, and until now it took opening the call hierarchy to learn it. Clicking a
|
||||
lens answers with every instantiation site, and — for a client that advertised
|
||||
`window/showDocument` — jumps to the first of them. The count is not a second
|
||||
census: it is computed by the very walk `callHierarchy/incomingCalls` is
|
||||
computed by, so the lens and the hierarchy view can never disagree (TODO.md
|
||||
§9c).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The population is `incomingCalls`'s population, and nothing else.** N is
|
||||
the number of instantiation *sites* — the sum of every `fromRanges` entry
|
||||
`callHierarchy/incomingCalls` would list for that module, not the number of
|
||||
instantiating modules. A module instantiated twice inside one `top` reads
|
||||
"2 instantiations", because that is what a user counting instances means.
|
||||
`the_count_is_exactly_what_incoming_calls_would_list` asserts the equality
|
||||
directly rather than restating the arithmetic.
|
||||
- **An instantiation at file scope is not counted**, because it has no
|
||||
enclosing module to be a caller. That is inherited, not decided here: it is
|
||||
the rule `hierarchy::callers_in` already applied, and the whole point of
|
||||
reusing the census is that this feature does not get to have its own
|
||||
opinion. Such a file is illegal SystemVerilog anyway and only reachable
|
||||
through the tolerant parser.
|
||||
- **The census is by name.** Two modules named `fifo` in one workspace get the
|
||||
same count on both their lenses, and clicking either shows every site of
|
||||
either. Same limitation `callHierarchy/incomingCalls` has, for the same
|
||||
reason: an instantiation names a module, and nothing in the source says
|
||||
which of two same-named declarations it meant.
|
||||
- **The lens's range is the declaration's own name span.** Clients draw a lens
|
||||
on the line *above* `range.start`, so the name span puts it directly over
|
||||
the header and nowhere else. A declaration whose name span is empty — what
|
||||
the tolerant parser produces for `module ;` — gets no lens: there is no line
|
||||
to sit on, and an invented one would decorate the wrong code.
|
||||
- **An interface is a module declaration.** `interface bus; ... endinterface`
|
||||
parses to the same `ast::Module` node with `kw == "interface"`, so it is
|
||||
reached by `instantiations::declarations` and instantiated through the same
|
||||
`ItemKind::Instantiation`. No branch was written for it; a test pins that it
|
||||
works.
|
||||
- **`resolveProvider: false`, and every lens is complete.** Title, command and
|
||||
arguments are all computed up front, matching what completion, inlay hints
|
||||
and document links do in this server. The count is the expensive part and it
|
||||
is exactly what a resolve would have to compute, so a two-stage protocol
|
||||
would buy nothing.
|
||||
- **A module with no instantiations gets a display-only lens** — a `Command`
|
||||
whose `command` is the empty string, which is what rust-analyzer ships for
|
||||
the same case and what clients render as plain text. There is nothing to
|
||||
open; a click that led to an empty list would be worse than no click. It
|
||||
also carries no `arguments`.
|
||||
- **`window/showDocument` shows only the first site.** LSP has no
|
||||
server-initiated "peek these seven places" — that is VS Code's
|
||||
`editor.action.showReferences`, a *client-side* command, and this repo's
|
||||
extension declares none (and this round did not touch `editors/`). The
|
||||
honest portable behaviour is: the command's result is the full list of
|
||||
`Location`s, for any caller that wants it, and the push opens the first one
|
||||
for a client that can be pushed to. A client without the capability still
|
||||
gets the list.
|
||||
- **`workspace/codeLens/refresh` is sent from `reindex()` only.** Not at
|
||||
startup: no buffer is open there, so there are no stale lenses to
|
||||
invalidate. Not on a keystroke either — a `didChange` cannot change any
|
||||
count, since the census is over instantiations in *other* files and a client
|
||||
re-requests lenses for the buffer it just edited anyway.
|
||||
- ~~**The count is computed against `Workspace::sources()`**, which reads every
|
||||
in-scope file from disk with open buffers overriding it. So an unsaved
|
||||
instantiation typed into another open buffer *is* counted, and a file
|
||||
changed on disk that no watcher reported is counted as of this request.~~
|
||||
**Superseded (incremental-index, 2026-08-27)** — see the assumption above.
|
||||
- ~~**The cost is one workspace walk per request, not one per module.**
|
||||
`hierarchy::callers_of_each` takes a batch precisely because `sources()`
|
||||
re-reads the whole file set: measured over the 860-file corpus, a
|
||||
three-module file costs 133 ms against 93 ms for a single name (debug build)
|
||||
— amortized, not tripled. The absolute number is the honest cost of having
|
||||
no instantiation-edge table in the index; see Status / TODO.~~
|
||||
**Superseded (incremental-index, 2026-08-27): the cost is a lookup.** The
|
||||
count comes from the index's instantiation-edge table, and the only I/O left
|
||||
is reading the handful of files that really do instantiate one of the names,
|
||||
to turn recorded byte spans into ranges — 0.26 ms for the same three-module
|
||||
file over the same corpus. The batch stays the primitive for the same
|
||||
reason at a smaller scale: one file instantiating three of the names is read
|
||||
once.
|
||||
- **The count is as of the index, which is as of its last build or update**
|
||||
(incremental-index, 2026-08-27) — superseding the assumption below that the
|
||||
count is computed against `Workspace::sources()` per request. A save, or any
|
||||
other rescan trigger, folds every open buffer in and makes an edit count; a
|
||||
keystroke alone no longer does. The trade and the alternatives considered are
|
||||
in `docs/features/incremental-index/README.md`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Request to `vlog_semantic` — an instantiation-edge table in the index
|
||||
|
||||
**Delivered (incremental-index, 2026-08-27).** `WorkspaceIndex::instantiations_of`
|
||||
exists with the shape proposed below — plus the owning declaration's name and
|
||||
full extent, which is what stopped `callers_of_each` re-parsing the file to
|
||||
find them — and `hierarchy::callers_of_each` is a lookup with its walk-and-parse
|
||||
body deleted. The census policies carried over by construction: the table is
|
||||
built by the same `instantiations::sites` walk the handler used to run, which
|
||||
was lifted into `vlog_semantic` for exactly that reason, and every one of this
|
||||
feature's QA tests passes unchanged. Measured 92 ms → 0.26 ms for a
|
||||
three-module file over the corpus. The original request, kept legible:
|
||||
|
||||
~~Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
|
||||
features now pay the same cost: every `textDocument/codeLens` request and
|
||||
every `callHierarchy/incomingCalls` walks `Workspace::sources()` — a re-read
|
||||
and tolerant re-parse of every in-scope file — because `WorkspaceIndex`
|
||||
records what a file *declares* and never what it *instantiates*. The ask: at
|
||||
index build time (the same rebuild `reindex()` already pays for), record the
|
||||
instantiation edges, e.g.
|
||||
|
||||
```rust
|
||||
/// Every instantiation of `name` across the indexed files:
|
||||
/// (file, instantiating-module name span, instance site span).
|
||||
pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]
|
||||
```
|
||||
|
||||
so `hierarchy::callers_of_each` becomes a lookup and its whole
|
||||
walk-and-parse body is deleted. The census policies (multi-instance
|
||||
statements = one site, textual not elaborated, both `ifdef` arms) must carry
|
||||
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.~~
|
||||
|
||||
|
||||
### `lucisv_server::hierarchy` — **changed, deliberately**
|
||||
|
||||
`incoming` was split so the census has exactly one implementation:
|
||||
|
||||
- **New public** `hierarchy::callers_of_each(ws, names: &[&str]) ->
|
||||
Vec<Vec<CallHierarchyIncomingCall>>` — the same walk, asked about a batch of
|
||||
names, answering one list per name in the order asked. It is now the
|
||||
primitive.
|
||||
- `hierarchy::incoming(ws, item)` is a one-line call into it with a
|
||||
one-element batch. **Its behaviour is unchanged**, empty-name guard
|
||||
included: the guard moved into the batch's per-name filter, where an empty
|
||||
name matches no file rather than every file.
|
||||
- The private `callers_in` now takes an already-parsed file (`&Uri`,
|
||||
`&Positions`, `&[Site]`) instead of a path and text, so one file is parsed
|
||||
once for a whole batch rather than once per name. The `Positions` for a file
|
||||
is now built whenever any name matches, rather than only when a caller was
|
||||
found — a `LineIndex::new` per candidate file, which the batch more than
|
||||
pays back.
|
||||
|
||||
Nothing else in `hierarchy.rs` moved, and its own tests are untouched and
|
||||
green.
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `ClientAbilities` gains **two** fields, both filled in `main.rs`:
|
||||
`code_lens_refresh` (from `workspace.codeLens.refreshSupport`) and
|
||||
`show_document` (from `window.showDocument.support`). Every existing test
|
||||
that builds `ClientAbilities { ..Default::default() }` is unaffected.
|
||||
- `request()` gains a `CodeLensRequest` arm, and its `ExecuteCommand` arm now
|
||||
routes `lucisv.showInstantiations` to `lens::execute` before falling through
|
||||
to `ports::execute`.
|
||||
- New private `show_instantiations(Vec<Location>) -> Result<Value, Failure>`
|
||||
(the answer, plus the optional push) and `refresh_code_lenses()` (the gated
|
||||
server-initiated request).
|
||||
- `reindex()` calls `refresh_code_lenses()` immediately after
|
||||
`end_indexing(bar)` and before the generation bump, the scope warnings and
|
||||
the republishes. Pinned by
|
||||
`the_refresh_rides_after_the_indexing_bar_comes_down`.
|
||||
- `response()`'s doc comment now names four ignorable answers rather than two.
|
||||
Its code is unchanged: the refresh's and the showDocument's ids are never in
|
||||
`applying`, so they fall through the existing lookup.
|
||||
|
||||
### `lucisv_server::main`
|
||||
|
||||
- `capabilities()` gains `code_lens_provider: Some(CodeLensOptions {
|
||||
resolve_provider: Some(false) })`.
|
||||
- `execute_command_provider.commands` is now a new local `commands()` —
|
||||
`ports::commands()` plus `lens::commands()` — rather than `ports::commands()`
|
||||
alone. A lens whose command is not advertised is a lens no client will run,
|
||||
so `every_advertised_command_is_one_the_server_runs` now checks both halves.
|
||||
|
||||
### `state::Workspace`, `vlog_parser`, `vlog_semantic`, `vlog_refactor`
|
||||
|
||||
**Untouched.** No signature moved and nothing was plumbed. The declarations
|
||||
come from `instantiations::declarations`, which already existed for the
|
||||
hierarchy, and the counts from `Workspace::sources()`, which already existed
|
||||
for it too.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
**No extension change**, and none was made. `vscode-languageclient` requests
|
||||
code lenses and renders them with no help from `extension.js`; it advertises
|
||||
`workspace.codeLens.refreshSupport` and `window.showDocument` itself.
|
||||
`smoke.js` sends `capabilities: {}`, so it takes the no-refresh,
|
||||
no-showDocument path — verified by running it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `codeLensProvider` advertised with `resolveProvider: false`
|
||||
- [x] `textDocument/codeLens` dispatched; one lens per module/interface
|
||||
declaration, on the name span, in source order
|
||||
- [x] Count reuses the `incomingCalls` census (`hierarchy::callers_of_each`),
|
||||
with an equality test against `hierarchy::incoming`
|
||||
- [x] Pluralization: "no instantiations" / "1 instantiation" / "N
|
||||
instantiations"
|
||||
- [x] `lucisv.showInstantiations` advertised and dispatched; answers every site
|
||||
as a `Location`; declines arguments it cannot read as `RequestFailed`
|
||||
- [x] `window/showDocument` pushed for the first site, gated on the client
|
||||
capability
|
||||
- [x] `workspace/codeLens/refresh` from `reindex()`, gated on
|
||||
`workspace.codeLens.refreshSupport`, after the progress bar comes down
|
||||
- [x] Unopened buffer → `null`; unnamed declaration → no lens; a buffer that
|
||||
parses to nothing → empty list
|
||||
- [x] Tests: 33 (19 in `lens.rs`, 9 in `server.rs`, 3 in `main.rs`, 2 e2e)
|
||||
- [x] TODO.md §9c checkbox, `docs/features/lucisv-server/README.md` capability
|
||||
table
|
||||
- [ ] **Not done, deliberately:** no second lens kind. A "top module"
|
||||
indicator, a parameter count, a "run this testbench" action are all
|
||||
plausible and none was asked for; one lens kind done well beats three
|
||||
guessed at.
|
||||
- [ ] **Not done, deliberately:** no `codeLens/resolve`. Everything a resolve
|
||||
could defer is the one expensive thing the lens *is*.
|
||||
- [ ] **Not done, deliberately:** no peek-references behaviour. It needs a
|
||||
client-side command declared in `editors/vscode/package.json`, which is
|
||||
out of this round's scope; `window/showDocument` is the portable
|
||||
substitute and reaches Neovim as well.
|
||||
- [ ] **Open, filed here:** the request costs one full `Workspace::sources()`
|
||||
read — 133 ms over the 860-file corpus in a debug build. That is the
|
||||
same cost `callHierarchy/incomingCalls` has always had, but a lens
|
||||
request arrives far more often than a hierarchy question. The real fix
|
||||
is an instantiation-edge table in `WorkspaceIndex`, built once per
|
||||
rescan, which would make both this and `incomingCalls` a lookup. That is
|
||||
a `vlog_semantic` change and belongs in its own round; **request
|
||||
recorded here, not made.** — **done, incremental-index, 2026-08-27.**
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent, §9c
|
||||
|
||||
- **The click-behaviour decision, and why.** The brief left this open with a
|
||||
fallback to display-only. I built the real jump, because reading
|
||||
`hierarchy::incoming` showed the locations were *already there* — every
|
||||
`fromRanges` entry is a site, paired with its file's URI — so
|
||||
`lucisv.showInstantiations` is a flatten and nothing more. The chain the
|
||||
brief worried might be heavy is about fifteen lines: `lens::execute` returns
|
||||
`Vec<Location>`, `Server::show_instantiations` pushes a
|
||||
`window/showDocument` for the first when the client advertised it, and the
|
||||
answer is the list either way. Display-only survives as the honest answer for
|
||||
the **zero** case only, where there is nothing to open — which is exactly
|
||||
where rust-analyzer uses the same empty-command trick. So: real behaviour
|
||||
everywhere it can mean something, display-only where it cannot.
|
||||
- **The arguments are `[module-name]`, not `[uri, name]`.** The brief
|
||||
suggested the URI first, in the style of the port commands. I dropped it
|
||||
after establishing that the census is *purely* by name —
|
||||
`hierarchy::incoming` reads only `item.name` and nothing else off its item —
|
||||
so a URI would be an argument the handler receives and ignores, and this
|
||||
repo does not ship those. One argument, all of it used.
|
||||
- **A name the workspace does not declare is not an error.** The brief asked
|
||||
for one. I did not build it, and the reason is a real failure mode rather
|
||||
than taste: the only index-backed way to ask "is this a module?" is
|
||||
`WorkspaceIndex::units`, and the index is rebuilt on *save*, so a module
|
||||
just typed into an open buffer is genuinely absent from it. Gating on that
|
||||
would make the command refuse the very lens that is on screen. Malformed
|
||||
arguments (missing, non-string, empty) are still declined as
|
||||
`RequestFailed`, per `ports.rs`; a well-formed name with no sites answers
|
||||
`[]`, which is the truth.
|
||||
- **The census was extracted rather than duplicated, and the batch is why.**
|
||||
Naively, `code_lenses` would call `hierarchy::incoming` once per module in
|
||||
the buffer — but `Workspace::sources()` re-reads every in-scope file from
|
||||
disk on *each* call, so a three-module file would read the workspace three
|
||||
times. So `incoming`'s body became `callers_of_each(ws, names)`, which reads
|
||||
the file set once and parses each candidate file once for the whole batch;
|
||||
`incoming` is now that function with a one-element batch. Measured over the
|
||||
860-file corpus: three names 133 ms, one name 93 ms — amortized, and pinned
|
||||
by `code_lenses_for_a_whole_file_cost_about_one_workspace_walk`, which fails
|
||||
if the ratio ever goes linear.
|
||||
- **The empty-name guard moved and got stricter.** It used to be an early
|
||||
return in `incoming`; it is now a per-name filter inside the batch, so one
|
||||
empty name in a batch of five costs nothing and cannot make the prefilter
|
||||
match every file. Same behaviour for `incoming`, which is still the only
|
||||
caller that could ever be handed one.
|
||||
- **The lens sits on the name span, not the header line.** Clients draw the
|
||||
lens on the line above `range.start`; the name span and the header line have
|
||||
the same start line, but the name span is the one that stays right when a
|
||||
declaration is written with attributes or a leading comment on the same
|
||||
line.
|
||||
- **Refresh placement.** Straight after `end_indexing(bar)` in `reindex()`,
|
||||
following the progress round's own precedent that the bar names the scan and
|
||||
everything after it is work on the scan's result. Order pinned by a test
|
||||
(`create, begin, end, refresh`) so it cannot drift silently. Nothing is sent
|
||||
at startup — there is no open buffer holding lenses there.
|
||||
- **A buffer with no named declarations returns before the workspace walk.**
|
||||
Otherwise opening a package or a header file would read every file in the
|
||||
project to produce an empty list.
|
||||
- Files touched: `crates/lucisv_server/src/lens.rs` (new),
|
||||
`crates/lucisv_server/src/hierarchy.rs`,
|
||||
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/main.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, `TODO.md`,
|
||||
`docs/features/lucisv-server/README.md`, this README. No engine crate, no
|
||||
`editors/`, no new dependency, no version bump.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets`: zero warnings. `cargo test --workspace`: **1943 passed, 0
|
||||
failed** (1910 on `HEAD` `34938fb`, measured — 33 new). `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`, exit 0. No
|
||||
commits.
|
||||
|
||||
The 33 tests, and what each group is for:
|
||||
|
||||
| tests | pin |
|
||||
|---|---|
|
||||
| `lens.rs` — `a_lens_counts_every_instantiation_in_the_workspace`, `the_title_counts_in_the_users_own_arithmetic` | the cross-file count, and 0/1/N pluralization including "not `1 instantiations`" |
|
||||
| `lens.rs` — `the_count_is_exactly_what_incoming_calls_would_list` | the agreement with `hierarchy::incoming`, asserted against its live answer rather than against a number |
|
||||
| `lens.rs` — `an_instantiation_at_file_scope_is_not_counted_because_no_one_calls_it` | the inherited caller rule, stated so a future change to it is visible here |
|
||||
| `lens.rs` — `the_lens_sits_on_the_declarations_own_name`, `every_module_in_a_file_gets_its_own_lens_in_source_order` | the range is the name span; one lens per declaration, source order |
|
||||
| `lens.rs` — `an_interface_is_a_module_declaration_and_gets_its_own_lens` | interfaces, which needed no branch |
|
||||
| `lens.rs` — `a_module_nothing_instantiates_gets_a_lens_that_does_not_click`, `a_clickable_lens_carries_the_module_name_as_its_only_argument`, `no_lens_is_ever_left_for_a_resolve_to_fill_in` | the two command shapes, and that nothing is left unresolved |
|
||||
| `lens.rs` — `a_buffer_this_server_was_never_shown_has_no_lenses_at_all`, `a_buffer_that_declares_no_module_gets_an_empty_list`, `a_buffer_that_is_not_verilog_at_all_gets_no_lenses_and_does_not_panic`, `a_declaration_the_parser_could_not_name_gets_no_lens` | the four refusals: `null`, empty, total on junk, no lens without a name span |
|
||||
| `lens.rs` — `the_command_answers_one_location_per_site`, `..._nothing_for_a_module_nothing_instantiates`, `..._declines_arguments_it_cannot_read`, `the_command_list_is_what_the_server_advertises` | the command: one location per site in file-then-position order, the empty answers, the refusals |
|
||||
| `lens.rs` — `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` | the batch really is one walk (corpus, skipped when absent) |
|
||||
| `server.rs` — `a_code_lens_request_counts_the_workspaces_instantiations`, `..._for_an_unopened_buffer_answers_null` | dispatch, and the `null` |
|
||||
| `server.rs` — `the_show_instantiations_command_answers_every_site`, `..._pushes_a_show_document_when_it_can`, `a_module_with_no_instantiations_pushes_nothing_and_shows_nothing`, `..._declines_arguments_it_cannot_read` | the command over the dispatch, both `showDocument` gate states, and the `RequestFailed` code |
|
||||
| `server.rs` — `a_rescan_asks_a_capable_client_to_refresh_its_code_lenses`, `a_client_that_cannot_refresh_code_lenses_is_never_asked_to`, `the_refresh_rides_after_the_indexing_bar_comes_down` | both polarities of the refresh gate, all three rescan paths, no refresh at startup, and the order against the progress bar |
|
||||
| `main.rs` — `code_lenses_resolve_nothing_because_every_lens_is_complete`, `code_lens_refresh_support_...`, `show_document_support_...` | the advertised option, and both capability readers at absent/false/true |
|
||||
| `e2e.rs` — `code_lenses_and_their_command_round_trip_over_the_wire` | the capability's JSON shape, the lens JSON (title, command, arguments, range, no `data`), the command's locations, the `null`, and that the lens's command is in `executeCommandProvider.commands` |
|
||||
| `e2e.rs` — `a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire` | the refresh on the wire, both gate states, against the real binary |
|
||||
|
||||
## QA log
|
||||
|
||||
- **2026-08-26 (QA)** — read this README, `hierarchy/README.md` (its QA log
|
||||
especially — the `ifdef` and generate-replication findings there turned out
|
||||
to answer several questions this round would otherwise have raised fresh),
|
||||
`instantiations.rs`, `hierarchy.rs` end to end (diffed function-by-function
|
||||
against `34938fb`), `lens.rs`, and the `server.rs`/`main.rs` diffs, before
|
||||
touching anything.
|
||||
|
||||
**Gates, independently re-run.** `cargo fmt --all -- --check`: clean.
|
||||
`cargo clippy --all-targets --workspace`: zero warnings. `cargo test
|
||||
--workspace`: **1943 passed, 0 failed** before any QA change, matching the
|
||||
dev's number exactly; **1952 passed, 0 failed** after adding 9 QA tests (6
|
||||
in `lens.rs`, 3 in `server.rs` — see below). `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`, exit 0,
|
||||
run twice (before and after the QA tests).
|
||||
|
||||
**1. The `hierarchy.rs` refactor.** Diffed `git show
|
||||
34938fb:crates/lucisv_server/src/hierarchy.rs` against the working tree
|
||||
function by function. `incoming` is now `callers_of_each(ws,
|
||||
&[item.name.as_str()]).pop().unwrap_or_default()` — a one-element batch.
|
||||
Confirmed by construction that `callers_of_each`'s per-file loop is
|
||||
unchanged in substance: same `parse_source_tolerant` (not the strict
|
||||
parser — a mode change would have silently changed counts on broken files,
|
||||
and it did not happen), same `site.inst.module != name` filter inside
|
||||
`callers_in`, same final sort. The only real change is *where* the
|
||||
prefilter and the parse happen: once per name before (`callers_in` took
|
||||
`path: &Path, text: &str`), once per **file** now, with the parsed `sites`
|
||||
reused across every name the batch is asking about.
|
||||
- *Empty name in a batch.* Traced by hand: `wanted` filters out any index
|
||||
whose name is empty or absent from the file's text, so an empty name
|
||||
never reaches `callers_in` and its slot in `answers` stays `Vec::new()`.
|
||||
Byte-identical to the old early-return in `incoming`. No new test needed
|
||||
— the dev's own doc comment states this and it holds.
|
||||
- *Duplicate names in one batch, `["m", "m"]`.* New test
|
||||
`qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count`
|
||||
(`lens.rs`) — a file with two `module m` declarations (reachable through
|
||||
the tolerant parser) instantiated once, opened as a buffer. Both indices
|
||||
are processed independently (the loop does not deduplicate `wanted`), so
|
||||
neither aliases nor corrupts the other — both lenses read "1
|
||||
instantiation". Redundant work (the same file is walked twice for the
|
||||
same name), not a correctness bug.
|
||||
- *A name that is a package, not a module.* Not a distinct code path:
|
||||
`callers_of_each` matches purely on `site.inst.module`, a string, with no
|
||||
knowledge of what kind of thing owns that name. Nothing to test beyond
|
||||
what `hierarchy.rs`'s own `qa_instantiation_in_a_package_does_not_crash`
|
||||
already covers.
|
||||
- **Verdict: behavior-preserving.** `incoming`'s own 25 tests are untouched
|
||||
and green, which is necessary but — per the brief — not sufficient; the
|
||||
above traces the edge cases a black-box test-pass rerun cannot see, and
|
||||
none of them diverge.
|
||||
|
||||
**2. Count honesty.** The Assumptions section already states the load-bearing
|
||||
facts: *the population is `incomingCalls`'s, by name, and one `Instantiation`
|
||||
is one site "however many instances it declares"* — that last part is
|
||||
`hierarchy.rs`'s own documented policy (2026-08-25 QA round), inherited
|
||||
rather than decided here. Checked whether the fixture agreement test would
|
||||
actually catch a divergence: it cannot, structurally — `lens.rs` and
|
||||
`hierarchy::incoming` both bottom out in the literal same
|
||||
`hierarchy::callers_of_each` call, so "agreement" is guaranteed by
|
||||
construction, not by the fixture's shape. What the fixture's shape *does*
|
||||
affect is whether **this feature's own test suite** would notice if that
|
||||
shared implementation's semantics ever changed under it — e.g. if
|
||||
`callers_of_each` started counting instances instead of AST nodes, no
|
||||
existing `lens.rs` test using `TOP` (two separate statements) would catch
|
||||
it, because two separate statements give the same answer either way. Added
|
||||
6 tests to `lens.rs` pinning the number itself over shapes the fixture
|
||||
never exercises, each with expected output derived independently (by
|
||||
reading `instantiations.rs`'s `walk`, not by running the code first):
|
||||
- `qa_a_multi_instance_statement_is_one_site_not_two` — `sub u1 (), u2
|
||||
();` is **one** `Instantiation` node with two `Instance` entries, and
|
||||
reads "1 instantiation", one `Location`. Matches
|
||||
`hierarchy/README.md`'s stated policy exactly (it names this exact
|
||||
source shape). Not a finding — a confirmed, disclosed design decision —
|
||||
but it was untested at the code-lens layer, where a user is more likely
|
||||
to notice the number than in a hierarchy view.
|
||||
- `qa_a_module_that_instantiates_itself_counts_its_own_instantiation` —
|
||||
self-recursion reads "1 instantiation", one site, no hang. Consistent
|
||||
with `hierarchy.rs`'s own self-instantiation and cycle handling (each
|
||||
request answers one hop).
|
||||
- `qa_two_files_declaring_the_same_module_name_get_the_same_count_on_both`
|
||||
— two files each declaring `module m`, one real instantiation of `m`
|
||||
elsewhere: opening *either* declaration reads "1 instantiation" — the
|
||||
workspace-wide total, not zero and not partitioned. Matches the
|
||||
documented "census is by name" Assumption; confirms it holds in both
|
||||
directions (the fixture I found only tried one file, not the other).
|
||||
- `qa_two_declarations_of_the_same_name_in_one_file_each_get_their_own_lens_same_count`
|
||||
— described above under the hierarchy refactor; also a code-lens-level
|
||||
consequence of the same policy: **two lenses**, same count on both, in
|
||||
one buffer.
|
||||
- `qa_a_generate_replicated_instantiation_counts_the_written_statement_once`
|
||||
— a `generate for` loop wrapping one instantiation reads "1
|
||||
instantiation" regardless of the genvar's range (textual, not
|
||||
elaborated), matching `hierarchy.rs`'s own precedent for the identical
|
||||
shape.
|
||||
- `qa_an_ifdef_guarded_instantiation_counts_both_arms` — `` `ifdef``/``
|
||||
`else`` both arms read "2 instantiations". This is `hierarchy.rs`'s
|
||||
disclosed `ifdef` policy (2026-08-25 finding, fixed by documentation
|
||||
then) surfacing on a second, more visible feature. Not re-litigated here
|
||||
since the underlying behavior was already reviewed and accepted by the
|
||||
lead; pinned so a change to it is visible from `lens.rs` too, not only
|
||||
`hierarchy.rs`.
|
||||
|
||||
None of the six disagreed with `hierarchy::incoming` (they structurally
|
||||
cannot), and none exposed a new corruption or miscount — every number
|
||||
above is the intentional, already-documented arithmetic. The value added is
|
||||
regression coverage at the layer users actually read the number from.
|
||||
|
||||
**3. Cost / request amplification.** Traced `code_lenses` in `lens.rs`:
|
||||
one call to `hierarchy::callers_of_each(ws, &names)` with the *whole*
|
||||
buffer's declared names, which itself calls `ws.sources()` exactly once
|
||||
inside its single `for (path, text) in ws.sources()` loop — confirmed by
|
||||
reading the loop body, not by profiling. No per-lens or per-module
|
||||
`sources()` call exists anywhere in the path from `CodeLensRequest` to the
|
||||
answer. The **index-table follow-up**: filed in Status/TODO ("an
|
||||
instantiation-edge table in `WorkspaceIndex`... request recorded here, not
|
||||
made"), in the same style as `hierarchy/README.md`'s own equivalent backlog
|
||||
bullet from the prior round — consistent with house precedent, but neither
|
||||
one is written as a *concrete* Handshake (a proposed `vlog_semantic`
|
||||
function signature and contract) the way CLAUDE.md's Handshakes section is
|
||||
meant to capture a cross-module request. **Minor, LOW severity, not fixed**:
|
||||
recommend the lead decide whether a backlog TODO bullet is sufficient here
|
||||
(matching existing house style) or whether, now that *two* features would
|
||||
benefit from the same index change, it is worth promoting to an actual
|
||||
Handshakes-section proposal with a named function shape. Not fixed
|
||||
unilaterally — this is a documentation-structure judgment call, not a typo.
|
||||
|
||||
**4. `showDocument` push.** Read `show_instantiations` and `deliver` side
|
||||
by side: `deliver` is the only function that inserts into `self.applying`;
|
||||
`show_instantiations` calls `send_request(ShowDocument::METHOD, ...)`
|
||||
directly and never touches `applying`, so its response id always falls
|
||||
through `response()`'s `let Some(command) = self.applying.remove(...) else
|
||||
{ return }` — exactly the mechanism the doc comment claims. Confirmed via
|
||||
the dev's own tests that the gate (`self.abilities.show_document`) is
|
||||
checked before the push, that a client without it still gets the full
|
||||
location list, and that the pushed request's shape (`uri` of the first
|
||||
site, `takeFocus: true`, `selection` = that site's range) is correct.
|
||||
**New test**
|
||||
`qa_a_showdocument_push_and_an_applyedit_push_stay_independent_when_both_are_outstanding`
|
||||
(`server.rs`) — one `PROPAGATE_PORTS` command outstanding (an `applyEdit`
|
||||
push, tracked in `applying`) and one `SHOW_INSTANTIATIONS` command
|
||||
outstanding (a `showDocument` push, not tracked) at the same time,
|
||||
answered in reverse send order. The showDocument answer produces no
|
||||
message (correctly ignored even though it carries no `applied` field at
|
||||
all, which would be a type-mismatch panic risk if `response()` ever tried
|
||||
to interpret it as an `ApplyWorkspaceEditResponse`); the applyEdit answer
|
||||
is still routed to its own command correctly afterward. This was asked for
|
||||
explicitly in the brief and had no existing test — ids are allocated by a
|
||||
strictly increasing counter (`send_request`), so collision was never
|
||||
actually possible, but the mechanism is now pinned rather than just argued.
|
||||
Also confirmed by reading the `ExecuteCommand` dispatch arm:
|
||||
`lucisv.showInstantiations` returns from inside the `if` before
|
||||
`ports::execute`'s `Ok((edit, warnings)) => self.deliver(...)` branch is
|
||||
ever reached, so `deliver()` cannot fire for it — no test needed beyond the
|
||||
existing `the_show_instantiations_command_answers_every_site` asserting
|
||||
`session.requests().is_empty()` for a client without `apply_edit` either.
|
||||
|
||||
**5. Refresh discipline.** Verified independently: `refresh_code_lenses`
|
||||
gates only on `self.abilities.code_lens_refresh`, never on
|
||||
`work_done_progress` — the dev's own
|
||||
`a_rescan_asks_a_capable_client_to_refresh_its_code_lenses` already uses
|
||||
`ClientAbilities { code_lens_refresh: true, ..Default::default() }` (so
|
||||
`work_done_progress` is `false`) and gets three refreshes, which is the
|
||||
independent-gates case the brief asked about, already covered. Never at
|
||||
startup (`reindex` is not called there). **New test**
|
||||
`qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh`
|
||||
(`server.rs`) — two open buffers, one save: exactly one
|
||||
`workspace/codeLens/refresh`, confirming the call sits before the
|
||||
per-buffer republish loop in `reindex()` rather than inside it (the dev's
|
||||
existing test only ever opened one buffer, so this distinction was
|
||||
argued from reading the code, not from a test, before now). Order-pinned
|
||||
by the dev's own `the_refresh_rides_after_the_indexing_bar_comes_down`;
|
||||
re-verified by hand against `reindex()`'s body. Response ignored: same
|
||||
`applying`-lookup mechanism as `showDocument`, covered by the new
|
||||
interleaving test's reasoning (refresh never inserts into `applying`
|
||||
either).
|
||||
|
||||
**6. Command surface.** `execute_command_provider.commands` is `commands()`
|
||||
= `ports::commands()` ++ `lens::commands()`; `main.rs`'s own
|
||||
`every_advertised_command_is_one_the_server_runs` now checks both halves
|
||||
are contained, not just equality with the concatenation (equality alone
|
||||
would not have caught one list silently dropping an entry the other
|
||||
didn't add back). `git diff --stat -- crates/lucisv_server/src/ports.rs`
|
||||
confirms it is untouched. Confirmed by reading the `ExecuteCommand` arm
|
||||
(see point 4) that `lucisv.showInstantiations` never reaches `deliver()`.
|
||||
|
||||
**7. CLAUDE.md compliance.** `grep` for `unwrap()`/`expect(`/`panic!` in
|
||||
`lens.rs` and `hierarchy.rs` outside `#[cfg(test)]`: none. Same check
|
||||
against the added lines in `server.rs`/`main.rs`: every hit is inside
|
||||
`mod tests`. No `#[allow(...)]`, no `unsafe`, anywhere in the diff. Every
|
||||
public item in `lens.rs` carries a one-line doc comment. `TODO.md`'s §9c
|
||||
item text is untouched — only the checkbox flipped to `[x]`, with a
|
||||
"→ delivered" paragraph appended below it, matching the rule ("leave the
|
||||
item text intact"). This README's seven sections are each present exactly
|
||||
once.
|
||||
|
||||
**C. Corpus, machine-checked.** New test
|
||||
`qa_corpus_counts_agree_with_grep_derived_ground_truth` (`lens.rs`),
|
||||
against `corpus/common_cells/src/cdc_fifo_gray.sv` (three module
|
||||
declarations, same file the dev's own perf test already uses). Ground
|
||||
truth built by hand with `grep -rnE '\bNAME\b' corpus --include='*.sv'
|
||||
--include='*.svh'`, read line by line to exclude the declaration itself
|
||||
and doc-comment mentions (`cdc_fifo_gray_clearable.sv` has several, e.g.
|
||||
"In contrast to the cdc_fifo_gray version..." — a real risk if the walk
|
||||
ever matched comment text, which `instantiations::sites` structurally
|
||||
cannot):
|
||||
| module | grep-derived instantiation sites | lens read |
|
||||
|---|---|---|
|
||||
| `cdc_fifo_gray` | 1 (`common_cells/test/cdc_fifo_tb.sv:49`, `i_dut`) | "1 instantiation" |
|
||||
| `cdc_fifo_gray_src` | 1 (`cdc_fifo_gray.sv:130`, inside `cdc_fifo_gray` itself) | "1 instantiation" |
|
||||
| `cdc_fifo_gray_dst` | 1 (`cdc_fifo_gray.sv:145`, inside `cdc_fifo_gray` itself) | "1 instantiation" |
|
||||
All three agree. Run in release (`cargo test -p lucisv_server --release
|
||||
qa_corpus_counts_agree_with_grep_derived_ground_truth -- --nocapture`);
|
||||
skips cleanly when `corpus/` is not checked out, matching the dev's own
|
||||
corpus test's pattern.
|
||||
|
||||
**Everything else tried to break, and did not:**
|
||||
- A workspace root fixture helper (`Tree::write` in `lens.rs`'s tests) did
|
||||
not create parent directories, so a nested relative path (`"a/m.sv"`)
|
||||
failed with `NotFound` the first time this round's cross-file-collision
|
||||
test tried to use one. **Fixed directly** (`fs::create_dir_all` on the
|
||||
parent before `fs::write`) — an unambiguous test-infrastructure gap, not
|
||||
a behavior change, and it was blocking test C's fixture from being
|
||||
written at all.
|
||||
- Malformed `executeCommand` arguments (missing, non-string, empty string)
|
||||
for `lucisv.showInstantiations`: all three still answer `RequestFailed`
|
||||
with a message naming "module name" — re-verified against the dev's own
|
||||
`the_command_declines_arguments_it_cannot_read` and
|
||||
`the_show_instantiations_command_declines_arguments_it_cannot_read`.
|
||||
- A name the workspace does not declare (`"never-heard-of-it"`): `[]`, not
|
||||
an error, as documented and tested by the dev.
|
||||
- `resolveProvider: false` and every lens carrying a complete `Command`
|
||||
with no `data`: re-verified against `no_lens_is_ever_left_for_a_resolve_to_fill_in`.
|
||||
|
||||
**Verdict: committable as-is.** No corruption, no idempotency risk (this
|
||||
feature touches no formatter output), no dropped comments — none of those
|
||||
invariants are in this feature's blast radius at all, since it only reads
|
||||
and answers LSP requests. The one open item (point 3, the index-table
|
||||
request's concreteness) is a documentation-polish question for the lead,
|
||||
not a defect, and does not block shipping. 9 new tests added, all green;
|
||||
gates re-run clean before and after. No commits made.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. The round's two judgment calls were both right. Building the real
|
||||
jump instead of the display-only fallback cost ~15 lines because the
|
||||
locations already existed — exactly the "check what the code makes clean"
|
||||
outcome the brief asked for — and the zero-count lens staying display-only
|
||||
matches rust-analyzer's precedent. The hierarchy.rs refactor is the
|
||||
correct shape: one census with the batch as the primitive, `incoming` as a
|
||||
one-element batch, and the corpus ratio test making the amortization a
|
||||
tested property instead of a hope. I read the refactor diff myself and
|
||||
concur with QA's function-by-function verdict — same parse mode, same
|
||||
filters, the empty-name guard equivalent in its new position.
|
||||
|
||||
QA's count-honesty tests were the right instinct: the agreement test
|
||||
alone cannot catch semantic drift when both paths share one function, so
|
||||
pinning the absolute policies (multi-instance = one site, textual
|
||||
recursion, both ifdef arms) at the lens layer is what actually holds the
|
||||
numbers still. On QA's LOW finding, I agreed and promoted the
|
||||
index-table request to a concrete Handshakes entry with a named shape —
|
||||
two features now pay the sources() walk, which is exactly when a backlog
|
||||
bullet stops being enough. Accepted as shipped.
|
||||
@@ -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
|
||||
@@ -217,9 +253,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 +385,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 +791,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.
|
||||
@@ -0,0 +1,124 @@
|
||||
# VS Code Marketplace page
|
||||
|
||||
## Goal
|
||||
|
||||
Turn the VS Code extension's Marketplace presentation into a user-facing
|
||||
overview of lucisv: a recognizable icon and banner, clear install and usage
|
||||
instructions, accurate discovery metadata, and a complete visual catalogue of
|
||||
the editing, formatting, analysis, navigation, hierarchy, refactoring, and
|
||||
workspace features that ship in the bundled language server.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The platform-specific extension packages ship `lucisv` and
|
||||
`lucisv-server`, as release 0.10.1 does; users should not be given build or
|
||||
`PATH` setup instructions on the Marketplace page.
|
||||
- The Marketplace Details tab renders `editors/vscode/README.md`; the Features
|
||||
tab is generated from `package.json` contribution points. Since `vsce` does
|
||||
not recognize the Gitea repository host for relative-URL rewriting, README
|
||||
artwork uses absolute HTTPS links to the repository's raw PNG files.
|
||||
- Marketplace publishing rejects user-provided SVG images. Editable SVG
|
||||
artwork therefore lives here as source, while the extension README and icon
|
||||
use rendered PNG files under `editors/vscode/images/`.
|
||||
- ~~`https://lucisv.dev` is the public documentation homepage declared by the
|
||||
documentation site~~ — **corrected at lead review**: the domain does not
|
||||
exist (NXDOMAIN, checked 2026-08-27), so `homepage` and the README's
|
||||
documentation link point at the repository instead. Restore them the day the
|
||||
domain is real. The checked-out Git remote is the canonical source
|
||||
repository.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** the shipped capability table in
|
||||
`docs/features/lucisv-server/README.md`, the static grammar/snippet/settings
|
||||
contributions in `editors/vscode/package.json`, and release 0.10.1 notes in
|
||||
`CHANGELOG.md`.
|
||||
- **Promises** every user-visible shipped capability is represented in the
|
||||
Details page, including newer 0.8–0.10 features that the former README did
|
||||
not foreground.
|
||||
- **Promises** only allowed VS Code Marketplace categories and a PNG icon of
|
||||
at least 256×256 pixels are declared in the extension manifest.
|
||||
- **Promises** the extension package includes the rendered images but does not
|
||||
include the SVG source artwork.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Inventory the extension's static contributions and server capabilities.
|
||||
- [x] Inspect tag/release 0.10.1 and carry its bundled-binary install model into
|
||||
the page.
|
||||
- [x] Add icon, banner, discovery keywords, resources, and the Snippets
|
||||
category to the manifest.
|
||||
- [x] Replace build-oriented copy with install, quick-use, feature, settings,
|
||||
and troubleshooting guidance.
|
||||
- [x] Add two visual diagrams and a compact label row to the Details page.
|
||||
- [x] Render all Marketplace-facing artwork as PNG and verify its dimensions.
|
||||
- [x] Validate the manifest, Markdown image targets, and package contents.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — Marketplace presentation refresh
|
||||
|
||||
Read the latest local tag (`v0.10.1`), its changelog entry, the language-server
|
||||
capability table, editor guide, extension manifest, grammar, snippets, and
|
||||
settings. The release page itself was not reachable through the web index, so
|
||||
the signed repository state at `v0.10.1` and its checked-in release notes are
|
||||
the release source of truth.
|
||||
|
||||
Rewrote the extension README for end users and removed all build, packaging,
|
||||
and extension-development instructions. Added the 0.10.1 platform matrix and
|
||||
made the bundled tool/server behavior explicit. Added a full capability matrix
|
||||
covering formatting, diagnostics, completion/templates, navigation,
|
||||
presentation, hierarchy, refactoring, and workspace lifecycle.
|
||||
|
||||
Added a waveform/chip icon and two diagrams using one dark visual system. SVG
|
||||
sources are retained in this feature directory for future edits; PNG renders
|
||||
are the only versions referenced or packaged because VS Code Marketplace
|
||||
publishing rejects user SVGs. Updated manifest metadata using the official
|
||||
extension-manifest field and category list.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — local validation
|
||||
|
||||
- Parsed `package.json` with Node and checked the local icon path and all
|
||||
absolute README image targets.
|
||||
- Confirmed the icon is 512×512 and both diagrams render at 1200px wide.
|
||||
- Ran `vsce ls` to verify the PNGs, README, manifest, snippets, grammar, and
|
||||
extension entry point are included, while SVG sources are outside the
|
||||
extension package.
|
||||
- Compared the README feature matrix against the complete server capability
|
||||
table and the manifest's language, grammar, snippet, color, and setting
|
||||
contributions.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-27 — lead. Verdict: accepted with corrections; commits with the
|
||||
all-platforms-package round.**
|
||||
|
||||
The page itself is good work: the capability matrix was cross-checked by the
|
||||
round's own QA against the server capability table, the artwork ships as PNG
|
||||
with SVG sources kept out of the package, and the manifest additions are all
|
||||
legitimate Marketplace fields. Three corrections at review, all applied
|
||||
directly by the lead:
|
||||
|
||||
1. **`https://lucisv.dev` does not exist** (NXDOMAIN). The Assumptions entry
|
||||
presented it as a fact nobody had checked. `homepage` and the README's
|
||||
documentation link now point at the repository; the assumption is struck
|
||||
through with the correction, not deleted.
|
||||
2. **The install table was six packages, not seven** — the universal
|
||||
no-binary fallback was dropped in the rewrite, which broke the Handshake
|
||||
the concurrent editor-platform-vsix round had explicitly requested of this
|
||||
one (its README, "Requested of `editor-marketplace-page`"). A row for it
|
||||
is restored. Found by that round's QA.
|
||||
3. **A troubleshooting entry for the duplicate-hover trap**: the pre-rename
|
||||
`vfmt` extension left installed alongside lucisv attaches a second
|
||||
language server and every hover/diagnostic shows twice — diagnosed live on
|
||||
the owner's machine (2026-08-27) after a bug report; the server itself
|
||||
answers once, verified over the wire in both single-file and workspace
|
||||
modes.
|
||||
|
||||
Process note, recorded rather than hidden: this round ran concurrently with
|
||||
editor-platform-vsix and rewrote `editors/vscode/README.md` while that round
|
||||
was editing it, discarding its edits mid-flight; the platform round
|
||||
re-applied them additively. Concurrent rounds over one file cost a re-apply
|
||||
and an audit — coordinate ownership of shared files next time.
|
||||
@@ -0,0 +1,43 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="430" viewBox="0 0 1200 430">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1200" y2="430" gradientUnits="userSpaceOnUse"><stop stop-color="#07111F"/><stop offset="1" stop-color="#0C1C2C"/></linearGradient>
|
||||
<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10Z" fill="#5BC0FF"/></marker>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="160%"><feDropShadow dx="0" dy="8" stdDeviation="10" flood-color="#000" flood-opacity=".35"/></filter>
|
||||
</defs>
|
||||
<rect width="1200" height="430" rx="30" fill="url(#bg)"/>
|
||||
<text x="54" y="63" fill="#F4F8FC" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif" font-size="29" font-weight="700">Built as one coherent language toolchain</text>
|
||||
<text x="54" y="96" fill="#90A5B8" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif" font-size="16">The extension is the front door; the bundled server connects every editor action to the same analysis engines.</text>
|
||||
|
||||
<g filter="url(#shadow)" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif">
|
||||
<g transform="translate(54 141)">
|
||||
<rect width="230" height="205" rx="22" fill="#111F2F" stroke="#29465E"/>
|
||||
<rect x="22" y="22" width="72" height="28" rx="14" fill="#193C54"/><text x="37" y="41" fill="#8CD8FF" font-size="12" font-weight="700">VS CODE</text>
|
||||
<text x="22" y="86" fill="#F4F8FC" font-size="23" font-weight="700">lucisv extension</text>
|
||||
<text x="22" y="120" fill="#A8BAC9" font-size="14">File types + grammar</text><text x="22" y="146" fill="#A8BAC9" font-size="14">Snippets + theme colors</text><text x="22" y="172" fill="#A8BAC9" font-size="14">LSP client</text>
|
||||
</g>
|
||||
<g transform="translate(360 141)">
|
||||
<rect width="270" height="205" rx="22" fill="#10252D" stroke="#2C5A5B"/>
|
||||
<rect x="22" y="22" width="96" height="28" rx="14" fill="#17413D"/><text x="38" y="41" fill="#7FF5DE" font-size="12" font-weight="700">BUNDLED</text>
|
||||
<text x="22" y="86" fill="#F0FFFC" font-size="23" font-weight="700">lucisv-server</text>
|
||||
<text x="22" y="120" fill="#A8C5C1" font-size="14">LSP 3.18 over stdio</text><text x="22" y="146" fill="#A8C5C1" font-size="14">Incremental document overlay</text><text x="22" y="172" fill="#A8C5C1" font-size="14">Request cancellation + progress</text>
|
||||
</g>
|
||||
<g transform="translate(706 141)">
|
||||
<rect width="440" height="205" rx="22" fill="#171D30" stroke="#3D4669"/>
|
||||
<text x="22" y="46" fill="#F5F2FF" font-size="20" font-weight="700">Shared Rust engines</text>
|
||||
<g font-size="13" font-weight="700">
|
||||
<rect x="22" y="68" width="114" height="34" rx="10" fill="#243451"/><text x="42" y="90" fill="#8CD8FF">PARSER</text>
|
||||
<rect x="148" y="68" width="124" height="34" rx="10" fill="#1B413D"/><text x="167" y="90" fill="#7FF5DE">FORMATTER</text>
|
||||
<rect x="284" y="68" width="116" height="34" rx="10" fill="#46321E"/><text x="307" y="90" fill="#FFD194">LINTER</text>
|
||||
<rect x="22" y="114" width="160" height="34" rx="10" fill="#2B2546"/><text x="43" y="136" fill="#C8B7FF">SEMANTIC MODEL</text>
|
||||
<rect x="194" y="114" width="206" height="34" rx="10" fill="#422331"/><text x="218" y="136" fill="#FFACC0">REFACTOR ENGINE</text>
|
||||
</g>
|
||||
<text x="22" y="180" fill="#AAB5CC" font-size="14">Workspace index • include graph • open-buffer overlay</text>
|
||||
</g>
|
||||
</g>
|
||||
<path d="M294 244H346" stroke="#5BC0FF" stroke-width="4" marker-end="url(#arrow)"/>
|
||||
<path d="M640 244H692" stroke="#5BC0FF" stroke-width="4" marker-end="url(#arrow)"/>
|
||||
<g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif">
|
||||
<rect x="54" y="374" width="322" height="34" rx="17" fill="#173B36"/><text x="74" y="396" fill="#85F1DC" font-size="13" font-weight="700">v0.10.1 · TOOL + SERVER INCLUDED</text>
|
||||
<text x="1146" y="396" fill="#6F8498" font-size="13" text-anchor="end">macOS · Linux · Windows</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,78 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="560" viewBox="0 0 1200 560">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1200" y2="560" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#0E223A"/><stop offset="1" stop-color="#050A12"/>
|
||||
</linearGradient>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="160%"><feDropShadow dx="0" dy="10" stdDeviation="12" flood-color="#000" flood-opacity=".32"/></filter>
|
||||
</defs>
|
||||
<rect width="1200" height="560" rx="32" fill="url(#bg)"/>
|
||||
<circle cx="1100" cy="-10" r="240" fill="#2A5E80" opacity=".13"/>
|
||||
<circle cx="80" cy="560" r="220" fill="#315D59" opacity=".12"/>
|
||||
<text x="56" y="69" fill="#F4F8FC" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif" font-size="30" font-weight="700">One extension. The whole RTL editing loop.</text>
|
||||
<text x="56" y="103" fill="#91A6BA" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif" font-size="17">Fast feedback from the same Rust parser, formatter, linter, semantic model, and workspace index.</text>
|
||||
|
||||
<g filter="url(#shadow)" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif">
|
||||
<g transform="translate(50 146)">
|
||||
<rect width="202" height="334" rx="20" fill="#101D2C" stroke="#264158"/>
|
||||
<rect x="18" y="18" width="48" height="8" rx="4" fill="#38E8C5"/>
|
||||
<text x="18" y="64" fill="#EAFBF7" font-size="22" font-weight="700">Format</text>
|
||||
<text x="18" y="98" fill="#A9BAC8" font-size="15">Whole file</text><text x="18" y="124" fill="#A9BAC8" font-size="15">Range + multi-range</text>
|
||||
<text x="18" y="150" fill="#A9BAC8" font-size="15">On type + on save</text><text x="18" y="176" fill="#A9BAC8" font-size="15">Alignment inference</text>
|
||||
<rect x="18" y="208" width="166" height="72" rx="12" fill="#0A302E"/>
|
||||
<text x="32" y="237" fill="#7FF5DE" font-size="13" font-weight="700">VERIFIED OUTPUT</text>
|
||||
<text x="32" y="262" fill="#BBD7D1" font-size="13">safe • idempotent</text>
|
||||
<path d="M18 303H72V286H108V318H148V296H184" fill="none" stroke="#38E8C5" stroke-width="5" stroke-linejoin="round"/>
|
||||
</g>
|
||||
<g transform="translate(274 146)">
|
||||
<rect width="202" height="334" rx="20" fill="#101D2C" stroke="#264158"/>
|
||||
<rect x="18" y="18" width="48" height="8" rx="4" fill="#FFB45B"/>
|
||||
<text x="18" y="64" fill="#FFF4E8" font-size="22" font-weight="700">Diagnose</text>
|
||||
<text x="18" y="98" fill="#A9BAC8" font-size="15">Parse diagnostics</text><text x="18" y="124" fill="#A9BAC8" font-size="15">Live lint rules</text>
|
||||
<text x="18" y="150" fill="#A9BAC8" font-size="15">Safe quick fixes</text><text x="18" y="176" fill="#A9BAC8" font-size="15">Fix all</text>
|
||||
<rect x="18" y="208" width="166" height="72" rx="12" fill="#392614"/>
|
||||
<text x="32" y="237" fill="#FFD194" font-size="13" font-weight="700">EDITING-AWARE</text>
|
||||
<text x="32" y="262" fill="#E1C7A8" font-size="13">tolerant parsing</text>
|
||||
<circle cx="42" cy="306" r="12" fill="#FFB45B"/><path d="M39 300V309L46 314" fill="none" stroke="#392614" stroke-width="3" stroke-linecap="round"/>
|
||||
<text x="64" y="312" fill="#BFCBD5" font-size="13">instant feedback</text>
|
||||
</g>
|
||||
<g transform="translate(498 146)">
|
||||
<rect width="202" height="334" rx="20" fill="#101D2C" stroke="#264158"/>
|
||||
<rect x="18" y="18" width="48" height="8" rx="4" fill="#5BC0FF"/>
|
||||
<text x="18" y="64" fill="#EDF8FF" font-size="22" font-weight="700">Understand</text>
|
||||
<text x="18" y="98" fill="#A9BAC8" font-size="15">Semantic colors</text><text x="18" y="124" fill="#A9BAC8" font-size="15">Hover + macros</text>
|
||||
<text x="18" y="150" fill="#A9BAC8" font-size="15">Inlay hints</text><text x="18" y="176" fill="#A9BAC8" font-size="15">Rainbow scopes</text>
|
||||
<rect x="18" y="208" width="166" height="72" rx="12" fill="#102C40"/>
|
||||
<text x="32" y="237" fill="#84D3FF" font-size="13" font-weight="700">DESIGN INTELLIGENCE</text>
|
||||
<text x="32" y="262" fill="#B9D3E2" font-size="13">symbols, types, ports</text>
|
||||
<g fill="none" stroke="#5BC0FF" stroke-width="3"><circle cx="49" cy="307" r="13"/><circle cx="101" cy="307" r="13"/><circle cx="153" cy="307" r="13"/><path d="M62 307H88M114 307H140"/></g>
|
||||
</g>
|
||||
<g transform="translate(722 146)">
|
||||
<rect width="202" height="334" rx="20" fill="#101D2C" stroke="#264158"/>
|
||||
<rect x="18" y="18" width="48" height="8" rx="4" fill="#A98BFF"/>
|
||||
<text x="18" y="64" fill="#F4F0FF" font-size="22" font-weight="700">Navigate</text>
|
||||
<text x="18" y="98" fill="#A9BAC8" font-size="15">Definition + type</text><text x="18" y="124" fill="#A9BAC8" font-size="15">References + symbols</text>
|
||||
<text x="18" y="150" fill="#A9BAC8" font-size="15">Call hierarchy</text><text x="18" y="176" fill="#A9BAC8" font-size="15">Type hierarchy</text>
|
||||
<rect x="18" y="208" width="166" height="72" rx="12" fill="#241D3C"/>
|
||||
<text x="32" y="237" fill="#C8B7FF" font-size="13" font-weight="700">WORKSPACE-WIDE</text>
|
||||
<text x="32" y="262" fill="#C9C0E1" font-size="13">filelist-aware index</text>
|
||||
<path d="M28 316L64 290L101 316L139 290L176 316" fill="none" stroke="#A98BFF" stroke-width="4" stroke-linecap="round"/>
|
||||
</g>
|
||||
<g transform="translate(946 146)">
|
||||
<rect width="202" height="334" rx="20" fill="#101D2C" stroke="#264158"/>
|
||||
<rect x="18" y="18" width="48" height="8" rx="4" fill="#FF6F91"/>
|
||||
<text x="18" y="64" fill="#FFF0F4" font-size="22" font-weight="700">Refactor</text>
|
||||
<text x="18" y="98" fill="#A9BAC8" font-size="15">Cross-file rename</text><text x="18" y="124" fill="#A9BAC8" font-size="15">Add/remove ports</text>
|
||||
<text x="18" y="150" fill="#A9BAC8" font-size="15">Propagate ports</text><text x="18" y="176" fill="#A9BAC8" font-size="15">Repair includes</text>
|
||||
<rect x="18" y="208" width="166" height="72" rx="12" fill="#391C28"/>
|
||||
<text x="32" y="237" fill="#FFACC0" font-size="13" font-weight="700">MULTI-FILE EDITS</text>
|
||||
<text x="32" y="262" fill="#E1BCC6" font-size="13">one undoable change</text>
|
||||
<path d="M30 304H82L72 294M82 304L72 314M172 304H120L130 294M120 304L130 314" fill="none" stroke="#FF6F91" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</g>
|
||||
</g>
|
||||
<g font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif" font-size="13" font-weight="700">
|
||||
<rect x="50" y="508" width="132" height="28" rx="14" fill="#143B36"/><text x="68" y="527" fill="#7FF5DE">VERILOG 2001</text>
|
||||
<rect x="192" y="508" width="158" height="28" rx="14" fill="#182F44"/><text x="210" y="527" fill="#84D3FF">SYSTEMVERILOG</text>
|
||||
<rect x="360" y="508" width="94" height="28" rx="14" fill="#302744"/><text x="380" y="527" fill="#C8B7FF">LSP 3.18</text>
|
||||
<rect x="464" y="508" width="148" height="28" rx="14" fill="#3A2918"/><text x="483" y="527" fill="#FFD194">RUST-POWERED</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.8 KiB |
@@ -0,0 +1,28 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="40" y1="28" x2="470" y2="490" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#102846"/>
|
||||
<stop offset="1" stop-color="#050A12"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="signal" x1="68" y1="330" x2="445" y2="158" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#38E8C5"/>
|
||||
<stop offset="0.56" stop-color="#5BC0FF"/>
|
||||
<stop offset="1" stop-color="#A98BFF"/>
|
||||
</linearGradient>
|
||||
<filter id="glow" x="-30%" y="-30%" width="160%" height="160%">
|
||||
<feGaussianBlur stdDeviation="8" result="blur"/>
|
||||
<feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
|
||||
</filter>
|
||||
</defs>
|
||||
<rect x="20" y="20" width="472" height="472" rx="112" fill="url(#bg)"/>
|
||||
<rect x="29" y="29" width="454" height="454" rx="104" fill="none" stroke="#2D4968" stroke-width="2"/>
|
||||
<g fill="#17334D">
|
||||
<circle cx="96" cy="104" r="5"/><circle cx="416" cy="104" r="5"/>
|
||||
<circle cx="96" cy="408" r="5"/><circle cx="416" cy="408" r="5"/>
|
||||
</g>
|
||||
<path d="M72 320H142V198H215V340H289V152H363V274H440" fill="none" stroke="#13324D" stroke-width="34" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M72 320H142V198H215V340H289V152H363V274H440" fill="none" stroke="url(#signal)" stroke-width="18" stroke-linecap="round" stroke-linejoin="round" filter="url(#glow)"/>
|
||||
<g fill="#FFB45B" stroke="#FFE0B5" stroke-width="4">
|
||||
<circle cx="142" cy="198" r="12"/><circle cx="215" cy="340" r="12"/><circle cx="289" cy="152" r="12"/><circle cx="363" cy="274" r="12"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,785 @@
|
||||
# editor-platform-vsix
|
||||
|
||||
## Goal
|
||||
|
||||
Installing the VS Code extension has always been half an install: the `.vsix`
|
||||
is platform-independent JavaScript and the *server it spawns* is a binary the
|
||||
user has to build or download and put on `PATH` first. This round closes that
|
||||
gap the way rust-analyzer and ruff close it — **platform-specific `.vsix`
|
||||
packages that carry the binaries inside them**. Five packages, one per
|
||||
platform we cross-build for; VS Code picks the one matching the machine by the
|
||||
`--target` stamped into the package, downloads only that one, and the
|
||||
extension spawns the server out of its own install directory. The old
|
||||
platform-independent package stays, unchanged in behaviour, as the universal
|
||||
fallback for a platform we do not build (and for anyone who prefers their own
|
||||
binary on `PATH`).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`vsce`'s target names and rustc's triples are two different vocabularies**,
|
||||
and the mapping between them is a hand-written table. `vsce` validates
|
||||
`--target` against its own fixed list; nothing derives one name from the
|
||||
other.
|
||||
|
||||
| vsce target | rust triple | why that triple |
|
||||
|---|---|---|
|
||||
| `darwin-arm64` | `aarch64-apple-darwin` | the host build |
|
||||
| `darwin-x64` | `x86_64-apple-darwin` | Intel Macs (also runs under Rosetta) |
|
||||
| `linux-x64` | `x86_64-unknown-linux-musl` | static, so it runs on every distro |
|
||||
| `linux-arm64` | `aarch64-unknown-linux-musl` | same, for ARM servers/Pi/Asahi |
|
||||
| `win32-x64` | `x86_64-pc-windows-gnu` | `.exe`, DLLs Windows 10+ ships |
|
||||
|
||||
- **Linux gets the musl build, not the glibc one.** `x86_64-unknown-linux-gnu`
|
||||
is still built and shipped as a loose artifact (it exists for shops that
|
||||
require a native glibc link — see `tools/RELEASING.md`), but the *extension*
|
||||
embeds musl: a statically linked binary runs on any distro at any glibc
|
||||
vintage, which is exactly the property an extension installed by a stranger
|
||||
needs. There is no second `linux-x64` package to choose between.
|
||||
- **Alpine is an accepted gap in the *targeted* packages.** `vsce` has separate
|
||||
`alpine-x64` / `alpine-arm64` targets and VS Code running on Alpine looks for
|
||||
*those*, not for `linux-x64` — so an Alpine user gets no platform package.
|
||||
Building two more `--target`ed packages with identical contents to satisfy a
|
||||
name is not worth the release-matrix growth today; if someone asks, it is a
|
||||
two-line change (`alpine-x64` ← the same musl triple). Since 2026-08-27 the
|
||||
all-platforms package covers that user anyway (see below): it is target-less,
|
||||
so Alpine is offered it, and Node's `process.platform` there is plain
|
||||
`'linux'`, which is the directory our static-musl binaries sit in.
|
||||
- **VSIX extraction does not preserve the executable bit.** This is why
|
||||
`extension.js` chmods what it is about to spawn rather than trusting the
|
||||
package's file modes — the same thing rust-analyzer's extension does, for the
|
||||
same reason. `release.sh` still `chmod +x`es the staged binaries before
|
||||
packaging, so the mode inside the zip is right; the client-side chmod is the
|
||||
belt to that suspenders.
|
||||
- **No version handshake.** The bundled server is the one built from the same
|
||||
tree as the extension, so extension and server always match by construction.
|
||||
A user who points `lucisv.serverPath` at something else takes that risk, as
|
||||
before.
|
||||
- **The binaries are the same ones `dist/` ships.** `release.sh` stages them
|
||||
*out of* `dist/`, so the file a user gets from the release page and the file
|
||||
inside the `.vsix` are byte-identical (and the `.vsix` copies are covered
|
||||
transitively by `SHA256SUMS`' entry for the package).
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `editor-packaging`** — the spawn contract, unchanged: binary
|
||||
name `lucisv-server`, no arguments, LSP on stdin/stdout. The only thing this
|
||||
feature changes is *which path* is spawned, never how.
|
||||
|
||||
**Consumed from `tools/release.sh`** — the `dist/lucisv[-server]-<version>-<triple>`
|
||||
naming. The staging step reads those exact names; renaming an artifact breaks
|
||||
packaging loudly (a missing `cp` source), not silently.
|
||||
|
||||
**Promised to `extension.js`** — the `bin/` layout contract, three shapes and
|
||||
no fourth:
|
||||
|
||||
| package | `bin/` holds |
|
||||
|---|---|
|
||||
| universal `lucisv-<v>.vsix` | **nothing** — no `bin/` directory at all |
|
||||
| a platform `lucisv-<v>-<target>.vsix` | exactly `lucisv` and `lucisv-server` (`.exe` on Windows), flat |
|
||||
| the all-platforms `lucisv-<v>-all.vsix` | exactly ten files, `<platform>-<arch>/lucisv{,-server}` for the five platforms |
|
||||
|
||||
Names are always plain — no version, no triple. `release.sh` asserts all three
|
||||
shapes with `unzip -Z1` after every package it builds, so "the extension found a
|
||||
stale binary from the previous target" cannot ship. The all-platforms
|
||||
directory names are literally the `${process.platform}-${process.arch}` strings
|
||||
`extension.js` builds at runtime; that they also happen to equal vsce's target
|
||||
names is a convenience, not a dependency (nothing passes `--target` for that
|
||||
package).
|
||||
|
||||
**Promised to `tools/audit_artifacts.sh`** — every loose binary in `dist/` is
|
||||
still named `lucisv[-server]-<version>-<triple>`; the `.vsix` names all end in
|
||||
`.vsix` — `lucisv-<v>-all.vsix` included — and are skipped by the audit's
|
||||
existing case arm before its "unrecognized artifact name" arm can see them.
|
||||
|
||||
**Promised to `tools/prune_release_assets.sh`** — a `--cross` run produces
|
||||
exactly seven `.vsix` names, and those are the names the prune script checks
|
||||
one by one: `lucisv-<v>.vsix`, the five `lucisv-<v>-<vsce-target>.vsix`, and
|
||||
`lucisv-<v>-all.vsix`. Adding or renaming a package means editing that script's
|
||||
suffix list too, or the release fails naming the file it could not find.
|
||||
|
||||
**Requested of `editor-marketplace-page`** — that round rewrote
|
||||
`editors/vscode/README.md` end-to-end for a marketplace audience while this one
|
||||
was running, and any further rewrite of it must keep two things: its install
|
||||
table naming **seven** packages, not six (the five platform ones, `all`, and the
|
||||
universal fallback), and a bundled-binaries sentence covering both layouts —
|
||||
`bin/lucisv-server` in a platform package,
|
||||
`bin/<platform>-<arch>/lucisv-server` in the all-platforms one. Both were
|
||||
re-applied additively onto their rewrite; see the work log.
|
||||
|
||||
**Requested of other modules** — none.
|
||||
|
||||
## Resolution order in the extension
|
||||
|
||||
`extension.js` picks the server command from three candidates, most specific
|
||||
first:
|
||||
|
||||
1. **A `lucisv.serverPath` the user actually set.** Detected with
|
||||
`inspect('serverPath')`, not `get()`: `get()` cannot tell a user's setting
|
||||
from the manifest's own `"default": "lucisv-server"`, and that default would
|
||||
otherwise shadow the bundled binary for *everyone*. Any of
|
||||
`globalValue`, `workspaceValue`, `workspaceFolderValue` or their three
|
||||
language-scoped variants counts as "the user set it"; `defaultValue` and
|
||||
`defaultLanguageValue` do not, because those are contributed defaults, not
|
||||
user intent. Most specific wins, matching VS Code's own `get()` precedence.
|
||||
2. **The bundled binary**, whichever of two layouts this package uses —
|
||||
`<extension>/bin/lucisv-server`(`.exe`) first, then
|
||||
`<extension>/bin/<platform>-<arch>/lucisv-server`(`.exe`). A file existing is
|
||||
the whole runtime test for "which kind of package am I" — no build-time flag,
|
||||
no manifest field. Both misses mean no bundled binary.
|
||||
3. **The bare name `lucisv-server`**, looked up on `PATH`. What the universal
|
||||
package has always done, and what a `cargo build` + `PATH` install still
|
||||
does.
|
||||
|
||||
The CLI (`bin/lucisv`) is chmod'ed alongside the server even though nothing in
|
||||
the extension spawns it: it is shipped so a user who installed the extension
|
||||
already has the command-line tool, and a non-executable file would make that
|
||||
claim false.
|
||||
|
||||
## The all-platforms package
|
||||
|
||||
`lucisv-<version>-all.vsix` is one package carrying **all five platforms'
|
||||
binary pairs**, sorted into directories and chosen between at runtime:
|
||||
|
||||
```
|
||||
bin/
|
||||
darwin-arm64/lucisv, lucisv-server
|
||||
darwin-x64/lucisv, lucisv-server
|
||||
linux-x64/lucisv, lucisv-server (static musl)
|
||||
linux-arm64/lucisv, lucisv-server (static musl)
|
||||
win32-x64/lucisv.exe, lucisv-server.exe
|
||||
```
|
||||
|
||||
**The directory names are `${process.platform}-${process.arch}`**, not vsce
|
||||
target names — `extension.js` concatenates those two Node values and looks the
|
||||
result up. That the five strings happen to be spelled the same way vsce spells
|
||||
its targets is a coincidence worth having (one vocabulary in the release script
|
||||
instead of two) and nothing more: this package is built **without** `--target`,
|
||||
so vsce's names never enter the picture. Picking Node's own vocabulary is what
|
||||
makes the lookup a two-line function with no table in it, and what makes a
|
||||
platform we do not ship fail the obvious way — nothing on disk, fall through to
|
||||
`PATH`, exactly like the universal package.
|
||||
|
||||
Why it exists, given five perfectly good targeted packages:
|
||||
|
||||
- **Alpine, and anything else vsce names separately.** VS Code on Alpine asks
|
||||
the marketplace for `alpine-x64`, not `linux-x64`, so it is never offered our
|
||||
Linux package — but its `process.platform` is plain `'linux'` (Node does not
|
||||
distinguish libc), so it walks straight into `bin/linux-x64/`, and the binary
|
||||
there is statically linked musl, which is precisely what Alpine wants. The
|
||||
gap the targeted matrix leaves open is closed by not participating in the
|
||||
targeting at all.
|
||||
- **One file to mirror.** An internal file share, a locked-down machine, an
|
||||
offline lab: one `.vsix` that works on whatever the person on the other end
|
||||
turns out to be running beats a table of five and a question.
|
||||
- **Unknown or mixed fleets**, where whoever hands out the package does not know
|
||||
the architecture in advance.
|
||||
|
||||
The trade-off is size, and it is not small: every user downloads every
|
||||
platform's binaries — 13.0 MB against 3.0 MB for a platform package (and 0.75 MB
|
||||
for the universal one; measured on 0.10.1). That is why it is a seventh option
|
||||
rather than the only one; when the platform is known, the platform package is
|
||||
still the right answer.
|
||||
|
||||
**Built only with `--cross`**, because it needs all five pairs to exist. An
|
||||
ordinary `tools/release.sh` produces six of the seven names and no `-all` one.
|
||||
|
||||
## What gets built, and when
|
||||
|
||||
| | `release.sh` | `release.sh --cross` |
|
||||
|---|---|---|
|
||||
| universal `lucisv-<v>.vsix` | yes | yes |
|
||||
| `darwin-arm64` (host) | yes | yes |
|
||||
| the other four | no | yes |
|
||||
| `lucisv-<v>-all.vsix` | no | yes |
|
||||
|
||||
Without `--cross` there are no cross binaries to embed, so only the host
|
||||
package can be built — building it anyway (rather than only the universal one)
|
||||
keeps the packaging path exercised on every ordinary release run, including the
|
||||
embedded-server smoke test. The CI release workflow runs `--cross`, so releases
|
||||
always carry all seven.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `rustup target add --toolchain stable aarch64-unknown-linux-musl` on the
|
||||
build Mac, and the line recorded in `tools/RELEASING.md`'s one-time setup.
|
||||
- [x] `tools/release.sh`: `aarch64-unknown-linux-musl` in the `--cross` set,
|
||||
same rust-lld linker and `DYLD_FALLBACK_LIBRARY_PATH` as the x86-64 musl
|
||||
build; its two binaries land in `dist/` and in `SHA256SUMS`.
|
||||
- [x] `editors/vscode/extension.js`: three-step server resolution, `inspect()`
|
||||
for user intent, chmod of both bundled binaries.
|
||||
- [x] `editors/vscode/package.json`: `lucisv.serverPath` description mentions
|
||||
the bundled default.
|
||||
- [x] `tools/release.sh`: stage `bin/`, package per target, remove `bin/`,
|
||||
with an `EXIT` trap so a failure cannot leave binaries in the tree.
|
||||
- [x] `tools/release.sh`: `unzip -Z1` content assertions for every package, and
|
||||
an LSP smoke test of the server unzipped out of the host package.
|
||||
- [x] `tools/audit_artifacts.sh`: `aarch64-unknown-linux-musl` arm.
|
||||
- [x] `editors/vscode/.gitignore`: `bin/`.
|
||||
- [x] Docs: this file, `tools/RELEASING.md`, `editors/vscode/README.md`.
|
||||
- [x] **The all-platforms package** (2026-08-27): `extension.js`'s layered
|
||||
`bin/` lookup, `release.sh`'s `package_all_vsix` under `--cross`, the
|
||||
ten-entry content assertion, and a second embedded-server smoke test
|
||||
driven out of `bin/<host-target>/` inside that package.
|
||||
- [x] `tools/prune_release_assets.sh`: the seven-package check moved out of
|
||||
`release.yml`'s inline step into a tools/ script, checked by name.
|
||||
- [x] Docs for the all package: this file, `tools/RELEASING.md`, the top-level
|
||||
`README.md`, `docs/features/ci-release/README.md`, and
|
||||
`editors/vscode/README.md` (re-applied onto the concurrent
|
||||
`editor-marketplace-page` rewrite — see the work log).
|
||||
- [ ] **Not done, and not doable here:** none of the seven packages has been
|
||||
*installed into a real VS Code*. `require('vscode')` resolves only in the
|
||||
extension host, so the resolution order above is proven by reading it,
|
||||
by a stubbed-`context` harness over a fake directory tree, and by the
|
||||
packaging assertions — not by an editor picking the right package off a
|
||||
marketplace. The Linux and Windows packages have additionally never
|
||||
been *executed* anywhere — same standing limitation the loose binaries
|
||||
have had since `--cross` existed. The Alpine claim in particular is
|
||||
reasoned from Node's documented `process.platform` values, not observed
|
||||
on an Alpine machine.
|
||||
- [ ] **Not done, deliberate:** `alpine-x64` / `alpine-arm64` packages (see
|
||||
Assumptions), and a `linux-x64` glibc variant.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev agent
|
||||
|
||||
- **Toolchain.** `rustup target add --toolchain stable
|
||||
aarch64-unknown-linux-musl` ran clean (`rust-std` component only, no linker
|
||||
needed — `rust-lld` links it, exactly like the x86-64 musl target).
|
||||
`rustup target list --installed` now shows six targets. The line is in
|
||||
`tools/RELEASING.md`'s one-time-setup block.
|
||||
- **`release.sh` structure.** The new `aarch64-unknown-linux-musl` build sits
|
||||
next to the x86-64 musl one with the identical env pair
|
||||
(`DYLD_FALLBACK_LIBRARY_PATH="$tc/lib"` +
|
||||
`CARGO_TARGET_..._LINKER=rust-lld`); the copy loop just gained the triple.
|
||||
Packaging became three pieces: `vsce_target_for` (the triple→vsce-target
|
||||
table), `package_vsix` (stage `bin/`, package, remove `bin/`), and
|
||||
`expect_vsix_bins` (assert what a package carries). `bin_dir` is removed by an
|
||||
`EXIT` trap set before the first build, so an interrupted or failed run cannot
|
||||
leave a stale binary where the next package — or a developer's `git status` —
|
||||
would pick it up.
|
||||
- **The universal package is packaged first and with `bin/` provably absent**
|
||||
(`rm -rf` immediately before, `expect_vsix_bins` with no expected entries
|
||||
immediately after). That ordering matters: the universal package is the one
|
||||
that must never accidentally carry a platform's binaries.
|
||||
- **The embedded smoke test is a real round trip.** The host package is
|
||||
unzipped into `target/vsix-check/` (gitignored, outside the session
|
||||
scratchpad), both binaries are asserted present, the server is chmod'ed and
|
||||
driven through the same `smoke.js` LSP session the loose binary gets, and the
|
||||
directory is removed. So the claim "installing the extension gives you a
|
||||
working server" is tested against a file that has actually been through the
|
||||
zip.
|
||||
- **`inspect()` and not `get()`** is the one non-obvious line in
|
||||
`extension.js`, and the reason is in the file: `get()` returns
|
||||
`"lucisv-server"` for a user who has never touched the setting, because that
|
||||
is the manifest default — so a `get()`-based check would make the bundled
|
||||
binary unreachable for every user who did not explicitly override it. The
|
||||
scope list is most-specific-first and excludes `defaultValue` /
|
||||
`defaultLanguageValue`.
|
||||
- **The objdump question was answered by running it, not guessed.** This
|
||||
machine's `x86_64-unknown-linux-gnu-objdump` *does* parse an aarch64 ELF —
|
||||
`-p` prints `file format elf64-little` and the full program header table, and
|
||||
finds zero `NEEDED` entries in our static binary — so the new arm keeps the
|
||||
same `NEEDED` check the x86-64 musl arm uses. It also asserts `file -b`'s own
|
||||
`ARM aarch64` and `statically linked`, for two reasons the comment states:
|
||||
objdump's `elf64-little` does not name the architecture at all (so `file` is
|
||||
the only thing checking we did not ship an x86-64 binary under an aarch64
|
||||
name), and a future binutils that stopped parsing aarch64 would make the
|
||||
`NEEDED` grep pass *by finding nothing* — the exact quiet failure the audit
|
||||
exists to prevent.
|
||||
- **`x86_64-unknown-linux-gnu` gets no `.vsix`.** It is still built and still
|
||||
audited; `linux-x64` is the musl build because a static binary is the right
|
||||
thing to hand a stranger. Recorded in Assumptions so nobody re-litigates it
|
||||
silently.
|
||||
- **The no-`--cross` path was run too**, into a throwaway `-o` directory, to
|
||||
confirm the decision in "What gets built": host pair, universal package,
|
||||
`darwin-arm64` package, embedded smoke test, checksums, exit 0.
|
||||
- **`.vscodeignore` was left alone** and confirmed not to exclude `bin/` (it
|
||||
lists `smoke.js`, `.vscode/**`, `.gitignore` and nothing else). `bin/` is in
|
||||
`editors/vscode/.gitignore` instead, as a second line of defence behind the
|
||||
`EXIT` trap.
|
||||
- Did not bump any version, did not `git commit`/`git push`, did not touch
|
||||
`crates/`. `TODO.md` was read; the two items that touch editor packaging
|
||||
(§6 "Editor packaging", §6 "Release prep") are already `[x]` and neither
|
||||
mentions platform-specific packages, so nothing was checked off.
|
||||
|
||||
**Validation run on this machine (from the real repo path, never the
|
||||
scratchpad — `vsce` collects zero files under the scratchpad's UUID segment,
|
||||
`docs/features/editor-packaging` QA Finding 2):**
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `bash -n tools/release.sh tools/audit_artifacts.sh` | clean |
|
||||
| `node --check editors/vscode/extension.js` | clean |
|
||||
| `python3 -c json.load` on `editors/vscode/package.json` | valid |
|
||||
| `cargo fmt --check` | clean |
|
||||
| `cargo clippy --all-targets` | clean, no new warnings |
|
||||
| `cargo test -p lucisv_server` | **1015 unit + 50 e2e + 3 grammar green**, 5 ignored, 0 failed |
|
||||
| `tools/release.sh --cross` | exit 0 — 18 artifacts + `SHA256SUMS` (table below) |
|
||||
| `tools/release.sh -o target/relcheck-dist` (no `--cross`) | exit 0 — host pair, universal `.vsix`, `darwin-arm64` `.vsix`, `SHA256SUMS` |
|
||||
| `tools/audit_artifacts.sh dist` | **12 binaries audited, exit 0** |
|
||||
| embedded-server smoke (host `.vsix`, unzipped to `target/vsix-check/`) | `smoke: OK`, 10 messages |
|
||||
| `shasum -a 256 -c SHA256SUMS` in `dist/` | 18/18 OK |
|
||||
|
||||
**Artifacts from `tools/release.sh --cross` (lucisv 0.10.0):**
|
||||
|
||||
| `.vsix` | size | `extension/bin/` |
|
||||
|---|---|---|
|
||||
| `lucisv-0.10.0.vsix` (universal) | 487,837 | *(nothing — `unzip -Z1` reports "filename not matched")* |
|
||||
| `lucisv-0.10.0-darwin-arm64.vsix` | 2,721,294 | `lucisv-server`, `lucisv` |
|
||||
| `lucisv-0.10.0-darwin-x64.vsix` | 2,991,683 | `lucisv-server`, `lucisv` |
|
||||
| `lucisv-0.10.0-linux-x64.vsix` | 3,121,350 | `lucisv-server`, `lucisv` |
|
||||
| `lucisv-0.10.0-linux-arm64.vsix` | 2,970,545 | `lucisv-server`, `lucisv` |
|
||||
| `lucisv-0.10.0-win32-x64.vsix` | 2,906,955 | `lucisv-server.exe`, `lucisv.exe` |
|
||||
|
||||
Plus the twelve loose binaries, now including
|
||||
`lucisv-0.10.0-aarch64-unknown-linux-musl` (1,930,768) and
|
||||
`lucisv-server-0.10.0-aarch64-unknown-linux-musl` (4,022,088). `file -b` on the
|
||||
latter: `ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically
|
||||
linked, not stripped`.
|
||||
|
||||
Three things were checked beyond "it built":
|
||||
|
||||
- **The `--target` really is stamped in.** `extension.vsixmanifest` carries
|
||||
`TargetPlatform="darwin-arm64"` / `"linux-arm64"` / `"win32-x64"` in the
|
||||
respective packages, and the universal one contains no `TargetPlatform`
|
||||
attribute at all — that attribute is how VS Code picks a package.
|
||||
- **The executable bit survives packaging.** `unzip -Z` reports `-rwxr-xr-x`
|
||||
for both entries inside the packages. The client-side chmod stays anyway,
|
||||
because it is *VS Code's extraction*, not the zip, that drops the bit.
|
||||
- **The `EXIT` trap was negative-controlled**, not assumed: with an `npx` stub
|
||||
on `PATH` that fails whenever it sees `--target`, `release.sh` staged
|
||||
`editors/vscode/bin/`, failed the platform package, and exited — and
|
||||
`editors/vscode/bin/` was gone afterwards, with `git status --short
|
||||
editors/vscode` showing only the intended edits. A packaging failure cannot
|
||||
leave a binary in the tree.
|
||||
|
||||
**Not run, and why:** no package was installed into VS Code (the extension host
|
||||
is the only place `require('vscode')` resolves — unchanged limitation since
|
||||
2026-08-19), so the resolution order in `extension.js` is proven by reading and
|
||||
by the packaging assertions, not by an editor. The Linux and Windows binaries
|
||||
were not executed anywhere (no such machine in the release loop; `file`- and
|
||||
`objdump`-audited instead), which means the four non-host packages have never
|
||||
had their embedded server spawned. The marketplace's own `--target` selection
|
||||
was likewise not exercised: nothing here is published, so the check that
|
||||
`TargetPlatform` is present is as far as it goes.
|
||||
|
||||
### 2026-08-27 — lead (post-QA): chmod both bundled binaries unconditionally
|
||||
|
||||
QA's Finding 1: with a user-set `lucisv.serverPath`, the `||` chain in
|
||||
`activate` short-circuited past `bundledBinary(context, 'lucisv-server')`, so
|
||||
only the CLI got chmod'ed and `editors/vscode/README.md`'s "makes both
|
||||
executable" was one clause too strong. Fixed at the code, not the wording:
|
||||
the bundled server is now resolved into a `bundledServer` local before the
|
||||
`||` chain, so both binaries are made executable on every activation and the
|
||||
README sentence is exactly true. Two lines plus a comment; `node --check`
|
||||
clean. Lead-authored directly — the dev/QA loop would add latency, not safety
|
||||
(precedent: the 0.4.2 entry in docs/features/editor-packaging).
|
||||
|
||||
### 2026-08-27 — lead (follow-up): the release publishes the packages only
|
||||
|
||||
Owner decision, implemented in the ci-release feature (see
|
||||
docs/features/ci-release/README.md, 2026-08-27 work log entry): the release
|
||||
page now carries the six `.vsix` packages and `SHA256SUMS` only. The loose
|
||||
per-triple binaries are still built and audited — the packages are made from
|
||||
them — but no longer attached; standalone binaries are build-your-own.
|
||||
Nothing in this feature's scripts changed: `release.sh` still produces the
|
||||
full `dist/`, and the pruning lives in `release.yml` after the audit.
|
||||
|
||||
### 2026-08-27 — dev agent (round 2): the all-platforms package
|
||||
|
||||
Owner request: a seventh package carrying every platform's binaries, chosen at
|
||||
runtime — plus a consolidation of the CI release flow. Four code files.
|
||||
|
||||
- **`extension.js`: `bundledBinary` became a two-candidate lookup**, flat first,
|
||||
`bin/<platform>-<arch>/` second, `undefined` if both miss. It is a `.find()`
|
||||
over two `asAbsolutePath` results and nothing else: no package-kind flag, no
|
||||
manifest field, no table of platform names. Everything downstream — the
|
||||
`.exe` suffix, the chmod-in-`try`/`catch`, the
|
||||
`userServerPath() || bundledServer || 'lucisv-server'` order, the two calls in
|
||||
`activate` — is untouched, so the fat layout is covered for the CLI and the
|
||||
server at once. The doc comment now describes both layouts and states the
|
||||
fall-through for a platform we ship nothing for (`win32-arm64`): nothing on
|
||||
disk in either layout, so `PATH`, exactly like the universal package.
|
||||
- **Node's vocabulary, not vsce's.** The directory names are
|
||||
`${process.platform}-${process.arch}` because that is the string the extension
|
||||
can build with no lookup table. That the five values happen to be spelled the
|
||||
way vsce spells its targets is why `release.sh` can reuse `vsce_target_for`
|
||||
for the staging directory names — a convenience recorded in Assumptions, not
|
||||
a dependency: the package is built with **no** `--target`, so vsce's naming
|
||||
never enters it. Verified in the artifact: `extension.vsixmanifest` in
|
||||
`lucisv-0.10.1-all.vsix` carries no `TargetPlatform` attribute at all, same as
|
||||
the universal package.
|
||||
- **`release.sh`: `package_all_vsix`**, called only under `--cross`, and given
|
||||
`$vsix_triples` — the same list the per-platform loop just used — rather than
|
||||
a second copy of the five triples. It stages each pair into
|
||||
`bin/<vsce-target>/`, `chmod +x`es them, packages with no `--target`, removes
|
||||
the staging dir, and asserts the contents. It builds its expected-entry list
|
||||
in the same loop that stages, so the assertion cannot drift from what was
|
||||
staged.
|
||||
- **`expect_vsix_bins` needed no change, which I checked rather than assumed.**
|
||||
Info-ZIP's `*` matches `/` (unlike a shell glob), so `extension/bin/*` lists
|
||||
nested paths — confirmed on a hand-built zip with both a flat and a nested
|
||||
entry before touching `release.sh`. The one wrinkle that could have bitten:
|
||||
the same test showed Info-ZIP *also* returns directory entries
|
||||
(`extension/bin/`, `extension/bin/darwin-arm64/`), which would have broken an
|
||||
exact-set comparison — but vsce writes **no** directory entries at all
|
||||
(`unzip -Z1 … | grep -c '/$'` = 0 on a real package), so the ten filenames
|
||||
come back and nothing else. Both facts are now in the function's comment.
|
||||
- **The embedded smoke test was made a function and called twice**, once per
|
||||
layout: the host platform package out of `extension/bin/`, the all-platforms
|
||||
package out of `extension/bin/darwin-arm64/`. That is the difference that
|
||||
matters — a fat package whose binaries were staged one directory too deep
|
||||
would package, assert fine, and then fail to spawn for every user; driving a
|
||||
real LSP session out of the nested path is what rules that out.
|
||||
- **`tools/prune_release_assets.sh`** is new and is the CI-flow half of the
|
||||
round; it is logged in full in `docs/features/ci-release/README.md`. The
|
||||
handshake it creates with this feature — the seven exact package names — is
|
||||
now in Handshakes above.
|
||||
- Did not bump any version, did not `git commit`/`git push`, did not touch
|
||||
`CHANGELOG.md` or `crates/`. `TODO.md` was read again; §6's editor-packaging
|
||||
and release-prep items are still `[x]` and still say nothing about the package
|
||||
matrix, so nothing was checked off.
|
||||
|
||||
**Validation, all from the real repo path (never the scratchpad — `vsce`
|
||||
collects zero files there, `docs/features/editor-packaging` QA Finding 2):**
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `bash -n` on `release.sh`, `audit_artifacts.sh`, `prune_release_assets.sh` | clean |
|
||||
| `node --check editors/vscode/extension.js` | clean |
|
||||
| `cargo fmt --check` | clean |
|
||||
| `cargo clippy --all-targets` | clean, 0 warnings |
|
||||
| `cargo test -p lucisv_server` | **1015 unit + 50 e2e + 3 grammar**, 5 ignored, 0 failed |
|
||||
| `tools/release.sh --cross` | exit 0 — 12 loose binaries + **7** `.vsix` + `SHA256SUMS`, every `bin/ contents ok` |
|
||||
| `tools/release.sh -o target/relcheck-dist` (no `--cross`) | exit 0 — host pair, universal `.vsix`, `darwin-arm64` `.vsix`, `SHA256SUMS`, **no `-all.vsix`**, one embedded smoke test rather than two |
|
||||
| `tools/audit_artifacts.sh dist` | **12 binaries audited, exit 0** — the 7 `.vsix`, `-all` included, all skipped by the `*.vsix` arm before the "unrecognized artifact name" arm sees them |
|
||||
| `shasum -a 256 -c SHA256SUMS` in `dist/` | 19/19 OK |
|
||||
| embedded smoke, host platform package (`extension/bin/`) | `smoke: OK`, 10 messages |
|
||||
| embedded smoke, all package (`extension/bin/darwin-arm64/`) | `smoke: OK`, 10 messages |
|
||||
|
||||
**`lucisv-0.10.1-all.vsix` — what is actually in it**, checked rather than
|
||||
assumed:
|
||||
|
||||
- **Exactly ten `extension/bin/` entries**, no more: `darwin-arm64/`,
|
||||
`darwin-x64/`, `linux-x64/`, `linux-arm64/` each with `lucisv` and
|
||||
`lucisv-server`, `win32-x64/` with the two `.exe`s. Mode `-rwxr-xr-x` inside
|
||||
the zip for all ten.
|
||||
- **All ten are byte-identical to the audited loose binaries.** Compared by
|
||||
SHA-256 of `unzip -p` output against `dist/lucisv[-server]-0.10.1-<triple>`
|
||||
for all five triples, both binaries each — ten of ten match. So the audit that
|
||||
gates the release covers what is inside this package too, transitively, the
|
||||
same way it does for the platform packages.
|
||||
- **No `TargetPlatform`** in its `extension.vsixmanifest` (checked), which is
|
||||
what makes VS Code offer it to any machine — Alpine included.
|
||||
- Size 13,025,877 bytes against 2,987,672 for `darwin-arm64` and 754,239 for the
|
||||
universal package. The "13.0 MB vs 3.0 MB" in the section above is that
|
||||
measurement, not an estimate.
|
||||
- The universal package still carries **no** `bin/` — `unzip -Z1
|
||||
lucisv-0.10.1.vsix 'extension/bin/*'` answers "filename not matched". It is
|
||||
asserted at build time by `expect_vsix_bins` with an empty expected set, and
|
||||
it is packaged before anything is staged, so nothing built later can reach
|
||||
back into an already-written zip.
|
||||
|
||||
**The extension's layered lookup was exercised, not only read.** The extension
|
||||
host is still the only place `require('vscode')` resolves, so I wrote a harness
|
||||
that stubs `vscode` and `vscode-languageclient/node` through
|
||||
`Module._load`, hands `activate()` a `context` whose `asAbsolutePath` points at
|
||||
a fake extension directory, and reads back the `command` the `LanguageClient`
|
||||
was constructed with. Thirteen assertions, all passing:
|
||||
|
||||
| Fake package | Resolved to |
|
||||
|---|---|
|
||||
| no `bin/` at all | `lucisv-server` (PATH) |
|
||||
| flat `bin/` | `bin/lucisv-server` |
|
||||
| `bin/darwin-arm64/` | `bin/darwin-arm64/lucisv-server` |
|
||||
| both layouts present | the **flat** one — most specific first |
|
||||
| only a foreign platform's directory | `lucisv-server` (PATH) |
|
||||
| `bin/darwin-arm64/` + a user `serverPath` | the user's path |
|
||||
|
||||
plus: both binaries come out `0755` in the flat and the nested layouts **and**
|
||||
when a user setting won the spawn (the lead's unconditional-chmod fix from round
|
||||
1 still holds in the nested layout), and a directory for another platform is
|
||||
left at `0644` — we do not chmod what we did not choose. This proves the file
|
||||
resolution and the chmod, and nothing about how VS Code behaves around it.
|
||||
|
||||
**The `EXIT` trap was negative-controlled against the new nested staging**, not
|
||||
assumed to still work: a fake `npx` on `PATH` proxying to the real one except
|
||||
when an argument ends in `-all.vsix`, where it exits 23. `tools/release.sh -o
|
||||
target/relfail --cross` built the universal package and all five platform
|
||||
packages (each asserted `bin/ contents ok`), then died on the all package with
|
||||
exit 23 — and `editors/vscode/bin/` was gone afterwards, five subdirectories and
|
||||
ten binaries included, with `git status --short editors/vscode` showing only
|
||||
this round's edits. A failure in the fat-package path cannot leave 13 MB of
|
||||
binaries in the working tree.
|
||||
|
||||
**Not verified, honestly:**
|
||||
|
||||
- **No package was installed into a real VS Code**, so which package the
|
||||
marketplace/`code --install-extension` hands a given machine, and whether the
|
||||
extension host's `context.asAbsolutePath` behaves as the harness stubs it, are
|
||||
still unproven here. Unchanged limitation since 2026-08-19.
|
||||
- **The Alpine claim is reasoning, not an observation.** It rests on two facts I
|
||||
did not test on an Alpine box: Node reports `process.platform === 'linux'`
|
||||
there (it does not distinguish libc), and VS Code on Alpine requests
|
||||
`alpine-x64`/`alpine-arm64` from a marketplace. Both are documented behaviour,
|
||||
and the second one is moot for a package with no `TargetPlatform` — but nobody
|
||||
here has watched an Alpine VS Code start our server.
|
||||
- **The Linux and Windows binaries inside the fat package have never been
|
||||
executed**, same as the loose ones and the platform packages. Only the
|
||||
`darwin-arm64` directory's server has been spawned.
|
||||
- **`x86_64-unknown-linux-gnu` is still in no package**, fat one included: the
|
||||
fat package carries the same five platforms the targeted packages do.
|
||||
- **A concurrent round was editing the tree.** `editors/vscode/package.json` and
|
||||
`editors/vscode/images/` were being changed by another agent (marketplace
|
||||
metadata, `docs/features/editor-marketplace-page/`) while these runs happened;
|
||||
one intermediate run of mine failed on *their* half-landed `"icon"` field
|
||||
before `images/icon.png` existed, which is a race between two agents and not a
|
||||
finding about either change. The numbers quoted above are from a final
|
||||
`--cross` run made after that settled, so they describe the tree as it stands.
|
||||
I did not touch either of their files.
|
||||
|
||||
**`editors/vscode/README.md` was written twice, and the second version is the
|
||||
one that survives — lead, this file has two rounds in it.** I first updated the
|
||||
old developer-facing README as this round asked: §0 gained the all-platforms
|
||||
package, the bundled-binary sentence covered both layouts, the
|
||||
`lucisv.serverPath` settings row and the Troubleshooting entry stopped naming
|
||||
only the universal package. The `editor-marketplace-page` round then **deleted
|
||||
that file** mid-round and replaced it, 70 seconds later, with a complete
|
||||
marketplace-audience rewrite — taking those edits with it. I did not restore my
|
||||
version over theirs; theirs is the better file for its audience and clobbering a
|
||||
finished rewrite to recover four paragraphs would be the wrong trade. Instead I
|
||||
re-applied the *requirement* onto their structure, additively and in their
|
||||
voice: an `all` row in their install table, a paragraph on when to pick it (with
|
||||
the Alpine reason and the 13 MB-vs-3 MB cost) and where the binaries sit in each
|
||||
layout, and one clause in their "Release 0.10.1 highlights" list. Their
|
||||
`lucisv.serverPath` row already reads "bundled" and their Troubleshooting entry
|
||||
already avoids naming the universal package, so those two needed nothing. The
|
||||
standing requirement is in Handshakes above for whoever edits that file next.
|
||||
|
||||
If the lead lands only one of the two rounds, note the dependency: their README
|
||||
now names a package that only *this* round's `release.sh` builds.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent
|
||||
|
||||
Scope: everything the dev's work log claims — gates, `--cross` and non-`--cross`
|
||||
`release.sh` runs, `.vsix` contents, `TargetPlatform`, `SHA256SUMS`,
|
||||
`audit_artifacts.sh`'s new aarch64 arm, `extension.js`'s resolution order and
|
||||
`inspect()` usage, the `EXIT` trap, and the docs. Ran everything from the real
|
||||
repo path (`/Users/guoliangchen/repo/verilogrustformatter`), never the session
|
||||
scratchpad (`docs/features/editor-packaging` QA Finding 2). All work in this
|
||||
entry; no source file was edited.
|
||||
|
||||
**Gates — all green, matching the dev's numbers exactly.**
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `bash -n tools/release.sh tools/audit_artifacts.sh` | clean |
|
||||
| `node --check editors/vscode/extension.js` | clean |
|
||||
| `python3 -c json.load` on `package.json` | valid |
|
||||
| `cargo fmt --check` | clean |
|
||||
| `cargo clippy --all-targets` (workspace) | clean, 0 warnings |
|
||||
| `cargo test -p lucisv_server` | **1015 unit + 50 e2e + 3 grammar**, 5 ignored, 0 failed — exact match |
|
||||
| `cargo test --workspace` | all green (also run, not just the dev's subset) |
|
||||
|
||||
**`tools/release.sh --cross`, re-run independently — exit 0, 18 artifacts, matching the claimed set exactly.**
|
||||
|
||||
- `dist/` after the run: 12 loose binaries (six triples × 2), 6 `.vsix`, `SHA256SUMS` — file names and sizes match the dev's table (`lucisv-server-0.10.0-aarch64-unknown-linux-musl` 4,022,088 bytes, `lucisv-0.10.0-aarch64-unknown-linux-musl` 1,930,768 — identical to the dev's numbers).
|
||||
- `shasum -a 256 -c SHA256SUMS` in `dist/`: **18/18 OK**.
|
||||
- `unzip -Z1`/`unzip -Z` on all six `.vsix`, independently: the universal package (`lucisv-0.10.0.vsix`, 324 entries) carries no `extension/bin/*` entries and no `TargetPlatform` attribute in `extension.vsixmanifest`. Each of the five platform packages (326 entries — exactly 2 more than universal) carries exactly `extension/bin/lucisv{,-server}` (`.exe` suffix on `win32-x64`), mode `-rwxr-xr-x` inside the zip, and the correct `TargetPlatform="…"` (`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64` respectively — checked all five, not just one).
|
||||
- Grepped every `.vsix`'s file list for `smoke`, `.gitignore`, `.vscodeignore`, `test`, `.git/`: nothing found in any of them — no dev-only clutter shipped.
|
||||
- `tools/audit_artifacts.sh dist`: **12 binaries audited, exit 0** — matches exactly (the six `.vsix` are correctly skipped by the pre-existing `*.vsix` case arm, not part of this round's diff).
|
||||
- Embedded smoke test ran as part of the build: `smoke: OK` against the server unzipped out of the `darwin-arm64` package, 10 messages — matches.
|
||||
|
||||
**`tools/release.sh` without `--cross`, re-run into a throwaway `-o` dir:** exactly host pair + `lucisv-0.10.0.vsix` (universal) + `lucisv-0.10.0-darwin-arm64.vsix`, 4 files total, `editors/vscode/bin/` absent afterward. Matches the "What gets built" table exactly.
|
||||
|
||||
**Breaking it, independently (not reusing the dev's own runs):**
|
||||
|
||||
1. **Ran `release.sh` twice in a row** (non-`--cross`, into two different `-o` dirs). Both exit 0, `editors/vscode/bin/` absent after each run, identical artifact name sets both times, `git status --short editors/vscode` showed only this round's four intended edits both times — no residue from run 1 leaking into run 2.
|
||||
2. **Pre-existing junk in `editors/vscode/bin/` before a run.** Created `editors/vscode/bin/lucisv-server` and `editors/vscode/bin/some-other-file` with garbage content by hand, then ran `release.sh -o /tmp/relcheck3 --no-vsix`. The script's `rm -rf "$bin_dir"` at line 53 (before the first build, unconditional on `--no-vsix`) wiped it; `bin/` was absent afterward and the run succeeded normally. A stale `bin/` from an interrupted prior run cannot contaminate the next one.
|
||||
3. **Independently re-ran the `EXIT`-trap negative control**, with my own fake `npx` (not the dev's), rather than trusting the dev's own report: a wrapper script on `PATH` that proxies to the real `npx` for everything except an invocation containing `--target`, which it fails with exit 17. Ran `release.sh -o /tmp/relcheck_fail`: the universal package built and was asserted clean (`bin/ contents ok`), then the `darwin-arm64` package's `vsce package --target darwin-arm64` hit the fake npx and failed; the script exited 17. `editors/vscode/bin/` was absent afterward and `git status --short editors/vscode` showed only the four intended edits — the trap covers a real mid-packaging failure, checked with a genuinely different negative control than the dev used, not a re-run of theirs.
|
||||
|
||||
**Audit script — the aarch64-musl arm checked adversarially.**
|
||||
|
||||
- **Unknown artifact name still fails**, confirmed on a copy: `lucisv-0.10.0-unknown-triple-xyz` (a renamed copy of the real `aarch64-apple-darwin` binary) produces `FAIL: … unrecognized artifact name — teach this script about it`, exit 1.
|
||||
- **Corrupted the aarch64-musl arm**, on a copy, never on `dist/` originals: overwrote a copy of `lucisv-server-0.10.0-aarch64-unknown-linux-musl` with `/bin/ls` (a Mach-O binary) under the same aarch64-musl-suffixed name. Audit failed it twice over — `not an aarch64 ELF: Mach-O universal binary …` and `musl build is not statically linked: …` — before even reaching the `objdump` `NEEDED` check, and exited 1 overall. This proves the arm's `file`-based architecture/static checks fire on a corrupted artifact, but it is a weaker test than I wanted: **I did not manage to isolate the `objdump -p … | grep NEEDED` line specifically** (no genuine dynamically-linked aarch64 Linux ELF was available on this Mac to substitute in — the closest available wrong-arch swap fails at the earlier `file`-based checks first, so the `NEEDED` grep is never reached in this control). The two checks are independent by construction (read separately in the source, matching the "two independent opinions" comment at `tools/audit_artifacts.sh:56`), so I read the `NEEDED` branch by inspection rather than exercising it in isolation — noting this as an honest gap in my own coverage, not a defect found.
|
||||
|
||||
**`extension.js` resolution logic, read line by line against the claims.**
|
||||
|
||||
- **`inspect()` scope order verified correct against VS Code's own documented precedence** (`SERVER_PATH_SCOPES`, `extension.js:58-65`) — not assumed from memory. VS Code's own `vscode.d.ts` doc comment for `WorkspaceConfiguration.inspect()` states the effective-value merge order, lowest to highest, as: `defaultValue`, `globalValue`, `workspaceValue`, `workspaceFolderValue`, `defaultLanguageValue`, `globalLanguageValue`, `workspaceLanguageValue`, `workspaceFolderLanguageValue`. That means *every* language-specific value outranks *every* non-language-specific one — a genuinely counter-intuitive rule (a `[verilog]`-scoped **User** setting beats a plain **workspace folder** setting) that I checked rather than trusted. Reversed and excluding the two `default*` entries (correctly excluded — see the file's own comment), the highest-to-lowest order is exactly `workspaceFolderLanguageValue, workspaceLanguageValue, globalLanguageValue, workspaceFolderValue, workspaceValue, globalValue` — which is the code's list, verbatim, in that order. The claim is correct.
|
||||
- **The bundled-CLI call is unconditional; the bundled-server call is short-circuited — worth documenting, not a bug (Finding 1 below).**
|
||||
- **`chmodSync` is in a `try { } catch { }` with no binding** (`extension.js:104-109`) — cannot throw uncaught; a read-only install or permission error is swallowed exactly as the comment says.
|
||||
- **`deactivate()`** (`extension.js:211-214`) is untouched by this round's diff (confirmed via `git diff HEAD~1`) and still calls `clearTimeout` + `client.stop()`.
|
||||
- **Windows `.exe` suffix** is handled consistently in both `bundledBinary()` (`extension.js:100`, via `process.platform === 'win32'`) and `release.sh`'s `package_vsix`/loose-binary loops (`case $triple in *windows*) exe=.exe ;;`) — same convention, both places.
|
||||
- **Activation with `bin/` absent (the universal package) does not throw**: `bundledBinary` returns `undefined` via `fs.existsSync` before any chmod attempt, and the `||` chain falls through to `'lucisv-server'` on `PATH`, exactly as before this round. `git diff HEAD~1 -- editors/vscode/extension.js` confirms the entire diff is additive (two new `require`s, two new functions, and the `activate()` server-path line) — the pre-existing behavior for the universal package's happy path is untouched code, not just untouched behavior.
|
||||
|
||||
**Finding 1 (confirmed, cosmetic, not blocking) — `editors/vscode/README.md:29`'s "makes both executable on first activation" is not quite true when a user has set `lucisv.serverPath`.**
|
||||
`extension.js:120` calls `bundledBinary(context, 'lucisv')` unconditionally, so the CLI is always chmod'ed if present. But `extension.js:124` is
|
||||
```js
|
||||
const serverPath = userServerPath() || bundledBinary(context, 'lucisv-server') || 'lucisv-server';
|
||||
```
|
||||
— plain JavaScript `||` short-circuits, so if `userServerPath()` returns a truthy value (the user set `lucisv.serverPath` in any of the six scopes `SERVER_PATH_SCOPES` checks), `bundledBinary(context, 'lucisv-server')` is **never called**, and the bundled `bin/lucisv-server` is never chmod'ed on that activation. This is not a functional bug — the binary in question is not the one being spawned in that scenario, so its mode is irrelevant — but `editors/vscode/README.md:29`'s "the extension spawns the server from there and makes both executable on first activation" states an unconditional "both" that has this one exception. The feature README's own Handshakes section is more careful — "chmods what it is about to spawn" (line 46) — which is the actually-accurate description and does not have this gap. Recommend loosening `README.md:29`'s wording to match the feature README's, or noting the exception; not fixed here since it is a one-clause doc-precision issue, not a typo, and the instructions ask QA to file rather than redesign.
|
||||
|
||||
**Pre-existing, out of scope for this round, flagged for the lead anyway — `tools/RELEASING.md:229-231` has a garbled sentence in the Appendix**, predating this round (confirmed via `git diff HEAD~1 -- tools/RELEASING.md`; the Appendix section is untouched by this diff): "that id registered with vsce by the owner\n has created in the Visual Studio Marketplace." reads as a broken edit — a clause was apparently left mid-rewrite. Not this feature's doc to fix (it's about marketplace publishing, unrelated to platform packaging), and not introduced by this round, but noted since I read the whole file.
|
||||
|
||||
**Docs cross-checked against reality, no other issues found:**
|
||||
|
||||
- `tools/RELEASING.md`'s `.vsix`-in-detail section (staging, `--target` invocation shape, `bin/` transience, the `unzip -Z1` assertion contract) matches `release.sh`'s actual code line for line.
|
||||
- `editors/vscode/README.md`'s section 0 install instructions, the `lucisv.serverPath` settings-table row, and the Troubleshooting section's "clear the setting, don't set it back to the default string" advice all match `extension.js`'s actual behavior (the last one specifically depends on the `inspect()`-not-`get()` distinction verified above — a user who explicitly sets `lucisv.serverPath` to the literal string `"lucisv-server"` does still count as "set", by design, since `inspect()` sees it in a scope, not as the manifest default).
|
||||
- The feature README's own Handshakes ("Promised to `extension.js`", "Promised to `tools/audit_artifacts.sh`") match what the code actually does, verified independently above rather than taken on the doc's word.
|
||||
- `TODO.md` was not re-checked in depth; the dev's claim that no existing checkbox needed updating was not disputed by anything found here.
|
||||
|
||||
**No BLOCKING findings.** Every claim in the dev's work log was independently reproduced with fresh runs and, where possible, fresh negative controls rather than re-trusting the dev's own — gates, both `release.sh` modes, all six `.vsix` contents (all five `TargetPlatform`s, not a sample), `SHA256SUMS`, the `EXIT` trap (with an independently-written stub), the audit script's new arm, and the `inspect()` precedence claim (checked against VS Code's own documented merge order, not memory). Finding 1 is cosmetic and already partially self-corrected by the feature README's own more careful wording elsewhere. The un-exercised `NEEDED`-check branch (audit script) is a coverage gap in this QA pass, not a defect — recorded honestly rather than papered over.
|
||||
|
||||
**Verdict: ship.**
|
||||
|
||||
### 2026-08-27 — QA agent (round 2): the all-platforms package + CI consolidation
|
||||
|
||||
Scope: the dev's round-2 work log claims only — the seventh `lucisv-<v>-all.vsix`
|
||||
package, `extension.js`'s layered `bundledBinary` lookup, `release.sh`'s
|
||||
`package_all_vsix`/`expect_vsix_bins` under `--cross`, `tools/prune_release_assets.sh`,
|
||||
and the `release.yml` step that calls it. Did not re-review the earlier
|
||||
six-package round (its own QA log entry above stands) or the concurrent
|
||||
`editor-marketplace-page` round, except where its output could break packaging.
|
||||
Ran everything from the real repo path (`/Users/guoliangchen/repo/verilogrustformatter`),
|
||||
never the scratchpad. No source file was edited; `dist/` was rebuilt by my own
|
||||
`--cross` run and left intact afterward (verified: 20 files, `shasum -c` 19/19
|
||||
OK, as the last action before writing this entry).
|
||||
|
||||
**Gates — all green.**
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `bash -n tools/release.sh tools/audit_artifacts.sh tools/prune_release_assets.sh` | clean |
|
||||
| `node --check editors/vscode/extension.js` | clean |
|
||||
| `python3 -c "import yaml; yaml.safe_load(...)"` on `.gitea/workflows/release.yml` | valid |
|
||||
| `cargo fmt --check` | clean |
|
||||
| `cargo clippy --all-targets` | clean, 0 warnings |
|
||||
| `cargo test -p lucisv_server` | **1015 unit + 50 e2e + 3 grammar**, 5 ignored, 0 failed — exact match to the dev's numbers |
|
||||
|
||||
**`tools/release.sh --cross`, re-run independently on this machine (lucisv 0.10.1) — exit 0, 12 loose binaries + 7 `.vsix` + `SHA256SUMS` (20 files, 19 checksummed entries), matching the dev's claimed set.**
|
||||
|
||||
- `unzip -Z1 lucisv-0.10.1-all.vsix 'extension/bin/*'`: exactly 10 entries — `darwin-arm64/`, `darwin-x64/`, `linux-x64/`, `linux-arm64/` each with `lucisv`+`lucisv-server`, `win32-x64/` with `lucisv.exe`+`lucisv-server.exe` only (`.exe` confirmed absent from the other four directories). `unzip -Z1 ... | grep -c '/$'` = 0, confirming vsce writes no directory entries here either.
|
||||
- Universal package still has no `bin/`: `unzip -Z1 lucisv-0.10.1.vsix 'extension/bin/*'` → "filename not matched". The five platform packages are unchanged — flat two entries each (`extension/bin/lucisv[-server]`, `.exe` only for `win32-x64`).
|
||||
- `extension.vsixmanifest`: no `TargetPlatform` attribute in `lucisv-0.10.1-all.vsix` or the universal package; `TargetPlatform="darwin-arm64"`/`"darwin-x64"`/`"linux-x64"`/`"linux-arm64"`/`"win32-x64"` present and correct in the respective five platform packages (checked all five).
|
||||
- Both embedded smoke tests ran during the build: `smoke: OK`, 10 messages, for the host platform package (`extension/bin/`) and for the all package (`extension/bin/darwin-arm64/`).
|
||||
- `tools/audit_artifacts.sh dist`: 12 binaries audited, exit 0.
|
||||
- `shasum -a 256 -c SHA256SUMS` in `dist/`: 19/19 OK.
|
||||
- `dist/` left intact at the end (re-verified after all later runs used throwaway `-o` dirs or copies).
|
||||
|
||||
**Byte-identity spot-check, `all` package vs. loose `dist/` binaries (SHA-256, both directions of the pair, two platforms as asked):**
|
||||
|
||||
- `darwin-arm64`: `unzip -p lucisv-0.10.1-all.vsix extension/bin/darwin-arm64/lucisv` and `extension/bin/darwin-arm64/lucisv-server` both hash identically to `dist/lucisv-0.10.1-aarch64-apple-darwin` and `dist/lucisv-server-0.10.1-aarch64-apple-darwin` (`51ca1cf2...` and `edaff0df...` respectively).
|
||||
- `win32-x64`: `unzip -p lucisv-0.10.1-all.vsix extension/bin/win32-x64/lucisv.exe` and `.../lucisv-server.exe` both hash identically to `dist/lucisv-0.10.1-x86_64-pc-windows-gnu.exe` and `dist/lucisv-server-0.10.1-x86_64-pc-windows-gnu.exe` (`f6c2dbfc...` and `6628bfeb...` respectively).
|
||||
|
||||
Four of four match. Confirms the audit that gates the release covers the fat package's contents transitively, as claimed.
|
||||
|
||||
**`tools/prune_release_assets.sh`, on copies of `dist/`, never the original — independent runs, not the dev's.**
|
||||
|
||||
- **Positive**: copied the full 20-file `dist/` to a scratch dir, ran `prune_release_assets.sh <dir> 0.10.1` — exit 0, 8 survivors (the 7 `.vsix` + `SHA256SUMS`), `shasum -c` re-verify inside the script passed for all 7.
|
||||
- **Negative, missing `-all.vsix`**: removed it from a fresh copy before running — `missing lucisv-0.10.1-all.vsix` on stderr, exit 1, **file count unchanged (19 before and after)** — the name-check loop runs entirely before any deletion, so a missing package deletes nothing rather than partially pruning.
|
||||
- **Negative, wrong version arg**: ran with `9.9.9` against the real 0.10.1 tree — `missing lucisv-9.9.9.vsix`, exit 1, file count unchanged (20 before and after, since this copy still had its original `dist/` contents).
|
||||
- **Negative, missing directory**: ran against a nonexistent path — `no dist directory at ...`, exit 2, as coded.
|
||||
|
||||
**`extension.js`'s layered `bundledBinary` lookup — exercised with my own harness, not the dev's** (none was left in the tree to re-run; confirmed via `find` and `git status --short`, which shows no untracked harness file). Wrote an independent Node script (`/tmp/qa_ext_harness/harness.js`, discarded after use) that stubs `vscode` and `vscode-languageclient/node` via `Module._load`, builds fake extension directories with `fs`, and calls `activate()` against a fake `context.asAbsolutePath`, reading back `serverOptions.command` from the `LanguageClient` constructor call and the on-disk file modes afterward. Eight cases, all matching the documented behaviour:
|
||||
|
||||
| Case | Result |
|
||||
|---|---|
|
||||
| no `bin/` at all | `lucisv-server` (PATH) |
|
||||
| flat `bin/` only | flat path, chmod 755 |
|
||||
| nested `bin/<own-platform>/` only | nested path, chmod 755 |
|
||||
| both layouts present | **flat** wins (most specific first); flat chmod'ed to 755, **nested left at 644 — not touched** |
|
||||
| only a foreign platform's directory present | falls through to `lucisv-server` (PATH) |
|
||||
| nested layout + user `serverPath` set (`globalValue`) | **user's path wins the spawn**, but the nested bundled server is **still chmod'ed to 755** — confirms the lead's round-1 fix (unconditional `bundledServer` resolution ahead of the `\|\|` chain) survived the new two-candidate lookup |
|
||||
| flat layout + user `serverPath` set to the literal string `"lucisv-server"` | counts as "set" (per `inspect()`, not `get()`); command resolves to that string, flat binary still chmod'ed |
|
||||
| nested layout + user `serverPath` set to a whitespace-only string | counts as unset; falls through to the nested bundled path |
|
||||
|
||||
This independently confirms: flat-over-nested precedence, foreign-platform fall-through, the "only chmod what was chosen" behavior the dev's own harness claimed, and — the specific thing this round's instructions flagged as a prior finding to re-check — that both bundled binaries still get chmod'ed even when a user-set `serverPath` wins the spawn, in the nested layout as well as the flat one.
|
||||
|
||||
**`EXIT` trap, negative-controlled a third way** (independently of both the round-1 QA control and the dev's round-2 control): a fake `npx` on `PATH` that fails only when an argument ends in `-all.vsix` (exit 42), proxying to the real `npx` otherwise. `tools/release.sh -o /tmp/qa_relfail --cross` built the universal package and all five platform packages (each asserted `bin/ contents ok`) before dying on the all-platforms step; `editors/vscode/bin/` (which by then holds five subdirectories, ten binaries) was gone immediately after, and `git status --short editors/vscode` showed only this round's four tracked-file edits — no residue.
|
||||
|
||||
**Docs vs. reality.**
|
||||
|
||||
- `tools/RELEASING.md`'s "twelve binaries and seven `.vsix` files" claim, the `.vsix`-in-detail section's staging/assertion description, and the publishing section's "seven `.vsix` packages plus `SHA256SUMS`" all match the actual `--cross` output above.
|
||||
- `docs/features/ci-release/README.md`'s seven-package claims, its `prune_release_assets.sh` validation table (20-file copy → 8 survivors, missing `-all.vsix` → exit 1 deletes nothing), and its description of the `release.yml` step order all match what I independently reproduced above.
|
||||
- `.gitea/workflows/release.yml` calls the script as `tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"`, between the artifact audit and the release-notes extraction — confirmed by reading the file; `RELEASE_NOTES.md` is written into `dist/` *after* pruning, so the prune step (which deletes everything not `*.vsix`/`SHA256SUMS`) cannot touch it.
|
||||
- Top-level `README.md` (lines 623, 710) states the `all` package and the seven-package release claim; both match reality.
|
||||
- `tools/audit_artifacts.sh`'s `*.vsix | SHA256SUMS | RELEASE_NOTES.md` skip arm (line 39) still covers `-all.vsix` before the "unrecognized artifact name" arm — confirmed by the clean 12-binary audit above.
|
||||
- `editors/vscode/.vscodeignore` still does not exclude `bin/`; `editors/vscode/.gitignore` still ignores it with a comment pointing at this feature.
|
||||
|
||||
**Finding 1 (confirmed, moderate, not blocking build/packaging) — `editors/vscode/README.md`'s install table names six packages, not the seven this feature's own Handshakes section promises.**
|
||||
|
||||
This feature's Handshakes section (`docs/features/editor-platform-vsix/README.md:103-104`, written by the dev in this same round) states as a requirement of `editor-marketplace-page`'s rewrite: "its install table naming **seven** packages, not six (the five platform ones, `all`, and the universal fallback)". The dev's own round-2 work log (lines 552-558) claims to have "re-applied the *requirement* onto their structure" and that the marketplace README's `lucisv.serverPath` row and Troubleshooting entry "already" satisfied the requirement, needing no change — but does not claim to have added the universal package to the install table, and it was never there. Checked directly: `editors/vscode/README.md:36-43`'s install table has exactly six rows (`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`, `all`); `grep -n "universal\|lucisv-<version>\.vsix\|PATH\\b" editors/vscode/README.md` finds no mention of the universal/platform-independent package anywhere in the file — not in the install table, not in Troubleshooting, not elsewhere. A reader of this developer-facing README has no way to learn the plain `lucisv-<version>.vsix` (PATH-based, smallest download, the fallback for a platform none of the six named packages cover) exists at all. This does not break packaging or any gate — `vsce package` for the universal target still runs and is still asserted `bin/`-free by `release.sh` — it is purely a documentation gap against the feature's own stated (and, per the work log, believed-satisfied) handshake. Filed rather than fixed, per QA's scope (verify, don't redesign); the fix is one added table row plus a clause, in `editor-marketplace-page`'s voice, matching the pattern already used for the `all` row.
|
||||
|
||||
**No other findings.** Every claim in the dev's round-2 work log — the seventh package's build and contents, the layered lookup and its chmod behavior (including the specific "still chmod'ed when a user setting wins" fix-survival check this round asked for), `expect_vsix_bins`'s handling of nested paths, the `EXIT` trap under the new nested staging, `prune_release_assets.sh`'s positive and negative behavior, and the docs — was independently reproduced with fresh runs, fresh negative controls, and a fresh harness rather than re-trusting the dev's own. The concurrent `editor-marketplace-page` round's `package.json` changes (icon, keywords, homepage) do not break packaging: the full `--cross` run above packaged all seven `.vsix` cleanly against the current tree, icon file present and valid.
|
||||
|
||||
**Verdict: ship, with Finding 1 (moderate, doc-only) for the lead to route — either fix `editors/vscode/README.md`'s install table now or hand it back to `editor-marketplace-page`.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-27 — lead. Verdict: accepted; commits with this round.**
|
||||
|
||||
Reviewed the full diff (7 files + this README), the dev's work log against the
|
||||
scripts' actual code, and QA's independent reproduction. Points reviewed and
|
||||
accepted:
|
||||
|
||||
1. **The staging design is the right shape**: `editors/vscode/bin/` exists only
|
||||
between `mkdir` and the post-package `rm -rf`, with an `EXIT` trap both
|
||||
agents negative-controlled independently, and every package's `bin/`
|
||||
contents asserted with `unzip -Z1` rather than assumed. The failure this
|
||||
guards against — one platform's server shipping inside another platform's
|
||||
package, or inside the universal one — is a corruption-adjacent class of
|
||||
bug, and it cannot happen silently.
|
||||
2. **The resolution order in `extension.js` is correct and honestly detected**:
|
||||
`inspect()` across all six user-writable scopes, in VS Code's own merge
|
||||
order (QA verified the order against documentation, including the
|
||||
language-scoped-beats-general rule), with the manifest default deliberately
|
||||
not counting as "set". The chmod-in-try/catch matches rust-analyzer's
|
||||
long-standing practice for the same VSIX-extraction reality.
|
||||
3. **`linux-x64` shipping musl is the right call** — a static server is what an
|
||||
extension installed by a stranger needs — and the gaps are recorded rather
|
||||
than hidden: no `x86_64-unknown-linux-gnu` package, no Alpine targets
|
||||
(universal fallback covers them), four non-host packages never executed on
|
||||
their own platforms.
|
||||
4. **QA's Finding 1** (short-circuited chmod of the unused bundled server) was
|
||||
fixed at the code level by the lead — see the work log — so the user-facing
|
||||
README's "both" is now unconditionally true. **Finding 2** (garbled
|
||||
pre-existing sentence in the RELEASING.md appendix) is real, predates this
|
||||
round, and is fixed by the lead in this same round. QA's disclosed coverage
|
||||
gap (the aarch64 `NEEDED` branch never fired against a genuine dynamic
|
||||
aarch64 ELF) is accepted: the branch is nine lines, read by three agents,
|
||||
and structurally identical to the x86-64 arm that *was* mutation-tested.
|
||||
|
||||
No version bump here: the packages are cut from whatever version the tree is
|
||||
at, and the next tagged release ships all six automatically via the unchanged
|
||||
`release.yml` → `release.sh --cross` path.
|
||||
|
||||
**2026-08-27 — lead review of round 2 (the all-platforms package + CI
|
||||
consolidation). Verdict: accepted; commits with this round; ships as 0.10.2.**
|
||||
|
||||
Reviewed the diff, the dev's work log, and QA's independent reproduction
|
||||
(its own Node harness for the layered lookup, its own `EXIT`-trap stub, a
|
||||
fresh `--cross` run, byte-identity spot-checks). Points accepted:
|
||||
|
||||
1. **The layered `bundledBinary` lookup is the smallest correct shape**: the
|
||||
file's existence remains the only runtime test for "which package am I",
|
||||
the flat layout wins so a platform package can never accidentally pick a
|
||||
foreign binary out of a fat layout, and the prior round's
|
||||
chmod-both-binaries fix survives (QA proved it with a user-set
|
||||
`serverPath` against a nested layout).
|
||||
2. **The `-all` package is target-less on purpose** — no `TargetPlatform` in
|
||||
its manifest, asserted by `release.sh` — which is precisely what makes it
|
||||
the honest answer for Alpine and any platform vsce refuses to name.
|
||||
3. **`tools/prune_release_assets.sh` consolidates the release contract in
|
||||
one place**: seven names checked, audited hashes preserved by filtering
|
||||
rather than recomputing, deletion only after every check passes (QA's
|
||||
negative controls confirm a failure deletes nothing).
|
||||
4. **QA's Finding 1** (the marketplace rewrite dropped the universal package
|
||||
from the install table, breaking this round's requested Handshake) was
|
||||
fixed by the lead in the marketplace round's review — a seventh row names
|
||||
the universal fallback.
|
||||
|
||||
Accepted limitations, unchanged from round 1: no real-editor run, four
|
||||
non-host platforms' binaries never executed, Alpine reasoned not observed.
|
||||
@@ -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`
|
||||
|
||||
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user