Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -1,10 +1,12 @@
|
||||
# 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. What the release page carries is the six .vsix packages —
|
||||
# the universal one plus darwin-arm64/darwin-x64/linux-x64/linux-arm64/
|
||||
# win32-x64 with the lucisv + lucisv-server binaries embedded — and
|
||||
# SHA256SUMS; each platform package is a must, and a missing one fails
|
||||
# the release. The loose binaries are still built for every target
|
||||
# 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).
|
||||
@@ -34,26 +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 six must exist
|
||||
# (release.sh would have failed earlier, but a missing package here is
|
||||
# exactly the failure this release exists to prevent, so it is checked
|
||||
# by name); the loose binaries were needed to build and audit them and
|
||||
# are dropped now. SHA256SUMS is filtered, not recomputed — the
|
||||
# published hashes are the audited ones — and re-verified after.
|
||||
# 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: |
|
||||
v=${GITHUB_REF_NAME#v}
|
||||
cd dist
|
||||
for t in "" -darwin-arm64 -darwin-x64 -linux-x64 -linux-arm64 -win32-x64; do
|
||||
[ -f "lucisv-$v$t.vsix" ] || {
|
||||
echo "missing lucisv-$v$t.vsix" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
grep '\.vsix$' SHA256SUMS > SHA256SUMS.tmp
|
||||
mv SHA256SUMS.tmp SHA256SUMS
|
||||
find . -type f ! -name '*.vsix' ! -name SHA256SUMS -delete
|
||||
shasum -a 256 -c SHA256SUMS
|
||||
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
|
||||
|
||||
+374
@@ -4,6 +4,380 @@ 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.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
|
||||
|
||||
@@ -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.10.1"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.10.1"
|
||||
version = "0.16.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -620,6 +620,10 @@ and sideload it:
|
||||
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:
|
||||
@@ -674,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
|
||||
@@ -703,10 +711,12 @@ 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 **six `.vsix` packages** — platform-specific ones for
|
||||
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, plus the
|
||||
universal no-binary fallback — and a `SHA256SUMS` to verify them with
|
||||
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
|
||||
@@ -720,7 +730,7 @@ 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
|
||||
@@ -703,6 +776,18 @@ and are not gaps.
|
||||
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).
|
||||
@@ -750,6 +835,34 @@ and are not gaps.
|
||||
— 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`.
|
||||
@@ -835,7 +948,10 @@ and are not gaps.
|
||||
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.
|
||||
`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).
|
||||
@@ -883,10 +999,12 @@ and are not gaps.
|
||||
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
|
||||
~~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. Two
|
||||
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
|
||||
@@ -1010,3 +1128,234 @@ 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`.
|
||||
- [ ] 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.
|
||||
+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,25 @@ 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.
|
||||
///
|
||||
/// 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 +80,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 +250,18 @@ 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()
|
||||
}
|
||||
|
||||
/// `` `define`` names starting with `prefix`, case-insensitively.
|
||||
pub fn macros(&self, prefix: &str) -> &[Macro] {
|
||||
matching(&self.macros, prefix, |m| &m.name)
|
||||
@@ -83,12 +273,26 @@ 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, so same-named declarations are
|
||||
// already adjacent and a plain `dedup` leaves one entry per module name —
|
||||
// which is exactly what `vlog_refactor::module_names` does to the same
|
||||
// list, minus the per-keystroke rebuild.
|
||||
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 +310,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 +336,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 +390,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 +420,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 +448,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]
|
||||
@@ -324,4 +554,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");
|
||||
}
|
||||
}
|
||||
@@ -33,11 +33,11 @@ use lsp_types::{
|
||||
use vlog_parser::token::{Comment, Token, TokenKind};
|
||||
use vlog_parser::{TextRange, KEYWORDS};
|
||||
use vlog_refactor::{InstantiationPlan, Layout, Site};
|
||||
use vlog_semantic::{Semantics, Symbol, SymbolKind};
|
||||
use vlog_semantic::{Semantics, Symbol, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use crate::candidates::starts_with_ignore_case;
|
||||
use crate::pairs;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::state::{first_token_from, Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::{self, Gate, Template};
|
||||
|
||||
@@ -59,6 +59,19 @@ const LIMIT: usize = 512;
|
||||
/// table built at index time. Unchanged from M4.
|
||||
const MODULE_LIMIT: usize = 64;
|
||||
|
||||
/// How far past a module's name [`module_header`] reads looking for the end of
|
||||
/// its header, smallest first.
|
||||
///
|
||||
/// A ladder rather than one bound because the lex is the whole cost of the
|
||||
/// slice and it is linear in what it is handed, so every header would
|
||||
/// otherwise pay for the widest one. The rungs come from measuring opentitan's
|
||||
/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB,
|
||||
/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB.
|
||||
/// The top rung is well past that, because a rung that is too small is not a
|
||||
/// wrong answer but a whole-file parse, and for those files that is 2–4 ms
|
||||
/// against the 0.6 ms of lexing 16 KB.
|
||||
const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024];
|
||||
|
||||
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
|
||||
/// order; the name follows so each tier is alphabetical within itself.
|
||||
const TIER_MODULE: char = '0';
|
||||
@@ -211,7 +224,10 @@ fn module_tier(
|
||||
let layout = layout_at(ws, doc, word.start);
|
||||
let site = Site { semantics: &doc.semantics, offset: word.start };
|
||||
|
||||
let names = vlog_refactor::module_names(ws.index(), &word.text);
|
||||
// The same names `vlog_refactor::module_names` answers, off the table
|
||||
// built with the index instead of off the index's whole symbol table —
|
||||
// which the old call rebuilt and re-sorted on every keystroke.
|
||||
let names = ws.candidates().modules(&word.text);
|
||||
if names.len() > MODULE_LIMIT {
|
||||
items.incomplete = true;
|
||||
}
|
||||
@@ -220,14 +236,145 @@ fn module_tier(
|
||||
// is silently skipped: a completion list is not the place to argue.
|
||||
let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue };
|
||||
let Some(definition) = ws.text_of(path) else { continue };
|
||||
let Ok(plan) = vlog_refactor::instantiation_plan(name, &definition, Some(site)) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(plan) = plan_for(ws.index(), name, &definition, site) else { continue };
|
||||
let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string();
|
||||
items.push(item(&plan, &layout, word.range(cursor), doc, &file, snippets));
|
||||
}
|
||||
}
|
||||
|
||||
/// One module's instantiation plan, off its header alone where that is the
|
||||
/// whole of what the plan reads, and off its whole file otherwise.
|
||||
///
|
||||
/// The slice is an optimisation and never an answer of its own. Two things
|
||||
/// send this back to the whole file, and both leave the answer exactly what it
|
||||
/// was before the slice existed:
|
||||
///
|
||||
/// * the slice does not plan at all — [`module_header`] cut a header this
|
||||
/// parser does not read as one;
|
||||
/// * the plan it produced has a port with neither a direction nor a type,
|
||||
/// which is what a **non-ANSI** port list looks like once its body is gone:
|
||||
/// `module m (a); input wire a;` writes the direction below the header, and
|
||||
/// the body is the part the slice drops.
|
||||
fn plan_for(
|
||||
index: &WorkspaceIndex,
|
||||
module: &str,
|
||||
definition: &str,
|
||||
site: Site<'_>,
|
||||
) -> Result<InstantiationPlan, String> {
|
||||
let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site));
|
||||
let Some(header) = module_header(index, module, definition) else { return whole() };
|
||||
match vlog_refactor::instantiation_plan(module, &header, Some(site)) {
|
||||
Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan),
|
||||
_ => whole(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text one skeleton is planned from: the declaring file's header alone
|
||||
/// where this function can find it, and the whole file where it cannot.
|
||||
///
|
||||
/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed
|
||||
/// the whole declaring file — three hundred lines of body to read a header a
|
||||
/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads
|
||||
/// nothing but the header, so nothing but the header needs to be parsed.
|
||||
///
|
||||
/// The prefix is kept **byte for byte**: every span the plan reads is an offset
|
||||
/// into the text it was parsed from, so cutting the front off would move them
|
||||
/// all. Only the body is dropped, and an `endmodule` is written in its place so
|
||||
/// the declaration is closed.
|
||||
pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option<String> {
|
||||
let [def] =
|
||||
index.units(module).iter().filter(|d| d.kind == SymbolKind::Module).collect::<Vec<_>>()[..]
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let name = def.name_span;
|
||||
// The index's span is as of the last scan. A file edited on disk since
|
||||
// then has moved it, and a slice taken at a stale offset would be a
|
||||
// different module's header — so the name has to still be there.
|
||||
if text.get(name.start as usize..name.end as usize) != Some(module) {
|
||||
return None;
|
||||
}
|
||||
let from = name.end as usize;
|
||||
for size in HEADER_WINDOWS {
|
||||
// A window that cuts a block comment or a string in half does not lex,
|
||||
// and one that cuts the port list in half runs out of tokens before
|
||||
// the `;`. Both answer "not in this window" and are asked again at the
|
||||
// next rung; both answer `None` at the last one.
|
||||
let window = text.get(from..text.len().min(from + size))?;
|
||||
if let Ok(tokens) = vlog_parser::tokenize(window) {
|
||||
if let Some(end) = header_end(&tokens) {
|
||||
let head = text.get(..from + end as usize)?;
|
||||
return Some(format!("{head}\nendmodule\n"));
|
||||
}
|
||||
}
|
||||
if from + size >= text.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Where the header that begins just after a module's name ends: the offset
|
||||
/// one past its terminating `;`, in the window's own coordinates.
|
||||
///
|
||||
/// A **whitelist**, not a scan for the first `;`: `module aes import
|
||||
/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the
|
||||
/// header. Anything this does not recognise — a compiler directive between the
|
||||
/// name and the port list, a header longer than the window — answers `None`,
|
||||
/// and the caller parses the whole file rather than guessing.
|
||||
fn header_end(tokens: &[Token]) -> Option<u32> {
|
||||
let mut at = 0;
|
||||
loop {
|
||||
let token = tokens.get(at)?;
|
||||
match token.text.as_str() {
|
||||
";" => return Some(token.span.end),
|
||||
// A lifetime qualifier: `module automatic foo (...);`.
|
||||
"static" | "automatic" => at += 1,
|
||||
// A package import written into the header, whose own `;` is not
|
||||
// the header's.
|
||||
"import" => at = skip_to_semicolon(tokens, at + 1)?,
|
||||
// The parameter list, the port list, and an attribute instance —
|
||||
// each one parenthesised, each one skipped whole.
|
||||
"#" | "(" => at = skip_parens(tokens, at)?,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the parenthesised group starting at `at`, which a `#` may introduce.
|
||||
fn skip_parens(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
while tokens.get(at)?.text == "#" {
|
||||
at += 1;
|
||||
}
|
||||
if tokens.get(at)?.text != "(" {
|
||||
return None;
|
||||
}
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" if depth == 1 => return Some(at + 1),
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the next `;` written outside any parentheses.
|
||||
fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
";" if depth == 0 => return Some(at + 1),
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 1: everything the scope chain at the cursor binds.
|
||||
fn scope_tier(items: &mut Items, doc: &Document, word: &Word) {
|
||||
for symbol in visible_symbols(&doc.semantics, word.start) {
|
||||
@@ -849,9 +996,12 @@ fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)>
|
||||
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
|
||||
/// `generate begin` reaches `generate`. Whichever comes first decides.
|
||||
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
|
||||
let Some(begin) = tokens.iter().position(|token| token.span.start == offset) else {
|
||||
// A token starting exactly at `offset` is the first one that starts at or
|
||||
// after it: every earlier token starts before, every later token after.
|
||||
let begin = first_token_from(tokens, offset);
|
||||
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
|
||||
return false;
|
||||
};
|
||||
}
|
||||
for token in tokens[..begin].iter().rev() {
|
||||
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
|
||||
return true;
|
||||
@@ -866,7 +1016,11 @@ fn is_procedural(tokens: &[Token], offset: u32) -> bool {
|
||||
/// Whether every parenthesis opened between `from` and `at` was closed again.
|
||||
fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
|
||||
let mut depth = 0i32;
|
||||
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
|
||||
// The tokens whose start falls in `[from, at)` are a contiguous run,
|
||||
// because starts rise across the vector — so the filter this replaced was
|
||||
// reading the whole buffer to reach a window the two bounds name outright.
|
||||
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
|
||||
for token in &tokens[window] {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
@@ -898,6 +1052,49 @@ module sub #(
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// [`is_procedural`] used to sweep the vector for the token starting at
|
||||
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
|
||||
/// two offsets name. Both now binary-search; both must answer exactly what
|
||||
/// the sweeps answered, at every byte and for every window.
|
||||
#[test]
|
||||
fn the_scope_gates_answer_what_their_sweeps_answered() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
|
||||
let tokens = &doc.tokens;
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = tokens.iter().position(|token| token.span.start == offset);
|
||||
let searched = {
|
||||
let begin = first_token_from(tokens, offset);
|
||||
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
|
||||
};
|
||||
assert_eq!(swept, searched, "the token starting at {offset}");
|
||||
}
|
||||
// Every `begin`/`end` opener in the buffer against a spread of cursors
|
||||
// after it: the two bounds are what pick the window out.
|
||||
let openers: Vec<u32> = tokens
|
||||
.iter()
|
||||
.filter(|t| t.text == "begin" || t.text == "(")
|
||||
.map(|t| t.span.end)
|
||||
.collect();
|
||||
assert!(openers.len() > 20, "premise: plenty of windows to check");
|
||||
for from in openers {
|
||||
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
|
||||
let mut depth = 0i32;
|
||||
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
@@ -948,7 +1145,7 @@ endmodule
|
||||
) -> (Tree, Workspace, Uri, Position) {
|
||||
let path = tree.write(file, 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;
|
||||
@@ -990,6 +1187,298 @@ endmodule
|
||||
items.iter().map(|item| item.label.as_str()).collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 0's header slice (2026-08-28) — it must change no answer
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every header shape the slice has to survive, as (file text, module).
|
||||
///
|
||||
/// The list is the argument that the slice changes nothing: each entry is
|
||||
/// planned both ways below and the two plans are compared field by field.
|
||||
const SHAPES: &[(&str, &str)] = &[
|
||||
// The ordinary ANSI header, params and all.
|
||||
(SUB, "sub"),
|
||||
// No ports at all.
|
||||
("module bare;\nendmodule\n", "bare"),
|
||||
// An empty port list.
|
||||
("module empty ();\n logic x;\nendmodule\n", "empty"),
|
||||
// A package import written into the header: its `;` is not the
|
||||
// header's, and a slice that stopped there would report no ports.
|
||||
(
|
||||
"package p;\n localparam int W = 4;\nendpackage\n\
|
||||
module imported import p::*; #(\n parameter int W = 8\n) (\n \
|
||||
input logic clk,\n output logic [W-1:0] q\n);\n \
|
||||
assign q = '0;\nendmodule\n",
|
||||
"imported",
|
||||
),
|
||||
// Two imports, then a parameter list.
|
||||
(
|
||||
"package p;\nendpackage\npackage q;\nendpackage\n\
|
||||
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
|
||||
"twice",
|
||||
),
|
||||
// A **non-ANSI** port list: the directions live in the body, which is
|
||||
// exactly what the slice drops.
|
||||
(
|
||||
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
|
||||
always @* b = |a;\nendmodule\n",
|
||||
"old",
|
||||
),
|
||||
// Non-ANSI with nothing declaring the ports at all.
|
||||
("module silent (a, b);\nendmodule\n", "silent"),
|
||||
// A comment and an attribute inside the header.
|
||||
(
|
||||
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"noisy",
|
||||
),
|
||||
// A lifetime qualifier.
|
||||
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
|
||||
// A second module in the same file, after the one being planned.
|
||||
(
|
||||
"module first (input logic a);\nendmodule\n\
|
||||
module second (output logic b);\nendmodule\n",
|
||||
"first",
|
||||
),
|
||||
// …and before it, so the slice's prefix carries a whole module.
|
||||
(
|
||||
"module first (input logic a);\nendmodule\n\
|
||||
module second (output logic b);\nendmodule\n",
|
||||
"second",
|
||||
),
|
||||
// A compiler directive between the name and the port list, which the
|
||||
// whitelist refuses outright.
|
||||
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
|
||||
// A directive *inside* the port list, which carries a warning the two
|
||||
// plans must both raise.
|
||||
(
|
||||
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
|
||||
`endif\n);\nendmodule\n",
|
||||
"ifdefd",
|
||||
),
|
||||
// An escaped identifier for the module and for a port.
|
||||
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
|
||||
// A header longer than the first rung of the window ladder.
|
||||
(WIDE, "wide"),
|
||||
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
|
||||
// instance, `(* ... *)`, right after the module name and before the
|
||||
// parameter list — the one shape the "noisy" case above is commented
|
||||
// as covering but does not (it has two comments, no attribute).
|
||||
// **Finding, not a regression this round introduced**: a module with
|
||||
// an attribute anywhere near its header is not indexed as a `Module`
|
||||
// unit at all (see
|
||||
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
|
||||
// so this pins the safe side effect — `module_header` declines before
|
||||
// its whitelist walk ever runs — rather than the whitelist's own
|
||||
// handling of attributes, which this shape cannot reach.
|
||||
(
|
||||
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"attributed",
|
||||
),
|
||||
// An attribute instance *inside* the port list, attached to one port.
|
||||
// Same finding as `attributed`: not indexed, so not reached either.
|
||||
(
|
||||
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
|
||||
);\nendmodule\n",
|
||||
"port_attributed",
|
||||
),
|
||||
// A single import declaration naming several packages, comma
|
||||
// separated (`import a::*, b::*;`) — one statement, not two, and the
|
||||
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
|
||||
(
|
||||
"package p;\nendpackage\npackage q;\nendpackage\n\
|
||||
module chained import p::*, q::*; (input logic a);\nendmodule\n",
|
||||
"chained",
|
||||
),
|
||||
// A parameter default whose string literal carries the exact bytes
|
||||
// the whitelist watches for — `;` and `)` — which must stay inside
|
||||
// the `String` token and never be mistaken for header punctuation.
|
||||
(
|
||||
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"stringy",
|
||||
),
|
||||
// CRLF line endings through the whole header.
|
||||
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
|
||||
];
|
||||
|
||||
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
|
||||
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
|
||||
input logic port_number_one_with_a_long_name,\n \
|
||||
input logic port_number_two_with_a_long_name,\n \
|
||||
input logic port_number_three_with_a_long_name,\n \
|
||||
input logic port_number_four_with_a_long_name,\n \
|
||||
input logic port_number_five_with_a_long_name,\n \
|
||||
output logic port_number_six_with_a_long_name\n);\n \
|
||||
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
|
||||
|
||||
/// The whole argument for the slice: for every shape above, the plan built
|
||||
/// from the header alone is the plan built from the whole file. Where it
|
||||
/// would not be — a non-ANSI list, a header the whitelist refuses — the
|
||||
/// guard in [`plan_for`] sends the question back to the whole file, so the
|
||||
/// comparison holds there too.
|
||||
#[test]
|
||||
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
|
||||
for (text, module) in SHAPES {
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let site = Site { semantics: &semantics, offset: 0 };
|
||||
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
|
||||
let ours = plan_for(&index, module, text, site);
|
||||
assert_eq!(ours, whole, "{module}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
|
||||
/// trivially for a shape the whitelist declines — both sides parse the
|
||||
/// whole file, so a wrong slice could hide behind that. These shapes must
|
||||
/// actually slice, so the comparison exercises the whitelist walk it is
|
||||
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
|
||||
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
|
||||
/// `;`/`)` sitting inside a string literal, and CRLF endings.
|
||||
#[test]
|
||||
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
|
||||
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
|
||||
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, *text)]);
|
||||
assert!(
|
||||
module_header(&index, module, text).is_some(),
|
||||
"{module}: expected the header to actually slice, not fall back whole-file"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
|
||||
/// round introduced: a module with an attribute instance (`(* ... *)`)
|
||||
/// anywhere near its header — right after its name, or on one of its
|
||||
/// ports — is not indexed as a `Module` unit **at all**.
|
||||
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
|
||||
/// at the very first line (no `[def]` to anchor on) before the whitelist
|
||||
/// walk ever runs, and completion's module tier — which sources its
|
||||
/// candidate names from the same table — never offers the module in the
|
||||
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
|
||||
/// completion-core one: it is filed in `docs/features/completion-core/
|
||||
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
|
||||
/// outside this round's touched files. The two "attribute" shapes this QA
|
||||
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
|
||||
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
|
||||
/// because both sides of that comparison fall back to the same whole-file
|
||||
/// parse, which this test makes explicit rather than leaving it as an
|
||||
/// unremarked side effect of the pin.
|
||||
#[test]
|
||||
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
|
||||
for module in ["attributed", "port_attributed"] {
|
||||
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, *text)]);
|
||||
assert!(
|
||||
index.units(module).is_empty(),
|
||||
"{module}: if this starts finding a unit, module_header should be re-audited \
|
||||
for whether it now slices attributes correctly rather than by lucky fallback"
|
||||
);
|
||||
assert!(
|
||||
module_header(&index, module, text).is_none(),
|
||||
"{module}: no unit to anchor on"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard is not decoration: a non-ANSI module really does plan
|
||||
/// differently off its header, and really is sent back to the whole file.
|
||||
#[test]
|
||||
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
|
||||
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
|
||||
let path = PathBuf::from("/rtl/old.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, text)]);
|
||||
let header = module_header(&index, "old", text).expect("the header slices");
|
||||
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
|
||||
assert!(
|
||||
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
|
||||
"premise: the header alone knows nothing about these ports"
|
||||
);
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let site = Site { semantics: &semantics, offset: 0 };
|
||||
let guarded = plan_for(&index, "old", text, site).expect("a plan");
|
||||
assert_eq!(guarded.ports[0].dir, "input");
|
||||
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
|
||||
}
|
||||
|
||||
/// The whole answer, pinned at the prefixes the hot path is worst at — the
|
||||
/// empty one and a one-character one, where every tier is at its widest.
|
||||
/// Tier 0 is what the slice changed, so the pin spells out every skeleton's
|
||||
/// label *and* the text it inserts, which is the part a wrong header would
|
||||
/// corrupt.
|
||||
#[test]
|
||||
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
|
||||
let tree = Tree::new("pinned");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
|
||||
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
|
||||
let (_tree, mut ws, uri, _) =
|
||||
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
|
||||
|
||||
// Nothing typed, then one character — the two widest requests there
|
||||
// are. `top` is in the answer because the buffer declares it and the
|
||||
// index holds it like any other module.
|
||||
let mut answer = |typed: &str| {
|
||||
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
|
||||
+ typed.len() as u32;
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let position = doc.positions().position(offset);
|
||||
items(completions(&ws, &uri, position, true))
|
||||
};
|
||||
for (typed, expected) in
|
||||
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
|
||||
{
|
||||
let items = answer(typed);
|
||||
let found: Vec<&str> =
|
||||
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
|
||||
assert_eq!(found, expected, "skeletons after typing {typed:?}");
|
||||
}
|
||||
|
||||
// …and the exact text one of them inserts, ports, defaults and all.
|
||||
let items = answer("");
|
||||
assert_eq!(
|
||||
inserted(find(&items, "sub").expect("the skeleton")),
|
||||
"\
|
||||
sub #(
|
||||
.WIDTH(${1:8})
|
||||
) ${2:u_sub} (
|
||||
.clk(clk),
|
||||
.data(${3:data}),
|
||||
.ready(${4:ready})
|
||||
);"
|
||||
);
|
||||
assert_eq!(
|
||||
inserted(find(&items, "alpha").expect("the skeleton")),
|
||||
"alpha ${1:u_alpha} (\n .clk(clk)\n );"
|
||||
);
|
||||
assert_eq!(
|
||||
inserted(find(&items, "submarine").expect("the skeleton")),
|
||||
"submarine ${1:u_submarine} ();"
|
||||
);
|
||||
}
|
||||
|
||||
/// A file edited on disk since the index last read it has moved every span
|
||||
/// the index holds, so the slice must not take one on trust.
|
||||
#[test]
|
||||
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
|
||||
let text =
|
||||
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
|
||||
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
|
||||
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
|
||||
// The same index against a file whose text has shifted underneath it.
|
||||
let moved = format!("// a line nobody told the index about\n{text}");
|
||||
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 0 — module hinting (M4, unchanged behaviour)
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1683,7 +2172,7 @@ endmodule
|
||||
filelist: Some("files.f".to_string()),
|
||||
..Default::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());
|
||||
ws.rebuild_index();
|
||||
@@ -1731,7 +2220,7 @@ endmodule
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus.clone()]);
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let build = started.elapsed();
|
||||
|
||||
// A buffer that is not on disk: it overlays the walk, so the corpus is
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -105,10 +105,15 @@ pub struct Rewrite {
|
||||
/// Rewrite every `` `include`` in the workspace that resolves to a file the
|
||||
/// client is about to rename.
|
||||
///
|
||||
/// The sweep reads the in-scope files (`Workspace::sources`, so an unopened
|
||||
/// file is read off disk and an open buffer contributes its unsaved text), and
|
||||
/// asks the include graph — never the filename — which of them point at
|
||||
/// something that moves.
|
||||
/// The sweep reads the files the include graph recorded an `` `include`` in
|
||||
/// (`Workspace::include_sources`, so an unopened one is read off disk and an
|
||||
/// open buffer contributes its unsaved text), and asks the include graph —
|
||||
/// never the filename — which of them point at something that moves.
|
||||
///
|
||||
/// It used to read *every* in-scope file, which on a 3 976-file workspace is
|
||||
/// 3 900-odd reads to answer "this file has no `` `include``". The graph
|
||||
/// already holds that answer; the argument that the smaller set gives the
|
||||
/// identical `Rewrite` is in `docs/features/file-operations/README.md`.
|
||||
pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
|
||||
let moves = Moves::announced(files);
|
||||
if moves.0.is_empty() {
|
||||
@@ -117,7 +122,7 @@ pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
|
||||
let graph = ws.includes();
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
let mut warnings = Vec::new();
|
||||
for (path, text) in ws.sources() {
|
||||
for (path, text) in ws.include_sources() {
|
||||
// The overwhelming majority of files include nothing; one substring
|
||||
// test each is what keeps this off the resolver for all of them.
|
||||
if !text.contains("`include") {
|
||||
@@ -520,7 +525,7 @@ mod tests {
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
ws.open_roots(vec![self.path.clone()]);
|
||||
ws.open_whole_workspace(vec![self.path.clone()]);
|
||||
ws
|
||||
}
|
||||
|
||||
@@ -542,6 +547,35 @@ mod tests {
|
||||
path_to_uri(path).expect("uri").as_str().to_string()
|
||||
}
|
||||
|
||||
/// The sufficiency property [`will_rename`]'s narrowed sweep rests on,
|
||||
/// asserted directly over whatever tree the caller built: every in-scope
|
||||
/// file the sweep no longer reads writes no `` `include`` this workspace
|
||||
/// can resolve, so its turn in the loop could only ever have `continue`d.
|
||||
///
|
||||
/// Checked as the complement rather than as an equality because it is the
|
||||
/// complement that could hide a lost edit: an extra file in the set costs
|
||||
/// a read, a missing one costs an `` `include`` left pointing at nothing.
|
||||
fn nothing_skipped_has_an_include_to_rewrite(ws: &Workspace) {
|
||||
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
|
||||
let graph = ws.includes();
|
||||
let mut skipped = 0usize;
|
||||
for (path, text) in ws.sources() {
|
||||
if read.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
skipped += 1;
|
||||
for include in scan(&text) {
|
||||
assert!(
|
||||
graph.resolve(Some(&path), &include).is_none(),
|
||||
"{} was skipped but its `include \"{}\"` resolves",
|
||||
path.display(),
|
||||
include.target
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(skipped > 0, "the tree must actually exercise the narrowing");
|
||||
}
|
||||
|
||||
/// The one file the rewrite touches, as (uri, the new path spellings).
|
||||
fn only_file(rewrite: &Rewrite) -> (String, Vec<String>) {
|
||||
let edit = rewrite.edit.as_ref().expect("an edit");
|
||||
@@ -579,6 +613,120 @@ mod tests {
|
||||
out
|
||||
}
|
||||
|
||||
/// A wide workspace where almost nothing includes anything — the shape a
|
||||
/// real one has, and the reason the sweep no longer reads all of it. The
|
||||
/// answer must be the one the whole-workspace sweep gave, and the property
|
||||
/// above must hold over the same tree.
|
||||
#[test]
|
||||
fn the_narrowed_sweep_reads_the_includers_and_answers_the_same() {
|
||||
let tree = Tree::new("narrowed");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
|
||||
let mut list = String::from("rtl/top.sv\nrtl/defs.svh\n");
|
||||
// Twenty files with no `include at all, plus two whose includes name
|
||||
// nothing on disk — both kinds are files the sweep may skip.
|
||||
for n in 0..20 {
|
||||
let rel = format!("rtl/quiet{n}.sv");
|
||||
tree.write(&rel, &format!("module quiet{n};\n wire w;\nendmodule\n"));
|
||||
list.push_str(&format!("{rel}\n"));
|
||||
}
|
||||
for n in 0..2 {
|
||||
let rel = format!("rtl/dangling{n}.sv");
|
||||
tree.write(&rel, &format!("`include \"no_such_{n}.svh\"\nmodule d{n};\nendmodule\n"));
|
||||
list.push_str(&format!("{rel}\n"));
|
||||
}
|
||||
tree.write("files.f", &list);
|
||||
let ws = tree.workspace();
|
||||
|
||||
assert_eq!(ws.sources().len(), 24, "the whole scope");
|
||||
assert_eq!(ws.include_sources().len(), 1, "only `top.sv` includes anything that lands");
|
||||
nothing_skipped_has_an_include_to_rewrite(&ws);
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
|
||||
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
|
||||
}
|
||||
|
||||
/// An `` `include`` typed into a buffer and not yet saved is in no edge the
|
||||
/// graph holds — the graph is rebuilt on save. The buffer is in the sweep
|
||||
/// whatever the graph says, which is what keeps that include rewritten.
|
||||
#[test]
|
||||
fn an_unsaved_include_is_still_rewritten() {
|
||||
let tree = Tree::new("unsaved_include");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
let top = tree.write("rtl/top.sv", "module t;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
|
||||
let mut ws = tree.workspace();
|
||||
assert_eq!(ws.include_sources().len(), 0, "premise: the graph knows of no include");
|
||||
|
||||
let buffered = "`include \"defs.svh\"\nmodule t;\nendmodule\n";
|
||||
ws.set_document(path_to_uri(&top).expect("uri"), buffered.to_string());
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
|
||||
assert_eq!(
|
||||
applied(buffered, &rewrite, &uri_of(&top)),
|
||||
"`include \"widths.svh\"\nmodule t;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// QA, 2026-08-28 attack: a chain `a.svh -> b.svh`. Renaming `b.svh` must
|
||||
/// narrow to `a.svh` (its *direct* includer, via `includers()`), and must
|
||||
/// **not** narrow away a file that includes `a.svh` but never spells
|
||||
/// `b.svh` at all — `will_rename` only ever rewrites a *direct* include of
|
||||
/// the file that moves, so a third-order includer has nothing to rewrite
|
||||
/// either way, but it must still not be mistaken for a candidate (which
|
||||
/// would cost a read, not a corruption, but is worth pinning).
|
||||
#[test]
|
||||
fn an_include_chain_narrows_to_the_direct_includer_of_the_moved_file() {
|
||||
let tree = Tree::new("chain");
|
||||
tree.write("rtl/b.svh", "`define W 8\n");
|
||||
let a = tree.write("rtl/a.svh", "`include \"b.svh\"\n");
|
||||
let c = tree.write("rtl/c.sv", "`include \"a.svh\"\nmodule c;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/a.svh\nrtl/b.svh\nrtl/c.sv\n");
|
||||
let ws = tree.workspace();
|
||||
|
||||
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
|
||||
assert!(read.contains(&a), "a.svh includes b.svh directly: {read:?}");
|
||||
assert!(read.contains(&c), "c.sv includes a.svh directly: {read:?}");
|
||||
nothing_skipped_has_an_include_to_rewrite(&ws);
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/b.svh", "rtl/renamed_b.svh")]);
|
||||
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
|
||||
// Only a.svh's own `include \"b.svh\"` line changes; c.sv's
|
||||
// `include \"a.svh\"` is untouched because a.svh itself did not move.
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&a), vec!["renamed_b.svh".to_string()]));
|
||||
}
|
||||
|
||||
/// QA, 2026-08-28 attack: an include spelled with different letter case
|
||||
/// than the file actually has on disk (`` `include "DEFS.svh"`` against a
|
||||
/// real `defs.svh`) — legal and silently resolved on the common
|
||||
/// case-insensitive filesystems (confirmed case-insensitive in this test
|
||||
/// environment). `IncludeGraph::found`/`found_as_if` resolve through the
|
||||
/// filesystem's own `Path::is_file`, so the includer still lands in `raw`
|
||||
/// (keyed by the *includer's* path, not the target's spelling) and
|
||||
/// therefore in `includers()`/`include_sources()` — the narrowing must not
|
||||
/// accidentally depend on the include's target spelling matching the
|
||||
/// disk's.
|
||||
#[test]
|
||||
fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() {
|
||||
let tree = Tree::new("case_mismatch");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
|
||||
let ws = tree.workspace();
|
||||
|
||||
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
|
||||
assert!(
|
||||
read.contains(&top),
|
||||
"top.sv's case-mismatched include still resolves and must narrow in: {read:?}"
|
||||
);
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
|
||||
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_directory_rename_keeps_the_bare_form() {
|
||||
let tree = Tree::new("samedir");
|
||||
@@ -599,6 +747,37 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Renaming a file that is open **on the large-file fast path**
|
||||
/// (`docs/features/large-file-mode/README.md`). The renamed file's own
|
||||
/// `` `include``s (it has none here — a netlist would not) are out of
|
||||
/// `will_rename`'s sweep because `Workspace::sources()` already leaves a
|
||||
/// fast-path buffer out entirely; what this pins is the other half: an
|
||||
/// **unrelated** small file's include *of* the large file still resolves
|
||||
/// and still gets rewritten, because resolution walks the filesystem
|
||||
/// (`IncludeGraph::resolve`, `Path::is_file`) rather than the source list
|
||||
/// the fast-path buffer was excluded from.
|
||||
#[test]
|
||||
fn renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it() {
|
||||
let tree = Tree::new("largerename");
|
||||
let net = tree.write("rtl/net.v", "module net;\nendmodule\n");
|
||||
let top = tree.write("rtl/top.sv", "`include \"net.v\"\nmodule t;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/top.sv\nrtl/net.v\n");
|
||||
let mut ws = tree.workspace();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
filelist: Some(tree.path.join("files.f").display().to_string()),
|
||||
large_file_threshold: 10,
|
||||
..Default::default()
|
||||
});
|
||||
let net_uri = path_to_uri(&net).expect("uri");
|
||||
// Padded past the 10-byte test threshold, so it opens on the fast path.
|
||||
ws.set_document(net_uri.clone(), format!("module net;\nendmodule\n{}", " ".repeat(20)));
|
||||
assert!(ws.document(&net_uri).expect("open").large, "premise: the fast path");
|
||||
|
||||
let rewrite = will_rename(&ws, &[tree.rename("rtl/net.v", "rtl/netlist.v")]);
|
||||
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
|
||||
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["netlist.v".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_directory_rename_re_spells_through_an_incdir() {
|
||||
let tree = Tree::new("crossdir");
|
||||
@@ -1055,7 +1234,7 @@ mod tests {
|
||||
// same read the index rebuild already pays on every save.
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![root.clone()]);
|
||||
ws.open_whole_workspace(vec![root.clone()]);
|
||||
let files = ws.index().files().len();
|
||||
assert!(files > 500, "the corpus is checked in: got {files}");
|
||||
let rename = FileRename {
|
||||
@@ -1401,7 +1580,7 @@ mod tests {
|
||||
let new = target_dir.join("prim_assert_renamed.sv");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![root.clone()]);
|
||||
ws.open_whole_workspace(vec![root.clone()]);
|
||||
let rename = FileRename { old_uri: uri_of(&old), new_uri: uri_of(&new) };
|
||||
|
||||
let run = || {
|
||||
|
||||
@@ -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, Site};
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
@@ -69,41 +71,49 @@ pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIn
|
||||
/// Who instantiates each of `names`, answered one list per name in the order
|
||||
/// asked.
|
||||
///
|
||||
/// 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 contains none of the names is skipped before it
|
||||
/// is parsed, which is what keeps the walk affordable: an instantiation of
|
||||
/// `fifo` has to write `fifo`.
|
||||
/// **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** is the primitive rather than the single name because
|
||||
/// [`Workspace::sources`] re-reads every in-scope file: one question per name
|
||||
/// would re-read the whole workspace once per name, and `lens.rs` asks about
|
||||
/// every module declared in a buffer at once. A file is parsed once for the
|
||||
/// whole batch.
|
||||
/// 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 searched for: nothing
|
||||
/// this server hands out is nameless, and the prefilter matches every file for
|
||||
/// one, which would parse the whole workspace to find nothing.
|
||||
/// 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();
|
||||
for (path, text) in ws.sources() {
|
||||
let wanted: Vec<usize> = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, name)| !name.is_empty() && text.contains(**name))
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(uri) = path_to_uri(&path) else { continue };
|
||||
let (tree, _) = parse_source_tolerant(&text);
|
||||
let sites = instantiations::sites(&tree.items);
|
||||
// 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 index in wanted {
|
||||
answers[index].extend(callers_in(&uri, &positions, &sites, names[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));
|
||||
}
|
||||
}
|
||||
for answer in &mut answers {
|
||||
@@ -152,31 +162,29 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOu
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every module in one already-parsed file that instantiates `name`, with its
|
||||
/// sites.
|
||||
/// 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,
|
||||
sites: &[Site<'a>],
|
||||
name: &str,
|
||||
edges: impl Iterator<Item = &'a InstantiationEdge>,
|
||||
) -> Vec<CallHierarchyIncomingCall> {
|
||||
let mut callers: Vec<(Decl<'a>, Vec<TextRange>)> = Vec::new();
|
||||
for site in sites {
|
||||
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])),
|
||||
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])),
|
||||
}
|
||||
}
|
||||
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(),
|
||||
})
|
||||
})
|
||||
@@ -186,20 +194,28 @@ fn callers_in<'a>(
|
||||
/// 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,
|
||||
@@ -335,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());
|
||||
@@ -527,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());
|
||||
|
||||
@@ -536,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");
|
||||
@@ -546,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");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -935,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,
|
||||
@@ -993,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,117 @@ 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
|
||||
@@ -164,10 +260,29 @@ impl IncludeGraph {
|
||||
from: Option<&Path>,
|
||||
include: &Include,
|
||||
exists: &dyn Fn(&Path) -> bool,
|
||||
) -> Option<PathBuf> {
|
||||
self.found_as_if(from, include, exists).map(|found| self.as_the_index_spells_it(found))
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::resolve`] as far as the *filesystem* answers it: the
|
||||
/// search rungs and `normalize`, without the index's own spelling.
|
||||
///
|
||||
/// The half of an edge that only a disk change can move, which is what the
|
||||
/// graph holds in `raw`.
|
||||
fn found(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
|
||||
self.found_as_if(from, include, &|path| path.is_file())
|
||||
}
|
||||
|
||||
/// [`IncludeGraph::found`] against a filesystem `exists` describes.
|
||||
fn found_as_if(
|
||||
&self,
|
||||
from: Option<&Path>,
|
||||
include: &Include,
|
||||
exists: &dyn Fn(&Path) -> bool,
|
||||
) -> Option<PathBuf> {
|
||||
let target = Path::new(&include.target);
|
||||
if target.is_absolute() {
|
||||
return exists(target).then(|| self.as_the_index_spells_it(normalize(target)));
|
||||
return exists(target).then(|| normalize(target));
|
||||
}
|
||||
let own = match include.system {
|
||||
true => None,
|
||||
@@ -177,7 +292,7 @@ impl IncludeGraph {
|
||||
.chain(self.incdirs.iter().map(PathBuf::as_path))
|
||||
.map(|dir| dir.join(target))
|
||||
.find(|candidate| exists(candidate))
|
||||
.map(|found| self.as_the_index_spells_it(normalize(&found)))
|
||||
.map(|found| normalize(&found))
|
||||
}
|
||||
|
||||
/// A resolved path, re-spelled the way the index spells that file.
|
||||
@@ -210,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.
|
||||
///
|
||||
@@ -229,6 +356,33 @@ impl IncludeGraph {
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Everything this graph answers with, as one deterministic string.
|
||||
///
|
||||
/// Test-only, and the witness for "a graph widened one folder at a time is
|
||||
/// the graph a whole rebuild would have produced": the two hash maps are
|
||||
/// rendered in sorted order, so the comparison is of the contents and never
|
||||
/// of the iteration order.
|
||||
#[cfg(test)]
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let mut out = format!("incdirs {:?}\n", self.incdirs);
|
||||
let mut known: Vec<&PathBuf> = self.known.iter().collect();
|
||||
known.sort();
|
||||
out.push_str(&format!("known {known:?}\n"));
|
||||
let mut folded: Vec<(&String, &Option<PathBuf>)> = self.folded.iter().collect();
|
||||
folded.sort();
|
||||
out.push_str(&format!("folded {folded:?}\n"));
|
||||
let mut edges: Vec<(&PathBuf, &Vec<PathBuf>)> = self.edges.iter().collect();
|
||||
edges.sort();
|
||||
out.push_str(&format!("edges {edges:?}\n"));
|
||||
// The unspelled edges too, so a widen that left a stale entry behind
|
||||
// fails here rather than waiting for the scope to grow far enough for
|
||||
// the spelling to notice.
|
||||
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
|
||||
raw.sort();
|
||||
out.push_str(&format!("raw {raw:?}\n"));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
|
||||
@@ -298,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() })
|
||||
}
|
||||
|
||||
@@ -541,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");
|
||||
@@ -735,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());
|
||||
|
||||
@@ -281,10 +281,13 @@ fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)>
|
||||
// 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)?;
|
||||
let last = doc.tokens.get(index)?;
|
||||
if last.span.end != offset {
|
||||
return None;
|
||||
@@ -412,6 +415,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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -25,8 +25,10 @@
|
||||
use lsp_types::{CodeLens, Command, Location, Uri};
|
||||
use serde_json::Value;
|
||||
|
||||
use vlog_semantic::instantiations;
|
||||
|
||||
use crate::hierarchy;
|
||||
use crate::state::Workspace;
|
||||
use crate::{hierarchy, instantiations};
|
||||
|
||||
/// Show every instantiation of a module: `[module-name]`.
|
||||
pub const SHOW_INSTANTIATIONS: &str = "lucisv.showInstantiations";
|
||||
@@ -179,7 +181,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());
|
||||
@@ -505,7 +507,7 @@ endmodule
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus]);
|
||||
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");
|
||||
@@ -567,7 +569,7 @@ endmodule
|
||||
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_roots(vec![tree_b.path.clone()]);
|
||||
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!(
|
||||
@@ -639,17 +641,73 @@ endmodule
|
||||
// the performance claim, measured
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// What a whole file's lenses cost over the real corpus, and — the point
|
||||
/// of the batch — that asking about three modules at once costs about what
|
||||
/// asking about one does, not three times as much.
|
||||
/// 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
|
||||
/// re-read the workspace once per declaration would fail the ratio.
|
||||
/// went back to re-reading the workspace would fail it by two.
|
||||
#[test]
|
||||
fn code_lenses_for_a_whole_file_cost_about_one_workspace_walk() {
|
||||
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");
|
||||
@@ -663,14 +721,17 @@ endmodule
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus]);
|
||||
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.
|
||||
// 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();
|
||||
@@ -680,18 +741,21 @@ endmodule
|
||||
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 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 < one_name * 2,
|
||||
"the batch is one walk, not one per module: {count} names cost {whole_file:?} \
|
||||
against {one_name:?} for one"
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,6 +10,7 @@ mod candidates;
|
||||
mod code_action;
|
||||
mod completion;
|
||||
mod convert;
|
||||
mod design_hierarchy;
|
||||
mod diagnostics;
|
||||
mod expand;
|
||||
mod file_ops;
|
||||
@@ -18,9 +19,10 @@ 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;
|
||||
@@ -28,6 +30,8 @@ mod locate;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
#[cfg(test)]
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod selection;
|
||||
@@ -61,10 +65,39 @@ use lsp_types::{
|
||||
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()?;
|
||||
@@ -72,6 +105,11 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
// 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();
|
||||
@@ -85,14 +123,50 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
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, 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.
|
||||
@@ -374,6 +448,29 @@ 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
|
||||
@@ -404,6 +501,26 @@ fn apply_edit_support(params: &InitializeParams) -> bool {
|
||||
.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
|
||||
@@ -495,6 +612,68 @@ fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`verbose_flag`] over what a spawn would really hand it.
|
||||
fn args(args: &[&str]) -> Result<bool, String> {
|
||||
verbose_flag(args.iter().map(|arg| (*arg).to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_arguments_is_the_spawn_every_editor_has_always_used() {
|
||||
assert_eq!(args(&[]), Ok(false), "and it must never become verbose by accident");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_one_flag_is_the_one_spelling() {
|
||||
assert_eq!(args(&["--verbose"]), Ok(true));
|
||||
// Twice says the same thing twice.
|
||||
assert_eq!(args(&["--verbose", "--verbose"]), Ok(true));
|
||||
// Every near miss is refused, `-v` included: one spelling, so a client
|
||||
// that guessed is told rather than silently given nothing.
|
||||
for wrong in ["-v", "--Verbose", "--verbos", "verbose", "--verbose=true", "--help"] {
|
||||
assert_eq!(args(&[wrong]), Err(wrong.to_string()), "{wrong} is not the flag");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_is_accepted_as_the_statement_of_fact_it_is() {
|
||||
// `vscode-languageclient` appends `--stdio` for TransportKind.stdio —
|
||||
// the spawn every real VS Code session actually makes. Rejecting it
|
||||
// crashed the extension five times and gave up (lead hotfix,
|
||||
// 2026-08-29); it must parse in every combination and change nothing.
|
||||
assert_eq!(args(&["--stdio"]), Ok(false));
|
||||
assert_eq!(args(&["--stdio", "--verbose"]), Ok(true));
|
||||
assert_eq!(args(&["--verbose", "--stdio"]), Ok(true));
|
||||
assert_eq!(args(&["--stdio", "--stdio"]), Ok(false));
|
||||
// And a near miss of IT is still refused.
|
||||
assert_eq!(args(&["--Stdio"]), Err("--Stdio".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_argument_we_do_not_take_is_the_one_reported() {
|
||||
// Named, so the message can say which word was wrong — the whole
|
||||
// reason this refuses instead of ignoring.
|
||||
assert_eq!(args(&["--verbose", "--colour"]), Err("--colour".to_string()));
|
||||
assert_eq!(args(&["--colour", "--verbose"]), Err("--colour".to_string()));
|
||||
assert_eq!(args(&["/some/file.sv"]), Err("/some/file.sv".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extension_ships_the_flag_off_which_is_what_no_argument_means() {
|
||||
// The two halves of the contract live in different languages: the
|
||||
// manifest's default decides whether `extension.js` puts `--verbose`
|
||||
// in the spawn arguments, and `verbose_flag` decides what the server
|
||||
// does with the arguments it gets. They must agree that the shipped
|
||||
// state is off.
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../editors/vscode/package.json");
|
||||
let text = std::fs::read_to_string(&path).expect("the extension manifest");
|
||||
let manifest: serde_json::Value = serde_json::from_str(&text).expect("valid json");
|
||||
let verbose = &manifest["contributes"]["configuration"]["properties"]["lucisv.verbose"];
|
||||
assert_eq!(verbose["type"], serde_json::json!("boolean"), "{verbose:#?}");
|
||||
assert_eq!(verbose["default"], serde_json::json!(false), "{verbose:#?}");
|
||||
assert_eq!(args(&[]), Ok(false), "which is what the server does with no argument");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_advertised_capability_is_implemented() {
|
||||
let caps = capabilities();
|
||||
@@ -677,6 +856,20 @@ mod tests {
|
||||
assert!(!ranges_formatting_support(&serde_json::Value::Null));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hierarchy_notifications_are_an_explicit_initialization_option() {
|
||||
let saying = serde_json::json!({ "initializationOptions": { "hierarchyView": true } });
|
||||
assert!(hierarchy_view_support(&saying));
|
||||
for silent in [
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({ "initializationOptions": { "hierarchyView": false } }),
|
||||
serde_json::json!({ "initializationOptions": { "hierarchyView": "yes" } }),
|
||||
serde_json::Value::Null,
|
||||
] {
|
||||
assert!(!hierarchy_view_support(&silent), "{silent:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() {
|
||||
// The gate's whole point: every client that shipped before this round
|
||||
|
||||
+918
-36
File diff suppressed because it is too large.
Load diff
@@ -26,7 +26,7 @@ use vlog_parser::token::{Token, TokenKind};
|
||||
|
||||
use crate::format;
|
||||
use crate::pairs;
|
||||
use crate::state::Document;
|
||||
use crate::state::{first_token_from, first_token_reaching, Document};
|
||||
|
||||
/// The character the client is told to trigger on. A newline is the one
|
||||
/// keystroke that opens a line whose indentation nobody has chosen yet.
|
||||
@@ -71,8 +71,14 @@ fn statement_edit(doc: &Document, position: Position, config: &Config) -> Option
|
||||
let offset = doc.positions().offset(position);
|
||||
// The character the client named has to actually be there, and it has to
|
||||
// be a `;` the lexer sees: one inside a string or a comment ends no
|
||||
// statement, and re-laying-out its line would be a guess.
|
||||
let typed = doc.tokens.iter().find(|token| token.span.end == offset)?;
|
||||
// statement, and re-laying-out its line would be a guess. A token that
|
||||
// ends exactly at `offset` is the first one that *reaches* it — everything
|
||||
// before ends earlier, everything after ends later — so a binary search
|
||||
// finds what the sweep this replaced found.
|
||||
let typed = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|t| t.span.end == offset)?;
|
||||
if !typed.is_sym(SEMICOLON) {
|
||||
return None;
|
||||
}
|
||||
@@ -264,9 +270,12 @@ fn inside_a_comment(token: &Token, at: u32) -> bool {
|
||||
/// line the user has just opened has none.
|
||||
fn first_on_line(doc: &Document, content: u32) -> Option<&Token> {
|
||||
let line = doc.line_index.line_col(content).0;
|
||||
doc.tokens
|
||||
// Every token before this index starts before `content`, so none of them
|
||||
// could have satisfied the sweep this replaced; within the tail the sweep's
|
||||
// remaining condition is the `Eof` test alone.
|
||||
doc.tokens[first_token_from(&doc.tokens, content)..]
|
||||
.iter()
|
||||
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
|
||||
.find(|token| token.kind != TokenKind::Eof)
|
||||
.filter(|token| doc.line_index.line_col(token.span.start).0 == line)
|
||||
}
|
||||
|
||||
@@ -646,6 +655,43 @@ mod tests {
|
||||
f(ws.document(&uri).expect("open"))
|
||||
}
|
||||
|
||||
/// The `;` handler used to sweep the token vector for the token ending at
|
||||
/// the cursor. Every byte of a buffer full of touching tokens must still
|
||||
/// name the same token — or no token, where the sweep found none.
|
||||
#[test]
|
||||
fn the_token_ending_at_the_cursor_is_the_one_the_sweep_returned() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
with(&text, |doc| {
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc.tokens.iter().find(|token| token.span.end == offset);
|
||||
let searched = doc
|
||||
.tokens
|
||||
.get(first_token_reaching(&doc.tokens, offset))
|
||||
.filter(|t| t.span.end == offset);
|
||||
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The same, for the indent handler's "first token at or after this byte":
|
||||
/// [`first_on_line`] is compared against the sweep it was written as.
|
||||
#[test]
|
||||
fn the_first_token_on_a_line_is_the_one_the_sweep_returned() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
with(&text, |doc| {
|
||||
for content in 0..=text.len() as u32 {
|
||||
let line = doc.line_index.line_col(content).0;
|
||||
let swept = doc
|
||||
.tokens
|
||||
.iter()
|
||||
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
|
||||
.filter(|token| doc.line_index.line_col(token.span.start).0 == line);
|
||||
let searched = first_on_line(doc, content);
|
||||
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at byte {content}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn config(indent_width: usize) -> Config {
|
||||
Config { indent_width, ..Config::default() }
|
||||
}
|
||||
|
||||
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| {
|
||||
@@ -84,7 +87,6 @@ pub fn execute(
|
||||
command: &str,
|
||||
arguments: &[Value],
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let sources = ws.sources();
|
||||
let refactoring = match command {
|
||||
ADD_PORT => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
@@ -93,10 +95,12 @@ pub fn execute(
|
||||
})?;
|
||||
match module_argument(arguments.get(1)) {
|
||||
ModuleArgument::Name(name) => {
|
||||
let sources = ws.module_sources(&path, std::slice::from_ref(&name));
|
||||
vlog_refactor::add_port(&sources, ModuleRef::Name(&name), decl)?
|
||||
}
|
||||
ModuleArgument::Position(position) => {
|
||||
let offset = offset_of(ws, arguments.first(), position)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::add_port(&sources, ModuleRef::At { file: &path, offset }, decl)?
|
||||
}
|
||||
ModuleArgument::Missing => {
|
||||
@@ -109,11 +113,13 @@ pub fn execute(
|
||||
REMOVE_PORT => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, REMOVE_PORT)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::remove_port(&sources, &path, offset)?
|
||||
}
|
||||
PROPAGATE_PORTS => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, PROPAGATE_PORTS)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::propagate_ports(&sources, &path, offset)?
|
||||
}
|
||||
other => return Err(format!("`{other}` is not a lucisv command.")),
|
||||
@@ -121,6 +127,22 @@ pub fn execute(
|
||||
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
|
||||
}
|
||||
|
||||
/// The files a port refactoring **at a position** reads: the fan-out of every
|
||||
/// module that position could name.
|
||||
///
|
||||
/// A command's position is looser than a code action's — `lucisv.addPort`
|
||||
/// takes one anywhere in the module it adds to — so the module the cursor sits
|
||||
/// *inside* is asked for as well as the ones its port element or its
|
||||
/// instantiation names. Both questions are the engine's own
|
||||
/// (`vlog_refactor`), so the set cannot drift from what the engine will then
|
||||
/// go looking for.
|
||||
fn sources_at(ws: &Workspace, path: &Path, offset: u32) -> Vec<(PathBuf, String)> {
|
||||
let Some(text) = ws.text_of(path) else { return ws.module_sources(path, &[]) };
|
||||
let mut modules = vlog_refactor::port_action_modules(&text, offset);
|
||||
modules.extend(vlog_refactor::enclosing_module(&text, offset));
|
||||
ws.module_sources(path, &modules)
|
||||
}
|
||||
|
||||
/// What the second argument of `lucisv.addPort` said.
|
||||
enum ModuleArgument {
|
||||
Name(String),
|
||||
@@ -244,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());
|
||||
@@ -323,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![
|
||||
@@ -357,6 +379,429 @@ mod tests {
|
||||
assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the answer is the whole workspace's answer, computed over a subset
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One action's title and the edits it carries, per file in path order.
|
||||
type Shape = (String, Vec<(String, Vec<String>)>);
|
||||
|
||||
/// A code action as a comparable value: its title and every edit it
|
||||
/// carries, per file in path order — the whole of what a client receives.
|
||||
/// `WorkspaceEdit.changes` is a `HashMap`, so it is sorted here rather
|
||||
/// than compared as it is stored.
|
||||
fn shape(actions: &[CodeActionOrCommand]) -> Vec<Shape> {
|
||||
actions
|
||||
.iter()
|
||||
.map(|action| {
|
||||
let CodeActionOrCommand::CodeAction(action) = action else {
|
||||
return ("a command".to_string(), Vec::new());
|
||||
};
|
||||
let mut changes: Vec<(String, Vec<String>)> = action
|
||||
.edit
|
||||
.as_ref()
|
||||
.and_then(|edit| edit.changes.as_ref())
|
||||
.map(|changes| {
|
||||
changes
|
||||
.iter()
|
||||
.map(|(uri, edits)| {
|
||||
let edits = edits
|
||||
.iter()
|
||||
.map(|edit| format!("{:?}{}", edit.range, edit.new_text))
|
||||
.collect();
|
||||
(uri.as_str().to_string(), edits)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
changes.sort();
|
||||
(action.title.clone(), changes)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What `code_actions` used to compute: the same engine call over every
|
||||
/// in-scope file. The equivalence tests below assert the new answer
|
||||
/// against this one rather than against a transcription of it.
|
||||
fn whole_workspace_at(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let doc = ws.document(uri).expect("an open document");
|
||||
let path = doc.path.clone().expect("a saved file");
|
||||
let sources = ws.sources();
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
.into_iter()
|
||||
.filter_map(|action| {
|
||||
let edit = workspace_edit(ws, &action.edit).ok()?;
|
||||
Some(CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: action.title,
|
||||
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
|
||||
edit: Some(edit),
|
||||
..Default::default()
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A workspace of `noise` files that have nothing to do with `sub`, plus
|
||||
/// `sub.sv` and three files that instantiate it.
|
||||
fn crowded(tree: &Tree, noise: usize) -> Workspace {
|
||||
tree.write("sub.sv", SUB);
|
||||
for n in 0..3 {
|
||||
tree.write(
|
||||
&format!("top{n}.sv"),
|
||||
&format!(
|
||||
"module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
for n in 0..noise {
|
||||
tree.write(
|
||||
&format!("noise{n}.sv"),
|
||||
&format!("module noise{n};\n logic a;\n wire b;\n assign b = a;\nendmodule\n"),
|
||||
);
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
ws
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_code_action_answers_what_the_whole_workspace_would() {
|
||||
let tree = Tree::new("equivalence");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
assert_eq!(subset.len(), 1, "{subset:#?}");
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
assert_eq!(action.title, "lucisv: remove port `rst` (updates 3 instantiations)");
|
||||
assert_eq!(
|
||||
shape(&subset),
|
||||
shape(&whole_workspace_at(&ws, &sub_uri, offset)),
|
||||
"the subset must answer exactly what every file would have"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_files_a_code_action_reads_are_the_modules_own_fan_out() {
|
||||
let tree = Tree::new("fanout");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
|
||||
assert_eq!(ws.sources().len(), 44, "the whole workspace");
|
||||
let read = ws.module_sources(&sub, &["sub".to_string()]);
|
||||
let mut names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["sub.sv", "top0.sv", "top1.sv", "top2.sv"], "and not one noise file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen() {
|
||||
let tree = Tree::new("unsaved");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
// A file the index knows as instantiating nothing, whose buffer now
|
||||
// instantiates `sub`. No save, so no edge in the index.
|
||||
let extra = tree.path.join("noise0.sv");
|
||||
let extra_uri = path_to_uri(&extra).expect("uri");
|
||||
let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n";
|
||||
ws.set_document(extra_uri.clone(), typed.to_string());
|
||||
assert!(
|
||||
ws.index()
|
||||
.instantiations_of("sub")
|
||||
.iter()
|
||||
.all(|edge| ws.index().path(edge.file) != Some(extra.as_path())),
|
||||
"the index has not seen the unsaved instantiation"
|
||||
);
|
||||
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
assert_eq!(action.title, "lucisv: remove port `rst` (updates 4 instantiations)");
|
||||
let edit = action.edit.as_ref().expect("an edit");
|
||||
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
|
||||
assert_eq!(shape(&subset), shape(&whole_workspace_at(&ws, &sub_uri, offset)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_refused_through_the_subset_as_well() {
|
||||
let tree = Tree::new("ambiguous");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
// A second declaration of `sub`, in a file nothing else names.
|
||||
tree.write("clone.sv", SUB);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().units("sub").len(), 2, "two declarations");
|
||||
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
// Both definers are in the set, so the engine sees the ambiguity and
|
||||
// refuses — which is no action, exactly as over the whole workspace.
|
||||
assert!(ws
|
||||
.module_sources(&sub, &["sub".to_string()])
|
||||
.iter()
|
||||
.any(|(path, _)| path.ends_with("clone.sv")));
|
||||
assert!(code_actions(&ws, &sub_uri, offset).is_empty());
|
||||
assert!(whole_workspace_at(&ws, &sub_uri, offset).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_computes_over_the_subset_and_answers_the_same() {
|
||||
let tree = Tree::new("command");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&sub_uri).expect("uri"),
|
||||
Value::String("sub".into()),
|
||||
Value::String("input logic cfg".into()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
|
||||
let whole =
|
||||
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
|
||||
.expect("adds");
|
||||
assert_eq!(warnings, whole.warnings);
|
||||
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
|
||||
assert_eq!(edit.changes.as_ref().expect("changes").len(), 4, "sub.sv and its three tops");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_file_scope_instantiation_lands_in_the_subset() {
|
||||
let tree = Tree::new("qa_filescope");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
// A file-scope (owner-less) instantiation of `sub` — illegal SV, but
|
||||
// a tolerant parse still produces an Instantiation item, and the old
|
||||
// whole-workspace engine would still edit it (collect_instantiations
|
||||
// walks tree.items directly). It records no InstantiationEdge (edges_of
|
||||
// requires an owner), so only the references_to half of rung 3 can
|
||||
// possibly find it.
|
||||
let filescope_path = tree.write("filescope.sv", "sub u_fs (.clk(c), .rst(r));\n");
|
||||
ws.rebuild_index();
|
||||
assert!(
|
||||
ws.index()
|
||||
.instantiations_of("sub")
|
||||
.iter()
|
||||
.all(|edge| ws.index().path(edge.file) != Some(filescope_path.as_path())),
|
||||
"file-scope site records no edge, as documented"
|
||||
);
|
||||
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
|
||||
let read = ws.module_sources(&sub, &["sub".to_string()]);
|
||||
let names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert!(
|
||||
names.contains(&"filescope.sv".to_string()),
|
||||
"file-scope instantiation site must be in the subset: {names:?}"
|
||||
);
|
||||
|
||||
// And the whole-workspace engine really would have edited it, so
|
||||
// omitting it from the subset would be a real divergence.
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let whole = whole_workspace_at(&ws, &sub_uri, offset);
|
||||
let CodeActionOrCommand::CodeAction(action) = &whole[0] else { panic!("an action") };
|
||||
let edit = action.edit.as_ref().expect("an edit");
|
||||
let fs_uri = path_to_uri(&filescope_path).expect("uri");
|
||||
assert_eq!(
|
||||
edits_for(edit, &fs_uri).len(),
|
||||
2,
|
||||
"the whole-workspace answer edits the file-scope site"
|
||||
);
|
||||
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption() {
|
||||
// The subset builder trusts the index for rungs 2/3, so a file that
|
||||
// changed on disk with nothing telling the server (no rebuild_index,
|
||||
// no didChange) is invisible to it — unlike the old `sources()` path,
|
||||
// which re-reads the directory fresh every call. Attack: write a
|
||||
// *second* definer of `sub` straight to disk, do NOT reindex, and
|
||||
// fire a code action. Judged against invariant 1 (never corrupt), not
|
||||
// against freshness: an answer that goes stale (or a refusal) is
|
||||
// fine; an edit that is not internally verified would not be.
|
||||
let tree = Tree::new("qa_stale_dup");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
// Sanity: before the duplicate exists anywhere, the subset offers the
|
||||
// action normally.
|
||||
assert_eq!(code_actions(&ws, &sub_uri, offset).len(), 1);
|
||||
|
||||
// Write a duplicate declaration straight to disk, bypassing the
|
||||
// server entirely (no rebuild_index, no set_document for this path).
|
||||
tree.write("dupe.sv", SUB);
|
||||
|
||||
// The index still knows only one definer, so the subset the server
|
||||
// computes is unaware of the ambiguity and still offers the action.
|
||||
assert_eq!(ws.index().units("sub").len(), 1, "the index has not been told");
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
assert_eq!(subset.len(), 1, "stale, but not refused — the index has not seen dupe.sv");
|
||||
|
||||
// The critical assertion: whatever it produced must still be an
|
||||
// honest, self-consistent, verified edit over the files it actually
|
||||
// read — not corruption of a file it never looked at. `dupe.sv`
|
||||
// itself must be untouched (never read, never in the edit) and the
|
||||
// edit that *was* produced must still verify against what changed.
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
let dupe_uri = path_to_uri(&tree.path.join("dupe.sv")).expect("uri");
|
||||
let edit = action.edit.as_ref().expect("an edit");
|
||||
assert!(
|
||||
edit.changes.as_ref().is_none_or(|c| !c.contains_key(&dupe_uri)),
|
||||
"the unindexed duplicate must not be touched: {edit:?}"
|
||||
);
|
||||
|
||||
// Once the index is told (rebuild_index, exactly what the watcher
|
||||
// does on a save it's told about), parity is restored: the subset
|
||||
// now sees the duplicate and refuses, exactly like the whole
|
||||
// workspace always would have.
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().units("sub").len(), 2, "now indexed");
|
||||
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "refuses once told");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_generate_block_instantiation_lands_in_the_subset() {
|
||||
let tree = Tree::new("qa_generate");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
let gen_path = tree.write(
|
||||
"gen.sv",
|
||||
"module gen;\n genvar i;\n generate\n for (i = 0; i < 2; i = i + 1) begin : g\n logic c, r;\n sub u_g (.clk(c), .rst(r));\n end\n endgenerate\nendmodule\n",
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert!(
|
||||
ws.index()
|
||||
.instantiations_of("sub")
|
||||
.iter()
|
||||
.any(|edge| ws.index().path(edge.file) == Some(gen_path.as_path())),
|
||||
"the generate-for body instantiation is a real edge"
|
||||
);
|
||||
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let read = ws.module_sources(&sub, &["sub".to_string()]);
|
||||
let names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert!(names.contains(&"gen.sv".to_string()), "{names:?}");
|
||||
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
let whole = whole_workspace_at(&ws, &sub_uri, offset);
|
||||
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_escaped_module_name_instantiation_parity_with_whole_workspace() {
|
||||
// Not a subset-specific question: does an escaped-identifier
|
||||
// instantiation (`\sub$weird u1 (...)`) even resolve to the module it
|
||||
// names, workspace-index-wise, so the subset builder's `units`/
|
||||
// `instantiations_of`/`references_to` lookups have anything to find?
|
||||
// Attacking whether the *subset* diverges from the *whole-workspace*
|
||||
// answer here, not whether escaped identifiers work at all (a
|
||||
// pre-existing question this round did not touch).
|
||||
let tree = Tree::new("qa_escaped");
|
||||
tree.write("esc.sv", "module esc;\n \\sub u_esc (.clk(c), .rst(r));\nendmodule\n");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let subset = code_actions(&ws, &sub_uri, offset);
|
||||
let whole = whole_workspace_at(&ws, &sub_uri, offset);
|
||||
// Whichever way the parser/binder treats the escaped identifier
|
||||
// `\sub ` (as `sub`, or as a distinct name), the subset and the
|
||||
// whole-workspace computation must agree either way.
|
||||
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_add_port_by_position_still_fans_out_to_instantiation_files() {
|
||||
// `a_command_computes_over_the_subset_and_answers_the_same` (the
|
||||
// dev's own equivalence test) drives `lucisv.addPort` with a
|
||||
// *module-name* argument. The *Position* argument takes a completely
|
||||
// different path to the module (`sources_at` → `port_action_modules`
|
||||
// + `enclosing_module`, rather than `module_sources` fed the name
|
||||
// directly) and is exactly the code action's own code path
|
||||
// (`ModuleArgument::Position` mirrors `ModuleRef::At`). Confirm it
|
||||
// still reaches every instantiating file, not just the declaring one.
|
||||
let tree = Tree::new("qa_add_by_position");
|
||||
let mut ws = crowded(&tree, 30);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&sub_uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
|
||||
Value::String("input logic cfg".into()),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
|
||||
assert_eq!(warnings.len(), 3, "one TODO warning per instantiating top: {warnings:?}");
|
||||
let changes = edit.changes.as_ref().expect("changes");
|
||||
assert_eq!(changes.len(), 4, "sub.sv and its three instantiating tops: {changes:?}");
|
||||
for n in 0..3 {
|
||||
let top_uri = path_to_uri(&tree.path.join(format!("top{n}.sv"))).expect("uri");
|
||||
assert_eq!(edits_for(&edit, &top_uri).len(), 1, "top{n}.sv must gain the connection");
|
||||
}
|
||||
|
||||
let whole =
|
||||
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
|
||||
.expect("adds");
|
||||
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled() {
|
||||
// A module the index has never seen at all — not stale, genuinely
|
||||
// absent, e.g. a brand-new buffer the user has not saved yet. Rung 2
|
||||
// (`index.units`) has nothing; only rung 1 (the request's own file)
|
||||
// can supply it. The cursor sits in that same new buffer, so rung 1
|
||||
// must be enough on its own — and it must not panic or silently
|
||||
// return no action just because the index is empty for this name.
|
||||
let tree = Tree::new("qa_unsaved_new_module");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.index().units("brandnew").is_empty(), "the index has never heard of it");
|
||||
|
||||
let text = "module brandnew (\n input logic a,\n input logic b\n);\nendmodule\n";
|
||||
let new_path = tree.path.join("brandnew.sv"); // never written to disk
|
||||
let new_uri = path_to_uri(&new_path).expect("uri");
|
||||
ws.set_document(new_uri.clone(), text.to_string());
|
||||
|
||||
let offset = text.find("input logic b").expect("b") as u32 + 12;
|
||||
let subset = code_actions(&ws, &new_uri, offset);
|
||||
assert_eq!(subset.len(), 1, "{subset:#?}");
|
||||
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
|
||||
assert_eq!(action.title, "lucisv: remove port `b` (no instantiation in scope)");
|
||||
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_command_is_declined() {
|
||||
let tree = Tree::new("unknown");
|
||||
|
||||
@@ -24,10 +24,20 @@ use crate::uri::path_to_uri;
|
||||
/// The identifier at `offset` and its current name, or the reason it cannot
|
||||
/// be renamed. Returning the reason — rather than `null` — is what puts the
|
||||
/// engine's sentence in the editor's rename box instead of a shrug.
|
||||
///
|
||||
/// Answered from the buffer's own analysis and the index alone: no file is
|
||||
/// read, nothing is parsed. This request is what the rename key sends before
|
||||
/// the rename box even opens, and reading the workspace for it froze the whole
|
||||
/// server for 2.5–3.0 s on OpenTitan. Which refusals that costs — and which of
|
||||
/// them `rename` then delivers instead — is the table in
|
||||
/// `docs/features/refactor-rename/README.md`.
|
||||
pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameResponse, String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?;
|
||||
if doc.path.is_none() {
|
||||
return Err(UNSAVED.to_string());
|
||||
}
|
||||
let target =
|
||||
vlog_refactor::prepare_rename_here(&doc.semantics, &doc.external, ws.index(), offset)?;
|
||||
Ok(PrepareRenameResponse::RangeWithPlaceholder {
|
||||
range: doc.positions().range(target.range),
|
||||
placeholder: target.name,
|
||||
@@ -44,7 +54,16 @@ pub fn rename(
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
let refactoring = vlog_refactor::rename(&ws.sources(), &path, offset, new_name)?;
|
||||
// The name the cursor sits on, read off the buffer, is what the index is
|
||||
// asked for the fan-out. No refusal is taken here: `vlog_refactor::rename`
|
||||
// is the one voice that decides, and it decides over the files below. A
|
||||
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
|
||||
// the engine will say so, and saying it is cheap either way.
|
||||
let sources = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(&path, &name, Some(new_name)),
|
||||
None => ws.sources(),
|
||||
};
|
||||
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
|
||||
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
for (path, edits) in &refactoring.edits {
|
||||
@@ -80,7 +99,7 @@ const UNSAVED: &str = "lucisv can only rename inside a saved file.";
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
@@ -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());
|
||||
|
||||
@@ -13,7 +13,7 @@ use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind}
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::pairs::analyze;
|
||||
use crate::state::Document;
|
||||
use crate::state::{first_token_reaching, Document};
|
||||
|
||||
/// One chain per requested position, in the order they were asked for.
|
||||
///
|
||||
@@ -41,7 +41,17 @@ fn chain(doc: &Document, offset: u32) -> SelectionRange {
|
||||
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
|
||||
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
|
||||
let mut spans = Vec::new();
|
||||
if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) {
|
||||
// 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);
|
||||
@@ -219,6 +229,26 @@ mod tests {
|
||||
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> {
|
||||
|
||||
+3381
-182
File diff suppressed because it is too large.
Load diff
@@ -28,6 +28,58 @@ 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
|
||||
@@ -36,8 +88,11 @@ 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>,
|
||||
@@ -60,6 +115,72 @@ pub struct ClientSettings {
|
||||
/// 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,
|
||||
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.
|
||||
@@ -78,6 +199,15 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// 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(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),
|
||||
@@ -88,6 +218,48 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,6 +323,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.
|
||||
@@ -183,11 +365,174 @@ mod tests {
|
||||
"exclude": exclude,
|
||||
"filelist": "",
|
||||
"inlineTemplates": true,
|
||||
"formatOnSave": false
|
||||
"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" } }));
|
||||
@@ -211,6 +556,29 @@ 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"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_vscode_payload_is_no_opinion_about_anything() {
|
||||
// Every setting at its `package.json` default: nulls and an empty
|
||||
|
||||
@@ -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;
|
||||
|
||||
+4436
-88
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();
|
||||
|
||||
@@ -121,18 +121,35 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
|
||||
encode(&within(absolute(doc), range))
|
||||
}
|
||||
|
||||
/// The tokens a range covers of a buffer nothing has lexed — the large-file
|
||||
/// fast path's answer to `semanticTokens/range`.
|
||||
///
|
||||
/// Identical to [`semantic_tokens_in_range`] in everything the client can see:
|
||||
/// the same classification, the same line splitting, the same encoding from
|
||||
/// the start of the document, the same overlap filter. The only difference is
|
||||
/// where the tokens come from — `large::window` lexes the window instead of
|
||||
/// the document's own (empty) token stream — and that a plain identifier can
|
||||
/// only ever be `variable`, because there is no `Semantics` to refine it with.
|
||||
/// See `docs/features/large-file-mode/README.md`.
|
||||
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
let window = crate::large::window(doc, range);
|
||||
let mut pieces = Vec::new();
|
||||
// The comment spans the lexer never saw go in first; `flatten` sorts, so
|
||||
// the order they are collected in cannot reach the wire.
|
||||
for span in &window.comments {
|
||||
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
for token in &window.tokens {
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
}
|
||||
encode(&within(flatten(pieces, doc), range))
|
||||
}
|
||||
|
||||
/// Classify the whole buffer, split at line boundaries, in wire order.
|
||||
fn absolute(doc: &Document) -> Vec<Absolute> {
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect_trivia(token, &mut pieces);
|
||||
if let Some(ty) = classify(token, &doc.semantics) {
|
||||
pieces.push(Piece {
|
||||
span: token.span,
|
||||
ty,
|
||||
modifiers: modifiers(token, &doc.semantics),
|
||||
});
|
||||
}
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
}
|
||||
flatten(pieces, doc)
|
||||
}
|
||||
@@ -151,13 +168,22 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect()
|
||||
}
|
||||
|
||||
/// One token's pieces: its comments and the token itself.
|
||||
///
|
||||
/// Comments live as trivia on the token that follows (or, for a trailing
|
||||
/// comment, precedes) them — including on the EOF token, which is what makes
|
||||
/// a comment at the end of the file reachable.
|
||||
fn collect_trivia(token: &Token, out: &mut Vec<Piece>) {
|
||||
/// a comment at the end of the file reachable. They are pushed **in source
|
||||
/// order** — leading comments, the token, then the trailing comment that sits
|
||||
/// after it on the same line — because [`flatten`] converts the offsets with a
|
||||
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
|
||||
/// and no two pieces here can start at the same byte.
|
||||
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
|
||||
for comment in &token.leading {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
if let Some(ty) = classify(token, semantics) {
|
||||
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
@@ -233,11 +259,18 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
/// multi-line macro invocation.
|
||||
fn flatten(pieces: Vec<Piece>, doc: &Document) -> Vec<Absolute> {
|
||||
let positions = doc.positions();
|
||||
// The pieces arrive in source order (see [`collect`]), so one monotonic
|
||||
// cursor measures each line once however many tokens sit on it. The
|
||||
// per-call converter re-measures from the line's start every time, which
|
||||
// is quadratic on a netlist's single million-byte line — seconds per
|
||||
// viewport, measured. Out-of-order pieces (the fast path's window-edge
|
||||
// comments) are answered identically, just without the saving.
|
||||
let mut walker = positions.walker();
|
||||
let mut flat: Vec<Absolute> = Vec::new();
|
||||
for piece in pieces {
|
||||
for line_span in split_lines(&doc.text, piece.span) {
|
||||
let start = positions.position(line_span.start);
|
||||
let end = positions.position(line_span.end);
|
||||
let start = walker.position(line_span.start);
|
||||
let end = walker.position(line_span.end);
|
||||
if end.character <= start.character {
|
||||
continue;
|
||||
}
|
||||
@@ -435,6 +468,44 @@ mod tests {
|
||||
assert_eq!(comments[1].0, 3);
|
||||
}
|
||||
|
||||
/// QA (fix-round re-verification): `collect_trivia` became `collect`,
|
||||
/// folding two callers' duplicated classify-and-push into one function
|
||||
/// that pushes a token's own piece *between* its leading comments and its
|
||||
/// trailing one. A single token flanked by both is the shape that
|
||||
/// exercises every branch of that function on one token, and `flatten`'s
|
||||
/// stable sort means the exact byte offsets have to be right regardless
|
||||
/// of the order `collect` happened to push them in.
|
||||
#[test]
|
||||
fn a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces() {
|
||||
let text = "/* lead */\nwire /* mid */ a;\n";
|
||||
let out = decoded(text);
|
||||
let comment = |n: usize| {
|
||||
out.iter()
|
||||
.filter(|&&(.., t, _)| t == Highlight::Comment as u32)
|
||||
.nth(n)
|
||||
.copied()
|
||||
.unwrap_or_else(|| panic!("comment {n} missing in {out:?}"))
|
||||
};
|
||||
// Line 0: "/* lead */" is 10 bytes, all ASCII.
|
||||
assert_eq!(comment(0), (0, 0, 10, Highlight::Comment as u32, 0));
|
||||
// Line 1: "wire /* mid */ a;" — `wire` at 0..4, the comment at 5..14
|
||||
// (9 bytes), `a` at 15.
|
||||
let keyword = out
|
||||
.iter()
|
||||
.find(|&&(l, c, _, t, _)| l == 1 && c == 0 && t == Highlight::Keyword as u32)
|
||||
.copied()
|
||||
.expect("the `wire` keyword");
|
||||
assert_eq!(keyword, (1, 0, 4, Highlight::Keyword as u32, 0));
|
||||
assert_eq!(comment(1), (1, 5, 9, Highlight::Comment as u32, 0));
|
||||
let ident = out
|
||||
.iter()
|
||||
.find(|&&(l, c, _, t, _)| l == 1 && c == 15 && t == Highlight::Variable as u32)
|
||||
.copied()
|
||||
.expect("the `a` identifier");
|
||||
// `a` is a real declaration in this fragment's full semantics.
|
||||
assert_eq!(ident, (1, 15, 1, Highlight::Variable as u32, DECLARATION));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_token_ever_spans_a_line_break() {
|
||||
let text = "/* a\n b\n c */\nmodule m;\nendmodule\n";
|
||||
@@ -594,6 +665,213 @@ mod tests {
|
||||
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the large-file fast path's window
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The classes a plain identifier can take once `Semantics` has spoken.
|
||||
/// A fast-path buffer has no `Semantics`, so every one of them is
|
||||
/// `variable` there — the one difference between the two paths, and the
|
||||
/// one this normalization folds away so the rest can be compared.
|
||||
fn coarse(ty: u32) -> u32 {
|
||||
let refined = [
|
||||
Highlight::Namespace,
|
||||
Highlight::Class,
|
||||
Highlight::Type,
|
||||
Highlight::EnumMember,
|
||||
Highlight::Parameter,
|
||||
Highlight::Variable,
|
||||
Highlight::Property,
|
||||
Highlight::Function,
|
||||
];
|
||||
match refined.iter().any(|&r| r as u32 == ty) {
|
||||
true => Highlight::Variable as u32,
|
||||
false => ty,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoded tokens with the identifier refinement folded away.
|
||||
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
|
||||
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
|
||||
}
|
||||
|
||||
/// Whether any construct in `doc` crosses `offset` — a block comment, a
|
||||
/// continued `` `define``, a multi-line macro call. A window boundary
|
||||
/// inside one of those is exactly where the fast path is *documented* to
|
||||
/// disagree, so the agreement property excludes them rather than
|
||||
/// pretending they do not exist.
|
||||
fn crosses(doc: &Document, offset: u32) -> bool {
|
||||
doc.tokens.iter().any(|token| {
|
||||
let spans = token
|
||||
.leading
|
||||
.iter()
|
||||
.map(|c| c.span)
|
||||
.chain(token.trailing.iter().map(|c| c.span))
|
||||
.chain(std::iter::once(token.span));
|
||||
spans.into_iter().any(|span| span.start < offset && offset < span.end)
|
||||
})
|
||||
}
|
||||
|
||||
/// **The agreement anchor.** For a window no multi-line construct reaches
|
||||
/// into, the fast path's answer is the full pipeline's answer — same
|
||||
/// spans, same lengths, same classes. Run over real corpus files, in the
|
||||
/// forty-line windows an editor asks for.
|
||||
#[test]
|
||||
fn the_window_lexer_answers_what_the_full_pipeline_answers() {
|
||||
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 = [
|
||||
corpus.join("picorv32/picorv32.v"),
|
||||
corpus.join("common_cells/src/fifo_v3.sv"),
|
||||
corpus.join("common_cells/src/rr_arb_tree.sv"),
|
||||
];
|
||||
let (mut compared, mut skipped) = (0, 0);
|
||||
for path in files {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||||
eprintln!("{} not checked out — skipping", path.display());
|
||||
continue;
|
||||
};
|
||||
let full = Document::new(Some(path.clone()), text.clone(), &WorkspaceIndex::default());
|
||||
let fast = Document::large(Some(path.clone()), text);
|
||||
assert!(!full.tokens.is_empty(), "{}: the premise", path.display());
|
||||
assert!(fast.tokens.is_empty(), "the fast path lexed nothing at open");
|
||||
let lines = full.line_index.line_count();
|
||||
let mut from = 0;
|
||||
while from < lines {
|
||||
let to = (from + 40).min(lines);
|
||||
let window = range((from, 0), (to, 0));
|
||||
// The two boundaries in bytes: the start of the first line and
|
||||
// the end of the last line the window lexes.
|
||||
let start = full.line_index.line_range(from + 1).map_or(0, |l| l.start);
|
||||
let end =
|
||||
full.line_index.line_range(to + 1).map_or(full.text.len() as u32, |l| l.end);
|
||||
if crosses(&full, start) || crosses(&full, end) {
|
||||
skipped += 1;
|
||||
from = to;
|
||||
continue;
|
||||
}
|
||||
assert_eq!(
|
||||
coarsely(&semantic_tokens_in_window(&fast, window)),
|
||||
coarsely(&semantic_tokens_in_range(&full, window)),
|
||||
"{}: lines {from}..{to}",
|
||||
path.display()
|
||||
);
|
||||
compared += 1;
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
assert!(compared > 50, "the corpus really is checked out: {compared} (skipped {skipped})");
|
||||
// The excluded windows are a small minority; if they ever became the
|
||||
// majority the property would be vacuous.
|
||||
assert!(skipped * 4 < compared, "too many windows excluded: {skipped} of {compared}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_of_a_fast_path_buffer_is_self_contained_like_a_range_answer() {
|
||||
let text = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
let doc = Document::large(None, text.to_string());
|
||||
let data = semantic_tokens_in_window(&doc, range((2, 0), (3, 0)));
|
||||
let first = data.first().expect("line 2 has tokens");
|
||||
assert_eq!(first.delta_line, 2, "encoded from the start of the document");
|
||||
assert_eq!(first.delta_start, 2, "the `wire` keyword's own column");
|
||||
assert!(decode(&data).iter().all(|&(line, ..)| line == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_path_identifier_is_a_plain_variable_with_no_declaration_modifier() {
|
||||
// The one documented difference: nothing analyzed the buffer, so the
|
||||
// module name is not a `class` and carries no `declaration` bit.
|
||||
let text = "module top;\nendmodule\n";
|
||||
let doc = Document::large(None, text.to_string());
|
||||
let data = decode(&semantic_tokens_in_window(&doc, range((0, 0), (1, 0))));
|
||||
let name = data.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("`top`");
|
||||
assert_eq!(name.3, Highlight::Variable as u32);
|
||||
assert_eq!(name.4, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_path_window_never_carries_a_token_from_outside_the_range() {
|
||||
let text = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
let doc = Document::large(None, text.to_string());
|
||||
let inside = decode(&semantic_tokens_in_window(&doc, range((2, 0), (3, 0))));
|
||||
assert!(!inside.is_empty(), "premise: line 2 has tokens");
|
||||
assert!(inside.iter().all(|&(line, ..)| line == 2), "{inside:?}");
|
||||
}
|
||||
|
||||
/// QA (fix-round re-verification): the load-bearing claim behind the
|
||||
/// walker's restart-on-backwards-offset behaviour is that a window's tail
|
||||
/// comment genuinely arrives at `flatten` *after* every token in byte
|
||||
/// order but is pushed into `pieces` *before* them (`semantic_tokens_in_window`
|
||||
/// pushes `window.comments` ahead of the token loop). This reproduces that
|
||||
/// exact shape through the real request path — a long declaration line
|
||||
/// followed by a banner comment that never closes — and checks two
|
||||
/// things: that the comment really is a byte-order tail relative to every
|
||||
/// token (the premise the walker's reset exists for), and that every
|
||||
/// token's and the comment's own position, once decoded off the wire,
|
||||
/// matches what `Positions::position` would say for the same offset —
|
||||
/// i.e. the single mid-window restart the out-of-order comment forces
|
||||
/// does not corrupt anything that comes after it.
|
||||
#[test]
|
||||
fn a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly() {
|
||||
let mut text = String::from("wire ");
|
||||
for n in 0..500 {
|
||||
text.push_str(&format!("a{n},"));
|
||||
}
|
||||
text.push_str("last;\n");
|
||||
let declaration_line_len = text.len() as u32;
|
||||
text.push_str("/* a banner that never closes\n");
|
||||
let doc = Document::large(None, text.clone());
|
||||
|
||||
// The final `within` filter re-checks the *exact* requested LSP
|
||||
// range (not the whole-line window `large::window` snapped to), so
|
||||
// the end has to reach past the comment's own start on line 1 for it
|
||||
// to survive onto the wire at all.
|
||||
let window_range = range((0, 0), (1, 50));
|
||||
let window = crate::large::window(&doc, window_range);
|
||||
assert!(!window.tokens.is_empty(), "premise: the declaration line lexed");
|
||||
assert_eq!(window.comments.len(), 1, "premise: the banner is one tail comment");
|
||||
let comment_span = window.comments[0];
|
||||
let last_token_end = window.tokens.iter().map(|t| t.span.end).max().expect("a token");
|
||||
assert!(
|
||||
comment_span.start >= declaration_line_len,
|
||||
"premise: the comment opens on the second line, after every token byte-wise"
|
||||
);
|
||||
assert!(
|
||||
comment_span.start >= last_token_end,
|
||||
"premise: the out-of-order shape this test targets — the comment \
|
||||
collected before the tokens in `pieces` has the higher byte offset"
|
||||
);
|
||||
|
||||
let positions = doc.positions();
|
||||
let decoded = decode(&semantic_tokens_in_window(&doc, window_range));
|
||||
assert!(decoded.iter().any(|&(_, _, _, ty, _)| ty == Highlight::Comment as u32));
|
||||
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
|
||||
// never reaches `pieces` — only the tokens `classify` keeps are
|
||||
// expected on the wire.
|
||||
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
|
||||
let expected = positions.position(token.span.start);
|
||||
let found = decoded
|
||||
.iter()
|
||||
.find(|&&(line, start, ..)| line == expected.line && start == expected.character);
|
||||
assert!(
|
||||
found.is_some(),
|
||||
"token at byte {} expected at {expected:?}, not found in {decoded:?}",
|
||||
token.span.start
|
||||
);
|
||||
}
|
||||
let comment_expected = positions.position(comment_span.start);
|
||||
assert!(
|
||||
decoded.iter().any(|&(line, start, _, ty, _)| line == comment_expected.line
|
||||
&& start == comment_expected.character
|
||||
&& ty == Highlight::Comment as u32),
|
||||
"comment at byte {} expected at {comment_expected:?}, not found in {decoded:?}",
|
||||
comment_span.start
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `semanticTokens/full/delta`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -629,7 +629,7 @@ endmodule
|
||||
fs::write(dir.join(name), text).expect("write");
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let path = dir.join(which);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let text = fs::read_to_string(&path).expect("read");
|
||||
@@ -1280,7 +1280,7 @@ endmodule
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![root.clone()]);
|
||||
ws.open_whole_workspace(vec![root.clone()]);
|
||||
|
||||
let open = |ws: &mut Workspace, rel: &str| -> (Uri, String) {
|
||||
let file = root.join(rel);
|
||||
|
||||
@@ -21,24 +21,15 @@
|
||||
//! See `docs/features/type-hierarchy/README.md`.
|
||||
|
||||
use lsp_types::{Range, SymbolKind, TypeHierarchyItem, Uri};
|
||||
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
|
||||
use vlog_parser::ast::Item;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
|
||||
use vlog_semantic::classes::{self, Decl};
|
||||
use vlog_semantic::{Definition, SymbolKind as SemanticKind};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::{path_to_uri, uri_to_path};
|
||||
|
||||
/// One class declaration: the node, and the extent of the whole
|
||||
/// `class ... endclass` it was written as.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Decl<'a> {
|
||||
class: &'a ClassDecl,
|
||||
/// Code extent of the declaration, attributes included — what a type
|
||||
/// hierarchy item's `range` is.
|
||||
span: TextRange,
|
||||
}
|
||||
|
||||
/// The class the cursor names, as the root of a type hierarchy — its own
|
||||
/// declaration, or any use of its name.
|
||||
///
|
||||
@@ -53,8 +44,9 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<TypeHierarc
|
||||
let doc = ws.document(uri)?;
|
||||
// The cursor on a declaration written in this buffer answers from the
|
||||
// buffer, unsaved edits and all — no index lookup can beat that.
|
||||
if let Some(decl) =
|
||||
declarations(&doc.tree.items).into_iter().find(|decl| touches(decl.class.name_span, offset))
|
||||
if let Some(decl) = classes::declarations(&doc.tree.items)
|
||||
.into_iter()
|
||||
.find(|decl| touches(decl.class.name_span, offset))
|
||||
{
|
||||
let positions = doc.positions();
|
||||
return Some(vec![item(uri.clone(), &positions, decl)?]);
|
||||
@@ -94,37 +86,38 @@ pub fn supertypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchy
|
||||
|
||||
/// Who extends this class, across the workspace.
|
||||
///
|
||||
/// Every in-scope file is walked, because the workspace index records what a
|
||||
/// file *declares* and not what it extends — there is no edge table to consult,
|
||||
/// exactly as there is none for instantiations
|
||||
/// (`docs/features/hierarchy/README.md`). A file whose text does not contain
|
||||
/// the name is skipped before it is parsed, which is what keeps the walk
|
||||
/// affordable: `extends base` has to write `base`.
|
||||
/// **A lookup in the workspace index's inheritance-edge table** since
|
||||
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
|
||||
/// file. The edges are recorded by the same [`classes::declarations`] walk this
|
||||
/// function used to run, at index time
|
||||
/// (`docs/features/incremental-index/README.md`), so the answer and its order
|
||||
/// are unchanged; only the files that really do extend the class are read now,
|
||||
/// and only to turn the recorded byte spans into line/character ranges.
|
||||
///
|
||||
/// An empty name is answered with nothing rather than searched for: nothing
|
||||
/// this server hands out is nameless, and the prefilter matches every file for
|
||||
/// one, which would parse the whole workspace to find nothing.
|
||||
/// 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 subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyItem> {
|
||||
if item.name.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let index = ws.index();
|
||||
let mut found: Vec<TypeHierarchyItem> = Vec::new();
|
||||
for (path, text) in ws.sources() {
|
||||
if !text.contains(&item.name) {
|
||||
continue;
|
||||
}
|
||||
let Some(uri) = path_to_uri(&path) else { continue };
|
||||
let (tree, _) = parse_source_tolerant(&text);
|
||||
let edges = index.subclasses_of(&item.name);
|
||||
let mut at = 0;
|
||||
while at < edges.len() {
|
||||
// The edges arrive in file order, so one file's are consecutive: read
|
||||
// its text once and build every item it holds.
|
||||
let file = edges[at].file;
|
||||
let group = &edges[at..][..edges[at..].iter().take_while(|e| e.file == file).count()];
|
||||
at += group.len();
|
||||
let Some(path) = index.path(file) else { continue };
|
||||
let Some(uri) = path_to_uri(path) else { continue };
|
||||
let Some(text) = ws.text_of(path) else { continue };
|
||||
let line_index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &line_index);
|
||||
for decl in declarations(&tree.items) {
|
||||
if extends_name(decl.class) != Some(item.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(built) = self::item(uri.clone(), &positions, decl) {
|
||||
found.push(built);
|
||||
}
|
||||
}
|
||||
found.extend(group.iter().map(|edge| &edge.subclass).filter_map(|subclass| {
|
||||
item_of(uri.clone(), &positions, &subclass.name, subclass.name_span, subclass.span)
|
||||
}));
|
||||
}
|
||||
found.sort_by(|a, b| {
|
||||
(a.uri.as_str(), key(a.selection_range)).cmp(&(b.uri.as_str(), key(b.selection_range)))
|
||||
@@ -132,16 +125,6 @@ pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyIt
|
||||
found
|
||||
}
|
||||
|
||||
/// The base class of one class declaration, as written — `None` when the
|
||||
/// header has no `extends`.
|
||||
///
|
||||
/// The name is the bare base: `extends base #(8)` stores `base`, because the
|
||||
/// parser keeps the parameter overrides on their own field, so a parameterized
|
||||
/// base needs no unwrapping here.
|
||||
fn extends_name(class: &ClassDecl) -> Option<&str> {
|
||||
class.extends.as_ref().map(|extends| extends.name.as_str())
|
||||
}
|
||||
|
||||
/// The base classes of the class an item names, in the file it names.
|
||||
fn bases_of(
|
||||
ws: &Workspace,
|
||||
@@ -200,20 +183,28 @@ fn classes_at(ws: &Workspace, doc: &Document, uri: &Uri, offset: u32) -> Vec<Typ
|
||||
/// The hierarchy item for one class declaration, positioned against the text it
|
||||
/// was parsed from.
|
||||
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<TypeHierarchyItem> {
|
||||
let name_span = decl.class.name_span;
|
||||
item_of(uri, positions, &decl.class.name, decl.class.name_span, decl.span)
|
||||
}
|
||||
|
||||
/// [`item`] from the parts, for a caller reading them out of the index's
|
||||
/// inheritance-edge table rather than off a parse tree.
|
||||
fn item_of(
|
||||
uri: Uri,
|
||||
positions: &Positions,
|
||||
name: &str,
|
||||
name_span: TextRange,
|
||||
span: TextRange,
|
||||
) -> Option<TypeHierarchyItem> {
|
||||
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(TypeHierarchyItem {
|
||||
name: decl.class.name.clone(),
|
||||
name: name.to_string(),
|
||||
// `interface class` is a different construct (IEEE 1800 §8.26) that
|
||||
// `vlog_parser` does not model at all, so there is nothing here that
|
||||
// could carry `SymbolKind::INTERFACE`.
|
||||
@@ -250,34 +241,11 @@ fn item_in_file(
|
||||
item(uri, &Positions::new(&text, &line_index), decl)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
|
||||
let mut out = Vec::new();
|
||||
collect(items, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
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),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The declaration of `name` in a parsed file: the one whose name sits at `at`,
|
||||
/// else the first of that name.
|
||||
fn find_class<'a>(items: &'a [Item], name: &str, at: Option<TextRange>) -> Option<Decl<'a>> {
|
||||
let decls: Vec<Decl> =
|
||||
declarations(items).into_iter().filter(|d| d.class.name == name).collect();
|
||||
classes::declarations(items).into_iter().filter(|d| d.class.name == name).collect();
|
||||
if let Some(at) = at {
|
||||
if let Some(exact) = decls.iter().find(|d| d.class.name_span == at) {
|
||||
return Some(*exact);
|
||||
@@ -351,7 +319,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());
|
||||
@@ -718,7 +686,7 @@ endclass
|
||||
tree.write("files.f", "base.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 base_uri = path_to_uri(&tree.path.join("base.sv")).expect("uri");
|
||||
ws.set_document(base_uri.clone(), BASE.to_string());
|
||||
|
||||
@@ -727,9 +695,14 @@ endclass
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_extends_is_a_subtype_before_it_is_saved() {
|
||||
// The sources a walk reads are the open buffers overlaid on disk, so a
|
||||
// just-typed `extends` counts.
|
||||
fn an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it() {
|
||||
// Superseded this round (incremental-index, 2026-08-27):
|
||||
// `an_unsaved_extends_is_a_subtype_before_it_is_saved` pinned the walk
|
||||
// over `Workspace::sources()`, so a keystroke in another buffer moved
|
||||
// the answer before anything rebuilt. Subtypes are the index's
|
||||
// inheritance-edge table now — as of its last build or update, both of
|
||||
// which fold every open buffer in. Same rule as the call hierarchy's
|
||||
// census, pinned from both sides.
|
||||
let (tree, mut ws, uri) = two("unsaved");
|
||||
let root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone();
|
||||
assert_eq!(subtypes(&ws, &root).len(), 1, "premise");
|
||||
@@ -737,7 +710,13 @@ endclass
|
||||
let fresh = tree.path.join("child.sv");
|
||||
let child_uri = path_to_uri(&fresh).expect("uri");
|
||||
ws.set_document(child_uri, "class child;\nendclass\n".to_string());
|
||||
assert!(subtypes(&ws, &root).is_empty(), "the buffer took the `extends` away");
|
||||
assert_eq!(
|
||||
subtypes(&ws, &root).len(),
|
||||
1,
|
||||
"the buffer alone does not move the answer — the index has not seen it"
|
||||
);
|
||||
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
|
||||
assert!(subtypes(&ws, &root).is_empty(), "the edit took the `extends` away");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1088,6 +1067,49 @@ endclass
|
||||
// the corpus, smoke-tested
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// What `subtypes` costs after the inheritance-edge table, against the
|
||||
/// workspace walk it replaced. `#[ignore]`d: it prints a number rather
|
||||
/// than asserting one — the budget is asserted in
|
||||
/// `the_corpus_uvm_classes_answer_all_three_requests`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn qa_perf_subtypes_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 lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv");
|
||||
let Ok(text) = fs::read_to_string(&lib) else {
|
||||
eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let uri = path_to_uri(&lib).expect("uri");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6;
|
||||
let child = prepare(&ws, &uri, offset).expect("the class")[0].clone();
|
||||
let base = supertypes(&ws, &child).first().cloned().expect("core_ibex_base_test");
|
||||
|
||||
let mut lookup = std::time::Duration::ZERO;
|
||||
let mut walk = std::time::Duration::ZERO;
|
||||
for _ in 0..3 {
|
||||
let started = std::time::Instant::now();
|
||||
let found = subtypes(&ws, &base);
|
||||
lookup = lookup.max(started.elapsed());
|
||||
assert!(!found.is_empty());
|
||||
let started = std::time::Instant::now();
|
||||
let _ = ws.sources();
|
||||
walk = walk.max(started.elapsed());
|
||||
}
|
||||
eprintln!(
|
||||
"typeHierarchy/subtypes over {} files: {lookup:?}; one workspace walk (what it \
|
||||
used to begin with) is {walk:?}",
|
||||
ws.index().files().len()
|
||||
);
|
||||
}
|
||||
|
||||
/// Every class of a real UVM-shaped corpus file, through all three
|
||||
/// requests, plus one known `extends` chain. Skipped when `corpus/` is not
|
||||
/// checked out (`tools/corpus_fetch.sh`), like the other corpus tests.
|
||||
@@ -1104,7 +1126,7 @@ endclass
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![corpus]);
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let uri = path_to_uri(&lib).expect("uri");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let files = ws.index().files().len();
|
||||
@@ -1113,7 +1135,7 @@ endclass
|
||||
// every item the protocol's containment rule.
|
||||
let doc = ws.document(&uri).expect("the open buffer");
|
||||
let names: Vec<String> =
|
||||
declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
|
||||
classes::declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
|
||||
assert!(names.len() > 20, "the file really is class-heavy: {}", names.len());
|
||||
let mut with_a_base = 0;
|
||||
for name in &names {
|
||||
|
||||
@@ -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,6 +112,29 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
|
||||
.any(|path| watched(&path, filelist))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
|
||||
+1492
-20
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.
|
||||
@@ -1973,7 +2045,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));
|
||||
@@ -2312,10 +2384,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 +2402,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)])])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2461,17 +2546,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 +2592,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 +2614,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,13 +2672,13 @@ 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(";")]),
|
||||
@@ -2652,9 +2743,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 +2787,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 +2831,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,23 +2972,9 @@ 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 } => {
|
||||
concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")])
|
||||
@@ -3094,3 +3186,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
|
||||
}
|
||||
@@ -1191,3 +1191,227 @@ endmodule
|
||||
module m;
|
||||
sub /* the one */ u (.a(b));
|
||||
endmodule
|
||||
====
|
||||
# a line comment trailing `end` pushes `else if` onto the next line
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // addr_phase_write
|
||||
else if (b) begin
|
||||
x = 2;
|
||||
end
|
||||
else begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // addr_phase_write
|
||||
else if (b) begin
|
||||
x = 2;
|
||||
end else begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a line comment trailing `end` pushes a one-statement `else` down too
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // fell through
|
||||
else if (b) x = 2;
|
||||
else x = 3;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end // fell through
|
||||
else if (b) x = 2;
|
||||
else x = 3;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a block comment trailing `end` still lets `else` cuddle
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end /* why */ else begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end /* why */ else begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment after `if (` stays inside the parentheses
|
||||
module m;
|
||||
always_comb begin
|
||||
if (// the first transaction
|
||||
a ||
|
||||
// or the last one
|
||||
b) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (
|
||||
// the first transaction
|
||||
a || // or the last one
|
||||
b
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a block comment before an if condition's `)` stays inside them
|
||||
module m;
|
||||
always_comb begin
|
||||
if (bitstuff /* && !serial_tx_se0 */) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (bitstuff /* && !serial_tx_se0 */) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# an if condition keeps comments on both sides of it
|
||||
module m;
|
||||
always_comb begin
|
||||
if (// only the leading one
|
||||
a) begin
|
||||
x = 1;
|
||||
end
|
||||
if (b /* and a trailing one */) begin
|
||||
x = 2;
|
||||
end
|
||||
if (// both ends
|
||||
c /* like this */) begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
if (
|
||||
// only the leading one
|
||||
a
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
if (b /* and a trailing one */) begin
|
||||
x = 2;
|
||||
end
|
||||
if (
|
||||
// both ends
|
||||
c /* like this */
|
||||
) begin
|
||||
x = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment after `while (` stays inside the parentheses
|
||||
module m;
|
||||
initial begin
|
||||
while (// keep adding while the agent wants more
|
||||
rcvd < sent ||
|
||||
// and while there are transactions left to drive
|
||||
cnt < num) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
while (
|
||||
// keep adding while the agent wants more
|
||||
rcvd < sent || // and while there are transactions left to drive
|
||||
cnt < num
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# `repeat` and `wait` keep a comment written before their `)`
|
||||
module m;
|
||||
initial begin
|
||||
repeat (n // how many
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
wait (w // until this settles
|
||||
) begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
repeat (
|
||||
n // how many
|
||||
) begin
|
||||
x = 1;
|
||||
end
|
||||
wait (
|
||||
w // until this settles
|
||||
) begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment after `case (` stays inside the parentheses
|
||||
module m;
|
||||
always_comb begin
|
||||
case (// the decoded opcode
|
||||
op)
|
||||
A: y = 1;
|
||||
default: y = 0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
case (
|
||||
// the decoded opcode
|
||||
op
|
||||
)
|
||||
A: y = 1;
|
||||
default: y = 0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,263 @@
|
||||
# a `ifdef opened part-way through an assign, each arm carrying the
|
||||
# construct's own `;` -- the block ends at the `endif, because there is no
|
||||
# `;` after it to stop at
|
||||
# hw/top_earlgrey/dv/env/chip_if.sv:1189 (the anchor)
|
||||
module m;
|
||||
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
|
||||
wire [3:0] aes_ctrl_rnd_ctr;
|
||||
assign aes_ctrl_rnd_ctr =
|
||||
`ifdef GATE_LEVEL
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
|
||||
`else
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
|
||||
`endif
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
|
||||
wire [3:0] aes_ctrl_rnd_ctr;
|
||||
assign aes_ctrl_rnd_ctr =
|
||||
`ifdef GATE_LEVEL
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
|
||||
`else
|
||||
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
|
||||
`endif
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# the same shape at *statement* level: a region between two call arguments,
|
||||
# balanced inside the parens, so the statement ends at its own `;`. Only the
|
||||
# statement is captured -- the function around it still formats
|
||||
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173
|
||||
class c;
|
||||
virtual function void build();
|
||||
abits = (dv_base_reg_field::type_id::create("abits"));
|
||||
abits.configure(
|
||||
.parent(this),
|
||||
.size(6),
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
.reset(32'h10),
|
||||
`else
|
||||
.reset(32'h07),
|
||||
`endif
|
||||
.has_reset(1));
|
||||
dmistat = 1;
|
||||
endfunction
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
virtual function void build();
|
||||
abits = (dv_base_reg_field::type_id::create("abits"));
|
||||
abits.configure(
|
||||
.parent(this),
|
||||
.size(6),
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
.reset(32'h10),
|
||||
`else
|
||||
.reset(32'h07),
|
||||
`endif
|
||||
.has_reset(1));
|
||||
dmistat = 1;
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
# a region between the elements of a concatenation, three brackets deep inside
|
||||
# an instantiation's parameter override -- the whole instantiation becomes the
|
||||
# block, ending at its `;`
|
||||
# hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621
|
||||
module chip;
|
||||
padring #(
|
||||
.DioPadType ({
|
||||
AnalogIn0, // RRAM_ANALOG
|
||||
`ifdef ANALOGSIM
|
||||
'0,
|
||||
`else
|
||||
CC2,
|
||||
`endif
|
||||
DualBidirTol // USB_N
|
||||
})
|
||||
) u_padring (
|
||||
.clk_scan_i(ast_base_clks.clk_sys),
|
||||
.scanmode_i(scanmode)
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module chip;
|
||||
padring #(
|
||||
.DioPadType ({
|
||||
AnalogIn0, // RRAM_ANALOG
|
||||
`ifdef ANALOGSIM
|
||||
'0,
|
||||
`else
|
||||
CC2,
|
||||
`endif
|
||||
DualBidirTol // USB_N
|
||||
})
|
||||
) u_padring (
|
||||
.clk_scan_i(ast_base_clks.clk_sys),
|
||||
.scanmode_i(scanmode)
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# two instantiation *heads* behind one `ifdef, sharing a connection list. The
|
||||
# region opened before the item, so this is the closing shape the
|
||||
# `directive-split` recovery already knew -- what changed is that
|
||||
# `take_list_directives` no longer harvests the `else as a list element and
|
||||
# reads the second arm's head as a positional connection
|
||||
# hw/top_earlgrey/dv/tb/tb.sv:105
|
||||
module tb;
|
||||
`ifdef DISABLE_ROM_INTEGRITY_CHECK
|
||||
chip_earlgrey_asic #(
|
||||
// This is to be used carefully, and should never be on for synthesis.
|
||||
.SecRomCtrlDisableScrambling(1'b1)
|
||||
) dut (
|
||||
`else
|
||||
chip_earlgrey_asic dut (
|
||||
`endif
|
||||
// Dedicated Pads
|
||||
.POR_N(dut.chip_if.dios[DioPadPorN]),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(cc1),
|
||||
`else
|
||||
.CC1(dut.chip_if.dios[DioPadCc1]),
|
||||
`endif
|
||||
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
`ifdef DISABLE_ROM_INTEGRITY_CHECK
|
||||
chip_earlgrey_asic #(
|
||||
// This is to be used carefully, and should never be on for synthesis.
|
||||
.SecRomCtrlDisableScrambling(1'b1)
|
||||
) dut (
|
||||
`else
|
||||
chip_earlgrey_asic dut (
|
||||
`endif
|
||||
// Dedicated Pads
|
||||
.POR_N(dut.chip_if.dios[DioPadPorN]),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(cc1),
|
||||
`else
|
||||
.CC1(dut.chip_if.dios[DioPadCc1]),
|
||||
`endif
|
||||
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
|
||||
);
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# a split `function` header: the header's own `;` closes a *header*, so the
|
||||
# block runs to `endfunction` and takes the `: label` with it
|
||||
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273
|
||||
class jtag_dtm_reg_dmi;
|
||||
function new(string name = "",
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
int unsigned n_bits = 50,
|
||||
`else
|
||||
int unsigned n_bits = 41,
|
||||
`endif
|
||||
int has_coverage = UVM_NO_COVERAGE);
|
||||
super.new(name, n_bits, has_coverage);
|
||||
endfunction : new
|
||||
|
||||
int after;
|
||||
endclass
|
||||
----
|
||||
class jtag_dtm_reg_dmi;
|
||||
function new(string name = "",
|
||||
`ifdef USE_DMI_INTERFACE
|
||||
int unsigned n_bits = 50,
|
||||
`else
|
||||
int unsigned n_bits = 41,
|
||||
`endif
|
||||
int has_coverage = UVM_NO_COVERAGE);
|
||||
super.new(name, n_bits, has_coverage);
|
||||
endfunction : new
|
||||
|
||||
int after;
|
||||
endclass
|
||||
====
|
||||
# the control: a region opened *and* closed inside the connection list still
|
||||
# conditions list elements, even with an outer region live, and the
|
||||
# instantiation still parses as an instantiation rather than becoming opaque
|
||||
module m;
|
||||
`ifdef OUTER
|
||||
chip dut (
|
||||
.A(a),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(c1),
|
||||
`else
|
||||
.CC1(d1),
|
||||
`endif
|
||||
.B(b)
|
||||
);
|
||||
`endif
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
`ifdef OUTER
|
||||
chip dut (
|
||||
.A(a),
|
||||
`ifdef ANALOGSIM
|
||||
.CC1(c1),
|
||||
`else
|
||||
.CC1(d1),
|
||||
`endif
|
||||
.B(b)
|
||||
);
|
||||
`endif
|
||||
endmodule
|
||||
====
|
||||
# comments survive: the ones written inside the block print once, as part of
|
||||
# its bytes, and the ones around it stay outside
|
||||
module m;
|
||||
// before the block
|
||||
assign y =
|
||||
`ifdef A
|
||||
a; // inside the first arm
|
||||
`else
|
||||
b; /* inside the second */
|
||||
`endif
|
||||
// after the block
|
||||
wire after;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// before the block
|
||||
assign y =
|
||||
`ifdef A
|
||||
a; // inside the first arm
|
||||
`else
|
||||
b; /* inside the second */
|
||||
`endif
|
||||
// after the block
|
||||
wire after;
|
||||
endmodule
|
||||
====
|
||||
# the keymgr shape: the take_gap parser fix and header_parens in one tree —
|
||||
# the comment written after `if (` stays inside the parens (the last of
|
||||
# bucket 2's 12; merged-tree pin the serial round could not add itself)
|
||||
module m;
|
||||
function automatic int f();
|
||||
if (// why
|
||||
!en() || b
|
||||
) begin
|
||||
return 1;
|
||||
end
|
||||
endfunction
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
function automatic int f();
|
||||
if (
|
||||
// why
|
||||
!en() || b
|
||||
) begin
|
||||
return 1;
|
||||
end
|
||||
endfunction
|
||||
endmodule
|
||||
@@ -0,0 +1,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 5.9 MiB of stack in an
|
||||
/// unoptimized build, more than a default test thread's 2 MiB. The size is
|
||||
/// the one every production parse site is given, so these tests fail if the
|
||||
/// guarantee is ever cut below what the depth limit needs.
|
||||
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()
|
||||
|
||||
@@ -1257,3 +1257,151 @@ 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",
|
||||
);
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -248,6 +248,45 @@ 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");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Guarantee 2: diagnostics and error nodes stay inside the file
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -71,6 +71,9 @@ 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",
|
||||
// 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",
|
||||
|
||||
@@ -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
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -142,6 +142,7 @@ impl<'a> Binder<'a> {
|
||||
kind,
|
||||
name_span,
|
||||
decl_span,
|
||||
detail_span: None,
|
||||
scope,
|
||||
child_scope: None,
|
||||
});
|
||||
@@ -501,6 +502,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -623,6 +623,40 @@ endclass
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins the opacity promise `docs/features/out-of-class-constraints/README.md`
|
||||
/// makes without a test of its own: an out-of-block `constraint C::name { ... }`
|
||||
/// is exactly as opaque as the in-class form above — same `ItemKind::Verbatim(_)`
|
||||
/// arm in `bind.rs`, reached by the same item walker, item position never
|
||||
/// entered into it.
|
||||
#[test]
|
||||
fn an_out_of_block_constraint_is_absent_but_nothing_crashes() {
|
||||
let src = "\
|
||||
class my_seq;
|
||||
rand int num_trans;
|
||||
extern constraint num_trans_c;
|
||||
endclass
|
||||
|
||||
constraint my_seq::num_trans_c {
|
||||
num_trans inside {[1:20]};
|
||||
}
|
||||
";
|
||||
let s = sem(src);
|
||||
// No symbol for the constraint name, in-class prototype or out-of-block
|
||||
// definition alike — both are `ItemKind::Verbatim(_)` leaves.
|
||||
assert!(s.symbols().iter().all(|sym| sym.name != "num_trans_c"));
|
||||
assert_eq!(
|
||||
s.symbols().iter().map(|sym| sym.name.as_str()).collect::<Vec<_>>(),
|
||||
vec!["my_seq", "num_trans"]
|
||||
);
|
||||
assert!(s.reference_at(nth(src, "num_trans inside", 0)).is_none());
|
||||
// Queries at every offset stay panic-free.
|
||||
for offset in 0..=src.len() as u32 {
|
||||
let _ = s.definition_of(offset);
|
||||
let _ = s.symbol_at(offset);
|
||||
let _ = s.reference_at(offset);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Workspace index
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -510,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,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.
|
||||
|
||||
@@ -6,17 +6,17 @@ 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 x86-64/ARM64 and RHEL 8-compatible Linux,
|
||||
Windows — both binaries each — plus the six `.vsix` packages and
|
||||
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 six `.vsix` packages
|
||||
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, each platform 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
|
||||
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 six packages.
|
||||
versions, written notes, and all seven packages.
|
||||
|
||||
## Assumptions
|
||||
|
||||
@@ -46,10 +46,19 @@ versions, written notes, and all six packages.
|
||||
|
||||
- Consumes `tools/release.sh --cross` unchanged: artifact names
|
||||
(`lucisv[-server]-<version>-<triple>[.exe]`,
|
||||
`lucisv-<version>[-<vsce-target>].vsix`, `SHA256SUMS`) and the
|
||||
version-from-binary convention. The workflow's pruning step depends on
|
||||
those `.vsix` names exactly — it checks all six by name and filters
|
||||
`SHA256SUMS` down to `.vsix` lines before publishing.
|
||||
`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
|
||||
@@ -79,12 +88,17 @@ versions, written notes, and all six packages.
|
||||
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 six packages exist by name, filters `SHA256SUMS`
|
||||
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.
|
||||
|
||||
@@ -127,6 +141,51 @@ versions, written notes, and all six packages.
|
||||
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)_
|
||||
|
||||
@@ -68,22 +68,46 @@ computed by, so the lens and the hierarchy view can never disagree (TODO.md
|
||||
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
|
||||
- ~~**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.
|
||||
- **The cost is one workspace walk per request, not one per module.**
|
||||
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.
|
||||
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
|
||||
|
||||
Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
|
||||
**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`
|
||||
@@ -100,7 +124,7 @@ 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.
|
||||
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.~~
|
||||
|
||||
|
||||
### `lucisv_server::hierarchy` — **changed, deliberately**
|
||||
@@ -206,7 +230,7 @@ no-showDocument path — verified by running it.
|
||||
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.**
|
||||
recorded here, not made.** — **done, incremental-index, 2026-08-27.**
|
||||
|
||||
## Work log
|
||||
|
||||
|
||||
@@ -81,9 +81,26 @@ 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`** — `module_definition`, `instantiation_plan`,
|
||||
`render_with` — through `module_tier`. 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
|
||||
@@ -221,6 +238,74 @@ 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 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 is left is
|
||||
64 real header parses, and the two ways down from there — memoizing the plan,
|
||||
or `completionItem/resolve` — both change something this round was not allowed
|
||||
to change. They are filed in `docs/perf/README.md`.
|
||||
|
||||
## Version 0.3.0
|
||||
|
||||
Every place `tools/RELEASING.md` says the version lives, plus the install
|
||||
@@ -269,9 +354,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 +760,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
|
||||
|
||||
@@ -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 |
@@ -35,13 +35,15 @@ binary on `PATH`).
|
||||
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.** `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 the universal package and needs
|
||||
`lucisv-server` on `PATH`, even though the musl binary we ship would have run
|
||||
there perfectly. Building two more 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).
|
||||
- **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
|
||||
@@ -67,16 +69,42 @@ feature changes is *which path* is spawned, never how.
|
||||
naming. The staging step reads those exact names; renaming an artifact breaks
|
||||
packaging loudly (a missing `cp` source), not silently.
|
||||
|
||||
**Promised to `extension.js`** — a platform package always contains **both**
|
||||
binaries under `bin/`, named plainly (`lucisv`, `lucisv-server`, with `.exe` on
|
||||
Windows) with no version or triple in the name; the universal package contains
|
||||
**no** `bin/` directory at all. `release.sh` asserts both with `unzip -Z1`
|
||||
after every package it builds, so "the extension found a stale binary from the
|
||||
previous target" cannot ship.
|
||||
**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 new `.vsix` names all end
|
||||
in `.vsix` and are skipped by the audit's existing case arm.
|
||||
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.
|
||||
|
||||
@@ -93,9 +121,11 @@ first:
|
||||
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**, `<extension>/bin/lucisv-server`(`.exe`), if the file
|
||||
exists. Its existence is the whole runtime test for "am I a platform package
|
||||
or the universal one" — no build-time flag, no manifest field.
|
||||
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.
|
||||
@@ -105,6 +135,54 @@ 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` |
|
||||
@@ -112,12 +190,13 @@ claim false.
|
||||
| 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 six.
|
||||
always carry all seven.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
@@ -137,13 +216,26 @@ always carry all six.
|
||||
- [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`.
|
||||
- [ ] **Not done, and not doable here:** none of the five packages has been
|
||||
- [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 and
|
||||
by the packaging assertions, not by an editor picking the right package
|
||||
off a marketplace. The Linux and Windows packages have additionally never
|
||||
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.
|
||||
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.
|
||||
|
||||
@@ -294,6 +386,180 @@ 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
|
||||
@@ -369,6 +635,88 @@ const serverPath = userServerPath() || bundledBinary(context, 'lucisv-server') |
|
||||
|
||||
**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.**
|
||||
@@ -407,3 +755,31 @@ accepted:
|
||||
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`
|
||||
|
||||
@@ -145,6 +145,16 @@ invariant #4 is not in play. The formatter is not involved in this path at all.
|
||||
have disagreed with the first in the corner cases nobody tests.
|
||||
- **`IncludeGraph::incdirs()`** — a read-only accessor, so a candidate
|
||||
spelling can be a suffix under a real include path rather than a guess.
|
||||
- **`IncludeGraph::includers()`** (added 2026-08-28) — a read-only accessor
|
||||
over the edge table's keys, which is what lets the sweep read the files
|
||||
that write a resolving `` `include`` instead of every file in scope. The
|
||||
property it stands on is `resolve`'s agreement with the `found` the edges
|
||||
were built from; it is written out under "The sweep reads the includers,
|
||||
not the workspace", and a change to either half must re-read it.
|
||||
**Scope note for the lead:** `includes.rs` is outside the Lane A file
|
||||
list this round was scoped to. The accessor is four lines, purely
|
||||
additive, and there is no second way to ask the graph this question
|
||||
without a second copy of the include scan — flagged rather than smuggled.
|
||||
- **`includes::normalize` is now `pub`** (it was private). A renamed path and
|
||||
a resolved include are compared, and they must be folded the same way; a
|
||||
fourth private copy of that loop is the one thing that guarantees they
|
||||
@@ -212,6 +222,47 @@ probe (`cargo test --release -p lucisv_server --bin lucisv-server
|
||||
file_ops::tests::perf -- --ignored --nocapture`), the same shape as
|
||||
`includes.rs`'s: it prints and asserts nothing but the corpus's presence.
|
||||
|
||||
### The sweep reads the includers, not the workspace (2026-08-28)
|
||||
|
||||
The prefilter above still cost a *read* of every file to run. On OpenTitan
|
||||
(3 976 files) that is 249 ms of `sources()` per gesture, and the server
|
||||
advertises `willRename` with a `**` folder filter, so **renaming any folder in
|
||||
the explorer paid it**.
|
||||
|
||||
The include graph already holds the answer. `IncludeGraph`'s edge table is
|
||||
built as `scan(text).filter_map(|include| self.found(Some(path), include))`
|
||||
over every in-scope file, and `resolve` is exactly `found` followed by the
|
||||
index's own spelling of the result — so `resolve` answers `Some` for an
|
||||
include if and only if `found` did. Therefore:
|
||||
|
||||
> **A file with no entry in the edge table writes no `` `include`` this
|
||||
> workspace can resolve, so every iteration of `will_rename`'s inner loop over
|
||||
> it hits `let Some(old) = graph.resolve(…) else { continue }`.** It can
|
||||
> produce neither an edit nor a warning, and reading it is reading the
|
||||
> workspace to answer "nothing".
|
||||
|
||||
`Workspace::include_sources` is that set — `IncludeGraph::includers()` — plus
|
||||
every **open buffer**, because the graph is rebuilt on save and an `` `include``
|
||||
typed and not yet saved is in the buffer and in no edge
|
||||
(`an_unsaved_include_is_still_rewritten`). The one-directional property is
|
||||
asserted directly over a hostile tree rather than argued
|
||||
(`nothing_skipped_has_an_include_to_rewrite`: every in-scope file the sweep
|
||||
skips is checked to have no resolving include, and the tree is asserted to
|
||||
actually exercise the skip).
|
||||
|
||||
Measured, `--release`:
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| synthetic 506 files, 1 of them including anything | reading the scope **16.1 ms** | reading the includers **18.9 µs**; whole answer **35.4 µs** |
|
||||
| OpenTitan, 3 976 files, 331 of them includers | `sources()` **249 ms** | whole answer **14.1 ms** |
|
||||
|
||||
Same staleness premise the rename family adopted the same day
|
||||
(`docs/features/refactor-rename/README.md`): the graph is the server's
|
||||
authority on who includes what, a file changed on disk with nothing telling
|
||||
this server is a file the sweep does not read, and open buffers are the
|
||||
exemption.
|
||||
|
||||
The notifications cost one `reindex()` each, which is the cost a save has.
|
||||
|
||||
## Status / TODO
|
||||
@@ -230,6 +281,10 @@ The notifications cost one `reindex()` each, which is the cost a save has.
|
||||
is still one search order and one path folding.
|
||||
- [x] `watch::watched` made public, so the notifications and the watcher share
|
||||
one scope test.
|
||||
- [x] The sweep reads the include graph's includers plus the open buffers
|
||||
rather than `sources()` (2026-08-28): `IncludeGraph::includers`,
|
||||
`Workspace::include_sources`, the one-directional property asserted over
|
||||
a hostile tree, and a before/after probe.
|
||||
- [x] Tests: 24 in `file_ops.rs`, 7 in `server.rs` (dispatch, warning volume,
|
||||
reindex, watcher-double, unopened file, `null`), 1 in `main.rs` (the
|
||||
capability on the wire), 1 e2e session (real binary, edit decoded,
|
||||
@@ -327,6 +382,45 @@ target/debug/lucisv-server` → OK, 9 messages, unchanged from `bf17ddd`
|
||||
JSON and adds no message). Perf measured as above. No new dependency, no
|
||||
version bump, no other crate touched.
|
||||
|
||||
**2026-08-28 — dev agent (performance wave, Lane A).** The sweep stops reading
|
||||
the workspace. `performance.md` §6e flagged `file_ops.rs:120`'s `ws.sources()`
|
||||
as the same shape as the rename family's, unmeasured; it is 249 ms of file
|
||||
reading per gesture on OpenTitan, and the server advertises `willRename` with
|
||||
a `**` folder filter, so **renaming any folder in the explorer paid it** to
|
||||
learn that 3 645 of 3 976 files write no `` `include`` that resolves.
|
||||
|
||||
The include graph already holds that fact. `IncludeGraph::includers()` — four
|
||||
lines, the edge table's keys — is the new accessor, `Workspace::include_sources`
|
||||
is the set (includers plus every open buffer, because the graph is rebuilt on
|
||||
save and an unsaved `` `include`` is in neither `raw` nor `edges`), and
|
||||
`will_rename`'s loop is otherwise untouched. The argument is one sentence long
|
||||
and is written up under "The sweep reads the includers, not the workspace":
|
||||
`resolve` is `found` plus a re-spelling, and `raw` is built from `found`, so a
|
||||
file with no edge has no include `resolve` answers — every iteration of the
|
||||
inner loop over it hits its first `continue`.
|
||||
|
||||
Rather than argue that by inspection alone it is asserted over a hostile tree:
|
||||
`nothing_skipped_has_an_include_to_rewrite` walks every in-scope file the sweep
|
||||
skips and checks each of its `` `include``s resolves to nothing, and asserts
|
||||
the tree exercises the skip at all. Two behaviour tests beside it —
|
||||
`the_narrowed_sweep_reads_the_includers_and_answers_the_same` (24 files, 1
|
||||
includer, 2 with dangling includes) and `an_unsaved_include_is_still_rewritten`.
|
||||
|
||||
Measured, `--release`: synthetic 506 files, reading the scope **16.1 ms** →
|
||||
reading the includers **18.9 µs**, whole answer **35.4 µs**
|
||||
(`perf::a_will_rename_before_and_after`). OpenTitan, 3 976 files with 331
|
||||
includers: `sources()` **249 ms** → whole answer **14.1 ms** (throwaway probe
|
||||
against the local checkout, deleted; no test depends on it).
|
||||
|
||||
**One scope deviation, flagged not smuggled:** `includes.rs` is outside the
|
||||
file list this lane was scoped to, and the accessor was added there anyway.
|
||||
The alternative was a second copy of the include scan inside `state.rs`, which
|
||||
is the one thing this module's Handshakes section already says must not
|
||||
happen. Recorded in Handshakes above and in the round's report.
|
||||
|
||||
Gates: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets` clean,
|
||||
`cargo test --workspace` green, `node editors/vscode/smoke.js` OK.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent, file operations (TODO.md §9c)
|
||||
@@ -514,8 +608,86 @@ nested-batch ordering is a documentation/robustness suggestion for the dev,
|
||||
not a blocker — no corruption path exists even in that shape, thanks to the
|
||||
safety net doing its job independently of what `Moves` models.
|
||||
|
||||
**2026-08-28 — QA agent (performance wave, Lane A).** Verified the round that
|
||||
moves `will_rename`'s sweep off `ws.sources()` onto
|
||||
`Workspace::include_sources()` (the include graph's `includers()`, plus open
|
||||
buffers). Worked alongside the rename-family QA pass in the same worktree;
|
||||
see `docs/features/refactor-rename/README.md`'s QA log for the shared gate
|
||||
run.
|
||||
|
||||
### Gates
|
||||
|
||||
`cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace` (0
|
||||
failures workspace-wide) and `node editors/vscode/smoke.js` all pass — see the
|
||||
refactor-rename QA entry for the exact run, which covered this round's diff
|
||||
in the same pass. `file_ops::tests::perf::one_rename_sweeps_the_whole_corpus_in_milliseconds`
|
||||
and `includes::tests::perf::building_the_graph_over_the_whole_corpus_is_milliseconds`
|
||||
fail in this worktree because `corpus/` is not checked out here; confirmed
|
||||
pre-existing (unchanged by this diff, present at `HEAD` before it) and
|
||||
unrelated.
|
||||
|
||||
### Attacks
|
||||
|
||||
The safety-net argument this narrowing rests on ("a file with no entry in the
|
||||
edge table writes no `` `include`` this workspace can resolve") is
|
||||
mechanical and did not need attacking on its own terms — `nothing_skipped_
|
||||
has_an_include_to_rewrite` already asserts it directly over whatever tree a
|
||||
test builds. What was worth attacking is whether `includers()` narrows in
|
||||
**every** file that matters, not just the ones the dev's own tree happened to
|
||||
build:
|
||||
|
||||
- **An include chain, `a.svh -> b.svh`, with a third file `c.sv -> a.svh`
|
||||
never spelling `b.svh` at all.** Renaming `b.svh` must narrow to `a.svh`
|
||||
(its direct includer) and rewrite only it; `c.sv` must not be mistaken for a
|
||||
candidate even though it transitively depends on the moved file through
|
||||
`a.svh`. Added `an_include_chain_narrows_to_the_direct_includer_of_the_moved_file`
|
||||
— passes: `will_rename` only ever rewrites a *direct* include of the moved
|
||||
file, which is exactly what `includers()` (a flat key set, not a
|
||||
reachability walk) bounds.
|
||||
- **A case-mismatched include spelling** — `` `include "DEFS.svh"`` written
|
||||
against a real `defs.svh` on disk, which macOS's default case-insensitive
|
||||
filesystem (confirmed case-insensitive on this machine) resolves silently.
|
||||
`IncludeGraph::found`/`found_as_if` key `raw` by the **includer's own path**,
|
||||
not the target's spelling, so the case mismatch does not stop the includer
|
||||
from landing in `includers()`. Added
|
||||
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites` — passes,
|
||||
narrows in and rewrites correctly.
|
||||
- **Unsaved includer, and the property test's own coverage** — re-read
|
||||
`an_unsaved_include_is_still_rewritten` and
|
||||
`nothing_skipped_has_an_include_to_rewrite`; both hold and both are
|
||||
exercised (`assert!(skipped > 0, ...)` in the property test actually forces
|
||||
the tree to have skippable files, so the property is not vacuously true).
|
||||
|
||||
No divergence found: every file `will_rename` would have read under the old
|
||||
`ws.sources()` sweep and actually needed (an includer of something that
|
||||
resolves) is still read under `include_sources()`, and no file that used to
|
||||
be read-and-skipped is now silently mis-included either. The `includes.rs`
|
||||
scope deviation the dev flagged (a four-line, purely additive accessor,
|
||||
outside Lane A's stated file list) is accepted as argued — the only
|
||||
alternative was a second copy of the include scan, which the feature's own
|
||||
Handshakes section already forbids.
|
||||
|
||||
### Summary
|
||||
|
||||
| Claim | Verdict |
|
||||
|---|---|
|
||||
| Gates | **Pass** |
|
||||
| `includers()` narrows in every file that can produce an edit or a warning | **Holds** under an include-chain attack and a case-mismatched-spelling attack, beyond the dev's own tree |
|
||||
| Scope deviation (`includes.rs::includers`) | Accepted, correctly flagged, minimal |
|
||||
|
||||
**Verdict: ship.** No findings against this round's diff. (The rename family's
|
||||
own residue finding, which needs the lead's ruling, is filed in
|
||||
`docs/features/refactor-rename/README.md` and does not touch this feature.)
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead, performance-wave Lane A (willRenameFiles).** The
|
||||
includers() narrowing is the same discipline as the rename fan-out
|
||||
applied to the include graph, QA's chain/case-spelling/unsaved attacks
|
||||
all pinned, and the property test ("nothing skipped has an include to
|
||||
rewrite") is the right shape of guarantee. Accepted; merged by the
|
||||
lead.
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
|
||||
@@ -15,6 +15,32 @@ per notification.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Amended (incremental-index, 2026-08-27): one notification is still one
|
||||
rescan, but a notification naming exactly one held source file takes the
|
||||
incremental path** — that file's contribution replaced, no progress bar, no
|
||||
log lines. A checkout filling the list, and a notification naming the
|
||||
filelist, are whole rebuilds exactly as before. `watch::one_scope_file` is
|
||||
the test. See `docs/features/incremental-index/README.md`.
|
||||
|
||||
- **Amended (index-scope, 2026-08-28): this feature now carries a little more
|
||||
weight than it did, and the difference is named here rather than left to be
|
||||
found.** A scope-widening `didOpen` used to run a whole rescan, which re-read
|
||||
every in-scope file and so *incidentally* caught anything that had changed on
|
||||
disk behind the server's back. Since that round it indexes only the folders it
|
||||
added. For a client that advertised
|
||||
`workspace.didChangeWatchedFiles.dynamicRegistration` — VS Code and Neovim
|
||||
both do — nothing is lost: the registered glob covers create, change and
|
||||
delete of every source file in the workspace, which is the mechanism, and the
|
||||
widen never was. For a client that did not, the **save-only model this README
|
||||
already documents is slightly narrower**: an external change in a folder
|
||||
already in scope now waits for the next whole rescan (a save of a file the
|
||||
index does not hold, a settings change, a folder change, a rename/delete
|
||||
notification) instead of possibly being caught by the next jump. That is the
|
||||
same class of window, not a new one — a save has taken the one-file
|
||||
incremental path since 2026-08-27, so such a session already had no reliable
|
||||
whole-tree re-read. Written up in full in
|
||||
`docs/features/index-scope/README.md`.
|
||||
|
||||
- **Registration is the only way in.** The protocol has no static
|
||||
`didChangeWatchedFiles` server capability — a server that wants file events
|
||||
must ask for them with `client/registerCapability`, and only a client that
|
||||
|
||||
@@ -127,8 +127,11 @@ Highest first, resolved on every index rebuild:
|
||||
| # | Scope | When |
|
||||
|---|---|---|
|
||||
| 1 | The files a **filelist** names | `lucisv.filelist` is set (absolute, or relative to the first workspace root), else the workspace root's `lucisv.toml` has a `filelist` key |
|
||||
| 2 | The **workspace-folder walk** | there is a workspace root — unchanged from before this feature |
|
||||
| 3 | Each **open file's own directory**, non-recursive | there is no workspace root at all (a single file opened) |
|
||||
| 2 | The **workspace-folder walk** | ~~there is a workspace root~~ **superseded (index-scope, 2026-08-27): `lucisv.index.scope: "workspace"` asks for it; it is no longer the default** |
|
||||
| 3 | Each **open file's own directory** | ~~non-recursive; there is no workspace root at all~~ **superseded (index-scope, 2026-08-27): this is now the default rung with a root too, raised `lucisv.index.scopeDepth` levels and walked. The non-recursive read survives unchanged for the rootless session at depth 0. See `docs/features/index-scope/README.md`** |
|
||||
|
||||
Rung 1 — this feature — is untouched by that round: a filelist is the project
|
||||
file, and it still defines the scope exactly, in any session.
|
||||
|
||||
Open buffers overlay every rung exactly as they did before: a buffer's text
|
||||
beats what is on disk, and a buffer whose path the scope does not name is
|
||||
|
||||
@@ -51,7 +51,9 @@ parser** a push does, so the two paths cannot drift.
|
||||
disk in the index by contributing itself (`Workspace::collect_sources` adds
|
||||
every open document with a path, whatever the scope ladder said). Removing
|
||||
the *last* folder is not a special case either: the session becomes the
|
||||
rootless one rung 3 of the scope ladder already describes, where the scope
|
||||
rootless one rung 3 of the scope ladder already describes (which
|
||||
index-scope, 2026-08-27, made the default rung for a rooted session as
|
||||
well), where the scope
|
||||
is the open buffers' own directories.
|
||||
- **One set of settings per session, not one per folder.** The pull sends no
|
||||
`scopeUri`. `ClientSettings` is a single struct read by `format::settings_for`
|
||||
@@ -72,6 +74,12 @@ parser** a push does, so the two paths cannot drift.
|
||||
first index is built against the default scope, and a pulled
|
||||
`lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands.
|
||||
Nothing is *wrong* in between, it is simply the wider scope.
|
||||
**2026-08-27:** `lucisv.index.maxFileSize` joins those two — a pulled cap
|
||||
that differs from the 1 MiB default costs the same one extra rescan — and
|
||||
`lucisv.index.logFiles` shows the other face of the same fact: the startup
|
||||
scan narrates itself at the default (on) whatever the user's setting says,
|
||||
because their answer has not arrived yet. Both are
|
||||
`docs/features/indexing-ux/README.md`.
|
||||
|
||||
## The settings model, stated once
|
||||
|
||||
|
||||
@@ -24,6 +24,21 @@ The five:
|
||||
5. `always @( /* c */ * )` loses the comment: `parse_sens_list` discarded
|
||||
comments written inside the parens of an implicit sensitivity list.
|
||||
|
||||
**Round 2 (2026-08-29, Lane B of the testbench-syntax wave).** The same
|
||||
feature, extended to `syntax_coverage.md`'s bucket 2: the 12 real OpenTitan
|
||||
files that parse with zero errors but whose *formatted output* the safety net
|
||||
refused. Three more bugs, all in `format.rs`'s layout, none needing a
|
||||
`verify.rs` change:
|
||||
|
||||
6. A line comment trailing the then-branch's `end` swallowed the `else` that
|
||||
followed it (`end // addr_phase_write` + `else if (...) begin` came back as
|
||||
one comment). 4 of the 12 files.
|
||||
7. A comment written inside a statement header's parentheses (`if (// why` ⏎
|
||||
`cond)`, `while (`, `repeat (`, `wait (`, `case (`) printed *after* the
|
||||
`)`, moving it across a token. 7 of the 12 files.
|
||||
8. `default;` — the case-item colon IEEE 1800 §12.5 makes optional — came
|
||||
back as `default:`, inventing a token the source never wrote. 1 file.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The four `#SKIP` expected outputs are the spec. None of them was changed.
|
||||
@@ -66,6 +81,46 @@ The five:
|
||||
enclosing group in this printer. The hug only applies when the value already
|
||||
contains a forced break, so no case without comments changed.
|
||||
|
||||
### Round 2 (2026-08-29)
|
||||
|
||||
- **`verify.rs` was not touched at all this round** (`git diff` on it is
|
||||
empty), and no normalization was added or broadened. Every fix is a layout
|
||||
change in `format.rs`; the safety net's judgement of all three shapes is
|
||||
unchanged, and four crafted (input, corrupted output) pairs assert it still
|
||||
rejects exactly the corruptions these bugs used to produce.
|
||||
- **The parser's trivia attachment is taken as given.** Nothing between a
|
||||
statement header's `(` and `)` owns trivia, so a comment written there is
|
||||
queued and lands on the next node that takes meta — the body statement, or
|
||||
a `case`'s first item. The formatter takes it back by *span* rather than
|
||||
asking the parser to change: a leading comment of the body that starts
|
||||
before the header's `)` was written inside the parentheses. This is Lane B's
|
||||
file-set constraint made into a design point, and it is exact, because a
|
||||
comment's byte span says unambiguously which side of the `)` it was on.
|
||||
- **The `)` is found in the source, not in the AST**, by skipping whitespace
|
||||
and comments forward from the end of the condition expression
|
||||
(`skip_trivia`). Only trivia can stand there for `if`/`while`/`repeat`/
|
||||
`wait`/`case`. If anything else turns up, the header prints its plain
|
||||
parentheses and takes nothing, so an unrecognized shape behaves exactly as
|
||||
it did before.
|
||||
- **A cuddled `else` is a layout decision, not a token.** `end` keeps `else`
|
||||
on its line unless the then-branch's own trailing comments end in a line
|
||||
comment, which would swallow it. A block comment still cuddles
|
||||
(`end /* why */ else`).
|
||||
- `for`, `foreach` and `do ... while` are **not** covered: the first two do
|
||||
not end their header in a single condition expression, and a `do`-`while`
|
||||
has no body after its parentheses to take the comment back from. All three
|
||||
still refuse cleanly and are pinned as refusals by a test.
|
||||
- A comment written *before* a header's `(` (`if /* c */ (a)`) is also not
|
||||
covered — the formatter has no offset for the `(`, so such a comment is
|
||||
treated as if it were inside and the file is still refused, exactly as it
|
||||
was before. No corpus use.
|
||||
- **`default;` is read from the source too.** `CaseItem` records no `colon`
|
||||
flag (the parser does `let _ = self.eat_sym(":")`), so `default_has_colon`
|
||||
looks at the byte after the keyword. With a null body the `;` hugs the
|
||||
keyword — `default;`, not `default ;` — while `default: ;` keeps both the
|
||||
colon and the space it already had. Generate-case `default` reads the same
|
||||
way.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser::token::Comment` gained a position** (the handshake request
|
||||
@@ -102,6 +157,80 @@ The five:
|
||||
and the top-level `README.md` (another agent's scope) are untouched;
|
||||
`cargo fmt` was run and left those files byte-identical.
|
||||
|
||||
### Round 2 (2026-08-29)
|
||||
|
||||
- **Nothing was changed outside `crates/vlog_formatter`.** Round 2 consumes
|
||||
the AST exactly as it stands: `Comment.span`, `Expr.span`, `CaseItem.span`
|
||||
and `Meta.leading`'s source order are the only new load-bearing surfaces,
|
||||
and all four already existed. `git diff` on `crates/vlog_parser` and
|
||||
`crates/vlog_semantic` is empty.
|
||||
- **Open handshake request to whoever owns `vlog_parser/src/parser.rs`
|
||||
(Lane A's file this wave).** `Parser::take_before_open` (`parser.rs:757`)
|
||||
calls `take_dangling()`, which drains the *whole* pending-comment queue —
|
||||
`pending_trailing`, `pending_leading` and the bracket token's own leading
|
||||
comments — rather than only the comments actually written in front of the
|
||||
bracket. So a comment written just after a statement header's `(` is
|
||||
swallowed by the first call inside the condition and printed between that
|
||||
call's callee and its own `(`:
|
||||
|
||||
```systemverilog
|
||||
if (// If keymgr is not enabled in the current LC
|
||||
!cfg.keymgr_vif.get_keymgr_en() || ...
|
||||
```
|
||||
|
||||
comes back as `!cfg.keymgr_vif.get_keymgr_en // If keymgr ...` ⏎ `() ||`.
|
||||
`header_parens` cannot take it back — it never reaches the body's leading
|
||||
comments — and the formatter cannot hoist it out past the `!` without a
|
||||
cutoff threaded through every `expr` call, which is far more machinery than
|
||||
the parser fix. **Requested fix**: in `take_before_open`, keep only the
|
||||
comments whose `span.start >= self.last_end()`, i.e. those written in the
|
||||
gap that ends at the bracket, and leave the rest queued. `last_end()`
|
||||
already exists (`parser.rs:611`). This is the last of the 12 bucket-2 files
|
||||
(`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv`); the shape is pinned as a
|
||||
clean refusal by
|
||||
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
|
||||
which is the test that should flip to a `.cases` entry when the parser fix
|
||||
lands.
|
||||
- **Format-cache discipline** (`topo.md` §2.3): this round changes formatter
|
||||
*output* for the shapes above, so the workspace version must be bumped at
|
||||
release or a stale `.lucisv_cache` will skip files that would now format
|
||||
differently. Flagged for the lead; no version was bumped here.
|
||||
|
||||
### Round 2's `take_before_open` request — **DELIVERED** (2026-08-29)
|
||||
|
||||
Filed by round 2 against whoever owns `crates/vlog_parser/src/parser.rs`;
|
||||
answered by the `directive-in-statements` round (see
|
||||
`docs/features/directive-in-statements/README.md`). The requested change and
|
||||
one more site it needed:
|
||||
|
||||
- `Parser::take_before_open` no longer calls `take_dangling()`. It takes only
|
||||
the comments whose `span.start >= self.last_end()` — the gap that ends at
|
||||
the bracket — through a new narrow sibling, `Parser::take_gap()`. Exactly
|
||||
the fix round 2 specified.
|
||||
- **That alone was not enough.** `CallComments::dangling` (the inside of an
|
||||
*empty* `()`, `parser.rs`'s postfix-call arm) drained the whole queue too,
|
||||
so with `before_open` fixed the comment was swallowed one line later —
|
||||
which is why the pinned shape's condition starts `!en()` and not `!en(x)`.
|
||||
It now uses `take_gap()` as well. Both sites are `CallComments`; nothing
|
||||
else changed.
|
||||
|
||||
Verified by composing this lane's parser with round 2's worktree in a
|
||||
scratchpad copy (round 2's files read-only, never edited): the whole workspace
|
||||
suite stays green except
|
||||
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
|
||||
which flips from pass to fail — i.e. the shape now formats — and the real
|
||||
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` formats cleanly, closing the 12th
|
||||
and last bucket-2 file. That test should become a `.cases` entry at merge, as
|
||||
round 2 predicted. Round 2's `expect_divergence` attack pairs all still pass:
|
||||
`verify.rs` is untouched by either lane.
|
||||
|
||||
Still open, and **not** this handshake: `return // c` ⏎ `g();`, round 2's
|
||||
"second, independent symptom". The parser no longer misplaces that comment
|
||||
into the call, but nothing owns a comment written between `return` and its
|
||||
expression, so it drifts and the safety net still refuses the file — refused
|
||||
before this round and refused after, byte-identical either way. It needs a
|
||||
comment slot on `StmtKind::Return`, which is an AST change with printer arms.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Bug 3 — closing block labels preserved (`end`, all `join` kinds,
|
||||
@@ -131,6 +260,34 @@ The five:
|
||||
The "re-enable the four `#SKIP` cases" item lives in the case-tables
|
||||
README's TODO and is now satisfied.
|
||||
|
||||
### Round 2 (2026-08-29)
|
||||
|
||||
- [x] Bug 6 — a line comment trailing `end` no longer swallows the `else`
|
||||
that follows it; a block comment still cuddles.
|
||||
- [x] Bug 7 — a comment written inside an `if`/`while`/`repeat`/`wait`/`case`
|
||||
header's parentheses is printed inside them, on the correct side of the
|
||||
condition.
|
||||
- [x] Bug 8 — `default;` keeps IEEE 1800 §12.5's optional colon off, and
|
||||
`default: ;` keeps it on.
|
||||
- [x] 11 of the 12 bucket-2 OpenTitan files format cleanly and are
|
||||
idempotent; the whole checkout is unchanged on disk. Before/after in
|
||||
the work log.
|
||||
- [x] 11 new `.cases` entries (10 in `comments.cases`, 1 in
|
||||
`statements.cases`) — each one asserts the output *and* that
|
||||
re-formatting it is a fixed point, which is what the harness does.
|
||||
- [x] 4 masked-corruption rejection pairs + an explicit
|
||||
comments-never-dropped assertion in `verification.rs`, plus 4 pinned
|
||||
refusals for the shapes deliberately left uncovered.
|
||||
- [x] `cargo fmt --check` clean, `cargo clippy --all-targets` silent,
|
||||
`cargo test --workspace` green, pinned corpus 813/820 (baseline 813,
|
||||
zero verification errors).
|
||||
- [ ] Not fixed, needs a change in `vlog_parser` (see Handshakes): a comment
|
||||
after `if (` when the condition starts with a call —
|
||||
`keymgr_scoreboard.sv`, the 12th file.
|
||||
- [ ] Not fixed, no corpus evidence, pinned as refusals: a comment inside a
|
||||
`for`/`foreach` header or a `do ... while (...)`; a comment written
|
||||
between a header keyword and its `(`.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-18 — dev agent
|
||||
@@ -239,6 +396,109 @@ an indented banner comment) formats cleanly, and `lucisv` on its own output is
|
||||
byte-identical. Every bug's original repro from the two feature READMEs was
|
||||
re-run through the built CLI and now exits 0.
|
||||
|
||||
### 2026-08-29 — dev agent (Lane B, testbench-syntax wave)
|
||||
|
||||
**Scope.** `syntax_coverage.md`'s bucket 2: the 12 OpenTitan files that parse
|
||||
with zero errors but whose formatted output the safety net refused. Measured
|
||||
first, against the real checkout at `/Users/guoliangchen/repo/opentitan`
|
||||
(`--no-cache --check` over all 3,943 `.sv`/`.svh`): **151 failures, 12 of them
|
||||
`verification failed:`** — reproducing the sweep exactly. The 12 are three
|
||||
shapes, not one:
|
||||
|
||||
| # | shape | files |
|
||||
|---|---|---|
|
||||
| 6 | `end // c` ⏎ `else …` — the trailing line comment swallows the `else` | 4 |
|
||||
| 7 | a comment inside a statement header's `(...)` prints after the `)` | 7 |
|
||||
| 8 | `default;` comes back as `default:` | 1 |
|
||||
|
||||
**Bug 6 — `end // c` then `else`.** `if_stmt` cuddled `else` onto the `end`
|
||||
line whenever the then-branch was a block. `stmt_as_body` has already printed
|
||||
the block's trailing comments by then, so ` else if (b) begin` landed *inside*
|
||||
a line comment's text and `verify.rs` saw one comment reading
|
||||
`// addr_phase_write else if (addr_phase_read) begin`. The whole fix is one
|
||||
extra condition on `then_is_block`: a free `trailing_ends_line(&then.meta)`
|
||||
that asks whether the last thing `trailing` prints is a `//` comment. A block
|
||||
comment still cuddles, which is what the source wanted anyway.
|
||||
|
||||
**Bug 7 — comments inside a header's parentheses.** The header's `(` and `)`
|
||||
are printed by `parens()` and belong to no node, so the parser has nowhere to
|
||||
put a comment written between them: it stays in the pending queue and lands on
|
||||
the next node that calls `take_meta` — the body statement (`if`, `while`,
|
||||
`repeat`, `wait`) or the first case item (`case`). Printed there, the comment
|
||||
sits after a `)` it was written before.
|
||||
|
||||
Fixed entirely on the formatter side, by span. `header_parens(cond, body_meta)`
|
||||
finds the closing `)` with `skip_trivia` (forward from `cond.span.end`; only
|
||||
whitespace and comments can stand there), takes every leading comment of the
|
||||
body that starts before it, splits them at `cond.span.start` into before/after
|
||||
buckets, and hands them to `paren_comments` — which is the existing
|
||||
`ExprKind::Paren { before, after }` layout, factored out and now shared by both
|
||||
callers rather than duplicated. It returns how many comments it consumed;
|
||||
`stmt_as_body_from` / `leading_from` / `case_body` skip exactly that many.
|
||||
`leading`, `stmt_as_body` and `case_body`'s old signature are all preserved as
|
||||
`skip = 0` wrappers, so the twelve other `stmt_as_body` call sites are
|
||||
untouched. When the source is not the expected shape (no `)` where one was
|
||||
expected, or nothing to take) the function returns the plain `parens(cond)` and
|
||||
takes nothing, so every input that formatted before formats identically.
|
||||
|
||||
`for`, `foreach` and `do ... while` were deliberately left out: the first two
|
||||
do not end their header in one condition expression and the third has no body
|
||||
after its parens. Confirmed they still refuse cleanly and pinned that with a
|
||||
test, so a later round sees them change rather than appear.
|
||||
|
||||
**Bug 8 — `default;`.** `parse_case_body` does `let _ = self.eat_sym(":")`, so
|
||||
the AST does not record whether the source wrote the colon, and `case_labels`
|
||||
printed `default:` unconditionally — inventing a token. Since `CaseItem.span`
|
||||
starts at the `default` keyword, `default_has_colon` reads the byte after it
|
||||
(through the same `skip_trivia`) and prints what was written. With a null body
|
||||
the `;` hugs the keyword, because `stmt_as_body` would otherwise lay the `;`
|
||||
out as a body and produce `default ;`. `default: ;` is unchanged.
|
||||
|
||||
**`verify.rs` is untouched** — `git diff` on it is empty. Per `topo.md` §2.1's
|
||||
standing template I added the rejection tests anyway: four crafted (input,
|
||||
corrupted output) pairs asserting the net still refuses the comment merged into
|
||||
`else if`, the comment moved across the `)`, `default;` → `default: ;` and its
|
||||
mirror `default: ;` → `default;`.
|
||||
|
||||
**Before / after on the real OpenTitan checkout** (3,943 files, `--no-cache
|
||||
--check`, nothing ever written — `git status` in the corpus shows only the
|
||||
pre-existing `hw/ip/aes/dv/tb/tb.sv` modification `syntax_coverage.md` already
|
||||
records):
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| total failures (exit 2) | 151 | 140 |
|
||||
| `verification failed:` | 12 | **1** |
|
||||
| `parse error:` / `lex error:` | 139 | 139 |
|
||||
| crashes | 0 | 0 |
|
||||
|
||||
All 11 fixed files were additionally formatted twice through `--stdout` and the
|
||||
two passes compared byte-for-byte: **idempotent**, and every checkout file's
|
||||
`md5` is unchanged. Pinned 820-file corpus: **813 passing** (baseline 813),
|
||||
zero verification errors, zero crashes — no regression.
|
||||
|
||||
**The 12th file, and why it is not mine to fix.**
|
||||
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` had *two* bucket-2 bugs; fixing the
|
||||
first (the `end // addr_phase_write` / `else if` merge at line 643) uncovered a
|
||||
second at line 1254 that is not a formatter layout bug at all. The comment
|
||||
there is written after `if (` and the condition starts with a call, so
|
||||
`Parser::take_before_open` — which drains the whole pending queue — hands it to
|
||||
`CallComments::before_open`, and the formatter faithfully prints it between the
|
||||
callee and its `(`. `header_parens` never sees it. Hoisting it back out of the
|
||||
expression past the `!` would need a suppression cutoff threaded through every
|
||||
`expr` call; the parser fix is one span check. Filed as an open handshake
|
||||
(above) with the exact patch, out of Lane B's file set, and pinned as a clean
|
||||
refusal by a test. Also confirmed the same parser bug bites
|
||||
`return // c` ⏎ `g();`, which is a second, independent symptom.
|
||||
|
||||
**Deviation from the brief**: 11 of 12 files, not 12, for the reason above.
|
||||
Nothing was worked around and no corruption ships — the 12th file is still
|
||||
refused and left byte-identical, which is the correct behavior until the parser
|
||||
lands its fix.
|
||||
|
||||
**Format-cache note for the lead**: formatter output changed, so the workspace
|
||||
version must be bumped at release (`topo.md` §2.3). Not bumped here.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
@@ -485,8 +745,187 @@ compliance (no unwrap/expect/panic in library paths, no new deps, no
|
||||
un-explained `#[allow]`, TODO.md/README.md/`lucisv` untouched) all confirmed
|
||||
by direct inspection, not just by trusting the work log's claims.
|
||||
|
||||
### 2026-08-29 — QA agent (Lane B, testbench-syntax wave)
|
||||
|
||||
**Scope**: round 2 only — the three bucket-2 fixes (bug 6 `end // c` + `else`,
|
||||
bug 7 `header_parens`, bug 8 `default;`) — with the adversarial charter aimed
|
||||
squarely at a dropped/merged comment, an invented/moved token, or a fix that
|
||||
only works on the corpus shapes. Built a `--no-cache --stdout`/`--check`
|
||||
attack harness (pass1 → pass2 byte comparison for idempotency) and ran ~30
|
||||
hand-crafted `.sv` files beyond the committed cases, then reproduced every
|
||||
number in the work log independently against the real checkouts.
|
||||
|
||||
**Tool chain** (workspace root, after adding the two regression tests below):
|
||||
`cargo fmt --check` clean; `cargo clippy --all-targets` silent, no new
|
||||
`#[allow]`; `cargo test --workspace` green — `vlog_formatter`'s
|
||||
`verification.rs` at 119/119 (118 + 1 new), `cases.rs` 1/1 (672 total cases
|
||||
across all `.cases` files, `grep -c '#SKIP'` zero everywhere). Confirmed
|
||||
`git diff --stat` on `crates/vlog_parser`, `crates/vlog_semantic`,
|
||||
`crates/vlog_formatter/src/verify.rs` is empty — the "verify.rs untouched"
|
||||
claim holds.
|
||||
|
||||
**Shape-A attacks (`end // c` / `else`)** — 5 crafted files: nested three-deep
|
||||
if-else-if chain with every `end` individually commented (correct, stable);
|
||||
the comment text containing the literal word "else" (correct, not
|
||||
mistaken for structure); a CRLF-terminated file with the same shape
|
||||
(correct); a pure block comment before `else` (still cuddles, as designed).
|
||||
**One real gap found** (below) with a mixed block+line trailing comment.
|
||||
|
||||
**Shape-B attacks (`header_parens`)** — 9 crafted files hitting the source
|
||||
scan directly: a `)` inside a string literal in the condition
|
||||
(`s == ")"`), a `)` inside a nested paren sub-expression, a `)` spelled
|
||||
inside a block comment (`/* looks like ) but is not */`), comments on both
|
||||
sides of the `cond.span.start` split simultaneously, a condition that is
|
||||
itself a `Paren` (double parens), `case`/`while`/`repeat`/`wait` each with
|
||||
both-sided comments, and a case with two commented items after the header to
|
||||
attack the skip-count plumbing. **All format correctly, keep every comment
|
||||
in its original stream position, and are idempotent — no corruption, no
|
||||
double-print, no drop.** Also re-confirmed the two documented refusal
|
||||
boundaries directly (not just via `cargo test`): a comment before the
|
||||
statement keyword's `(` (`if /* c */ (a)`) refuses cleanly (`token stream
|
||||
diverges ... input has comment ... output has symbol "("`), and a comment
|
||||
before a call in the condition refuses cleanly, matching the Handshakes
|
||||
description exactly.
|
||||
|
||||
**Shape-C attacks (`default`)** — 9 crafted files: `default ;` (extra space)
|
||||
normalizes to `default;`; `default: ;` unchanged; `default begin end` /
|
||||
`default: begin end` both correct with the colon exactly as written;
|
||||
`default y = 9;` (no colon, non-null body — a shape not explicitly named in
|
||||
the work log but legal per the same IEEE grammar) correctly keeps the colon
|
||||
off; two `default`s in one `case` (illegal but tolerated) round-trips both
|
||||
correctly; `default /* c */: y = 9;` (comment between keyword and colon)
|
||||
refuses cleanly rather than dropping or moving the comment. **One
|
||||
non-blocking style nit found** (below): a trailing comment on `default;`
|
||||
breaks the hug. `default;` inside a `generate case` without `begin`/`end`
|
||||
hits a **pre-existing parser error** ("expected item"), confirmed unrelated
|
||||
— `default begin : gd end` in the same position parses and formats fine, so
|
||||
this is generate-case's existing null-body restriction, not a regression
|
||||
from this round.
|
||||
|
||||
**Refusal-pin sabotage check**: confirmed by inspection that `StmtKind::For`
|
||||
and `StmtKind::DoWhile` were not touched by the diff at all (no
|
||||
`header_parens` call added), so their pinned refusal test is exercising the
|
||||
same pre-existing, unmodified comment-position divergence check from round
|
||||
1 — not a vacuous pass against dead code.
|
||||
|
||||
**Masked-corruption template**: all four crafted pairs genuinely attack the
|
||||
paths this round changed (else-swallow, comment-across-`)`, colon invented,
|
||||
colon dropped) rather than generic corruptions; re-ran them independently
|
||||
via `cargo test -p vlog_formatter the_bucket_two_corruptions_are_still_rejected`.
|
||||
|
||||
**Numbers reproduced independently**, all against the live checkouts, all
|
||||
read-only (`--check`/`--stdout` only):
|
||||
- OpenTitan (`/Users/guoliangchen/repo/opentitan` @ `0098135264`, the same
|
||||
pre-existing `hw/ip/aes/dv/tb/tb.sv` local edit `syntax_coverage.md`
|
||||
records, nothing else dirty): `lucisv --no-cache --check .` →
|
||||
**exactly 1** `verification failed:` (`hw/ip/keymgr/dv/env/
|
||||
keymgr_scoreboard.sv:1254`, byte-identical message to the Handshakes
|
||||
quote). Total failure count differs slightly from the work log's 140
|
||||
(146 here) — attributable to `.gitignore`/vendor-tree walk differences
|
||||
between sweeps, not to this round; the load-bearing number (verification
|
||||
failures) matches exactly.
|
||||
- Grepped the whole checkout for the three trigger shapes independently of
|
||||
the work log's file list (`end\s*//.*\n\s*else`, `(if|while|repeat|wait|
|
||||
case)\s*\(\s*//`, `^\s*default\s*;`) and got **exactly 12** candidate
|
||||
files. Ran each through format+idempotency: **10 format cleanly and are
|
||||
pass1==pass2 idempotent**, `keymgr_scoreboard.sv` is the documented
|
||||
refusal, and one grep hit (`spi_device_scoreboard.sv`) fails on an
|
||||
unrelated pre-existing macro-expansion parse error
|
||||
(`` `CREATE_TPM_CASE_STMT ``) before the formatter ever reaches the
|
||||
bucket-2 shape — confirms "11 of 12" exactly, with the 12th grep hit
|
||||
being a false positive from the search pattern, not a second bug.
|
||||
- Corpus gate: fetched `tools/corpus_fetch.sh`'s four pinned repos (820
|
||||
files: 131 + 613 + 35 + 41, matches exactly) and ran `scripts/score.sh`:
|
||||
`{"passing":813,"total":820,...}` — the exact baseline, zero
|
||||
`verification failed:` entries in `.score-results.tsv` (the 7 failures
|
||||
are all pre-existing parse/lex errors, none in the `other` bucket is a
|
||||
verification error).
|
||||
|
||||
**Findings**
|
||||
|
||||
*Should-fix*: none. No hard-invariant violation found in either crafted
|
||||
attacks or the real checkouts.
|
||||
|
||||
*Nit / informational* (both non-blocking — the safety net holds in both
|
||||
cases; regression tests added for both):
|
||||
|
||||
1. **`trailing_ends_line` (`format.rs`, the `Some(tr)` arm) checks whether
|
||||
the *merged* trailing text starts with `//`, not whether it ends in a
|
||||
line comment.** `Meta.trailing` merges several trailing comments into one
|
||||
string (see `ast.rs:92-96`); a line comment must physically be last in
|
||||
any such merge (nothing can follow `//` on the same source line), so the
|
||||
correct test is "does the merge end in one", not "does it start with
|
||||
one". For `end /* a */ // b` the merged text is `"/* a */ // b"`, which
|
||||
does not start with `//`, so `trailing_ends_line` returns `false` and
|
||||
`then_is_block` stays `true` — the `else` still tries to cuddle, exactly
|
||||
reproducing the bug this round fixes, on the one merge shape the fix's
|
||||
condition doesn't cover. **Not a corruption**: `verify.rs` catches it on
|
||||
reparse (the output's one merged comment doesn't match the input's two)
|
||||
and the file is refused, byte-identical, same as it was before this
|
||||
round (this exact shape always cuddled unconditionally pre-fix too, so
|
||||
it is not a regression — it is the fix's coverage boundary, undocumented
|
||||
until now). Pinned as a refusal, not fixed — narrowing `is_line_comment`
|
||||
into a "starts vs. ends" split is a real design decision (the merge
|
||||
already lost the individual comments' boundaries) that belongs to
|
||||
whoever next touches this heuristic, not a QA-scope patch. Regression
|
||||
test: `crates/vlog_formatter/tests/verification.rs::
|
||||
a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`.
|
||||
2. **A trailing comment on a colon-less `default;` breaks the hug and
|
||||
inserts a space**: `default; // fallback` formats to `default ; //
|
||||
fallback`. Root cause: `case_item`'s shortcut requires `is_bare(&item.
|
||||
stmt.meta)`, and a comment trailing the null statement lands in `item.
|
||||
stmt.meta.trailing`, which is not bare, so the shortcut is skipped and
|
||||
the general `case_labels` + `stmt_as_body` path inserts its usual
|
||||
`Doc::Line` between the label and the body. **Not a correctness issue**:
|
||||
the comment is kept verbatim in its original stream position, `verify.rs`
|
||||
accepts it (whitespace is not part of the token stream), and it is
|
||||
idempotent. It does contradict the round's stated design point
|
||||
("`default;`, not `default ;`") for this one sub-case. Pinned with an
|
||||
exact-output case rather than fixed, since teaching the shortcut to also
|
||||
fire with a bare-except-trailing-comment statement (and then print that
|
||||
comment itself) is a small but real behavior change outside a
|
||||
verify-and-report QA pass. Regression case:
|
||||
`crates/vlog_formatter/tests/cases/statements.cases`, "a trailing
|
||||
comment on a colon-less `default;` keeps the comment and the missing
|
||||
colon".
|
||||
|
||||
**Regression tests added this pass** (2 files, both green):
|
||||
- `crates/vlog_formatter/tests/verification.rs`:
|
||||
`a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`
|
||||
(finding 1 above, pins the safe refusal).
|
||||
- `crates/vlog_formatter/tests/cases/statements.cases`: one new case (finding
|
||||
2 above, pins the current — correct but slightly odd — output).
|
||||
|
||||
**Overall verdict**: **SHIP.** Both bucket-2 fixes claimed (11/12 files,
|
||||
verification failures 12→1) are reproduced exactly against the live
|
||||
OpenTitan checkout and the pinned 813/820 corpus, `verify.rs` is
|
||||
byte-for-byte untouched, and every crafted adversarial input across all
|
||||
three shapes either formats correctly with every comment preserved in place
|
||||
and idempotently, or is safely refused with the file left untouched — never
|
||||
corrupted. The two findings are both informational nits with permanent
|
||||
regression tests now guarding them; neither is a hard-invariant violation
|
||||
and neither blocks merge.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead, round 2 (bucket-2 round-trip bugs).** Reviewed
|
||||
after QA's SHIP; gates re-run on the worktree (fmt clean, formatter
|
||||
suite green). Three shapes, three root causes, all fixed where the bug
|
||||
lived — format.rs — with verify.rs, the parser and the semantics
|
||||
provably untouched, and the standing template honored: rejection tests
|
||||
added anyway, four of them attacking the fixed paths specifically.
|
||||
The dev's best decision was the one it did NOT make: the twelfth file
|
||||
is a parser bug (take_before_open draining the pending-comment queue),
|
||||
and it was filed as a specified Handshake instead of a cross-lane
|
||||
edit — the directive round is delivering it. QA's two informational
|
||||
pins are accepted as filed: the block-plus-line trailing-comment
|
||||
boundary stays a clean refusal (the safety net's job, done), and the
|
||||
`default ; // comment` stray space is a style wrinkle, not a token
|
||||
change. 11 of 12 files independently confirmed on the real checkout,
|
||||
corpus exactly at baseline. Formatter output changed, so the release
|
||||
bumps the workspace version per the format-cache rule — flagged and
|
||||
carried. Accepted; merged by the lead.
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes
|
||||
needed.**
|
||||
|
||||
|
||||
@@ -59,13 +59,19 @@ pair unrolls as far as the user keeps clicking.
|
||||
`TextRange::contains` excludes the end, which is right for a span of text
|
||||
and wrong for a caret — that is where a double-click and an end-of-word
|
||||
motion leave it.
|
||||
- **The scope ladder decides which files are searched.** `incomingCalls`
|
||||
reads `Workspace::sources()`, so a file a filelist or an `exclude` keeps out
|
||||
of the index instantiates nothing, exactly as it references nothing
|
||||
- **The scope ladder decides which files are searched.** `incomingCalls` reads
|
||||
the index's instantiation-edge table (incremental-index, 2026-08-27; it read
|
||||
`Workspace::sources()` before), so a file a filelist or an `exclude` keeps
|
||||
out of the index instantiates nothing, exactly as it references nothing
|
||||
(`docs/features/references-nav/README.md`).
|
||||
- **Open buffers beat disk.** The same `sources()` overlay every other
|
||||
- ~~**Open buffers beat disk.** The same `sources()` overlay every other
|
||||
cross-file answer uses, so an instantiation just typed and not yet saved is
|
||||
already a caller.
|
||||
already a caller.~~ **Superseded (incremental-index, 2026-08-27): the census
|
||||
is as of the index.** An index is built and updated from `collect_sources`,
|
||||
which still overlays every open buffer — so a save, or any other rescan
|
||||
trigger, makes a just-typed instantiation a caller. A keystroke alone no
|
||||
longer does. The trade is argued in
|
||||
`docs/features/incremental-index/README.md`.
|
||||
- **Nested module declarations.** Legal SystemVerilog; today's parser recovers
|
||||
them into sibling items rather than nesting them. The walk carries the
|
||||
innermost enclosing declaration either way, so both spellings attribute
|
||||
@@ -95,12 +101,13 @@ pair unrolls as far as the user keeps clicking.
|
||||
- **Consumes `vlog_parser`** — `parse_source_tolerant` for every file that is
|
||||
not the open buffer, `ast::Module`/`Instantiation` (read-only),
|
||||
`Item::span`, `LineIndex`. Nothing new is asked of the crate.
|
||||
- **Consumes `vlog_semantic::WorkspaceIndex`** — `units(name)` and
|
||||
`path(file)`, to turn a module name into the file that declares it. The
|
||||
index records what a file *declares* and **not what it instantiates**: there
|
||||
is no edge table, which is why `incomingCalls` walks files rather than
|
||||
querying. Adding such a table is a real option and is recorded as backlog
|
||||
below rather than assumed here.
|
||||
- **Consumes `vlog_semantic::WorkspaceIndex`** — `units(name)`, `path(file)`
|
||||
and, since 2026-08-27, `instantiations_of(name)`. The index records what a
|
||||
file instantiates now as well as what it declares, so `incomingCalls` is a
|
||||
lookup and the walk-and-parse body it used to have is gone
|
||||
(`docs/features/incremental-index/README.md`). The walk itself lives in
|
||||
`vlog_semantic::instantiations` — lifted out of this crate so the index's
|
||||
census and this module's per-buffer one are the same function.
|
||||
- **Consumes `crate::state::Workspace`** — `document`, `index`, `text_of`,
|
||||
`sources`. Nothing in `state.rs` was changed; the workspace stays immutable
|
||||
through all three handlers, and no cache was added.
|
||||
@@ -154,7 +161,14 @@ Release build, this machine, the checked-in 860-file corpus:
|
||||
| `outgoingCalls` for the corpus's densest module (`uart_reg_top.sv`, 63 instantiation sites, 4 distinct resolvable targets) | **2.2 ms** |
|
||||
| the same `incomingCalls` in a debug build | 106 ms |
|
||||
|
||||
Two things the table says. First, `incomingCalls` costs **4× less than M7's
|
||||
**Superseded (incremental-index, 2026-08-27).** The table above is what the
|
||||
walk cost; the edge table named below as "the place a future win lives" is
|
||||
where it went — `incomingCalls` is a lookup, and the only I/O left is reading
|
||||
the files that really do instantiate the name. The sibling measurement is a
|
||||
whole file's code lenses over the same corpus, 92 ms → 0.26 ms
|
||||
(`docs/features/incremental-index/README.md`). The reasoning the table
|
||||
supported, kept legible:
|
||||
~~Two things the table says. First, `incomingCalls` costs **4× less than M7's
|
||||
`textDocument/references`** on the same corpus (218 ms) even though it answers
|
||||
a superset of the question — it needs the *caller*, not just the span. The
|
||||
reason is the prefilter: a module that is instantiated somewhere has its name
|
||||
@@ -163,7 +177,7 @@ before it is parsed, and 834 of 860 files are. Second, what is left is
|
||||
**almost entirely file I/O** — `sources()` reads every in-scope file whether
|
||||
it will be parsed or not. That is the shared cost of every cross-file answer
|
||||
in this server, and the place a future win lives (see backlog); nothing in
|
||||
this feature can shave it alone.
|
||||
this feature can shave it alone.~~
|
||||
|
||||
`prepare` and `outgoingCalls` never walk the workspace at all: they parse the
|
||||
buffer and, at most, one file per distinct instantiated module.
|
||||
@@ -208,12 +222,12 @@ lucisv-server qa_perf_worst_case -- --ignored --nocapture`).
|
||||
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`,
|
||||
`cargo test --workspace`, `editors/vscode/smoke.js`
|
||||
- [x] `docs/features/lucisv-server/README.md` capability table + work log
|
||||
- [ ] Not done, backlog: an **instantiation edge table in `WorkspaceIndex`**,
|
||||
built with the index, which would make `incomingCalls` a map lookup and
|
||||
cost one extra tree walk per file at index time. Worth doing when
|
||||
something else wants the same edges (a design-tree view, an
|
||||
unused-module lint); today one request in 56 ms does not justify
|
||||
widening the index's contract.
|
||||
- [x] ~~Not done, backlog:~~ **done (incremental-index, 2026-08-27):** an
|
||||
**instantiation edge table in `WorkspaceIndex`**, built with the index,
|
||||
which makes `incomingCalls` a map lookup and costs one extra tree walk
|
||||
per file at index time. What finally wanted the same edges was the code
|
||||
lens paying the same 56 ms on every request, and a round that had to
|
||||
touch the index anyway.
|
||||
- [ ] Not done, deliberately: type hierarchy (`typeHierarchy`) for classes,
|
||||
interface and program instantiations as their own node kind, and any
|
||||
whole-tree "show me the design" view — this milestone is exactly the
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
# hover-declarations
|
||||
|
||||
## Goal
|
||||
|
||||
Hovering a name declared in **this** file has always shown the declaration
|
||||
itself — `local_text` prints the kind, the name and the source lines
|
||||
`decl_span` covers. Hovering a name declared in *another* file showed only
|
||||
`**port** — declared in `sub.sv:3``: enough to navigate to, not enough to read.
|
||||
The owner's ask (2026-08-27) is that the cross-file card carry the declaration
|
||||
too — for a port its direction, type and width, `input logic [7:0] addr` — so
|
||||
that reading a connection list does not require jumping out of the file. This
|
||||
round adds a fenced `systemverilog` snippet of the declaration's source line(s)
|
||||
under each candidate's existing heading, fetched at hover time and omitted
|
||||
entirely whenever it could be the wrong line.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The index stays text-free.** `Def` is `{file, name_span, kind}` and the
|
||||
persisted facts and `FACTS_FORMAT` are untouched
|
||||
(`docs/features/workspace-index/README.md`,
|
||||
`docs/features/index-persistence/README.md`). A hover is a rare, one-name,
|
||||
human-speed request; reading one file to answer it is the same trade
|
||||
`locate::line_number` has always made for the `file:line` half of the card.
|
||||
- **`reference.name` is the declared name.** Every `Definition::External`
|
||||
answer comes from a reference (`ExternalResolutions::definition_of` looks the
|
||||
target up by `ReferenceId`), and `resolve_external` finds the `Def` by
|
||||
passing exactly that `name` to `WorkspaceIndex::units` / `member`. So the
|
||||
name is the bare declared spelling — `WIDTH` for a `p::WIDTH` use, `clk` for
|
||||
a `.clk(...)` connection — never a qualified path. That is what makes it
|
||||
usable as the guard's expected text.
|
||||
- **Disk text is what the index was built from.** `Workspace::text_of` prefers
|
||||
an open buffer, which is right for a location and wrong for a snippet, so the
|
||||
open case is handled separately and never reaches `text_of`.
|
||||
- **A `decl_span` may be enormous.** A module's `decl_span` is its whole body
|
||||
(`bind_module` passes the item span), and one netlist line has no bound at
|
||||
all — hence the two caps below.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed**
|
||||
|
||||
- `crate::nav::indexed_def_for_symbol` — raised from private to `pub(crate)`,
|
||||
behaviour byte-for-byte unchanged. `nav.rs` walks it live-symbol → indexed
|
||||
`Def`; this feature walks the same relation the other way (scan the open
|
||||
buffer's symbols for the one that maps to this `Def`), which is precisely
|
||||
what `nav.rs`'s own `include_declaration` block already does for the
|
||||
declaration location. One matcher, so a hover snippet and a
|
||||
go-to-definition can never disagree about which declaration is which.
|
||||
- `Workspace::document_for_path`, `Workspace::text_of`, `WorkspaceIndex::path`.
|
||||
- `crate::convert::Positions::whole_lines`, `vlog_parser::LineIndex`.
|
||||
- `vlog_semantic::{Def, Symbol}` — read only; nothing added to either.
|
||||
|
||||
**Promised**
|
||||
|
||||
- `nav.rs` keeps its behaviour: the visibility change is the only edit to it,
|
||||
and its whole test module stays green unmodified.
|
||||
- The `` ```systemverilog `` fence tag is used for the new block, as the
|
||||
fence-tag contract in `docs/features/lucisv-server/README.md` requires — it
|
||||
is the only thing that colours a hover card.
|
||||
- Nothing is added to `Def`, to the facts file, or to `FACTS_FORMAT`; a cache
|
||||
written before this round is still current after it.
|
||||
**Superseded 2026-08-28 by `docs/features/port-detail-spans/README.md`**,
|
||||
which adds `Def::detail_span`, writes it in every declaration record and
|
||||
bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is
|
||||
discarded. This round's own promise held while it was this round's to
|
||||
make; the index is text-free either way (a span is not text).
|
||||
**Superseded again 2026-08-28 by `docs/features/hover-line-index/README.md`**,
|
||||
which adds `Def::lines` (each declaration's line number) and bumps
|
||||
`FACTS_FORMAT` 3 → 4. Same reading: a line number is not text either, and
|
||||
it is what makes this feature's heading free.
|
||||
- The heading line `**label** — declared in `file:line`` is unchanged, so a
|
||||
client (or a test) reading only that half sees exactly what it saw before.
|
||||
|
||||
## How the snippet is fetched
|
||||
|
||||
`declaration_snippet(ws, def, name)` in `hover.rs`, once per candidate:
|
||||
|
||||
1. **The target file is open** (`ws.document_for_path`). The index's span is
|
||||
against that file's *last saved* text, so an unsaved edit above the
|
||||
declaration has already moved it and reading the buffer at `def.name_span`
|
||||
would print whatever those offsets now cover. Match the `Def` to a live
|
||||
symbol **logically** instead — same name, and `indexed_def_for_symbol` maps
|
||||
it back to this same `Def` — and widen that symbol's live `decl_span` to
|
||||
whole lines.
|
||||
2. **Not open**: `ws.text_of(path)` (disk, since no buffer backs it), a fresh
|
||||
`LineIndex`, and `def.name_span` widened to whole lines.
|
||||
3. **Guard, both paths.** Slice the chosen text at the chosen name span and
|
||||
require it to equal the hovered name. `str::get` returns `None` for a span
|
||||
that runs past the text or lands mid-character, so a stale or shifted span
|
||||
fails the check rather than panicking. Any failure — unreadable file, no
|
||||
live symbol, text that does not spell the name — drops the snippet and
|
||||
leaves today's card exactly as it was. **A hover must never lie; less
|
||||
information beats wrong information.**
|
||||
|
||||
Note the asymmetry, and that it is deliberate: the open path widens
|
||||
`decl_span` (mirroring `local_text`, which is the only span a live symbol
|
||||
offers that covers a whole multi-line declaration), the disk path widens
|
||||
`def.name_span` (the only span the index holds). For the declarations the ask
|
||||
is about — ports, parameters, typedefs, a module header — both are one line
|
||||
and the two paths print the same thing.
|
||||
|
||||
## Cutting it down
|
||||
|
||||
`cut_to_size` trims trailing blank space (as `local_text` does; leading
|
||||
indentation stays, so the line reads as written) and then applies two caps,
|
||||
each with its own note under the fence:
|
||||
|
||||
| Cap | Value | Why |
|
||||
|---|---|---|
|
||||
| lines | `SNIPPET_LINES` = 5 | a module's `decl_span` is its whole body |
|
||||
| characters | `SNIPPET_CHARS` = 400 | one netlist line can be megabytes |
|
||||
|
||||
A cut appends ` …` inside the fence and `*shown to N lines*` /
|
||||
`*shown to N characters*` after it — the same shape as the macro card's
|
||||
`*truncated at N characters*`, so the two footnotes read as one convention.
|
||||
The character cap counts `char`s and cuts on a boundary.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `declaration_snippet` with the open-buffer and disk paths.
|
||||
- [x] Guard on both paths; snippet omitted on any mismatch.
|
||||
- [x] Line and character caps with a note.
|
||||
- [x] One snippet per candidate for an ambiguous name.
|
||||
- [x] `indexed_def_for_symbol` shared with `nav.rs`, behaviour unchanged.
|
||||
- [x] Tests (9 new, in `hover.rs`'s own test module).
|
||||
- [x] Hover row + hover section in `docs/features/lucisv-server/README.md`.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- Not done, deliberately: no facts/cache change, nothing in `vlog_semantic`,
|
||||
no TODO.md edit (no existing checklist item covers this; §8's hover items
|
||||
are all already checked, and inventing one is out of scope).
|
||||
- [x] **2026-08-28**: one disk read per file per hover (`disk_view` memo);
|
||||
QA finding 4 closed.
|
||||
- [x] **2026-08-28**: `live_symbol` (and `nav::indexed_references`) look a
|
||||
name up instead of scanning every symbol, with the first-match
|
||||
tie-break pinned by test.
|
||||
- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior
|
||||
`\r` into the fence; QA finding 2 closed.
|
||||
- [x] **2026-08-28** (`docs/features/hover-line-index/README.md`): the disk
|
||||
path's heading costs no read at all (`Def::lines`) and its snippet's
|
||||
read is shared across hovers, so the second hover into a closed file is
|
||||
free. `disk_view` is gone, subsumed by `Workspace::file_view`.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev
|
||||
|
||||
- Read the brief, `hover.rs`, `nav.rs`, `state.rs` and `convert.rs`. Confirmed
|
||||
the two facts the design rests on: `set_document` does **not** rebuild the
|
||||
index (so an open buffer really can hold a span the index does not know
|
||||
about — the case step 1 exists for), and `follow_one` looks a `Def` up by
|
||||
`reference.name`, which is what licenses using that name as the guard's
|
||||
expected text rather than trying to recover a name from `Def`.
|
||||
- Added `declaration_snippet`, `live_symbol`, `span_text`, `fenced` and
|
||||
`cut_to_size` to `hover.rs`, plus the two caps as consts. `symbol_hover`'s
|
||||
`External` arm now appends the snippet to each candidate's part; the heading
|
||||
it appends to is untouched.
|
||||
- Raised `nav::indexed_def_for_symbol` to `pub(crate)` with a doc line naming
|
||||
the second caller. No other change to `nav.rs`.
|
||||
- Decision: the open path uses `decl_span` and the disk path `name_span`,
|
||||
per the brief. Considered using `name_span` on both for symmetry — it would
|
||||
make a big module's card one header line rather than five — but that would
|
||||
drop the live-buffer case's only handle on a multi-line declaration, and the
|
||||
line cap already bounds the damage. Recorded in *How the snippet is fetched*
|
||||
so the asymmetry is a decision and not an accident.
|
||||
- Decision: no fallback from the open path to disk text. If a file is open and
|
||||
no live symbol matches, the buffer has been edited past the index and the
|
||||
indexed span is exactly the thing that cannot be trusted; falling back would
|
||||
re-introduce the wrong-line risk the guard exists to remove.
|
||||
- Nine tests added (listed below). Ran the gates: fmt
|
||||
clean, clippy `--all-targets` clean, `cargo test --workspace` green at 2372
|
||||
passed / 0 failed / 12 ignored.
|
||||
|
||||
**Tests added** (all in `crates/lucisv_server/src/hover.rs`, `mod tests`):
|
||||
|
||||
| Test | Pins |
|
||||
|---|---|
|
||||
| `a_cross_file_port_connection_shows_the_ports_own_declaration_line` | the ask: direction + type + width, and only that port's line |
|
||||
| `a_cross_file_module_instance_shows_its_header_line` | the module header, disk path |
|
||||
| `a_package_member_shows_its_declaration_line` | a `localparam` and a `typedef` through `import p::*` |
|
||||
| `an_unsaved_edit_that_moved_the_declaration_is_read_at_its_live_span` | live line, not the stale-span line (asserts the *new* width and the absence of the old) |
|
||||
| `a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line` | guard, disk half: file rewritten under a live index → no fence at all, heading intact |
|
||||
| `an_open_buffer_that_no_longer_declares_the_name_drops_the_snippet` | guard, live half: the port renamed away in the buffer |
|
||||
| `a_very_long_declaration_line_is_cut_with_a_note` | the character cap and its note |
|
||||
| `a_declaration_spanning_many_lines_is_cut_at_the_line_limit` | the line cap, via an open module whose `decl_span` is its body |
|
||||
| `two_files_declaring_one_name_each_get_their_own_snippet` | ambiguous name: both headings, both snippets |
|
||||
|
||||
### 2026-08-28 — dev (performance: one disk read, one name lookup)
|
||||
|
||||
Parts A2 and A3 of the "Improve LSP performance + hover accuracy" round.
|
||||
Behavior of every card is unchanged; both items are the same answer, reached
|
||||
with less work. Numbers in `docs/perf/README.md`.
|
||||
|
||||
- **A2 — one read per file per hover.** A hover into a *closed* file used to
|
||||
read that file and build a `LineIndex` over it twice: once in
|
||||
`locate::line_number` for the `file:line` heading, once in
|
||||
`declaration_snippet` for the fenced lines. This is QA's finding 4 below,
|
||||
and it is now closed. `symbol_hover` holds a per-request memo — one
|
||||
`(path, text, LineIndex)` in `disk_view` — that the heading and the snippet
|
||||
both read, and `declaration_snippet` no longer touches the disk at all: it
|
||||
is now the *open-buffer* path only, with the closed-file path inlined in
|
||||
`symbol_hover` beside the heading it shares a read with. The
|
||||
`spells_exactly` guard applies on both paths exactly as before. A card
|
||||
naming one file twice (two declarations in one file) now pays for one read,
|
||||
not two, which is why the memo is keyed by path rather than being a single
|
||||
`Option` per candidate.
|
||||
- Measured: 34 ms → 16.3 ms on QA's own 31.7 MB measurement, and 141 µs of
|
||||
a 148 µs hover at 10 000 lines is that one read. See `docs/perf`.
|
||||
- QA's measurement test was renamed
|
||||
`hovering_into_a_large_closed_file_reads_it_twice` →
|
||||
`..._reads_it_once`, since the doubling it was named for is gone. The QA
|
||||
log below still names the old spelling; that section is QA's to amend.
|
||||
- **A3 — `live_symbol` stops scanning every symbol.** Walking the whole
|
||||
buffer's symbol table and calling `nav::indexed_def_for_symbol` (two index
|
||||
lookups) on every symbol whose name happened to match — and reaching every
|
||||
symbol whose name did not — became a name-keyed lookup:
|
||||
`vlog_semantic::Semantics::symbols_named(name)`, two binary searches over a
|
||||
side table of symbol ids sorted by name, built once during `analyze`. Only
|
||||
same-named declarations are probed. A side table rather than a
|
||||
`HashMap<String, Vec<SymbolId>>` so that `Semantics` — which is cloned per
|
||||
document — does not carry a second copy of every name it already holds;
|
||||
four bytes per symbol against a `String` per symbol.
|
||||
- **The tie-break is preserved.** The map's lists are built by walking the
|
||||
symbols in order, so `symbols_named` yields declaration order — the same
|
||||
order, and the same first match, the old `symbols().iter().find(..)`
|
||||
made. Pinned by `looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
|
||||
in `crates/vlog_semantic/tests/semantics.rs`, which compares the two
|
||||
answers directly and asserts the earlier declaration comes first. QA's
|
||||
`duplicate_live_declarations_of_one_name_pick_the_first_one_silently`
|
||||
(finding 3 below) still passes, unchanged.
|
||||
- `nav.rs`'s `indexed_references` had the same scan-by-name for the
|
||||
declaration's live span; it is the same swap and was made in the same
|
||||
change, for the same reason.
|
||||
- `vlog_refactor::ports.rs:1154` has a third one (`symbols().iter()
|
||||
.position(|s| s.name == port && …)`). It is not a trivial swap — the
|
||||
predicate carries a kind and a span test and the code wants the
|
||||
*position* as a `SymbolId` — and it is in another crate, so it is left
|
||||
alone and recorded here rather than done.
|
||||
- Cost: four bytes per symbol. Measured saving on the lookup alone:
|
||||
8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`).
|
||||
|
||||
### 2026-08-28 — dev (the heading stops reading the file at all)
|
||||
|
||||
Round `hover-line-index` — full argument, measurements and tests in
|
||||
`docs/features/hover-line-index/README.md`. What changed *here*:
|
||||
|
||||
- **The `External` arm's disk branch no longer reads anything for the
|
||||
heading.** `Def` now carries `lines: DeclLines`, recorded when the file was
|
||||
indexed, so `**port** — declared in `sub.sv:2`` is a field lookup. The live
|
||||
branch is untouched and still asks the open buffer's own line index, because
|
||||
that buffer may hold unsaved edits the index has not seen — the same reason
|
||||
`declaration_snippet` matches a `Def` to a live symbol logically.
|
||||
- **`disk_view` was deleted.** Its job — one read per file per hover — is now
|
||||
`Workspace::file_view`'s, which does it once per file per *generation of that
|
||||
file*, so the next hover into the same file reads nothing. The four points
|
||||
that drop a held view are listed in that round's Handshakes.
|
||||
- **`spells_exactly` and both caps are untouched**, and a stale held view can
|
||||
only ever make a snippet vanish. Every existing test in this file passed
|
||||
unmodified.
|
||||
- **One corner moved deliberately**: a closed file that cannot be *read* now
|
||||
still gets its line in the heading (`sub.sv:2` rather than a bare `sub.sv`),
|
||||
because the line no longer depends on the read. Pinned by
|
||||
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read`.
|
||||
- Measured: a hover into a 12 MB closed file, 6.2 ms → **0.95 µs** on the
|
||||
second hover; the 31.7 MB probe above, 17.0 ms → **4.4 µs** on the second.
|
||||
The first touch is unchanged, because the snippet genuinely wants the text.
|
||||
|
||||
### 2026-08-28 — dev (CRLF, closing QA finding 2)
|
||||
|
||||
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
|
||||
`\r` inside the fence — is **fixed**, as part of `port-detail-spans`' PDS-4.
|
||||
Every line a card shows now goes through `attached_lines`, which strips a
|
||||
trailing `\r` as it composes each line; that covers both this feature's
|
||||
snippet path and `local_text`'s in-file path, which QA named as having the
|
||||
same property, because both reach it through `fenced_sections`. Display
|
||||
text only: no buffer is written.
|
||||
- QA's pinned regression test was named for the old behaviour
|
||||
(`a_crlf_multiline_snippet_keeps_interior_carriage_returns`) and asserted
|
||||
it; it is now `a_crlf_multiline_snippet_carries_no_carriage_returns` and
|
||||
asserts the opposite, plus that the lines read as written. The QA log below
|
||||
still names the old spelling; that section is QA's to amend.
|
||||
- No other change to this feature. `spells_exactly`, the caps and the
|
||||
disk/live split are untouched.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA
|
||||
|
||||
Read the brief, the dev's Work log, and `crates/lucisv_server/src/hover.rs` /
|
||||
`nav.rs` in full. Ran the gates first (all green before any probing): `cargo
|
||||
fmt --check` clean, `cargo clippy --all-targets --workspace -- -D warnings`
|
||||
clean, `cargo test --workspace` green — 1173 passed / 0 failed / 12 ignored
|
||||
(pre-existing) before this round's own probes were added.
|
||||
|
||||
Then attacked `declaration_snippet`, `live_symbol`, `span_text` and
|
||||
`cut_to_size` along the seven angles in the charter. Eight probe tests added
|
||||
to a new `mod qa_hover_declarations` in `hover.rs` (one `#[ignore]`d perf
|
||||
measurement); one real defect found and fixed with a ninth test pinning it.
|
||||
|
||||
**Finding 1 — MEDIUM, fixed.** *The guard was a fixed-length substring check,
|
||||
not a whole-identifier check, so an edit that only **extends** a name defeats
|
||||
it.* `declaration_snippet`'s guard (`hover.rs:243` and `:252`, before the fix)
|
||||
compared `span_text(text, span)` — a slice of exactly `name.len()` bytes at
|
||||
the *old, recorded* offset — against `name`. `def.name_span`'s length is
|
||||
whatever the name was when the index was last built; it does not grow if the
|
||||
file is edited without a reindex. So: index built on `input logic [7:0]
|
||||
addr;`, then the file is rewritten on disk to `input logic [7:0] addr2;`
|
||||
*without* triggering a reindex (an ordinary edit-then-hover-before-save-event
|
||||
race, exactly the staleness window this feature's guard exists for). The old
|
||||
span still covers exactly the four bytes `"addr"` — a *prefix* of the new
|
||||
`"addr2"` — so `span_text` returns `Some("addr")`, equals the hovered name,
|
||||
and the guard passed. The card for `.addr(...)` then showed
|
||||
`` input logic [7:0] addr2 `` under a heading that says `addr`'s declaration,
|
||||
one line pretending to be a name it is not — exactly the masked-corruption
|
||||
shape CLAUDE.md's invariant 4 is about, applied to this round's new safety
|
||||
net rather than `verify.rs`.
|
||||
- Repro (was a failing/panicking assertion, now a passing regression test):
|
||||
`a_disk_edit_that_only_appends_to_the_name_defeats_the_guard`,
|
||||
`hover.rs:1060`.
|
||||
- Fix: added `spells_exactly` (`hover.rs:293`) and `continues_a_name`
|
||||
(`hover.rs:306`), and switched both guard call sites
|
||||
(`declaration_snippet`'s live and disk branches) to it. It keeps the
|
||||
existing text-equality check and additionally requires that the
|
||||
character immediately outside the span on either side (if any) is not an
|
||||
identifier-continuation character (`[A-Za-z0-9_$]`) — turning a
|
||||
prefix/suffix match back into a miss. Applied to *both* branches for one
|
||||
guard, one guarantee, even though the live branch's `symbol.name_span`
|
||||
(a token span from a fresh parse) could not actually suffer this —
|
||||
`symbol.name == name` was already checked before the span comparison, so
|
||||
the length always matched there. No behavior change for any span that is
|
||||
a genuine whole identifier, which is every case the dev's 9 tests and the
|
||||
existing corpus tests exercise — full `cargo test --workspace` stayed
|
||||
green (1173 passed / 0 failed / 13 ignored, the 13th being this round's
|
||||
own perf probe) after the fix.
|
||||
- This does **not** close every staleness gap by design — a same-length
|
||||
edit that changes an identifier into a different same-length identifier,
|
||||
or that changes what a name's *kind* means without renaming it, is still
|
||||
the accepted risk window the Assumptions section already names ("a hover
|
||||
is a rare, one-name, human-speed request"). What the fix removes is
|
||||
specifically the case where the *shown text visibly disagrees with the
|
||||
name in the heading* — the one the guard's stated promise ("never show a
|
||||
wrong line") is about.
|
||||
|
||||
**Finding 2 — LOW, filed, not fixed.** *A CRLF file's multi-line snippet
|
||||
keeps the embedded `\r` on every interior line, only the last one is
|
||||
trimmed.* `cut_to_size` (`hover.rs`, unchanged by QA) calls `trim_end()` once
|
||||
on the whole cut string, which strips a *trailing* `\r` (and `\n`) but not an
|
||||
interior one before a kept newline. `local_text` (the in-file branch,
|
||||
pre-existing, not part of this round) has the identical property via the same
|
||||
`whole_lines`/`trim_end` shape, so this is not new behavior introduced by
|
||||
this feature, just newly reachable from a second call site. Cosmetic, not a
|
||||
correctness break: the bytes shown are exactly the file's own bytes, and a
|
||||
fenced code block renders them close to verbatim either way. Pinned as a
|
||||
permanent regression test rather than fixed, since a real fix (stripping
|
||||
`\r` before every kept `\n`, in both `local_text` and here) is a
|
||||
cross-cutting change to shared rendering, out of this round's stated scope
|
||||
(`hover.rs`'s `External` arm and its shared helper with `nav.rs`).
|
||||
- Repro: `a_crlf_multiline_snippet_keeps_interior_carriage_returns`,
|
||||
`hover.rs:1156`.
|
||||
|
||||
**Finding 3 — LOW/accepted, pinned as a regression test, not a defect of this
|
||||
round.** *Two live declarations of the same name+kind in one open buffer (a
|
||||
transient mid-edit state, e.g. a duplicate line not yet deleted) make
|
||||
`live_symbol`'s `.find()` pick whichever comes first in `Semantics::symbols()`
|
||||
order, silently.* `indexed_def_for_symbol` (`nav.rs:164`, visibility-only
|
||||
change this round) maps *any* live symbol with a matching name/kind/owner
|
||||
back to the single persisted `Def` for that name when the index itself has
|
||||
only one — it does not know or care that the *live* buffer momentarily has
|
||||
two. This is inherited, unchanged behavior from `nav.rs`'s existing
|
||||
go-to-definition matcher (the Handshakes section calls this out on purpose:
|
||||
"one matcher, so a hover snippet and a go-to-definition can never disagree").
|
||||
Not a lie in the sense the guard is about — the guard still requires the
|
||||
*chosen* symbol's own span to spell the name exactly, which it always does
|
||||
here by construction — but it is a silent, unsignaled choice between two
|
||||
candidates. Filed rather than fixed: fixing it means changing
|
||||
`indexed_def_for_symbol`'s matching rule, which is nav.rs's and explicitly
|
||||
out of this round's scope ("nav tests must stay green," brief line 27).
|
||||
- Repro: `duplicate_live_declarations_of_one_name_pick_the_first_one_silently`,
|
||||
`hover.rs:1126`.
|
||||
|
||||
**Finding 4 — perf note, not a defect, no action taken.** *A hover resolving
|
||||
into a large closed file reads the file and builds a `LineIndex` over it
|
||||
twice*: once inside `locate::line_number` (for the `file:line` heading — this
|
||||
predates this round) and again inside `declaration_snippet` (for the
|
||||
snippet — new this round), independently, from the same disk path. Measured
|
||||
in release mode: a 31.7 MB synthetic file (600k filler lines behind a small
|
||||
port declaration, `maxFileSize` raised so it indexes at all) took 34 ms for
|
||||
one hover — acceptable for a rare, single-shot request, but a real, avoidable
|
||||
doubling of I/O and linear scan work per disk-path candidate. A fix would
|
||||
mean threading one read/`LineIndex` through both `line_number` and
|
||||
`declaration_snippet`, which touches `locate.rs` (also used by `macro_hover`)
|
||||
and is a small refactor rather than a one-line change — noted per the
|
||||
charter's "note it, don't redesign" rather than attempted.
|
||||
- Measurement, `#[ignore]`d (writes ~30 MB, not a correctness assertion):
|
||||
`hovering_into_a_large_closed_file_reads_it_twice`, `hover.rs:1325`. Run
|
||||
with `cargo test --release -p lucisv_server large_closed -- --ignored
|
||||
--nocapture`.
|
||||
- **Amended 2026-08-28 — QA.** Closed by A2 (`docs/perf/README.md`):
|
||||
`symbol_hover`'s `disk_view` memo now shares one read + one `LineIndex`
|
||||
between the heading and the snippet. Re-ran the same measurement (now
|
||||
named `..._reads_it_once`): **17.0 ms**, against the documented
|
||||
"34 ms → 16.3 ms" — matches within the run-to-run noise `docs/perf/
|
||||
README.md` itself calls out. No longer an open finding.
|
||||
|
||||
**Verified, no finding** (angles from the charter that turned up nothing):
|
||||
UTF-8 multi-byte content before a declaration, on the same file, does not
|
||||
panic `span_text`/`whole_lines` (`multibyte_utf8_before_the_declaration_does_not_panic`,
|
||||
`hover.rs`) — both are `.get()`-based and this stayed a belt-and-braces pin.
|
||||
A declaration at byte offset 0 and a declaration on the file's last line with
|
||||
no trailing newline both render correctly, no underflow
|
||||
(`a_declaration_at_the_very_start_of_the_file_is_shown`,
|
||||
`a_declaration_on_the_last_line_with_no_trailing_newline_is_shown`). The line
|
||||
cap (`SNIPPET_LINES` = 5) and character cap (`SNIPPET_CHARS` = 400) are both
|
||||
exact-boundary-safe — 5 lines / 400 chars is not cut, 6 lines / 401 chars is,
|
||||
and a 400-char boundary landing mid multi-byte character is not split because
|
||||
`cut_to_size` counts with `char_indices`, never raw bytes
|
||||
(`exactly_the_line_cap_is_not_cut_one_more_is`,
|
||||
`exactly_the_char_cap_is_not_cut_one_more_is_and_boundary_is_safe`). A
|
||||
case-mismatched open buffer (same file, different-case path on a
|
||||
case-insensitive filesystem) is not recognized as "the target file open" by
|
||||
`document_for_path`'s exact `PathBuf` equality, so it falls back to the disk
|
||||
path rather than mixing the two identities — the safe direction, confirmed
|
||||
with unsaved edits in the mismatched buffer never leaking into the card
|
||||
(`a_case_mismatched_open_buffer_is_not_recognized_as_the_target_falls_back_to_disk`,
|
||||
macOS/Windows-gated). Multiple ambiguous candidates each render from their
|
||||
own file with no cross-contamination — the dev's own
|
||||
`two_files_declaring_one_name_each_get_their_own_snippet` already covers
|
||||
this and reads fine without a divider between candidates (each fenced block
|
||||
is its own visual unit).
|
||||
|
||||
**Gates, final.** `cargo fmt --check` clean. `cargo clippy --all-targets
|
||||
--workspace -- -D warnings` clean. `cargo test --workspace`: 1173 passed / 0
|
||||
failed / 13 ignored (12 pre-existing + this round's one perf probe).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-27 — lead.** Reviewed the full diff after QA's SHIP verdict;
|
||||
gates re-run independently (fmt clean, clippy silent, 1173 server tests
|
||||
green). The shape is right: no widening of persisted facts, snippets
|
||||
fetched at hover time from whichever text the span is valid against
|
||||
(live logical match through `nav.rs`'s one matcher, disk otherwise),
|
||||
and a guard that prefers no snippet to a wrong one. QA's MEDIUM find —
|
||||
the fixed-length substring guard passing on a name that had merely been
|
||||
*extended* in place — is precisely the masked-corruption shape
|
||||
invariant 4 exists for, applied correctly to a new forgiveness path
|
||||
outside `verify.rs`; the `spells_exactly` boundary check closes it on
|
||||
both the live and disk paths and the attack test pins it. The
|
||||
deliberate asymmetry (live path shows `decl_span`, disk path the name's
|
||||
line) is documented and bounded by the caps; the duplicate-live-symbol
|
||||
tie-break is inherited from the shared matcher and correctly pinned
|
||||
rather than re-designed. The CRLF interior-`\r` cosmetic and the
|
||||
double-read of large closed files are accepted as filed. Accepted;
|
||||
committed by the lead.
|
||||
@@ -0,0 +1,551 @@
|
||||
# hover-line-index
|
||||
|
||||
## Goal
|
||||
|
||||
The owner's report (2026-08-28): hovering a module instantiation is slow, and
|
||||
hovering one of its ports — to see the port's own declaration — is slow on the
|
||||
**first** try. Both land on the same code: a hover whose target is declared in
|
||||
a *closed* file read that whole file and built a whole `LineIndex` over it, for
|
||||
two things at once — the heading's `file:line`, and the fenced snippet of the
|
||||
declaration. On a netlist-adjacent file that read is milliseconds, and nothing
|
||||
was kept, so the *next* hover into the same file paid it again. The owner's
|
||||
design, which this round implements: put each declared name's **line number**
|
||||
into the index itself, where it costs a `u32` per declaration and is computed
|
||||
once when the file is scanned. The heading then costs no file access at all,
|
||||
and only the snippet still wants text — served from a small bounded cache of
|
||||
closed files' text in `Workspace`, so the first touch pays one read and no
|
||||
touch after it pays anything.
|
||||
|
||||
The shape of what that buys, measured below: a hover into a 12 MB closed file
|
||||
goes **6.2 ms → 0.9 µs on the second hover** and stays 6.2 ms on the first;
|
||||
the steady-state cross-file hover on a 10 000-line file goes **157 µs →
|
||||
13 µs**. The round also *measured the other suspect* and did not fix it — see
|
||||
Handshakes.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A line is a fact about the same snapshot the span is.** `Def::name_span`
|
||||
and `Def::lines.name` are read off one text in one pass, so a heading and a
|
||||
snippet can never name different generations of a file. Where the file has
|
||||
changed on disk with nothing telling the server, both are stale together,
|
||||
which is strictly better than the previous shape — a stale *offset* looked
|
||||
up in *fresh* text, whose line was arbitrary.
|
||||
- **Lines are 1-based, and are exactly what `LineIndex::line_col` reports.**
|
||||
That is what `locate::line_number` returned before, so the same headings come
|
||||
out.
|
||||
- **`FileFacts::from_analysis`'s caller has a line index already.** It is a
|
||||
server holding an open buffer's finished `Document`, which carries one. So
|
||||
the extra parameter costs the caller nothing, and `FileFacts::of` builds its
|
||||
own — one pass over the source's newlines, about 1 % of the parse it sits
|
||||
beside (`docs/perf/README.md`: `LineIndex::new` 115 µs against
|
||||
`parse_tolerant` 14.3 ms at 10 000 lines).
|
||||
- **The view cache is a cache and never a correctness input.** Every entry can
|
||||
be dropped at any moment with no change to any answer; a *stale* entry can
|
||||
only ever make a snippet disappear, never make it wrong, because
|
||||
`hover::spells_exactly` still checks the text at the span against the hovered
|
||||
name before anything is shown. That guard is unchanged and is still the last
|
||||
line of defence.
|
||||
- **Only closed files are cached.** `Workspace::file_view` returns `None` for a
|
||||
path an open buffer speaks for: that buffer's `Document` already holds its
|
||||
text and line index, and a second copy here would be a second opinion.
|
||||
- **The index is still text-free.** A line number is not text, exactly as a
|
||||
span is not text (`docs/features/workspace-index/README.md`'s promise, and
|
||||
the same reading `port-detail-spans` took for `detail_span`).
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `vlog_semantic` — `DeclLines`, and the carrier's extension story
|
||||
|
||||
```rust
|
||||
/// Where a declaration sits in its file, counted in lines.
|
||||
pub struct DeclLines {
|
||||
pub name: u32, // 1-based line of the declared name
|
||||
pub detail: Option<u32>, // 1-based line the detail span starts on
|
||||
}
|
||||
|
||||
pub struct Def {
|
||||
pub file: FileId,
|
||||
pub name_span: TextRange,
|
||||
pub kind: SymbolKind,
|
||||
pub detail_span: Option<TextRange>,
|
||||
pub lines: DeclLines, // new
|
||||
}
|
||||
|
||||
// One added parameter, because a record now carries lines:
|
||||
impl FileFacts {
|
||||
pub fn from_analysis(path, tree, defines, sem, lines: &LineIndex) -> FileFacts;
|
||||
}
|
||||
pub const FACTS_FORMAT: u32 = 4; // was 3
|
||||
```
|
||||
|
||||
**The carrier is one value per declaration, and it extends by gaining a
|
||||
field.** That is the owner's explicit ask ("keep the implementation flexible so
|
||||
we might even cache the port location") answered structurally rather than
|
||||
promised:
|
||||
|
||||
- **Ports already ride it.** A module's ports and parameters are indexed as
|
||||
*members*, and a member is a `Decl` exactly as a unit is — so
|
||||
`index.member("sub", "addr").lines.name` is that port's line, recorded in the
|
||||
same pass, with no extra table, no extra pass and no extra decision about
|
||||
"small projects". The owner's optional second step was already paid for by
|
||||
the first.
|
||||
- **A split port's two lines ride it too.** A non-ANSI port is named in the
|
||||
header and finished in the body (`detail_span`,
|
||||
`docs/features/port-detail-spans/README.md`), and `DeclLines::detail` is that
|
||||
body's line — the second position datum, already present, in the same value.
|
||||
- **A third one is a field.** A column, a rendered preview, an end line: add it
|
||||
to `DeclLines`, write it in `Writer::decl`, read it in `Reader::decl`, bump
|
||||
`FACTS_FORMAT`. Nothing else moves, because nothing else knows how many
|
||||
fields a `DeclLines` has. **Taken, 2026-08-29**, and it went exactly that
|
||||
way: `docs/features/vscode-hierarchy-sidebar/README.md` added
|
||||
`positions: Option<DeclPositions>` — the declared name's and the whole
|
||||
declaration's ranges in the units a client counts in — for `FACTS_FORMAT`
|
||||
4 → 5, so a design-hierarchy snapshot needs no file text at all. The one
|
||||
amendment that round made to the story above: those positions ride
|
||||
**file-scope declarations only**, because members outnumber units by two
|
||||
orders of magnitude and the record's `U` and `M` groups are separate, so
|
||||
the absence costs a member nothing. A member still carries its lines. A *parallel table* keyed by declaration was the
|
||||
alternative and was rejected: it would have to be kept in step with `Decl`
|
||||
through every merge, every incremental update and every record round-trip,
|
||||
and there is no second consumer to justify the indirection
|
||||
(`CLAUDE.md`, "Simplicity first").
|
||||
|
||||
### `vlog_semantic` — `FACTS_FORMAT` 3 → 4, justified
|
||||
|
||||
A record's per-declaration group grew two fields. The rule written at the
|
||||
constant is that **any** change to what a record holds bumps the format, and
|
||||
the reason it is a whole-store discard rather than a migration is
|
||||
`docs/features/index-persistence/README.md`'s: a reader that guessed at an
|
||||
older layout would read last month's field order as this month's. Concretely,
|
||||
a format-3 record read as a format-4 one would shift every field after the
|
||||
first declaration by two — which is why the format field in the store's header
|
||||
catches it first, and why `decode` rejects it even if something served it past
|
||||
the header (both pinned, see Tests). The cost is one re-parse of the workspace
|
||||
on the first scan after upgrading; the corpus measurement below says that is
|
||||
about 175 ms.
|
||||
|
||||
### `vlog_semantic` — fingerprint
|
||||
|
||||
`WorkspaceIndex::fingerprint`'s `sym` line now carries `line=` and `detail=`.
|
||||
That is what makes the house witness — incremental index == fresh build —
|
||||
cover the new field rather than ignore it; every existing equivalence test
|
||||
(`update_file`, `update_facts`, `add_facts` from records, the corpus sweep)
|
||||
now compares lines as well as spans, and all of them stayed green unmodified.
|
||||
|
||||
### `lucisv_server::state` — the closed-file view cache
|
||||
|
||||
```rust
|
||||
pub struct FileView { pub path: PathBuf, pub text: String, pub lines: LineIndex }
|
||||
impl Workspace {
|
||||
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>>;
|
||||
}
|
||||
```
|
||||
|
||||
Bounded by **four entries** and **8 MiB of text**, newest first, oldest
|
||||
evicted. Two bounds because they answer two questions: how many files one
|
||||
answer can name (a card names one or two; a references list walks a handful
|
||||
before moving on), and how much memory a netlist-shaped file may cost. The
|
||||
newest entry is kept whatever it weighs — one file can exceed the whole byte
|
||||
budget on its own, and a cache that refused to hold it would be useless for
|
||||
exactly the file it exists for — so a huge file simply evicts everything else.
|
||||
|
||||
**Every invalidation point, in full.** A view is dropped when:
|
||||
|
||||
| event | what is dropped | why |
|
||||
|---|---|---|
|
||||
| `set_document(uri, text)` — `didOpen`, `didChange`, a text-carrying `didSave` | that path's view | the buffer becomes the authority, and the held disk copy may predate the edits it carries |
|
||||
| `close_document(uri)` | that path's view | disk is the authority again, and the view predates every save that buffer made |
|
||||
| `update_one(path)` | that path's view | re-indexing one file *is* the claim its bytes moved |
|
||||
| `rebuild_index_with(..)` | **all** views | a rescan says nothing about which file moved |
|
||||
|
||||
Those four are every path in the server that can change what a file holds:
|
||||
`server.rs` reaches the first two directly from the sync notifications, and the
|
||||
last two through `reindex_one` / `reindex`, which is where a save, a watched
|
||||
file change, a client file operation and a settings change all land.
|
||||
|
||||
What survives all four is a file changed on disk with nothing telling this
|
||||
server — and there the *index* is stale by the same event, which is precisely
|
||||
what `spells_exactly` exists for.
|
||||
|
||||
### `lucisv_server::locate` — the sweep
|
||||
|
||||
`locate::line_number` and `locate::location` were the only two functions that
|
||||
read a whole file to answer a position question, and `line_number`'s only
|
||||
callers were `hover.rs`'s two. Both now take an open buffer's own line index
|
||||
when there is one and the shared view otherwise; neither reads a file directly
|
||||
any more. `location`'s open-buffer arm also stops cloning the whole buffer text
|
||||
(`text_of` returns a `String`) on the way to a range. Mechanical, no behaviour
|
||||
change: `location` is what `textDocument/definition`, references, the lens and
|
||||
the hierarchies build their `Location`s from, and a references list over one
|
||||
file now reads that file once instead of once per site.
|
||||
|
||||
An indexed declaration's line no longer goes through `line_number` at all —
|
||||
`Def::lines` is the answer. What is left for it is the spans the index records
|
||||
no line for, which today is a `` `define``'s (the macro hover card's
|
||||
`defined in file:line`). Those ride the shared view, so a second macro hover
|
||||
into one file is free; giving `Define` its own line would mean a field in
|
||||
`vlog_parser`'s `Define` and is filed rather than done — it buys the first
|
||||
touch of one card and costs a second crate a field.
|
||||
|
||||
### Suspect 2 — **reported, not fixed here; DELIVERED 2026-08-28** by `docs/features/scan-interleave/README.md`
|
||||
|
||||
The brief named a second suspect and asked for it to be measured and filed
|
||||
rather than redesigned. It is real, and on the owner's own complaint it is by
|
||||
far the larger of the two:
|
||||
|
||||
`Server::new` runs the whole startup scan **before** `run()`'s message loop
|
||||
takes its first message. `main.rs` answers `initialize` (through
|
||||
`initialize_finish`, which also consumes `initialized`) and only then builds
|
||||
the `Server` — so everything a client sends the instant the handshake is done
|
||||
sits in the OS pipe until the scan is over. Measured over a 200-file, 1 000-
|
||||
line-each workspace with a filelist (so the startup scan really indexes it):
|
||||
|
||||
| the first hover of a session | cold store | warm store |
|
||||
|---|---:|---:|
|
||||
| issued the moment `initialized` was sent | **780 ms** | **287 ms** |
|
||||
| the same hover once the scan is done | 64 µs | 61 µs |
|
||||
|
||||
Four orders of magnitude, and this round does not touch it: fixing it means
|
||||
answering requests during the scan (or scanning on another thread), which is a
|
||||
change to request scheduling and to what an answer *means* while the index is
|
||||
half-built. `docs/features/index-persistence`'s store already takes it from
|
||||
780 ms to 287 ms; the rest is the read, the completion word table's lex and
|
||||
the include scan, which that feature's README already names as uncached.
|
||||
**Request to whoever owns the message loop next:** this is where "the first
|
||||
hover is really slow" mostly lives, and the probe that measures it is
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`.
|
||||
|
||||
**DELIVERED, 2026-08-28.** `docs/features/scan-interleave/README.md` took the
|
||||
scan apart into per-file steps and drains the message queue between them, so a
|
||||
startup scan long enough to be worth it answers requests while it runs. The
|
||||
same probe, flipped and renamed
|
||||
(`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`), now
|
||||
reports **15.5 ms cold / 12.8 ms warm** where the table above says 780 / 287 —
|
||||
and the scan's own total moved by under a percent. The request is closed; what
|
||||
that round did *not* do (the files are still read eagerly, a rescan still makes
|
||||
requests wait) is filed in its own Status/TODO with numbers.
|
||||
|
||||
## Measured
|
||||
|
||||
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
|
||||
`--release`, `#[ignore]`d probes, `--test-threads=1`, means where the numbers
|
||||
are small enough to need one. Every figure below was taken on 2026-08-28,
|
||||
before and after, in the same session.
|
||||
|
||||
### Suspect 1 — the per-hover read
|
||||
|
||||
| what | before | after |
|
||||
|---|---:|---:|
|
||||
| hover on an **instantiation** into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms |
|
||||
| — the same hover again | 5.75 ms | **0.95 µs** |
|
||||
| hover on a **port** into the same file, first touch | 5.85 ms | 5.92 ms |
|
||||
| — the same hover again | 5.71 ms | **0.99 µs** |
|
||||
| hover into a 31.7 MB closed file, first touch (QA's own probe) | 17.0 ms | 16.8 ms |
|
||||
| — the same hover again | 17.0 ms | **4.4 µs** |
|
||||
| cross-file hover, 1 000-line target, mean of 20 | 39.8 µs | **4.7 µs** |
|
||||
| cross-file hover, 10 000-line target, mean of 20 | 157 µs | **12.9 µs** |
|
||||
| — one read + `LineIndex` of that file, for comparison | 149 µs | 158 µs |
|
||||
|
||||
Read the table as two claims. **The first touch is unchanged**, and it should
|
||||
be: the snippet genuinely wants that file's text, and reading it is what the
|
||||
6.2 ms is. **Every touch after it is free**, which is the shape the owner's
|
||||
"slow on the FIRST try" report describes — and the heading half is free even
|
||||
on the first touch, which is why a card with no snippet (an unreadable file, a
|
||||
guard miss) now costs nothing at all.
|
||||
|
||||
### The price paid for it
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| whole 860-file corpus scan, no cache | 338 ms | 343 ms |
|
||||
| — cold, filling the store | 372 ms | 374 ms |
|
||||
| — warm, every file from the store | 197 ms | 200 ms |
|
||||
| the store, 860 files | 2 312 802 B | 2 380 790 B |
|
||||
|
||||
The scan times are inside their own run-to-run noise: the added work is one
|
||||
`LineIndex::new` per parsed file, which the flush breakdown puts at under 1 %
|
||||
of that file's parse. The store grows **68 KB over 860 files — 2.9 %**, which
|
||||
is the two decimal numbers per declaration over roughly 13 000 declarations,
|
||||
and is the owner's "a few KB for 20 000 modules" measured on real source.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Measure both suspects before touching anything; both recorded above.
|
||||
- [x] `DeclLines` on `Decl` and on `Def`, computed in `facts_from_analysis`
|
||||
from the file's own `LineIndex`.
|
||||
- [x] `FileFacts::from_analysis` takes the line index; `FileFacts::of` builds
|
||||
one.
|
||||
- [x] Record codec: two fields per declaration, `FACTS_FORMAT` 3 → 4, with the
|
||||
justification above.
|
||||
- [x] `WorkspaceIndex::fingerprint` carries the lines, so incremental == fresh
|
||||
covers them.
|
||||
- [x] `Workspace::file_view` — bounded, LRU, four named invalidation points.
|
||||
- [x] `hover.rs`: heading from `Def::lines`, snippet from the shared view; the
|
||||
per-request `disk_view` memo is gone, subsumed.
|
||||
- [x] `locate.rs` swept onto the buffer's index / the shared view.
|
||||
- [x] Tests (11 new, listed in the work log) and two new `#[ignore]`d probes.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- [ ] **Not done, deliberately: `` `define``s get no indexed line.** A
|
||||
`Define` is `vlog_parser`'s, and giving it a line means a field in
|
||||
another crate's public type plus its own record fields, to save the
|
||||
*first* macro hover into one file and nothing after it. The shared view
|
||||
already covers the repeat.
|
||||
- [ ] **Not done, deliberately: the other `text_of` callers are untouched.**
|
||||
`rename`, `ports`, `hierarchy`, `type_hierarchy`, `completion`,
|
||||
`signature`, `inlay` and `nav` read whole files because they want whole
|
||||
files, not a line — the sweep was for the position-only readers. Routing
|
||||
them through the view cache would mean `text_of` handing out an `Rc`
|
||||
instead of a `String`, which is a different change with a different
|
||||
argument.
|
||||
- [x] **Reported, not fixed *here*: the first request of a session waits out
|
||||
the startup scan.** Numbers and the filed request are in Handshakes;
|
||||
**delivered 2026-08-28** by `docs/features/scan-interleave/README.md`
|
||||
(780 ms → 15.5 ms cold, 287 ms → 12.8 ms warm).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-28 — dev
|
||||
|
||||
**Measured first, both suspects, before a line of the fix was written.** Two
|
||||
new probes were needed and are part of the round:
|
||||
`perf::hovering_into_a_big_closed_file_first_touch_and_repeat` (an
|
||||
instantiation and a port, into a 12 MB file, first touch and repeat separately
|
||||
— the existing probes all reported means, which hide exactly the first/repeat
|
||||
split the owner's report is about) and
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` (over the wire,
|
||||
against the real binary, two whole sessions so the persistent store is cold in
|
||||
one and warm in the other). The second answered the brief's question about
|
||||
suspect 2 with a number four orders of magnitude larger than suspect 1's, which
|
||||
is worth saying plainly even though this round could not act on it.
|
||||
|
||||
**The carrier: a struct, not a bare `u32`.** `DeclLines { name, detail }`
|
||||
rather than `line: u32` on `Decl`, because the *second* datum already exists —
|
||||
a split port's body line — and because the owner asked for room for more. The
|
||||
alternative shapes were both worse: a bare `u32` would have needed a second
|
||||
field the day `detail` was wanted (and `detail` was wanted on day one), and a
|
||||
parallel table keyed by declaration would have to be kept in step with `Decl`
|
||||
through the merge, the incremental update and the record round-trip, for no
|
||||
consumer that exists. `Option<u32>` for `detail` rather than a `0` sentinel in
|
||||
the *type*, even though the *record* writes `0` for `None`: the record's
|
||||
sentinel is a framing decision (the stream stays flat, exactly as
|
||||
`detail_span`'s `0 0` already does) and the type's is an API decision, and
|
||||
those two should not be forced to be the same thing.
|
||||
|
||||
**`from_analysis` grew a parameter rather than growing a `&str`.** It could
|
||||
have taken `src: &str` and built its own index, but its one real caller —
|
||||
`Document::facts` — already holds a `LineIndex` over exactly that text, and
|
||||
handing it over is both cheaper and more honest about what the function needs.
|
||||
The test helper `as_a_server_analyzes` grew a fourth return value for the same
|
||||
reason.
|
||||
|
||||
**`FACTS_FORMAT` 3 → 4, not 2 → 3 as the brief said.** The brief was written
|
||||
against a tree where `port-detail-spans` had not yet been counted; the constant
|
||||
was already at 3 when this round started. Same rule, next number.
|
||||
|
||||
**The heading now comes from the index on the disk path, and that is a small
|
||||
behaviour change in one corner.** Before, a closed file that could not be read
|
||||
produced a bare `` `sub.sv` `` heading with no line; now it produces
|
||||
`` `sub.sv:2` ``, because the line no longer depends on the file being
|
||||
readable. That is more information and not less, it is the line the index
|
||||
recorded from the text it indexed, and it is pinned by
|
||||
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` — which
|
||||
deletes the file and requires the heading to survive. Every other card is
|
||||
byte-identical: the full suite passed unmodified before a single new test was
|
||||
added, including the stale-span, guard, CRLF, cap and ambiguity tests.
|
||||
|
||||
**The live path was deliberately left alone.** An open buffer's heading still
|
||||
comes from that buffer's own line index and *not* from `Def::lines`, because
|
||||
the buffer may hold unsaved edits the index has not seen — the same reason
|
||||
`declaration_snippet` matches a `Def` to a live symbol logically instead of
|
||||
reading at the indexed span (`docs/features/hover-declarations/README.md`).
|
||||
Zero I/O either way, so there is nothing to win by unifying them and a
|
||||
correctness property to lose.
|
||||
|
||||
**`disk_view` is gone, subsumed.** Its whole job — one read per file per hover
|
||||
— is now the view cache's, which does the same thing per *session* instead of
|
||||
per request. The per-request memo would have been a second cache in front of
|
||||
the first.
|
||||
|
||||
**Files touched.** `crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`,
|
||||
`crates/vlog_semantic/tests/workspace.rs`,
|
||||
`crates/lucisv_server/src/{state.rs,locate.rs,hover.rs,index_cache.rs,perf.rs}`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, this README,
|
||||
`docs/features/{hover-declarations,workspace-index,index-persistence}/README.md`,
|
||||
`docs/perf/README.md`, `TODO.md`. No new dependency, no `unsafe`, no
|
||||
`#[allow]`, no version bump, no commits.
|
||||
|
||||
**Tests added.**
|
||||
|
||||
| test | where | pins |
|
||||
|---|---|---|
|
||||
| `every_declared_names_line_is_recorded_when_the_file_is_indexed` | `vlog_semantic/tests/workspace.rs` | line 1, a middle line, the last line with no trailing newline, and a member's line — each checked against the source line's own text |
|
||||
| `crlf_and_multibyte_text_do_not_shift_a_declarations_line` | same | `\r\n` line endings, and three- and four-byte characters ahead of the declaration |
|
||||
| `a_split_ports_two_lines_ride_the_same_carrier` | same | the extension story: a non-ANSI port's header line *and* body line, and an ANSI port's `None` |
|
||||
| `a_declarations_lines_survive_the_record_round_trip` | same | encode → decode → equal, and through `IndexBuilder` to a `Def` |
|
||||
| `a_store_from_any_previous_facts_format_is_dropped_not_misread` | `lucisv_server/src/index_cache.rs` | **rewritten**: every format `1..FACTS_FORMAT` is discarded by the header, *and* a genuine format-3 record (today's minus the two line fields) fails `decode` even served past the header. Was pinned at the literal `2` and would have gone on testing 2 forever |
|
||||
| `a_closed_files_text_is_read_once_and_then_reused` | `lucisv_server/src/state.rs` | the cache exists: the file is rewritten behind the server's back and the second view is the first |
|
||||
| `a_file_an_open_buffer_speaks_for_has_no_view_of_its_own` | same | closed files only |
|
||||
| `every_way_a_files_text_can_move_drops_its_view` | same | all four invalidation points, each by the same warm-change-event-check experiment |
|
||||
| `the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text` | same | both bounds, LRU order, and that a file over the whole byte budget is still cached and evicts the rest |
|
||||
| `a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` | `lucisv_server/src/hover.rs` | the round's central claim: the file is deleted and the heading still names its line, snippet correctly dropped |
|
||||
| `a_second_hover_into_one_closed_file_reads_nothing` | same | the snippet's read is shared: the file is rewritten and the second card is the first |
|
||||
|
||||
Two `#[ignore]`d probes added (`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`,
|
||||
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`); one existing probe
|
||||
(`hovering_into_a_large_closed_file_reads_it_once`) grew a second timing so it
|
||||
reports the repeat beside the first touch.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
--workspace` silent. `cargo test --workspace` green, 0 failed. The counts, by
|
||||
binary: `lucisv_server`'s unit tests **1 210 passed / 24 ignored** (+6 passing,
|
||||
+1 `#[ignore]`d probe), its `e2e` suite **56 passed / 2 ignored** (+1
|
||||
`#[ignore]`d probe), `vlog_semantic`'s `workspace` suite **66 passed** (+4).
|
||||
One test was renamed rather than added
|
||||
(`a_store_from_the_previous_facts_format_is_dropped_not_misread` →
|
||||
`a_store_from_any_previous_facts_format_is_dropped_not_misread`), so nothing
|
||||
was quietly dropped.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-28 — QA
|
||||
|
||||
Verdict: **SHIP.** No correctness bug found in the round's own code — every
|
||||
finding below is a test-coverage gap, closed in this pass with permanent
|
||||
regression tests. All seven charter items checked; details follow.
|
||||
|
||||
**1. Heading staleness — reproduced, and the documented window holds.**
|
||||
Constructed the exact attack: index `sub.sv` from its original text, then
|
||||
rewrite it on disk (`addr` moved from line 2 to line 6, and the byte offset
|
||||
the index still holds for it now lands inside a comment) with no `didSave`, no
|
||||
watcher event and no `update_one`/`rebuild_index` call — before any hover has
|
||||
ever read the file, so the view cache is empty and the read the snippet does
|
||||
is genuinely against the *new* bytes. Result: the heading still shows
|
||||
`sub.sv:2` (the index's last-scanned line, not the file's true current one),
|
||||
and the snippet is dropped by `spells_exactly` rather than showing whatever
|
||||
now sits at that byte range — no wrong line and no wrong snippet, matching the
|
||||
README's Assumptions ("both are stale together") exactly. Pinned:
|
||||
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`
|
||||
(`crates/lucisv_server/src/hover.rs`). The docs (this README's Assumptions
|
||||
section, and `Workspace::file_view`'s doc comment at
|
||||
`crates/lucisv_server/src/state.rs:1043`) already state this honestly — no
|
||||
doc fix needed.
|
||||
|
||||
**2. `DeclLines` correctness — dev's tests already cover the awkward
|
||||
offsets** (line 1, the last line with no trailing newline, CRLF, multi-byte
|
||||
text ahead of the declaration, a split port's two lines, an ANSI port's
|
||||
`None`) and check each recorded line against the source line's own text, not
|
||||
just against a hand-computed expectation. No drift found; ran unmodified.
|
||||
|
||||
**3. View-cache attacks — three untested-but-correct paths, now covered.**
|
||||
The cache's own logic (`trim_views`, `cached_view`,
|
||||
`crates/lucisv_server/src/state.rs:349` and `:1061`) was already right by
|
||||
inspection and by trace, but three of the charter's named attacks had no
|
||||
regression test, meaning a future refactor could break any of them silently:
|
||||
- *Recency, not insertion order.* `cached_view`'s `rotate_right` had no test
|
||||
at all. Added
|
||||
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`:
|
||||
fills the cache, re-touches the oldest entry, adds a fifth file, and
|
||||
requires the just-touched file to survive while the untouched one is what
|
||||
falls off instead.
|
||||
- *`update_one` selectivity.* Every existing invalidation test warms one
|
||||
file's view at a time, so a hypothetical `update_one` that widened to
|
||||
`views.clear()` would still pass all of them. Added
|
||||
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`.
|
||||
- *A second oversized file.* The existing bound test caches exactly one
|
||||
file over the byte budget; it never tries a second one. Added
|
||||
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`,
|
||||
confirming the cache stays at one entry (the newest) rather than
|
||||
accumulating unbounded huge files.
|
||||
All three pass against the round's code unmodified — genuine coverage gaps,
|
||||
not bugs.
|
||||
|
||||
**4. Format bump — the single-decl test's premise checked, and generalized.**
|
||||
`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread`
|
||||
genuinely constructs a format-3 record (verified by hand: `strip_the_line_
|
||||
fields` removes exactly the two trailing fields of the one declaration `M`
|
||||
has, and the record that results is what format 3 actually wrote — not merely
|
||||
a v3 header over v4 bytes). That fixture has only one declaration, so it could
|
||||
not have caught a field-shift that landed on a *second* declaration's fields
|
||||
rather than on a tag literal. Added
|
||||
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_
|
||||
rejected_not_misread`, generalizing the stripper to N declarations (both units
|
||||
and members) and covering a two-unit file and a mixed unit+split-port-member
|
||||
file. Both decode to `None`, confirming the structural reason this is safe in
|
||||
general: a field-shift by exactly one declaration's two line-fields always
|
||||
lands either on a tag literal (`"M"`, `"I"`, …) or on the next declaration's
|
||||
`name`/`kind` string fields, and a Verilog identifier can never parse as
|
||||
`u32`, so `Reader::num` fails and `decode` returns `None` rather than building
|
||||
a `Decl` out of someone else's fields. No misread constructed; the
|
||||
"guilty until proven innocent" bar is met.
|
||||
|
||||
**5. Equivalence — confirmed, not just claimed.** `cargo test --workspace`
|
||||
green with 0 failures both before and after this pass's additions (dev's
|
||||
counts: `lucisv_server` 1210 passed/24 ignored, `vlog_semantic` `workspace` 66
|
||||
passed — both unmodified by this pass except for the new tests below). Read
|
||||
the `hover.rs` and `locate.rs` diffs directly: the live-buffer branch is
|
||||
untouched, `location()`'s open-buffer arm is a straight substitution
|
||||
(`doc.positions()` for the old `Positions::new(&text, &index)` built from a
|
||||
clone of the same text), and the disk branch is the only place behavior can
|
||||
differ — which is exactly the one documented corner (an unreadable closed
|
||||
file now shows its indexed line). No other behavior change found.
|
||||
|
||||
**6. Numbers reproduced**, `--release`, this machine, this session:
|
||||
- `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`: first
|
||||
touch 5.75 ms (instantiation) / 5.65 ms (port), repeat 1.35 µs / 1.89 µs —
|
||||
same order as the README's 6.23 ms / 0.95 µs and 5.92 ms / 0.99 µs; run-
|
||||
to-run noise, not drift.
|
||||
- `state::tests::qa_perf_cold_warm_and_half_warm_scans` (860-file corpus):
|
||||
store size **2 380 790 bytes** — an exact match to the README's "after"
|
||||
figure, confirming the +68 KB / 2.9 % growth claim against the real
|
||||
corpus rather than trusting the doc's arithmetic. Scan times (325 / 350 /
|
||||
186 ms) were in the same band as the README's (343 / 374 / 200 ms);
|
||||
machine noise, no regression.
|
||||
- `e2e::a_hover_issued_during_the_initial_scan_waits_for_it`: 748.7 ms cold
|
||||
/ 274.0 ms warm for the first hover issued the moment `initialized` is
|
||||
sent, vs. 26.3 µs / 40.2 µs once the scan is done — the same four-orders-
|
||||
of-magnitude gap the README reports (780 / 287 ms vs. 64 / 61 µs). The
|
||||
test genuinely exercises the wait (it asserts the answer resolves
|
||||
correctly across files, and the two timings are taken across the real
|
||||
wire protocol against the shipped binary) — the Handshake in this
|
||||
README's "Suspect 2" section is accurate and not overstated.
|
||||
|
||||
**7. Full gates**, run after adding the tests above:
|
||||
- `cargo fmt --all -- --check`: clean (after formatting the new tests —
|
||||
two blocks needed `cargo fmt`'s wrapping, applied).
|
||||
- `cargo clippy --all-targets --workspace`: clean, no warnings.
|
||||
- `cargo test --workspace`: green. `lucisv_server` unit tests **1214
|
||||
passed** (dev's 1210 + this pass's 4), `vlog_semantic` `workspace` suite
|
||||
**67 passed** (dev's 66 + this pass's 1). 0 failed anywhere in the
|
||||
workspace, including doctests.
|
||||
- `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
**Tests added this pass** (5, all permanent regressions, all green):
|
||||
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`,
|
||||
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`,
|
||||
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`,
|
||||
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`
|
||||
(all `crates/lucisv_server/src/`), and
|
||||
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_rejected_not_misread`
|
||||
(`crates/vlog_semantic/tests/workspace.rs`).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
|
||||
independently (fmt clean, clippy silent, 2440 workspace tests green).
|
||||
This round is the owner's design implemented at the right altitude:
|
||||
`DeclLines` as a field on the carrier the index already had — not a
|
||||
parallel table — so ports got their lines for free through the member
|
||||
entries and the extension story is "add a field, bump the format",
|
||||
exactly the flexibility the owner asked for. The +68 KB store growth
|
||||
on the 860-file corpus scales to the owner's 20 000-module thought
|
||||
experiment at the few-tens-of-KB order they predicted. The `FileView`
|
||||
cache is honest about its one unwatchable staleness case and leans on
|
||||
`spells_exactly` correctly (a stale view omits, never lies); QA's
|
||||
staleness repro pins the heading/snippet pair going stale *together*.
|
||||
The dev's rewrite of the format-discard test from a pinned literal to
|
||||
all-previous-formats is the kind of fix that outlives the round.
|
||||
Suspect 2 — the first request of a session waiting 287–780 ms behind
|
||||
the startup scan — is confirmed genuine by dev and QA independently
|
||||
and is the dominant remainder of the owner's "slow on first try";
|
||||
correctly filed as a Handshake, next round's work. Accepted; committed
|
||||
by the lead.
|
||||
@@ -0,0 +1,682 @@
|
||||
# incremental-index
|
||||
|
||||
## Goal
|
||||
|
||||
Until this round **any** change rebuilt the whole workspace index: a save of
|
||||
one file re-read, re-tokenized, re-parsed and re-analyzed every file in scope,
|
||||
rebuilt the completion tables and rebuilt the include graph. On the checked-in
|
||||
860-file corpus that is 1.5 s of work, in a debug build, on every `didSave`.
|
||||
This round makes the common case what it should always have been — **when
|
||||
exactly one in-scope file changed, only that file's contribution is
|
||||
replaced** — under an invariant strong enough to make the shortcut safe: the
|
||||
index an update produces is *the index a whole rebuild would have produced*,
|
||||
byte for byte. The same round lands the two edge tables that were filed as
|
||||
Handshakes months apart and always wanted the same shape: **who instantiates
|
||||
module M** and **who extends class C**, recorded as the index is built. With
|
||||
them, `callHierarchy/incomingCalls`, `textDocument/codeLens` and
|
||||
`typeHierarchy/subtypes` stop walking the workspace on every request and become
|
||||
lookups — 92 ms → 0.26 ms for a whole file's code lenses, 82 ms → 0.71 ms for
|
||||
`subtypes`, measured below.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The equivalence invariant is the round.** For any workspace `W` and any
|
||||
file `F` in it: `build(W)` and `build(W \ F).update_file(F)` are the *same
|
||||
index* — same `FileId`s, same disambiguation order, same unit and member
|
||||
tables, same edge tables, same per-file `` `define`` tables. Not "equivalent
|
||||
where anything looks", **equal**: `WorkspaceIndex::fingerprint()` renders
|
||||
every observable and the two fingerprints are compared directly. The same
|
||||
holds for `remove_file`, and for the two composed into a rename.
|
||||
- **A `FileId` is a position in the path-sorted file list and nothing else,
|
||||
which is what it has always been.** The brief allowed interning ids per path
|
||||
and retiring them, so that an insert or a remove would not renumber. That was
|
||||
considered and **not** done, and the reason is the invariant above. Interned
|
||||
ids differ between "a whole build" and "a build minus F, then F added back" —
|
||||
F would take the next free id rather than its sorted-position one — so the
|
||||
two histories could only be *equivalent*, never *equal*, and equality would
|
||||
have to be re-established observable by observable in every consumer that
|
||||
reads the numeral. Three do: `find_define` returns its hits in `FileId`
|
||||
order, `candidates.rs` iterates `0..files().len()`, and the crate's own tests
|
||||
compare `files()`. Renumbering keeps the strongest statement available —
|
||||
*the same index* — and costs one merge pass over records already in memory,
|
||||
no file read and no file re-parsed. **Disambiguation was already order-derived
|
||||
and still is**: a name's declarations are pushed in one loop over the
|
||||
path-sorted per-file records, so the order is the path order, and the ids
|
||||
happen to agree with it because they are that same position. Nothing reads a
|
||||
`FileId` numeral to decide an order.
|
||||
- **Ids do not survive an add or a remove, and nothing in the tree holds one
|
||||
across an update.** The only place a `FileId` is stored is a `Def` inside a
|
||||
buffer's `ExternalResolutions`, and `update_one` refreshes every open
|
||||
buffer's overlay exactly as `rebuild_index` does. The server is single
|
||||
threaded and no update can interleave with a request.
|
||||
- **The index keeps every file's contribution unmerged.** `FileFacts` — the
|
||||
path, the define table, the file-scope declarations, the members, the
|
||||
instantiation edges and the inheritance edges — used to live only until
|
||||
`IndexBuilder::finish` and now lives in the index. (**Since
|
||||
index-persistence, 2026-08-27** it also lives on *disk*: `FileFacts` is
|
||||
public, encodable and decodable, and a record put back through
|
||||
`IndexBuilder::add_facts` gives the index the file's parse would have.) That is what makes the
|
||||
restricted re-merge possible, and it is the round's honest memory cost: the
|
||||
same names and spans the merged tables hold, held once more, per file. No
|
||||
`Semantics` and no source text is retained, exactly as before.
|
||||
- **The cheap path is "a file the index already holds"**, and everything else
|
||||
is a whole rebuild. A file *appearing* changes what other files' `` `include``s
|
||||
resolve to, and answering that needs a walk; a file the index does not hold
|
||||
is also how a brand-new file gets in at all. So the gate is one membership
|
||||
test, and it is stated as such rather than guessed at per trigger.
|
||||
- **A save carries no progress bar any more, and that is the visible protocol
|
||||
delta.** The bar exists because a whole scan takes perceptible seconds; one
|
||||
file is one parse. No bar, no per-file log line, and no scope warnings — the
|
||||
last because warnings come from *resolving* the scope, and the scope was not
|
||||
re-resolved. Everything else a rebuild does after the scan still happens: the
|
||||
generation bump, the code-lens refresh, and a republish of every open buffer.
|
||||
- **The republish stays wholesale.** Every open buffer's diagnostics are
|
||||
computed against the index, so any of them may have moved; narrowing to "the
|
||||
buffers that could have changed" needs a cross-file dependency graph this
|
||||
server does not have. Filed, not guessed at.
|
||||
- **The census is now as of the index, which is as of its last build or
|
||||
update.** This is a real behaviour change and it is the one the round argues
|
||||
hardest for. `hierarchy::callers_of_each` and `type_hierarchy::subtypes` used
|
||||
to walk `Workspace::sources()` per request, which folds open buffers over
|
||||
disk — so a keystroke in *another* buffer moved a code-lens count before
|
||||
anything rebuilt. They read the index's edge tables now, and an index is only
|
||||
ever as of its last build or update. Both of those fold every open buffer in,
|
||||
so a save (or any rescan trigger) makes the edit count; a keystroke alone
|
||||
does not. In exchange the lens, the call hierarchy and every other index-shaped
|
||||
answer are consistent with each other by construction, and the census costs a
|
||||
lookup instead of a workspace walk. Pinned from both sides in
|
||||
`an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it`
|
||||
and `an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it`.
|
||||
- **The census *policies* did not move, and could not have**: the tables are
|
||||
built by the very walks the request handlers used to run. One
|
||||
`Instantiation` node is one site however many instances it declares; a
|
||||
`generate for` body is one site, not the elaborated four; both arms of an
|
||||
`` `ifdef`` are sites; matching is by the name as written; an instantiation at
|
||||
file scope is not an edge, because nothing calls it; a gate primitive names
|
||||
no module. Every one of `lens.rs`'s QA tests passes unchanged, and the same
|
||||
policies are now pinned at the source of the numbers as well
|
||||
(`the_instantiation_table_records_the_census_the_hierarchy_counts`).
|
||||
- **An edge's spans are as of the index; the ranges are as of the text now.**
|
||||
Turning a recorded byte span into a line/character range needs the file's
|
||||
text, which is read fresh (open buffer beating disk, as always). For a buffer
|
||||
edited since the last update the two disagree — the same staleness
|
||||
`item_in_file` has carried since the hierarchy shipped, on the same files,
|
||||
for the same reason.
|
||||
- **The include graph's one incremental limit is stated rather than papered
|
||||
over.** `IncludeGraph::update_file` re-scans the changed file's own edges and
|
||||
re-learns the known-file and folded-spelling tables from the index's list; it
|
||||
does **not** re-resolve any *other* file's edges. For the case the server uses
|
||||
it in — one file's text changed, the file set did not — there is nothing
|
||||
stale at all. When the update is a removal, another file's `` `include`` of
|
||||
the removed file keeps its edge until the next whole rebuild. Named here
|
||||
because it is the only thing in this round that is not exactly a rebuild.
|
||||
- **The completion word table is exact, and pays for it in memory.**
|
||||
`Candidates` keeps a per-file word list and a per-word file count, so one
|
||||
file's words can be given back without re-lexing the other 859. Over the
|
||||
corpus that is ~40k `String`s of per-file lists (QA measured 39,673 — the
|
||||
work log's original ~170k estimate was 4.3x high; ~1.38 MB) on top of the
|
||||
~17k distinct
|
||||
words — single-digit megabytes, for the difference between "the word table is
|
||||
correct" and "the word table drifts until something rebuilds".
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `vlog_semantic` — the index gains an incremental API and two edge tables
|
||||
|
||||
```rust
|
||||
impl WorkspaceIndex {
|
||||
/// Insert or replace one file. Gives the index a whole build would have.
|
||||
pub fn update_file(&mut self, path: PathBuf, src: &str);
|
||||
/// Drop one file, reporting whether it was there.
|
||||
pub fn remove_file(&mut self, path: &Path) -> bool;
|
||||
/// Every observable, rendered — the equivalence witness.
|
||||
pub fn fingerprint(&self) -> String;
|
||||
|
||||
pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge];
|
||||
pub fn subclasses_of(&self, name: &str) -> &[InheritanceEdge];
|
||||
pub fn instantiations(&self) -> impl Iterator<Item = (&str, &[InstantiationEdge])>;
|
||||
pub fn subclasses(&self) -> impl Iterator<Item = (&str, &[InheritanceEdge])>;
|
||||
}
|
||||
|
||||
pub struct DeclSite { pub name: String, pub name_span: TextRange, pub span: TextRange }
|
||||
pub struct InstantiationEdge { pub file: FileId, pub owner: DeclSite, pub site_span: TextRange }
|
||||
pub struct InheritanceEdge { pub file: FileId, pub subclass: DeclSite }
|
||||
```
|
||||
|
||||
- `InstantiationEdge` carries the owner's whole `DeclSite` rather than just its
|
||||
name span, because that is what a `CallHierarchyItem` is: `name` is the
|
||||
item's name, `name_span` its `selectionRange`, `span` its `range`. The
|
||||
code-lens README's proposed shape asked for "(file, instantiating-module name
|
||||
span, instance site span)"; the extra two fields are what stopped
|
||||
`callers_of_each` needing to re-parse the file to find them.
|
||||
- `IndexCounts` gains `instantiations` and `inheritances`. Additive; every
|
||||
field is still public and every existing read still compiles.
|
||||
- **Two modules were lifted into this crate**, because the index now records
|
||||
what they find and a second copy of either walk would be free to drift from
|
||||
the one the request handlers use:
|
||||
- `vlog_semantic::instantiations` — moved verbatim from
|
||||
`lucisv_server::instantiations`. `hierarchy.rs`, `lens.rs` and `inlay.rs`
|
||||
import it from here now; its own tests moved with it.
|
||||
- `vlog_semantic::classes` — the class-declaration walk that was private to
|
||||
`lucisv_server::type_hierarchy`, plus `extends_name`. `type_hierarchy.rs`
|
||||
uses it and no longer has a copy.
|
||||
- `IndexBuilder` is unchanged in shape and still sorts in `finish`; `finish` is
|
||||
now `merge(None)` over the sorted records, which is the same loop
|
||||
`update_file` runs restricted to the affected keys. **That is the equivalence
|
||||
proof**: there is exactly one place any table's order is decided.
|
||||
|
||||
### `lucisv_server::state`
|
||||
|
||||
- `Workspace::update_one(&mut self, path: &Path) -> bool` — the incremental
|
||||
rescan for one file. `false` means "not a file this index holds; rebuild".
|
||||
It patches all four pieces of state a rebuild produces (index, completion
|
||||
tables, include graph, every open buffer's overlay) and is documented
|
||||
piece by piece at the function.
|
||||
**Amended (index-persistence, 2026-08-27):** it also writes the file's new
|
||||
record through to the on-disk index cache, using
|
||||
`WorkspaceIndex::facts_for` to take back the record the update just made
|
||||
rather than parsing anything twice. An hour of saves is an hour of work the
|
||||
next session does not repeat.
|
||||
- `Workspace::update_one_checked` is the `#[cfg(test)]` paranoid form: it runs
|
||||
the update, then rebuilds the whole workspace and asserts the two agree on
|
||||
the index's fingerprint *and* on the completion word table.
|
||||
|
||||
### `lucisv_server::candidates` / `includes`
|
||||
|
||||
- `Candidates::update_file(index, path, text)` / `remove_file(index, path)` and
|
||||
`IncludeGraph::update_file(path, text, known)` / `remove_file(path, known)`.
|
||||
Both are the incremental forms of their `build`, and both are exact for the
|
||||
case `update_one` uses them in.
|
||||
|
||||
### `lucisv_server::watch`
|
||||
|
||||
- `watch::one_scope_file(changes, filelist) -> Option<PathBuf>` — the one file a
|
||||
watcher notification named, when it named exactly one and that one is not the
|
||||
filelist. The gate on the fast path for the watcher trigger.
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `reindex_one(&mut self, path) -> bool`, taken by `didSave` and by a
|
||||
one-file `didChangeWatchedFiles`, falling through to `reindex()` when it
|
||||
declines.
|
||||
|
||||
## The fast-path trigger table
|
||||
|
||||
| trigger | path | bar |
|
||||
|---|---|---|
|
||||
| `didSave` naming one file the index holds | incremental | none |
|
||||
| `didSave` naming a file the index does not hold (a new file) | whole rebuild | yes |
|
||||
| `didChangeWatchedFiles` naming one held source file | incremental | none |
|
||||
| `didChangeWatchedFiles` naming two or more files (a checkout) | whole rebuild | yes |
|
||||
| `didChangeWatchedFiles` naming the filelist | whole rebuild | yes |
|
||||
| `didChangeConfiguration` moving `exclude`/`filelist`/`maxFileSize`/`index.scope`/`index.scopeDepth` | whole rebuild | yes |
|
||||
| `didOpen` that widened the scope | whole rebuild | yes |
|
||||
| `didChangeWorkspaceFolders` that moved the root set | whole rebuild | yes |
|
||||
| `didRenameFiles` / `didDeleteFiles` | whole rebuild | yes |
|
||||
|
||||
Pinned by `the_fast_path_is_taken_for_one_held_file_and_for_nothing_else`
|
||||
(rows 1–5 and the settings row) and by the tests the earlier rounds left on
|
||||
the remaining rows.
|
||||
|
||||
## Derived state, and how each piece is patched
|
||||
|
||||
| state | what it reads | on an incremental update |
|
||||
|---|---|---|
|
||||
| `WorkspaceIndex.files` / `facts` | the file set | one record replaced, inserted or removed |
|
||||
| `units`, `members` | every file's declarations | the keys this file declared before or declares now, re-merged from the records in path order |
|
||||
| `instantiations`, `subclasses` | every file's edges | same, keyed by instantiated module / base class |
|
||||
| `defines` | this file only | replaced with the record |
|
||||
| `Candidates::units` / `macros` | the index alone | re-derived from the (already updated) index |
|
||||
| `Candidates::words` | every file's tokens | this file's words given back and its new ones taken, by per-word file count |
|
||||
| `IncludeGraph::edges` | this file's `` `include``s | re-scanned for this file; other files' left standing (see Assumptions) |
|
||||
| `IncludeGraph::known` / `folded` | the file set | re-learned from `index.files()` |
|
||||
| every open buffer's `ExternalResolutions` | the index | refreshed, as after a rebuild |
|
||||
| the persistent index cache | this file's new record | written through, from the record `update_file` just made — no second parse (`docs/features/index-persistence/README.md`, 2026-08-27) |
|
||||
| the diagnostics generation | — | bumped |
|
||||
| the client's code lenses | the index | refresh requested |
|
||||
|
||||
An add or a remove takes the *whole* merge rather than the restricted one,
|
||||
because every id after the change moves; it is still one pass over records in
|
||||
memory, with no file read and no file re-parsed.
|
||||
|
||||
## Measured
|
||||
|
||||
Debug build, this Mac, the checked-in 860-file corpus, printed by the
|
||||
`#[ignore]`d probes (`cargo test -p lucisv_server -- --ignored --nocapture`).
|
||||
|
||||
| | before | after |
|
||||
|---|---:|---:|
|
||||
| `textDocument/codeLens`, a three-module file | 92 ms (one workspace walk, then a parse of every file mentioning a name) | **0.26 ms** |
|
||||
| `typeHierarchy/subtypes`, `core_ibex_base_test` | 82 ms (same shape) | **0.71 ms** |
|
||||
| rescan after one file changed | 1.50 s (whole rebuild) | **33 ms** (45×) |
|
||||
|
||||
The "before" column for the two requests is measured in the same probe as the
|
||||
"after": `Workspace::sources()` is still there and still costs what it always
|
||||
did, so the row is one walk of the corpus against the lookup that replaced it,
|
||||
in the same process on the same run. The reindex row is the whole rebuild and
|
||||
the one-file update measured back to back over the same workspace.
|
||||
|
||||
The 33 ms is dominated by two things that are *not* the file: re-deriving the
|
||||
completion `units`/`macros` tables from the index (a `workspace_symbols("")`
|
||||
over ~12k members, sorted) and the merge pass over every file's records. Both
|
||||
are O(index), not O(files read), and neither parses anything. Making them
|
||||
O(change) is possible and was not done: 45× is the win that was asked for, and
|
||||
the next 3× is a bigger change to `Candidates` than this round should carry.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `WorkspaceIndex::update_file` / `remove_file`, exact-equality equivalence
|
||||
with a whole build, pinned from six directions
|
||||
- [x] `WorkspaceIndex::fingerprint` as the one equivalence witness, used by
|
||||
both crates' tests
|
||||
- [x] Instantiation and inheritance edge tables, built by the walks the request
|
||||
handlers used to run
|
||||
- [x] `hierarchy::callers_of_each` is a lookup; its `sources()` walk deleted
|
||||
- [x] `lens.rs` counts through it unchanged; `type_hierarchy::subtypes` is a
|
||||
lookup
|
||||
- [x] The census policies pinned at the source of the numbers as well as at the
|
||||
lens
|
||||
- [x] `Workspace::update_one` patching index, completion tables, include graph
|
||||
and every open buffer's overlay
|
||||
- [x] `Server::reindex_one`: no bar, no log, no scope warnings; generation
|
||||
bumped, lenses refreshed, every open buffer republished
|
||||
- [x] The fast-path trigger table, pinned row by row
|
||||
- [x] The paranoid corpus sweep: every mutation checked against a whole rebuild
|
||||
- [x] The three inherited obligations from index-scope's Review
|
||||
- [ ] **Not done, deliberately:** no narrowing of the republish. A lint reads
|
||||
the index, so any open buffer's diagnostics may have moved; narrowing
|
||||
correctly needs a dependency graph this server does not have, and
|
||||
narrowing incorrectly is a stale red squiggle.
|
||||
- [ ] **Not done, deliberately:** no incremental path for a file appearing or
|
||||
vanishing *without* the index already holding it. It is a rebuild, it is
|
||||
rare, and the include graph's cross-file resolution is what makes it one.
|
||||
- [ ] **Not done, deliberately:** the index is not updated on `didChange`. A
|
||||
keystroke would cost a second parse and a second analysis of the buffer
|
||||
on top of the one `Document::new` already does, per keystroke, to make a
|
||||
count in *another* file fresher than the file on disk.
|
||||
- [ ] **Filed, not done:** `Candidates::units`/`macros` are re-derived whole on
|
||||
every incremental update. They are index-derived and correct; they are
|
||||
also most of the 33 ms.
|
||||
- [ ] **Filed, not done:** an incremental update cannot re-resolve another
|
||||
file's `` `include`` when a file is removed. See Assumptions.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev agent (incremental single-file updates, the edge tables)
|
||||
|
||||
- **The FileId decision was the first one and it went against the brief, with
|
||||
the invariant as the argument.** The brief asked for interned, retired ids so
|
||||
that an insert would not renumber. Interning makes ids *stable* but makes the
|
||||
two histories the round has to compare merely equivalent, and the brief's own
|
||||
acceptance test says to make the equivalence exact if anything observable
|
||||
reads the numeral — three things do. Renumbering keeps `FileId` meaning
|
||||
exactly what it has always meant (a position in the path-sorted list), makes
|
||||
the comparison a string equality on a fingerprint, and costs one merge pass
|
||||
over in-memory records. The stability interning would have bought is worth
|
||||
nothing here: the only `FileId`s that outlive a call are the ones in each
|
||||
buffer's overlay, and those are refreshed by the update itself.
|
||||
- **The merge is the equivalence proof, not a test of it.** `IndexBuilder::finish`
|
||||
and `WorkspaceIndex::update_file` both end in one function, `merge`, which
|
||||
loops over the path-sorted per-file records pushing what it meets. `merge(None)`
|
||||
rebuilds every table; `merge(Some(affected))` clears and refills only the keys
|
||||
the changed file could have moved. Same loop, same order, so a restricted
|
||||
merge and a whole one cannot disagree — there is nowhere for them to disagree.
|
||||
That is why the round could afford to keep the per-file records rather than
|
||||
invent a patching scheme with its own ordering rules.
|
||||
- **The affected set is coarse on purpose.** `members` is keyed by unit and the
|
||||
affected set names *units*, not `(unit, member)` pairs: rebuilding one whole
|
||||
package's member sub-table is a handful of entries, and a finer key would be
|
||||
a second ordering rule to keep honest.
|
||||
- **Two walks were lifted into `vlog_semantic` rather than copied.** The
|
||||
instantiation census is what `lens.rs`'s QA tests pin, so a second copy of
|
||||
that walk inside the index would have been licence for the numbers to drift.
|
||||
`instantiations.rs` moved whole (its tests with it) and
|
||||
`type_hierarchy`'s private class walk became `classes.rs`. Both moves are
|
||||
mechanical; the census policies are now a property of one function each.
|
||||
- **The unsaved-buffer census delta is the round's one behaviour loss and it is
|
||||
argued rather than hidden.** Two tests pinned "a just-typed instantiation in
|
||||
another buffer counts": they were the walk's own freshness, not a policy, and
|
||||
they cannot survive a table built at index time. Both are rewritten in the
|
||||
house style under `// Superseded this round:` to pin the new rule from both
|
||||
sides — the buffer alone moves nothing, and the update moves it. The three
|
||||
alternatives were considered and rejected in the README's Assumptions: a
|
||||
per-keystroke index update (a second parse and analysis per keystroke), an
|
||||
edges-only per-keystroke update (breaks the equivalence invariant outright —
|
||||
edges from the buffer, declarations from disk, an index equal to no build at
|
||||
all), and a live overlay of dirty buffers over the table (needs dirty
|
||||
tracking the server does not do).
|
||||
- **Eight progress tests changed, all for the same one reason and none of them
|
||||
weakened.** A save is the trigger those tests reached for when they needed a
|
||||
rescan, and a save is exactly what stops being one. Each now uses a trigger
|
||||
that really does rescan — two files in one watcher event, or a settings
|
||||
change — and keeps its own subject (the bar goes up and comes down, the bar
|
||||
is down before the republish, the refresh rides after it, three outstanding
|
||||
requests answer by id). `a_save_puts_a_bar_up_and_takes_it_down_again` was
|
||||
renamed to name the trigger it now uses, and the property it used to carry —
|
||||
that a save reports itself — is replaced by
|
||||
`a_one_file_save_costs_no_bar_and_no_log_line`, which is the new rule.
|
||||
- **One lens test's assertion was superseded, and its replacement is stronger.**
|
||||
`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted
|
||||
`whole_file < one_name * 2` — "the batch is one walk, not one per module".
|
||||
There is no walk; both sides are microseconds dominated by one file read
|
||||
each, so the ratio pins noise. It now asserts what the round actually bought:
|
||||
a whole file's lenses cost less than a tenth of one workspace walk, measured
|
||||
in the same loop.
|
||||
- **The e2e progress transcript lost a bar**, which is the model becoming
|
||||
visible on the wire again: startup (empty scope, `0 files indexed`), the
|
||||
widening `didOpen` (`1 file indexed`), and then a save that reports nothing
|
||||
because it is one parse.
|
||||
- **The three inherited obligations are pinned as permanent tests**, in
|
||||
`state.rs` beside the scope tests they belong with: lowering `scopeDepth`
|
||||
narrows the index on the next rescan (the settings axis moves both ways,
|
||||
unlike the open axis); a filelist appearing mid-session flips the ladder to
|
||||
rung 1 *and changes what is indexed*, with the open buffer still overlaid;
|
||||
and a buffer opened outside every root rides the folder rung like a rootless
|
||||
one, its own directory at depth 0 and `/` at depth 99.
|
||||
- Files touched: `crates/vlog_semantic/src/workspace.rs`,
|
||||
`crates/vlog_semantic/src/lib.rs`,
|
||||
`crates/vlog_semantic/src/instantiations.rs` (moved in),
|
||||
`crates/vlog_semantic/src/classes.rs` (new),
|
||||
`crates/vlog_semantic/tests/workspace.rs`,
|
||||
`crates/lucisv_server/src/{state,server,hierarchy,lens,type_hierarchy,inlay,candidates,includes,watch,main}.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, `TODO.md`,
|
||||
`docs/features/{code-lens,type-hierarchy,hierarchy,workspace-index,lucisv-server,indexing-ux,work-done-progress,file-watching}/README.md`,
|
||||
this README. No new dependency, no version bump, no `docs/site/`, no commits.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2244
|
||||
passed, 0 failed, 8 ignored** — measured against a clean `HEAD` worktree's
|
||||
**2217 passed, 5 ignored**, so 27 new passing tests and 3 new `#[ignore]`d
|
||||
probes, with 2 superseded in place and 1 renamed.
|
||||
`cargo test -p vlog_formatter`: 180 passed across its seven binaries (114 of them `verification.rs`), untouched — `verify.rs` never appears in this round's diff. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`.
|
||||
|
||||
The 30 new tests, and what each is for:
|
||||
|
||||
| test | pins |
|
||||
|---|---|
|
||||
| `adding_a_file_gives_the_index_a_whole_build_would_have` (vlog_semantic) | the hard direction: the new file sorts first, so every later id and every table naming one moves |
|
||||
| `replacing_a_file_touches_only_what_that_file_said` (vlog_semantic) | the restricted merge: the other file's edge survives, the replaced file's does not |
|
||||
| `removing_a_file_gives_the_index_a_whole_build_would_have` (vlog_semantic) | removal, renumbering down, edges going with the file, removing twice |
|
||||
| `removing_a_file_moves_the_disambiguation_winner` (vlog_semantic) | the sharpest derived answer: the file that won a duplicate name is the file that goes |
|
||||
| `a_file_that_redefines_a_name_another_file_declares_lands_in_path_order` (vlog_semantic) | insertion into a table that already holds the other file's copy, both directions |
|
||||
| `a_rename_is_a_remove_and_an_add_and_lands_where_a_build_would_put_it` (vlog_semantic) | the rename-shaped sequence |
|
||||
| `an_update_survives_every_degenerate_file_there_is` (vlog_semantic) | empty, whitespace, not-Verilog, does-not-lex, comment-only; and an empty index |
|
||||
| `a_full_build_and_a_build_minus_one_plus_that_one_are_the_same_index` (vlog_semantic) | the headline invariant, over a six-file fixture, with **every** file taken out and put back |
|
||||
| `the_instantiation_table_records_the_census_the_hierarchy_counts` (vlog_semantic) | every census policy at the source of the numbers, plus the spans a hierarchy item is built from |
|
||||
| `the_inheritance_table_records_every_class_that_names_a_base` (vlog_semantic) | file order, a parameterized base, a class in a package, a class in a module, the counts |
|
||||
| `the_edge_tables_are_empty_for_a_workspace_with_no_edges` (vlog_semantic) | the degenerate lookups, and a default index |
|
||||
| `only_a_file_the_index_already_holds_takes_the_incremental_path` (state) | the gate, from four sides, including a file that becomes held |
|
||||
| `one_files_edit_reaches_every_table_the_index_answers_from` (state) | declaration, instantiation edge, inheritance edge, completion word, include edge — all five in one update |
|
||||
| `a_file_the_cap_or_the_disk_takes_away_leaves_the_index` (state) | removal through `update_one`: deleted on disk, and grown past the cap |
|
||||
| `an_open_buffer_beats_disk_on_the_incremental_path_too` (state) | `collect_sources`'s precedence, for one file |
|
||||
| `the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus` (state) | the paranoid sweep: 172 real files, 6 mutated five ways, every one checked against a whole rebuild |
|
||||
| `lowering_the_scope_depth_narrows_the_index_on_the_next_rescan` (state) | inherited obligation (a) |
|
||||
| `a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one` (state) | inherited obligation (b), on the index's content and not just the rescan |
|
||||
| `a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one` (state) | inherited obligation (c), at depth 0 and at depth 99 |
|
||||
| `qa_perf_one_file_against_the_whole_rebuild` (state, `#[ignore]`) | the 45× |
|
||||
| `the_fast_path_is_taken_for_one_held_file_and_for_nothing_else` (server) | the trigger table, five rows |
|
||||
| `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses` (server) | what the fast path keeps |
|
||||
| `a_one_file_save_costs_no_bar_and_no_log_line` (server) | what it drops |
|
||||
| `a_one_file_save_answers_from_the_file_it_saved` (server) | the edit reaches the index and the rest of the workspace is untouched |
|
||||
| `a_whole_rescan_puts_a_bar_up_and_takes_it_down_again` (server, renamed) | the bar's own rule, on a trigger that still rescans |
|
||||
| `qa_perf_lens_lookup_against_the_walk_it_replaced` (lens, `#[ignore]`) | 0.26 ms against 92 ms |
|
||||
| `qa_perf_subtypes_lookup_against_the_walk_it_replaced` (type_hierarchy, `#[ignore]`) | 0.71 ms against 82 ms |
|
||||
| `a_save_of_one_file_updates_the_index_over_the_wire` (e2e) | the real binary: the save moves the definition answer, and the untouched file answers exactly what it did |
|
||||
| `a_class_is_found_wherever_it_may_be_written`, `a_parameterized_base_names_the_bare_class`, `a_declarations_extent_contains_its_own_name` (vlog_semantic `classes`) | the lifted walk, in its new home |
|
||||
|
||||
Two tests were superseded in place and are named in the work log above:
|
||||
`an_unsaved_instantiation_is_a_caller_before_it_is_saved` and
|
||||
`an_unsaved_extends_is_a_subtype_before_it_is_saved`, both replaced by the
|
||||
`…counts_from_the_moment_the_index_sees_it` form; and
|
||||
`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` was renamed and
|
||||
given the stronger assertion.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent (equivalence attack pass)
|
||||
|
||||
**Verdict up front: committable as-is.** No production-code defect found
|
||||
under any constructed attack. One documentation-accuracy finding (LOW,
|
||||
non-blocking) in the Assumptions section's memory estimate. Nine new tests
|
||||
added, all passing, none exposing a bug — they pin behavior that was correct
|
||||
but unverified against the specific adversarial shapes below.
|
||||
|
||||
**Gates, re-run from a clean state (before adding anything):**
|
||||
`cargo fmt --all -- --check` clean. `cargo clippy --all-targets --workspace`
|
||||
zero warnings. `cargo test --workspace`: 2244 passed, 0 failed, 8 ignored —
|
||||
matches the dev's own count exactly. `cargo test -p vlog_formatter`: 180
|
||||
passed across seven binaries (114 `verification.rs`) — `verify.rs` does not
|
||||
appear anywhere in `git diff 7266b13` (`git diff --name-only | grep verify`:
|
||||
empty). `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`. After adding the tests below, `cargo test --workspace`: **2253
|
||||
passed, 0 failed, 8 ignored** (2244 + 9 new), fmt and clippy still clean.
|
||||
|
||||
**1. The ghost hunt and the affected-keys verdict — verified clean.**
|
||||
`WorkspaceIndex::update_file`'s `Ok(at)` arm computes `affected` as
|
||||
`Affected::of(&self.facts[at])` (the *old* record's names) then
|
||||
`affected.add(&facts)` (the *new* record's names) — a union of both sides,
|
||||
read directly at `crates/vlog_semantic/src/workspace.rs:311-315`. That is the
|
||||
side that matters: a name only the old record declared is still in the
|
||||
cleared set even though the new record no longer supplies it, so `merge`'s
|
||||
`self.units.remove(name)` followed by a full re-scan of **every** file's
|
||||
current facts (not just the changed one, `workspace.rs:422-460`) leaves
|
||||
nothing behind for it — no stale one-entry `Vec` survives. Constructed the
|
||||
exact ghost explicitly:
|
||||
`a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it`
|
||||
(vlog_semantic `tests/workspace.rs`) — a file that is the *sole* declarer of
|
||||
`solo` stops declaring it; `units("solo")` comes back empty and the
|
||||
fingerprint matches a fresh build. Passes. The same union covers edge-table
|
||||
keys too: `Affected::add` extends `modules` from `facts.instantiations` and
|
||||
`bases` from `facts.subclasses` (`workspace.rs:487-489`), so a file that stops
|
||||
instantiating `M` shrinks `M`'s table the same way — already covered by the
|
||||
dev's own `replacing_a_file_touches_only_what_that_file_said`, re-verified
|
||||
here by re-running it and by the new sequence test below.
|
||||
|
||||
**2. Byte-identical histories, adversarially — six new tests, all pass**
|
||||
(`crates/vlog_semantic/tests/workspace.rs`):
|
||||
- `a_long_interleaved_sequence_matches_a_fresh_build_at_every_step` — update
|
||||
A, update B, remove A, re-add A, update B again, fingerprint-checked after
|
||||
**every** step (not just at the end, which would miss a bug that only shows
|
||||
two steps later).
|
||||
- `a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it`
|
||||
— the ghost hunt above.
|
||||
- `adding_a_new_file_that_duplicates_an_existing_name_lands_by_path_order_either_direction`
|
||||
— the dev's own duplicate-name test only attacks the restricted-merge
|
||||
(`Ok(at)`) arm; this attacks the whole-merge (`Err(at)`, brand-new file)
|
||||
arm, both sort directions.
|
||||
- `find_define_answers_in_current_file_id_order_after_cross_file_updates` —
|
||||
`` `define``/`` `undef`` shadowing across files, then a renumbering add, then
|
||||
the answer re-checked in the new id order.
|
||||
- `updating_a_file_to_empty_text_differs_from_removing_it` — confirmed
|
||||
**different**, deliberately: `update_file(path, "")` keeps the file's
|
||||
`FileId` slot (still a file, contributing nothing); `remove_file` drops the
|
||||
slot and renumbers everything after it. Not pinned anywhere else in the
|
||||
round's own tests, so pinned here.
|
||||
- `same_named_files_in_different_directories_updated_alternately_stay_correct`
|
||||
— two files named `defs.sv` in different directories, updated A then B then
|
||||
A again, fingerprint-checked at each step (identity is the path,
|
||||
`binary_search_by` compares `PathBuf`s, never the filename alone).
|
||||
|
||||
**3. The moved walks — verbatim, confirmed byte-for-byte.**
|
||||
`diff` of `crates/lucisv_server/src/instantiations.rs` (at `7266b13`) against
|
||||
`crates/vlog_semantic/src/instantiations.rs`: the only changes are added doc
|
||||
comments (the "Lifted from..." note and two new one-line field docs); every
|
||||
line of code, every test, is identical. `classes.rs` is new but its three
|
||||
functions (`declarations`, `collect`, `extends_name`) are line-for-line
|
||||
identical to the private walk `type_hierarchy.rs` used to carry (compared
|
||||
directly against `git show 7266b13:crates/lucisv_server/src/type_hierarchy.rs`
|
||||
lines 141-274). `hierarchy::callers_of_each` and `type_hierarchy::subtypes`
|
||||
were rewritten (not moved) to read the new edge tables instead of walking
|
||||
`Workspace::sources()`; read both in full. The file-grouping `subtypes` and
|
||||
`callers_in` rely on ("edges arrive in file order, so one file's are
|
||||
consecutive") holds by construction: `merge` always fully clears and
|
||||
rebuilds an affected key's whole vector by iterating `self.facts` in
|
||||
ascending `FileId` order (never appends to a partial vector across separate
|
||||
merges), so the grouping invariant cannot be violated by any sequence of
|
||||
incremental updates, not just the initial build. Re-ran `lens.rs`'s QA policy
|
||||
tests and `the_instantiation_table_records_the_census_the_hierarchy_counts` /
|
||||
`the_inheritance_table_records_every_class_that_names_a_base` — unchanged,
|
||||
passing. `git diff --stat` on `hierarchy.rs`/`type_hierarchy.rs`/`lens.rs`
|
||||
test bodies: exactly the two superseded freshness tests
|
||||
(`an_unsaved_instantiation_is_a_caller_before_it_is_saved` →
|
||||
`an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it`,
|
||||
and the `extends` equivalent) plus the renamed/strengthened lens ratio test
|
||||
(`code_lenses_for_a_whole_file_cost_about_one_workspace_walk` →
|
||||
`..._a_fraction_of_a_workspace_walk`) and one doc-comment-only touch on
|
||||
`qa_perf_worst_case_common_word_module_name` (no logic change). Each
|
||||
supersession keeps the original point per house style: both rewritten tests
|
||||
assert the buffer alone does *not* move the count and then that
|
||||
`ws.update_one(path)` does — the same "unsaved edit is visible" property the
|
||||
old tests pinned, restated for a table that is index-fresh rather than
|
||||
per-request-fresh.
|
||||
|
||||
**4. `Candidates::words` exact bookkeeping — two new tests, both pass**
|
||||
(`crates/lucisv_server/src/candidates.rs`):
|
||||
`a_shared_word_dropped_from_one_file_is_still_offered_by_the_other` and
|
||||
`updating_the_same_file_twice_in_a_row_never_double_counts_or_goes_negative`.
|
||||
Read `set_words` (`candidates.rs:78-99`): it removes the *previous* call's
|
||||
words for this path before counting the new ones, so calling it twice in a
|
||||
row for the same path decrements based on the first call's own words, never
|
||||
double-decrements, and never underflows.
|
||||
|
||||
**5. The freshness delta's edges — verified against the code, not just the
|
||||
docs.** `hover::narrowed_to_the_include_graph` (`hover.rs:84-105`) is the
|
||||
concrete case: `candidates` come from `find_define`, which only ever
|
||||
enumerates files the index *currently* holds, while `reachable` comes from
|
||||
`includes::reachable_from`, whose first hop is resolved live off the buffer's
|
||||
own current text (`includes.rs:344-350`, "resolved against the buffer's
|
||||
*current* text rather than looked up in the graph") — buffer-fresh — before
|
||||
walking the rest of the graph via the index-fresh `IncludeGraph::edges`. The
|
||||
docs (`code-lens`, `hierarchy`, `type-hierarchy` READMEs, and this feature's
|
||||
own Assumptions) consistently say which surfaces are index-fresh (lens
|
||||
counts, `incomingCalls`, `subtypes`) versus buffer-fresh (an include's own
|
||||
first hop, go-to-definition, document links) — no surface was found
|
||||
mismarked.
|
||||
|
||||
**6. Fast-path discipline.**
|
||||
- Two saves in one batch: added
|
||||
`two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates`
|
||||
(`server.rs`). `process_batch` handles one message at a time
|
||||
(`for message in batch`, `server.rs:316`), so two `didSave`s in one burst
|
||||
are **two independent incremental updates**, not coalesced and not a full
|
||||
rebuild — confirmed: no progress bar, both files' edits land, generation
|
||||
bumps by 4 (2 saves × 2 bumps each — `set_document` bumps once for the
|
||||
buffer's own new text, `reindex_one` bumps once more for the fast path;
|
||||
these are orthogonal and both fire per save, which the test now pins
|
||||
explicitly since it was not obvious from the docs alone).
|
||||
- Generation bump / lens refresh / resultId: `reindex_one` bumps `generation`
|
||||
exactly once and calls `refresh_code_lenses()` exactly once
|
||||
(`server.rs:1365-1374`), pinned by the dev's own
|
||||
`a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
|
||||
`result_id()` is `self.generation.to_string()` (`server.rs:1024-1025`), so
|
||||
a fast-path update does move a pull-diagnostics client's `resultId` — no
|
||||
new test needed, it follows directly from the generation bump.
|
||||
No-bar/no-log: pinned by `a_one_file_save_costs_no_bar_and_no_log_line`,
|
||||
re-run, passing.
|
||||
- A save during another operation: the server is single-threaded and
|
||||
`process_batch` runs to completion before the next receive, so there is no
|
||||
interleaving to attack — matches the dev's own note.
|
||||
- A file whose *path* is held but which *is* the filelist: not reachable in
|
||||
practice — a filelist is a `.f`/similar file, never a `.sv`/`.v`/`.svh`
|
||||
source, so it is never a member of `self.index.files()` and
|
||||
`Workspace::update_one`'s gate (`state.rs:36`) returns `false` for it
|
||||
regardless of the watcher-side `one_scope_file` exclusion
|
||||
(`watch.rs:27-38`) — the two gates agree by construction rather than by
|
||||
coincidence, so no separate test was added for this shape.
|
||||
|
||||
**7. The include-graph gap — severity-checked, confirmed LOW/harmless
|
||||
(dangling, not wrong).** Traced every consumer of `IncludeGraph::edges`: only
|
||||
`reachable`/`reachable_from` read it (`document_links`/`definition` resolve
|
||||
live off disk via `resolved()`, never consulting `self.edges`). After a file
|
||||
`B` is removed, another file `A`'s stale forward-edge to `B` can make
|
||||
`reachable(A)` include `B`'s now-dangling path — but `B` has no `FileId` in
|
||||
the index any more, so `hover::narrowed_to_the_include_graph`'s filter
|
||||
(`ws.index().path(*file).is_some_and(|p| reachable.contains(p))`) can never
|
||||
match a *candidate* against that ghost path, because no surviving file's
|
||||
current path can equal a path the index no longer assigns to anyone. The
|
||||
answer is a superset that can only ever be harmlessly too permissive, never
|
||||
one that manufactures a wrong single-file narrowing. It self-heals the moment
|
||||
`A` itself is next incrementally updated (`IncludeGraph::update_file`
|
||||
re-resolves `A`'s own edges fresh off disk). No test added — this is a
|
||||
reachability argument about aliasing that a unit test would have to
|
||||
special-case anyway; recorded here for the record instead.
|
||||
|
||||
**8. Perf and memory claims — spot-reproduced, one discrepancy found.**
|
||||
Reproduced all three timing claims on this machine, same corpus, debug build:
|
||||
`qa_perf_one_file_against_the_whole_rebuild`: 1.517 s → 33.8 ms (45×, matches
|
||||
the README's 1.50 s → 33 ms exactly). `qa_perf_lens_lookup_against_the_walk_it_replaced`:
|
||||
67.1 ms → 0.297 ms (README: 92 ms → 0.26 ms — same order of magnitude, machine
|
||||
variance accounts for the rest). `qa_perf_subtypes_lookup_against_the_walk_it_replaced`:
|
||||
66.9 ms → 0.720 ms (README: 82 ms → 0.71 ms — very close). All three: **verified
|
||||
clean.**
|
||||
|
||||
**Finding (LOW, documentation accuracy, non-blocking).** The Assumptions
|
||||
section's memory estimate for `Candidates::per_file` — "Over the corpus that
|
||||
is ~170k `String`s of per-file lists on top of the ~17k distinct words —
|
||||
single-digit megabytes" — was checked against the real corpus with a scratch
|
||||
probe (`Candidates::build` over all 860 corpus files, then
|
||||
`per_file.values().map(Vec::len).sum()` and a byte estimate from
|
||||
`String::capacity()`; probe not kept, reproducible in one line from a REPL-ish
|
||||
test). Measured: **16,750 distinct words** (matches the "~17k" half of the
|
||||
claim) but **39,673 per-file word entries** — about **4.3× lower** than the
|
||||
claimed "~170k" — and **~1.38 MB** of per-file `String` storage, itself well
|
||||
under "single-digit megabytes." The *conclusion* ("single-digit megabytes,"
|
||||
i.e. the design is memory-cheap enough) is not undermined — if anything the
|
||||
real number is more favorable than claimed — but the specific "~170k" figure
|
||||
in the Assumptions section does not match reality and is not pinned by any
|
||||
test in the round. Not blocking; worth a one-line correction next time this
|
||||
README is touched.
|
||||
|
||||
**9. CLAUDE.md compliance.** No `unwrap()`/`expect()`/`panic!` in library code
|
||||
in any touched file, checked by grepping each file up to its own
|
||||
`#[cfg(test)]` module (`workspace.rs`, `instantiations.rs`, `classes.rs`,
|
||||
`state.rs`, `candidates.rs`, `includes.rs`, `server.rs`, `watch.rs`,
|
||||
`hierarchy.rs`, `type_hierarchy.rs`, `lens.rs`) — zero matches in all eleven.
|
||||
No `unsafe` anywhere in the diff. This README has all seven required
|
||||
sections, each exactly once (plus three extra ones the format allows: the
|
||||
fast-path trigger table, the derived-state table, Measured). `verify.rs` does
|
||||
not appear in the diff at all. Every corpus-dependent test checked is
|
||||
skip-guarded (`if !corpus.is_dir() { ...; return; }`). `TODO.md`'s completed
|
||||
items are struck through with the original text kept and a note appended,
|
||||
matching the project's existing convention for closing an item without
|
||||
deleting it. `docs/site/` diff is empty — untouched, as required. Spot-checked
|
||||
the struck Handshakes in `code-lens` and `hierarchy` READMEs against the
|
||||
actual code (`instantiations_of`/`subclasses_of` signatures, the lifted
|
||||
`vlog_semantic::instantiations`/`classes` modules) — accurate.
|
||||
|
||||
**Fixes made:** none to production code — every constructed attack passed.
|
||||
**Tests added (9, all passing):** the six `vlog_semantic` tests and two
|
||||
`candidates.rs` tests listed above, plus
|
||||
`two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates`
|
||||
in `server.rs`.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(2253 workspace tests, 0 failed), clean. The round's deviation was
|
||||
better than my brief: keeping FileIds as sorted positions and paying
|
||||
one in-memory merge per update buys byte-identical histories — the
|
||||
strongest equivalence there is — where my interned-ids design would
|
||||
have bought mere observational equivalence plus three consumers to
|
||||
audit forever. The structural argument (finish and update_file ending
|
||||
in the one merge over path-sorted records) is the same
|
||||
one-implementation discipline this codebase now uses everywhere, and
|
||||
QA's ghost hunt confirmed the affected-keys union reads both the old
|
||||
and new records, which is the single place the design could have
|
||||
silently rotted. The moved census walks are byte-for-byte verbatim,
|
||||
the policy numbers stand, and the freshness delta — counts as of the
|
||||
index, not of unsaved keystrokes — is the right trade, pinned from
|
||||
both sides.
|
||||
|
||||
The measured wins close two of the audit's oldest filed Handshakes
|
||||
with a 350x lens speedup and a 45x one-file rescan, on top of the
|
||||
scope round's narrowing — together these are the large-workarea story
|
||||
the owner asked for. QA's nine adversarial tests (the long
|
||||
sequences, define shadowing across renumbering, burst double-saves)
|
||||
are permanent. I corrected the one LOW finding (the per-file word-list
|
||||
estimate, 4.3x high; the conclusion stood). The three filed leftovers
|
||||
(wholesale republish, Candidates re-derivation cost, the include
|
||||
removal edge) are honest and none blocks. Accepted as shipped.
|
||||
@@ -75,6 +75,15 @@ slice that can panic.
|
||||
and no bump would let a changed buffer answer "unchanged". One notification =
|
||||
one reparse = one stamp = one `publish`. Pinned by
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`.
|
||||
**Amended 2026-08-28 by `docs/features/change-debounce/README.md`**: a
|
||||
`didChange` now records the composed text as dirty and the analysis runs at
|
||||
the next flush, so the promise reads **one *flush* is one `set_document`,
|
||||
one generation bump and one publish per dirty buffer** — however many
|
||||
ranges *and however many notifications* it coalesced. What the promise
|
||||
protects is unchanged: the counter never moves twice for work done once and
|
||||
never fails to move for a buffer whose text changed. The test above still
|
||||
passes as written; its helper flushes after each notification, which is the
|
||||
quiet-period timer firing.
|
||||
- **Changes what the client is told at `initialize`.**
|
||||
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
|
||||
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,703 @@
|
||||
# indexing-ux
|
||||
|
||||
## Goal
|
||||
|
||||
Three things a user of a *large* workspace has been asking the index for, all
|
||||
of them about knowing and controlling what the scan is doing. **(1) A per-file
|
||||
size cap** — `lucisv.index.maxFileSize`, 1 MiB by default: a Verilog file
|
||||
bigger than a mebibyte is almost always a generated netlist or a dumped trace,
|
||||
and indexing one costs minutes and answers nothing anybody asked. **(2) A
|
||||
counting progress bar** — the `$/progress` bar that `work-done-progress` put up
|
||||
was deliberately indeterminate, because `rebuild_index` was one opaque call;
|
||||
this round makes the build observable per file, so the bar says `137/860
|
||||
core_ibex_env.sv` and carries a real percentage. **(3) Per-file status in the
|
||||
editor's output channel** — `lucisv.index.logFiles`, on by default: one
|
||||
`window/logMessage` naming each file as it is parsed, plus a line for each file
|
||||
the cap skipped, so "why is this symbol missing" and "why is this scan slow"
|
||||
are answerable without a debugger. All three settings ride both settings doors
|
||||
(push and pull) for free, because `settings.rs` is the one parser for both.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The cap's blast radius is every `sources()` consumer, not just the
|
||||
index** (QA log, 2026-08-27, lead-expanded): a capped file is invisible to
|
||||
the workspace index, the hierarchy census (code-lens counts,
|
||||
incomingCalls), type-hierarchy subtypes, cross-file navigation, rename's
|
||||
collection sweep, and willRenameFiles' include rewriting. This is the one
|
||||
coherent reading — "which files exist as far as this server is concerned"
|
||||
— and nothing dangles, because the file is equally absent from every
|
||||
layer. The honesty gap QA proved: a rename that would have touched a
|
||||
capped file leaves its text stale on disk with no warning. Follow-up
|
||||
filed (see the task the lead spawned): sweeps that WRITE should say when
|
||||
the cap hid files from them.
|
||||
|
||||
|
||||
- **The cap applies to walked files only; an open buffer is always indexed in
|
||||
full.** The user opened it deliberately, and an editor that refused to
|
||||
understand the file on screen because of a size setting would be absurd.
|
||||
`collect_sources` reads the scope's files (capped) and *then* folds every
|
||||
open buffer in over the top (uncapped) — the same override that has always
|
||||
made a buffer beat disk.
|
||||
**Amended 2026-08-27 by large-file-mode, and this is the one exception:** a
|
||||
buffer over `lucisv.largeFile.threshold` (4 MiB by default) was never lexed
|
||||
or parsed at all, so it contributes *nothing* to the index — and it takes
|
||||
the disk copy of its own path out with it, rather than leaving the index
|
||||
describing bytes the buffer no longer has. The two settings do not overlap
|
||||
in intent: this one is about files nobody asked for, that one is about the
|
||||
file on screen. The interaction table is in
|
||||
`docs/features/large-file-mode/README.md`.
|
||||
- **The cap is enforced with `fs::metadata` before the read.** The whole
|
||||
saving is that a 200 MB netlist is never read into memory; a cap applied
|
||||
after `read_to_string` would be a cap that costs what it saves. A file whose
|
||||
metadata cannot be read is not skipped — it simply fails the read, as it
|
||||
always did.
|
||||
- **`0` means no cap, and must be exactly today's behaviour.** Pinned against
|
||||
the real corpus: the index built with the default cap and the index built
|
||||
with `maxFileSize: 0` are the same files in the same order with the same
|
||||
counts (`the_default_cap_changes_nothing_about_the_real_corpus`). It is
|
||||
true today because the largest file in `corpus/` is 94 KB — eleven times
|
||||
under the cap, and **zero** corpus files exceed 1 MiB — and that test is
|
||||
what notices if a future corpus or a future default changes it.
|
||||
- **A wrong-typed cap falls back to 1 MiB, not to 0.** Every other setting in
|
||||
`settings.rs` drops a bad value and goes silent; here "silent" has to mean
|
||||
the shipped default, because reading junk as `0` would turn the cap *off*,
|
||||
which is the failure the setting exists to prevent.
|
||||
- **The cap is a *server indexing* cap and nothing else.** It is not pushed
|
||||
into `lucisv_core`'s walk and not into the CLI's formatting path: `lucisv
|
||||
format` on a 4 MB file must still format it, and a `lucisv.toml` has no
|
||||
key for this. It lives in `Workspace::collect_sources`, which is the one
|
||||
place the server decides which files exist.
|
||||
- **…which means a refactoring sees the cap too.** `Workspace::sources()` —
|
||||
what a workspace rename and `find_references` read — goes through the same
|
||||
`collect_sources`. That is the consistent answer rather than an oversight: a
|
||||
file that is not in the index is not a file this server rewrites. Stated
|
||||
here because it is the one non-obvious reach of the setting.
|
||||
- **The denominator is the work list after `exclude` and after the cap.** It
|
||||
is `vlog_semantic::index_order`'s length, known before the first parse, so
|
||||
the bar counts towards a number the scan will actually reach. **Amended
|
||||
(index-scope, 2026-08-28): a scope widen's work list is the files it is
|
||||
actually indexing** — the folders it added, plus the open buffers it refreshes
|
||||
— so a jump into a 25-file folder of a 4 000-file project says `1/25`, not
|
||||
`1/3979`. That is the same rule, not an exception to it: the denominator has
|
||||
always been "what this scan will do", and a widen simply does less. The bar's
|
||||
**end message is unchanged** and still names the whole index
|
||||
(`"N files indexed"`), because the bar names the scan and the message names
|
||||
what the workspace now holds. No test in this feature moved; the fixtures
|
||||
here are small enough that a widen's work list is the whole scope, and the
|
||||
new denominator has its own test in `state.rs`
|
||||
(`a_widen_bar_counts_the_new_files_and_not_the_whole_scope`).
|
||||
- **The percentage only counts up, and the last file always reports.** See the
|
||||
throttle below; `the_report_schedule_never_floods_and_never_stops_short`
|
||||
checks both properties across nine workspace sizes.
|
||||
- **`logFiles` defaults to on.** The owner asked for it, and the channel it
|
||||
lands in is hidden until somebody opens it — `MessageType::LOG` goes through
|
||||
`vscode-languageclient`'s `default:` branch straight to
|
||||
`outputChannel.appendLine`, with no popup, no channel reveal and no trace
|
||||
gate (read out of `node_modules/vscode-languageclient/lib/common/client.js`,
|
||||
not assumed). A user who minds turns it off.
|
||||
- **The startup scan runs at the defaults, because settings arrive after it.**
|
||||
Both doors deliver settings only once `initialized` has been seen, so the
|
||||
first index build always uses the 1 MiB cap and always logs its files, even
|
||||
for a user who set neither. A differing cap then costs one extra rescan when
|
||||
it lands — the same one `lucisv.exclude` has always cost
|
||||
(`docs/features/folders-and-config/README.md`) — and a `logFiles: false`
|
||||
takes effect from the second rescan onwards. This is visible in the
|
||||
measurements below, where the "off" rows still carry the startup scan's 860
|
||||
lines.
|
||||
- **The skip *count* survives with the log off.** The skip lines are gated by
|
||||
`logFiles` like every other per-file line, but the progress `end` message
|
||||
becomes `"N files indexed, M skipped"` whenever `M > 0`, whatever the log
|
||||
setting says. A user who silenced the log should still learn that part of
|
||||
their workspace is not in the index.
|
||||
- **Changing the cap rescans; changing the log setting does not.**
|
||||
`max_file_size` changes *which files exist* as far as this server is
|
||||
concerned, exactly as `exclude` and `filelist` do, so it joins them in
|
||||
`set_client_settings`'s change test. `log_files` changes only how loudly the
|
||||
next rescan narrates itself.
|
||||
- **The completion tables and the include graph are outside the bar's count.**
|
||||
They are built from the same list after the index, and cost a small fraction
|
||||
of the parse. A bar that reached 100% and then sat there would be worse than
|
||||
one that ends.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### `vlog_semantic` — one addition, `build` redefined over it
|
||||
|
||||
`WorkspaceIndex::build` was one opaque call, so nothing outside the crate
|
||||
could see a rebuild advance. It is now the loop over two new public items,
|
||||
and its own signature and behaviour are unchanged:
|
||||
|
||||
```rust
|
||||
pub fn index_order<'a>(files: impl IntoIterator<Item = (PathBuf, &'a str)>)
|
||||
-> Vec<(PathBuf, &'a str)>; // sorted by path, one entry per path
|
||||
|
||||
pub struct IndexBuilder; // new() / add_file(path, src) / finish()
|
||||
|
||||
pub fn build<'a>(files: …) -> WorkspaceIndex {
|
||||
let mut builder = IndexBuilder::new();
|
||||
for (path, src) in index_order(files) { builder.add_file(path, src); }
|
||||
builder.finish()
|
||||
}
|
||||
```
|
||||
|
||||
- **Why the builder rather than a callback parameter.** A callback would have
|
||||
put a `&mut dyn FnMut` in a crate whose whole documented character is
|
||||
"pure: the same inputs always give the same index". The builder adds no
|
||||
parameter to anything and no closure to any signature; the caller that wants
|
||||
to watch simply runs the loop itself.
|
||||
- **Why `index_order` is public alongside it.** The builder hands out
|
||||
`FileId`s in call order, and *both* the file ids and the disambiguation
|
||||
order of a name declared twice are the path order `build` used to establish
|
||||
privately. Exporting the ordering rule is what keeps a watched build and a
|
||||
plain `build` the same index — and the server needs the list's length before
|
||||
the first parse anyway, for the progress denominator. It is the honest
|
||||
alternative to a comment telling callers to sort.
|
||||
**Superseded in part (index-scope, 2026-08-27):** ~~the builder hands out
|
||||
`FileId`s in call order~~ — it sorts inside `finish` now, so feeding it
|
||||
`index_order`'s list is no longer required for correctness. `index_order`
|
||||
stays public and unchanged for the denominator, and `build` still calls it so
|
||||
a duplicate path is not parsed twice.
|
||||
- **Proof of equivalence: every existing `vlog_semantic` test is unchanged**
|
||||
and every one of them goes through `build`. One new test
|
||||
(`the_incremental_builder_is_what_build_is_made_of`) drives the builder path
|
||||
directly and asserts the same `files()`, the same `counts()`, the same
|
||||
winning `Def` for a path handed over twice.
|
||||
- **Noted, not done:** `vlog_refactor::rename::Scope::build` re-derives the
|
||||
same sort-and-dedup by hand, with a comment saying so
|
||||
(`crates/vlog_refactor/src/rename.rs:148`). It could now call `index_order`.
|
||||
Out of this round's scope; filed here.
|
||||
|
||||
### `lucisv_server::state`
|
||||
|
||||
- `Workspace::rebuild_index_with(&mut dyn FnMut(IndexEvent))` and
|
||||
`open_roots_with(roots, …)` are the watched forms; `rebuild_index()` and
|
||||
`open_roots()` keep their exact old signatures and behaviour as the
|
||||
unwatched forms. `server.rs` always watches, so the unwatched pair is now
|
||||
reachable from tests alone and is `#[cfg(test)]` — several dozen call sites
|
||||
across the crate, none of which has an opinion about progress.
|
||||
- **Amended (incremental-index, 2026-08-27):** a rescan triggered by exactly
|
||||
one file the index already holds does not go through `rebuild_index_with` at
|
||||
all — it is `Workspace::update_one`, which reports no events, puts no bar up
|
||||
and writes no log lines, because one parse is not a scan to narrate. Every
|
||||
whole rescan is unchanged. The cap still applies, through the same
|
||||
`oversize` test, and a file that grew past it leaves the index on the
|
||||
incremental path too.
|
||||
- `pub enum IndexEvent<'a> { Parsing { done, total, path }, Skipped { path,
|
||||
size, cap } }`. Numbers and paths only: this module speaks no protocol, and
|
||||
the wording of every message stays in `server.rs`.
|
||||
**Amended (index-persistence, 2026-08-27):** a third variant, `Cached {
|
||||
done, total, path }` — the same three numbers, for a file the persistent
|
||||
index cache answered for instead of a parse. A new variant rather than a
|
||||
flag on `Parsing`, so that every consumer is asked by the compiler what it
|
||||
wants to say about a file that was not parsed.
|
||||
- `ClientSettings::max_file_size` is read in `collect_sources`; nothing else
|
||||
in `state.rs` changed.
|
||||
|
||||
### `lucisv_server::settings`
|
||||
|
||||
- Two new fields, `max_file_size: u64` and `log_files: bool`, parsed from
|
||||
`lucisv.index.maxFileSize` / `lucisv.index.logFiles`. VS Code nests a dotted
|
||||
setting id under each segment, so the section arrives as
|
||||
`{"index": {"maxFileSize": …}}`; an `index` that is missing, `null`, or not
|
||||
an object leaves both at their defaults.
|
||||
- **`ClientSettings`'s `Default` is now hand-written.** Two of the fields do
|
||||
not default to silence (1 MiB, and the log on), which a derive cannot say.
|
||||
Every other field is its type's zero, exactly as the derive produced, so
|
||||
every `..Default::default()` in the crate keeps meaning what it meant.
|
||||
- `DEFAULT_MAX_FILE_SIZE` is public so the tests and the docs name one number.
|
||||
|
||||
### `lucisv_server::server`
|
||||
|
||||
- `IndexWatch` turns `IndexEvent`s into a `$/progress` report and a
|
||||
`window/logMessage`, and counts the skips. It holds `&Connection` rather
|
||||
than `&Server`, because the workspace is borrowed mutably for the whole of
|
||||
the rebuild it is watching; `Server::new` and `reindex` therefore destructure
|
||||
`self` into its `connection` and `workspace` fields around the call. Same
|
||||
value, same operations, same order.
|
||||
- `Server::notify` and `Server::progress` now delegate to free `notify_on` /
|
||||
`progress_on` functions taking a `&Connection` — one implementation, two
|
||||
callers, no duplicated send.
|
||||
- `end_indexing` takes the skip count and says `"N files indexed, M skipped"`
|
||||
when it is non-zero.
|
||||
**Amended (index-persistence, 2026-08-27):** it takes the *cached* count as
|
||||
well and names it first — `"860 files indexed, 858 from cache, 2 skipped"` —
|
||||
because a scan that finished suspiciously fast should say why. Same rule as
|
||||
the skip count: the number is in the end message whether or not the per-file
|
||||
log is on. `IndexWatch` also grows an arm for `IndexEvent::Cached`, whose log
|
||||
line reads `cached: <path>` where a parsed file's reads `indexing: <path>`,
|
||||
and whose bar tick is identical — a cached file is a file of the work list,
|
||||
and the bar flying through them is the point.
|
||||
**Amended again (index-scope, 2026-08-28):** a third arm,
|
||||
`IndexEvent::Analyzed`, for a file that went into the index from an **open
|
||||
buffer's own finished analysis** rather than from a parse or from the store.
|
||||
Its log line reads `analyzed: <path>`; its bar tick is identical again. It
|
||||
deliberately adds **no** clause to the end message — one file out of a
|
||||
workspace is not why a scan finished fast, and "N from cache" keeps meaning
|
||||
the persistent store and nothing else, which is the sentence
|
||||
`index-persistence`'s e2e transcripts assert. See
|
||||
`docs/features/index-scope/README.md`.
|
||||
- `begin` still carries **no** percentage: the first honest one is the first
|
||||
file's.
|
||||
|
||||
### `editors/vscode`
|
||||
|
||||
- Two new `contributes.configuration` properties. No `extension.js` change:
|
||||
`synchronize: { configurationSection: 'lucisv' }` already pushes the whole
|
||||
section including the nested `index` object, and `new LanguageClient('lucisv',
|
||||
…)` already owns an output channel that `vscode-languageclient` appends every
|
||||
`MessageType::LOG` message to verbatim.
|
||||
- `smoke.js` sends `capabilities: {}` and no `index` section, so it takes the
|
||||
no-bar path with the log at its default; it passes untouched.
|
||||
|
||||
## Cost, measured
|
||||
|
||||
Release build, this Mac, 860-file `corpus/`, min of three runs of a session
|
||||
that does two full scans (startup + one save-triggered rescan):
|
||||
|
||||
| progress | logFiles | wall | stdout | log lines | `report`s |
|
||||
|---|---|---|---|---|---|
|
||||
| off | off* | 668.8 ms | 1.16 MB | 860 | 0 |
|
||||
| off | on | 670.9 ms | 1.34 MB | 1720 | 0 |
|
||||
| on | off* | 687.0 ms | 1.50 MB | 860 | 1720 |
|
||||
| on | on | 704.9 ms | 1.69 MB | 1720 | 1720 |
|
||||
|
||||
\* the settings push lands *after* the startup scan, so the "off" rows still
|
||||
carry the startup scan's 860 lines; only the second scan is quiet. That is
|
||||
what makes the rows subtract cleanly.
|
||||
|
||||
So, **per 860-file rescan**: 860 log lines ≈ 173 KB (≈ 201 B each, mostly
|
||||
absolute path), 860 reports ≈ 160 KB (≈ 186 B each). Both features on cost
|
||||
**≈ 18 ms on a ~690 ms two-scan session — about 2.6%**, and about 333 KB of
|
||||
extra stdout per rescan.
|
||||
|
||||
**Stated honestly: at 10,000 files the log is the part that gets ugly.** The
|
||||
reports are throttled to at most 1000 per rescan whatever the size, so they
|
||||
stay at ~190 KB; the log is not, so it would be ~2 MB of JSON on every save.
|
||||
That is a real number and a real cost, and the follow-up is batching (one
|
||||
`logMessage` per N files, or per directory) — **filed, not invented here**,
|
||||
because a batching scheme designed without a user complaining about it would
|
||||
be guessing at the wrong granularity. The escape hatch exists today: turn
|
||||
`lucisv.index.logFiles` off.
|
||||
|
||||
## The throttle rule
|
||||
|
||||
```rust
|
||||
const MAX_REPORTS: usize = 1000;
|
||||
fn reports(done: usize, total: usize) -> bool {
|
||||
let step = total.div_ceil(MAX_REPORTS).max(1);
|
||||
(done + 1).is_multiple_of(step) || done + 1 == total
|
||||
}
|
||||
```
|
||||
|
||||
Up to 1000 files, `step` is 1 and every file reports. Past that, every
|
||||
⌈total/1000⌉-th file reports — at most 1000 per rescan, so the bar still moves
|
||||
in steps of a tenth of a percent, which is under a pixel. The `|| done + 1 ==
|
||||
total` is the reason 10,001 files do not leave the bar one file short of the
|
||||
work it finished. Both regimes are pinned: the rule itself exhaustively for
|
||||
nine sizes, and a real 1100-file workspace end to end.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `lucisv.index.maxFileSize`, bytes, default 1 MiB, `0` disables
|
||||
- [x] Enforced on `fs::metadata` before the read, walked files only
|
||||
- [x] Open buffers exempt, and pinned as such
|
||||
- [x] A cap change rescans; `logFiles`, `lineLength`, `indent`,
|
||||
`formatOnSave`, `inlineTemplates` still do not
|
||||
- [x] `$/progress` `report`s carrying `n/total file.sv` and a real percentage
|
||||
- [x] Throttled to ≤ 1000 reports per rescan, last file always reported
|
||||
- [x] The same reports on the startup build and on every reindex trigger
|
||||
- [x] `window/logMessage` (`MessageType::LOG`) per file, plus skip lines
|
||||
- [x] Both gated by `lucisv.index.logFiles`, default on; skip **count**
|
||||
survives with the log off, in the `end` message
|
||||
- [x] `vlog_semantic::IndexBuilder` + `index_order`, with `build` redefined as
|
||||
the loop over them and every existing test unchanged
|
||||
— ~~and the builder's ordering contract carried by a doc comment~~
|
||||
**superseded (index-scope, 2026-08-27): `finish` sorts, so the contract
|
||||
is the code**
|
||||
- [x] `package.json` declares both settings, with the 0-disables semantics and
|
||||
the open-buffer exemption in the descriptions
|
||||
- [x] 21 new tests; 7 existing progress tests updated for the reports
|
||||
- [ ] **Not done, deliberately:** no batching of the log lines. See "Cost,
|
||||
measured" — the number is stated, the follow-up is named, and the
|
||||
granularity is not guessed at.
|
||||
- [ ] **Not done, deliberately:** no cap in `lucisv_core`'s walk or in the
|
||||
CLI. `lucisv format` on a huge file must still format it.
|
||||
- [ ] **Not done, deliberately:** no `lucisv.toml` key for the cap. It is an
|
||||
editor-session resource setting, not a project style decision — the same
|
||||
reason `serverPath` has no config key.
|
||||
- [ ] **Filed, not done:** `vlog_refactor::rename::Scope::build` could call
|
||||
`index_order` instead of re-deriving the sort/dedup.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-27 — dev agent (indexing UX: cap, counting bar, per-file log)
|
||||
|
||||
- **`vlog_semantic`: builder, not callback — and the reason is `FileId`.**
|
||||
The brief allowed either and asked for a justification. The builder shape
|
||||
did *not* fight the code, but it did expose an invariant: `build` sorted and
|
||||
deduped privately, and both the file ids and a duplicate name's
|
||||
disambiguation order depend on that. An `IndexBuilder` alone would have
|
||||
pushed "remember to sort" onto every caller as a comment. Exporting
|
||||
`index_order` beside it turns that into a call, and the server needed the
|
||||
ordered list's *length* before parsing anyway (the progress denominator), so
|
||||
the second public item has a real second use rather than being an
|
||||
abstraction for a user that does not exist. `build` is now three lines over
|
||||
the two of them; every existing `vlog_semantic` test is byte-identical and
|
||||
green, which is the equivalence proof.
|
||||
- **The cap went in `collect_sources`, one `fs::metadata` ahead of the read.**
|
||||
That is the one place the walked list becomes text, so it is the cheapest
|
||||
point and the only one where "never read the netlist" is true. Consequence
|
||||
found and documented rather than papered over: `Workspace::sources()` — the
|
||||
refactoring path — shares that function, so the cap reaches a workspace
|
||||
rename too. That is the consistent reading of "which files exist as far as
|
||||
this server is concerned", and it is now written down in Assumptions.
|
||||
- **`ClientSettings::default()` is hand-written now.** Two settings whose
|
||||
default is not silence (1 MiB, log on) cannot be derived, and pushing them
|
||||
into `Option`s would have made every use site re-decide what unset means.
|
||||
Every other field keeps the derive's value, so no existing
|
||||
`..Default::default()` changed meaning — the whole suite passing unchanged
|
||||
is the check.
|
||||
- **A wrong-typed `maxFileSize` falls back to the default, not to 0.** This is
|
||||
the one place this module's "drop it and go silent" rule needed a direction:
|
||||
silence here is 1 MiB, because reading junk as 0 would silently un-cap.
|
||||
- **Nested keys, because VS Code nests them.** `lucisv.index.maxFileSize`
|
||||
arrives as `{"index": {"maxFileSize": …}}` through both doors; the parser
|
||||
reads `lucisv.get("index")` once and a non-object `index` is the same as no
|
||||
`index`. Pinned through `from_section` too, since these are the first nested
|
||||
keys to go through the pull door.
|
||||
- **`IndexWatch` holds `&Connection`, not `&Server`.** The workspace is
|
||||
borrowed mutably for the whole rebuild, so `Server::new` and `reindex`
|
||||
destructure `self` and hand the watcher the connection field. `notify` and
|
||||
`progress` were re-pointed at free `notify_on`/`progress_on` functions so
|
||||
there is still exactly one place a notification is sent.
|
||||
- **The report message names the file, the log line names the path.** The bar
|
||||
is a few dozen characters of status bar; the path belongs in the channel
|
||||
that has room for it.
|
||||
- **`human_size`, not a fixed MiB.** The first draft printed
|
||||
`skipped (0.0 MiB > 0.0 MiB cap)` for a 4 KiB file under a 1 KiB cap — the
|
||||
e2e test caught it. The cap is settable to anything, so the unit adapts:
|
||||
bytes, KiB, MiB.
|
||||
- **Seven existing tests were updated, all of them pinning "no report".**
|
||||
That assumption is exactly what this round removes, so each one gained its
|
||||
reports rather than being relaxed:
|
||||
`the_startup_index_build_runs_under_the_first_bar`,
|
||||
`a_save_puts_a_bar_up_and_takes_it_down_again`,
|
||||
`the_bar_is_down_before_the_republish`,
|
||||
`every_rescan_path_gets_its_own_bar_and_its_own_token` (its "no invented
|
||||
percentages" line became "every report is inside its own bar", which is the
|
||||
stronger property),
|
||||
`the_refresh_rides_after_the_indexing_bar_comes_down`,
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
|
||||
`one_folder_notification_is_one_rescan_with_one_bar_and_one_generation`, plus
|
||||
the e2e `indexing_reports_its_progress_over_the_wire`.
|
||||
- **One surprise worth recording:** `package small;` does not index —
|
||||
`small` is a SystemVerilog keyword (charge strength). Two new fixtures were
|
||||
renamed to `small_pkg` after that cost ten minutes.
|
||||
- Files touched: `crates/vlog_semantic/src/workspace.rs`,
|
||||
`crates/vlog_semantic/src/lib.rs`, `crates/vlog_semantic/tests/workspace.rs`,
|
||||
`crates/lucisv_server/src/settings.rs`, `crates/lucisv_server/src/state.rs`,
|
||||
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/tests/e2e.rs`,
|
||||
`editors/vscode/package.json`, `TODO.md`,
|
||||
`docs/features/work-done-progress/README.md`,
|
||||
`docs/features/lucisv-server/README.md`, this README. No new dependency, no
|
||||
version bump, no `docs/site/`, no commits.
|
||||
|
||||
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
|
||||
--all-targets`: zero warnings. `cargo test --workspace`: **2197 passed, 0
|
||||
failed** (2176 on `HEAD` — 21 new). `cargo test -p vlog_formatter`: green.
|
||||
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`:
|
||||
`smoke: OK`. Corpus: 0 of 860 files exceed 1 MiB (largest, `picorv32.v`, is
|
||||
94 KB), and the default-cap index is identical to the uncapped one — pinned
|
||||
by a test, not just measured.
|
||||
|
||||
The 21 tests, and what each is for:
|
||||
|
||||
| test | pins |
|
||||
|---|---|
|
||||
| `the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off` (settings) | the default, the empty sub-section, `0`, and no upper bound |
|
||||
| `a_wrong_typed_size_cap_leaves_the_default_standing` (settings) | six wrong types, and four wrong shapes of `index` itself |
|
||||
| `the_file_log_is_on_until_a_client_turns_it_off` (settings) | absence, both booleans, five wrong types |
|
||||
| `the_index_settings_come_through_the_pull_door_too` (settings) | the nesting survives `from_section`, one set of rules |
|
||||
| `a_walked_file_over_the_cap_is_left_out_of_the_index` (state) | the cap itself |
|
||||
| `the_default_cap_is_a_mebibyte_and_zero_turns_it_off` (state) | a real >1 MiB file against the shipped default, then `0` |
|
||||
| `an_open_buffer_is_indexed_however_big_the_file_is` (state) | the exemption |
|
||||
| `every_skipped_file_is_reported_with_its_size_and_the_cap` (state) | the `Skipped` event's path, size and cap |
|
||||
| `the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first` (state) | the denominator is post-exclude, post-cap; events are in index order |
|
||||
| `the_default_cap_changes_nothing_about_the_real_corpus` (state) | cap-on == cap-off over `corpus/`, files and counts |
|
||||
| `the_bar_counts_the_files_as_it_goes` (server) | `1/2 a.sv` at 50%, `2/2 b.sv` at 100% |
|
||||
| `the_reports_thin_out_when_the_workspace_is_huge` (server) | 1100 real files: ≤1000 reports, monotonic, last is `1100/1100` |
|
||||
| `the_report_schedule_never_floods_and_never_stops_short` (server) | the rule at 1, 2, 999, 1000, 1001, 1999, 2000, 12345, 40000 |
|
||||
| `the_end_message_names_what_the_cap_skipped` (server) | `"1 file indexed, 1 skipped"`, with the log **off** |
|
||||
| `a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not` (server) | both halves of the cap through the real dispatch |
|
||||
| `every_indexed_file_is_named_in_the_log_and_so_is_every_skip` (server) | one line per file, `MessageType::LOG`, the skip line's sizes |
|
||||
| `the_file_log_goes_quiet_when_the_setting_is_off` (server) | not one line, skips included |
|
||||
| `the_file_log_does_not_wait_for_a_progress_bar` (server) | the log is not gated on the progress capability |
|
||||
| `a_new_cap_rescans_and_a_new_log_setting_does_not` (server) | the change detection, both directions, through `didChangeConfiguration` |
|
||||
| `the_incremental_builder_is_what_build_is_made_of` (vlog_semantic) | builder == `build`: files, ids, counts, duplicate-path winner |
|
||||
| `the_size_cap_and_the_file_log_work_over_the_wire` (e2e) | the real binary: nested setting → rescan → symbol gone, log lines, report and end message decoded off the wire |
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-27 — QA agent (one round: cap, counting bar, per-file log)
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets
|
||||
--workspace`: zero warnings. `cargo test --workspace`: **2197 passed, 0
|
||||
failed** (matches the dev's number exactly; one incidental failure of an
|
||||
unrelated pre-existing timing-budget test,
|
||||
`lens::tests::code_lenses_for_a_whole_file_cost_about_one_workspace_walk`,
|
||||
during a run made while several other `cargo`/release builds were competing
|
||||
for CPU in the background — reran clean in isolation twice, not a regression,
|
||||
not touched by this round). `cargo test -p vlog_formatter`: 114 passed,
|
||||
`verify.rs` untouched (confirmed via `git status`/`git diff` — it never
|
||||
appears). `node smoke.js target/debug/lucisv-server`: OK.
|
||||
|
||||
All temporary attack code below was added directly to the tracked files
|
||||
listed, run, and then removed with a diff-identical revert verified against a
|
||||
saved copy of the original `git diff` before continuing — no attack code
|
||||
remains in the working tree.
|
||||
|
||||
**1. FileId/ordering invariant — VERDICT: safe today, latent risk in the
|
||||
abstraction.** `WorkspaceIndex::build` and `Workspace::rebuild_index_with`
|
||||
(the only two callers of `IndexBuilder::add_file` in the tree) both feed it
|
||||
`index_order`'s list, in order, so the two are provably identical — confirmed
|
||||
independently by feeding a workspace with a case/depth-nontrivial duplicate
|
||||
module name (`z_late.sv` / `a_early.sv`, both declaring `dup`) through `build`
|
||||
and through a manual `index_order` + `IndexBuilder` loop: same `FileId`s, same
|
||||
disambiguation winner (`a_early.sv` first, both ways).
|
||||
|
||||
But **Closed by index-scope, 2026-08-27** (see `docs/features/index-scope/README.md`):
|
||||
`IndexBuilder::add_file` now keeps its file's declarations to itself and
|
||||
`finish` sorts them by path before handing out any `FileId`, so no insertion
|
||||
order can reach the result. QA's construction below is a permanent test,
|
||||
`no_insertion_order_can_change_what_the_builder_produces`. The finding as
|
||||
filed, kept legible:
|
||||
|
||||
`IndexBuilder` itself enforces nothing — it is a dumb accumulator, and the
|
||||
ordering guarantee is carried entirely by the doc comment ("Feed it
|
||||
`index_order`'s list"), not the type system. Direct attack, temporarily added
|
||||
to `crates/vlog_semantic/tests/workspace.rs` and run:
|
||||
```rust
|
||||
let files = [
|
||||
("z_late.sv", "module dup (input a); endmodule\n"),
|
||||
("a_early.sv", "module dup (input b); endmodule\n"),
|
||||
];
|
||||
let mut wrong = IndexBuilder::new();
|
||||
for (p, s) in files { wrong.add_file(PathBuf::from(p), s); } // raw order, NOT index_order
|
||||
let wrong = wrong.finish();
|
||||
let right = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
|
||||
assert_eq!(wrong.files(), right.files()); // FAILS
|
||||
```
|
||||
Result: `wrong.files() == ["z_late.sv", "a_early.sv"]` vs.
|
||||
`right.files() == ["a_early.sv", "z_late.sv"]` — `FileId(0)` and the `dup`
|
||||
disambiguation winner both flip. So insertion order **does** leak into the
|
||||
result the moment a caller bypasses `index_order`, exactly as the brief
|
||||
warned. Severity: **MEDIUM, not HIGH** — both current production call sites
|
||||
are verified correct, so this is not a live bug in this round's shipped code,
|
||||
but it is a real footgun for the one thing the README itself flags as
|
||||
"filed, not done" (`vlog_refactor::rename::Scope::build` migrating to
|
||||
`IndexBuilder` later). Suggest, as a non-blocking follow-up: either have
|
||||
`IndexBuilder::add_file` debug-assert paths arrive in non-decreasing order,
|
||||
or fold `index_order` into `IndexBuilder` itself (e.g. buffer-then-sort on
|
||||
`finish()`) so the invariant can't be bypassed by a future caller who didn't
|
||||
read the doc comment.
|
||||
|
||||
**2. The cap's blast radius through `sources()` — documentation gap, coherent
|
||||
behavior.** `Workspace::sources()` is also consumed by
|
||||
`crates/lucisv_server/src/hierarchy.rs:90` (codeLens counts /
|
||||
`callers_of_each`), `ports.rs:61,87`, `nav.rs:132` (`find_references`), and
|
||||
`type_hierarchy.rs:112` (subtypes) — not just `rename.rs`/`file_ops.rs`. The
|
||||
indexing-ux README's Assumptions section and the `lucisv-server` README's new
|
||||
paragraph name only the rename/refactoring reach ("a refactoring sees the cap
|
||||
too"); the existing per-endpoint table rows for `callHierarchy/incomingCalls`
|
||||
and `typeHierarchy/subtypes` (`docs/features/lucisv-server/README.md` lines
|
||||
46 and 50) are untouched by this diff and say nothing about the cap, even
|
||||
though those two consumers are exposed identically. The behavior itself is
|
||||
coherent — a capped file is invisible everywhere consistently, nothing
|
||||
dangles — but a future reader of those two table rows would not learn that a
|
||||
netlist over the cap silently vanishes from an instantiation count or a
|
||||
subtype list too.
|
||||
|
||||
Concretely reproduced the rename case as the sharpest instance (temporarily
|
||||
added to `crates/lucisv_server/src/rename.rs`, run, reverted): a workspace
|
||||
with `sub.sv` (declares `sub`), `top.sv` (open, instantiates `sub`), and a
|
||||
4 KB `netlist.sv` over a 1 KiB cap that *also* instantiates `sub`. Renaming
|
||||
`sub` to `child`:
|
||||
```rust
|
||||
let (edit, warnings) = rename(&ws, &uri, at(TOP, "sub u_sub"), "child").expect("renames");
|
||||
// changes.len() == 2 (sub.sv, top.sv) — netlist.sv is absent
|
||||
// warnings == [] — nothing at all says netlist.sv exists or was skipped
|
||||
```
|
||||
So a rename leaves `netlist.sv` with a stale, now-broken reference to the old
|
||||
name, **with zero warning anywhere in the rename response** — not in
|
||||
`refactoring.warnings`, not in any diagnostic. The only place this is ever
|
||||
surfaced is the output-panel skip line from whichever index build happened to
|
||||
run earlier (`logFiles` on), which is decoupled in time from the specific
|
||||
rename and easy to have scrolled past. Severity: **MEDIUM** — the "not
|
||||
indexed → not rewritten" design is defensible and documented as intentional,
|
||||
but the complete silence *at the point of the risky action* is a real UX gap.
|
||||
Suggest as a follow-up: have `rename`/`find_references` check
|
||||
`ws.sources()` against a cheap re-walk (or thread the skip list through) and
|
||||
fold "N file(s) over the size cap may also reference this symbol" into
|
||||
`refactoring.warnings` when the cap is non-zero.
|
||||
|
||||
**3. Cap edge semantics.**
|
||||
- **Exact boundary, pinned by hand (dev's suite doesn't cover it):** a file of
|
||||
exactly 1024 bytes against a 1024-byte cap is **not** skipped — `oversize`
|
||||
is `size > cap`, so the cap is inclusive (`≤ cap` survives). Verified with a
|
||||
temporary test in `state.rs` creating a file measured at exactly 1024 bytes
|
||||
on disk and confirming it appears in the index under a 1024-byte cap.
|
||||
Correct and sensible, just untested — worth a permanent test.
|
||||
- **Metadata failure:** confirmed consistent with the documented behavior —
|
||||
`oversize`'s `fs::metadata(path).ok()?` returns `None` on failure, so the
|
||||
file is not reported as skipped; it falls through to
|
||||
`fs::read_to_string`, which will also fail for the same reason, and the
|
||||
file is silently absent from `texts` exactly as it always was pre-cap. No
|
||||
regression, no new silent-failure mode.
|
||||
- **Growing file mid-scan:** not a race, as claimed — `oversize` and the read
|
||||
are back-to-back for one file within one scan.
|
||||
- **Symlinks:** verified directly (a symlink `link.sv` → a 5053-byte
|
||||
`target_big.sv`, plus a `symlink_metadata` comparison showing 13 bytes for
|
||||
the link itself vs. 5053 via `fs::metadata`). `oversize` uses `fs::metadata`
|
||||
(follows the link), and so does the subsequent `fs::read_to_string` — the
|
||||
cap is measured against the same bytes that would be read, not the
|
||||
symlink's own size. Coherent, no bug.
|
||||
|
||||
**4. Settings parsing.**
|
||||
- Nested `{"index": {"maxFileSize": …}}` and the wrong-type→default fallback:
|
||||
verified via the dev's own tests, both green.
|
||||
- **Flat `{"index.maxFileSize": …}` shape (untested by the dev's suite):**
|
||||
confirmed by a temporary test that `lucisv.get("index")` looks for a
|
||||
literal `"index"` key, so a flattened dotted key is invisible to the parser
|
||||
and silently resolves to the default (1 MiB) — same as `index` being
|
||||
absent entirely. Coherent with the module's "drop it and go silent"
|
||||
philosophy, but this specific shape isn't pinned by a test, unlike every
|
||||
other edge case in this settings addition. Low-severity gap, easy add.
|
||||
- Pull-door parity (`from_section`): verified via the dev's own test, green.
|
||||
|
||||
**5. Throttle honesty.** The dev's own
|
||||
`the_report_schedule_never_floods_and_never_stops_short` already covers the
|
||||
rule exhaustively at 1, 2, 999, 1000, 1001, 1999, 2000, 12345, 40000, and
|
||||
`the_reports_thin_out_when_the_workspace_is_huge` exercises it against 1100
|
||||
real files end to end. Both ran green in the full-suite run; no gaps found
|
||||
worth a separate synthesis.
|
||||
|
||||
**6. Logging gate.** Verified via the dev's own tests
|
||||
(`the_file_log_goes_quiet_when_the_setting_is_off`,
|
||||
`every_indexed_file_is_named_in_the_log_and_so_is_every_skip` asserting
|
||||
`MessageType::LOG` specifically — not `INFO` — and
|
||||
`the_file_log_does_not_wait_for_a_progress_bar`). All green. No gaps found.
|
||||
|
||||
**7. The 8 updated tests.** Read every diff hunk. Seven of them
|
||||
(`the_startup_index_build_runs_under_the_first_bar`,
|
||||
`a_save_puts_a_bar_up_and_takes_it_down_again`,
|
||||
`the_bar_is_down_before_the_republish`,
|
||||
`the_refresh_rides_after_the_indexing_bar_comes_down`,
|
||||
`the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down`,
|
||||
`one_folder_notification_is_one_rescan_with_one_bar_and_one_generation`, and
|
||||
the e2e `indexing_reports_its_progress_over_the_wire`) only insert `"report"`
|
||||
entries into an already-asserted ordering sequence — their original point
|
||||
(bar goes up, comes down, in the right place relative to X) is intact.
|
||||
The eighth, `every_rescan_path_gets_its_own_bar_and_its_own_token`, is the one
|
||||
whose point *was* "no report is ever invented" — that assumption is exactly
|
||||
what this round removes, and it is replaced with the strictly stronger "every
|
||||
report belongs to a currently-open bar" check, under an explicit `// Superseded
|
||||
this round:` comment. That is the correct way to retire an assumption per
|
||||
CLAUDE.md's house style, and it is the one case that needed it.
|
||||
|
||||
**8. CLAUDE.md compliance.**
|
||||
- No `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)]` in any touched
|
||||
non-test code (`server.rs`, `settings.rs`, `state.rs`, `workspace.rs`,
|
||||
`lib.rs`) — checked directly, clean.
|
||||
- Every new `pub` item (`index_order`, `IndexBuilder` + its three methods,
|
||||
`IndexEvent`, `open_roots_with`, `rebuild_index_with`) has a doc comment.
|
||||
- The feature README has all seven required sections exactly once (plus two
|
||||
extra informational sections, "Cost, measured" and "The throttle rule",
|
||||
which CLAUDE.md doesn't forbid).
|
||||
- The superseded-assumption annotations in `TODO.md`,
|
||||
`docs/features/work-done-progress/README.md`, and
|
||||
`docs/features/folders-and-config/README.md` all follow the existing house
|
||||
style (`~~struck~~` + a dated "Superseded ... by ..." note that keeps the
|
||||
original reasoning legible) consistently.
|
||||
- `verify.rs` is untouched — confirmed absent from `git status` and `git
|
||||
diff` entirely.
|
||||
- The new corpus-gated tests (`the_default_cap_changes_nothing_about_the_real_corpus`
|
||||
in `state.rs`) follow the `if !corpus.is_dir() { eprintln!("corpus/ not
|
||||
checked out — skipping"); return; }` convention exactly as the pre-existing
|
||||
corpus tests in `vlog_semantic` do.
|
||||
|
||||
**C. Beyond the list.**
|
||||
- **`maxFileSize: 1`** (temporary test in `state.rs`): every walked file
|
||||
skipped, index ends up with 0 files (not a panic, not an error), and an
|
||||
opened buffer is still indexed in full afterward. Server stays functional
|
||||
at the extreme.
|
||||
- **`logFiles` toggled mid-session:** already covered by the dev's own
|
||||
`the_end_message_names_what_the_cap_skipped` (toggles `logFiles` false in
|
||||
the same session as a cap change) and `a_new_cap_rescans_and_a_new_log_setting_does_not`.
|
||||
Both green; no gap found.
|
||||
- **Overhead measurement, ~18 ms / 2.6% claim:** attempted an independent
|
||||
spot-reproduction twice (a release/LTO build that did not finish in
|
||||
reasonable time in this sandboxed environment, then a debug-mode custom
|
||||
harness that hit a broken pipe in its own scratch code talking to the real
|
||||
binary over a hand-rolled 860-file corpus session — a bug in the throwaway
|
||||
harness, not reproduced against the dev's own passing corpus-based tests).
|
||||
Not independently re-measured; **not verified numerically**. The mechanism
|
||||
itself is architecturally sound for the claimed order of magnitude — one
|
||||
extra `fs::metadata` call and one extra `window/logMessage`/`$/progress`
|
||||
notification per file, both cheap, no additional passes over file content —
|
||||
so I have no reason to doubt the figure, but I did not confirm it myself.
|
||||
- **`human_size` rounding boundary — new finding, LOW-MEDIUM, cosmetic
|
||||
only.** `human_size(1_048_575)` (one byte under 1 MiB) prints `"1024.0
|
||||
KiB"` instead of switching to the MiB branch, because `1_048_575.0 / 1024.0
|
||||
== 1023.999...` is `< MIB` so it takes the KiB arm, then rounds *up* to
|
||||
`1024.0` at `{:.1}` precision. Same failure mode one level up:
|
||||
`human_size(1_073_741_823)` (one byte under 1 GiB, which this function has
|
||||
no branch for) prints `"1024.0 MiB"`. Verified directly:
|
||||
```
|
||||
1048575 -> 1024.0 KiB
|
||||
1073741823 -> 1024.0 MiB
|
||||
```
|
||||
This is the same class of bug the e2e test already caught once (`"0.0 MiB >
|
||||
0.0 MiB"`), just at the opposite (upper) rounding edge, and only reachable
|
||||
today via a skip line whose size or cap happens to land in one of those
|
||||
windows — cosmetic, no effect on cap enforcement or index correctness.
|
||||
Worth a follow-up fix (e.g. bump the branch threshold down by half a unit,
|
||||
or format then re-check which unit the rounded string actually names).
|
||||
|
||||
**Verdict: committable as-is.** No correctness regression, no invariant
|
||||
violated, all four gates green, 2197/2197 tests passing. Two MEDIUM findings
|
||||
(the `IndexBuilder` ordering footgun, and the silent rename-blast-radius gap)
|
||||
are both documented-intentional-behavior-with-an-honesty-gap rather than bugs
|
||||
in what shipped, and are appropriately deferred as dev follow-ups rather than
|
||||
blockers. One LOW-MEDIUM new cosmetic finding (`human_size` rounding) and two
|
||||
LOW test-coverage gaps (exact-boundary cap, flat settings key) are cheap to
|
||||
add later and do not affect behavior today.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-27 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself,
|
||||
clean. The three features land the way the owner asked and the details
|
||||
show the right instincts: junk cap values fall back to 1 MiB rather
|
||||
than 0 (misparse must never un-cap), the denominator is the real work
|
||||
list known before the first parse, the skip count outlives the log
|
||||
toggle, and the vlog_semantic change follows the established
|
||||
redefinition pattern with `index_order` exported so the FileId
|
||||
ordering rule is a call, not a comment.
|
||||
|
||||
Rulings on QA's findings. The builder-ordering footgun (MEDIUM) is
|
||||
real and correctly assessed as latent — both production callers funnel
|
||||
through index_order, proven by QA's both-ways construction — and the
|
||||
fix belongs to the next round, whose scope work is precisely the
|
||||
future caller at risk: round 18's brief requires making the builder
|
||||
order-insensitive or formally enforcing the contract, with QA's attack
|
||||
as the acceptance test. The cap blast radius (MEDIUM) is accepted as
|
||||
the one coherent reading — absent from every layer equally — and I
|
||||
have expanded the Assumptions to name every consumer, with the
|
||||
write-path warning gap (a rename silently leaving a capped file's text
|
||||
stale) filed as a visible follow-up task rather than buried. The
|
||||
human_size rounding bug (LOW) I fixed directly with the unit chosen by
|
||||
what the rounded number reads as, plus the boundary test. The
|
||||
unreproduced 18 ms overhead claim stands as the dev's measurement with
|
||||
QA's non-verification noted — the mechanism is sound and the number is
|
||||
not load-bearing. Accepted as shipped.
|
||||
@@ -0,0 +1,440 @@
|
||||
# interactive-latency
|
||||
|
||||
## Goal
|
||||
|
||||
Make the request and notification paths a user *feels* — the ones that run
|
||||
while they type and move the cursor — cost what they have to cost and no
|
||||
more, and say with measured numbers where the rest of the time goes. Round 1
|
||||
(`docs/perf/README.md`) established the baseline and named the open question
|
||||
it could not answer from inside the crate: what a `didChange` →
|
||||
`publishDiagnostics` round trip actually takes over the wire. This round
|
||||
answers that, breaks one flush down stage by stage, and takes the
|
||||
identity-safe wins the breakdown justifies — which turned out to be six token
|
||||
lookups that were sweeping the whole buffer for something a binary search
|
||||
answers in twenty nanoseconds. Nothing on the parse path was touched: the
|
||||
measurements say the remaining cost is lexing and parsing, and that is a
|
||||
change this round deliberately does not make.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The token stream rises and never overlaps.** Every binary search added
|
||||
here rests on one property of `Document.tokens`: the lexer emits tokens in
|
||||
source order, so `end[i] <= start[i+1] <= end[i+1]` and both
|
||||
`span.start < offset` and `span.end < offset` are monotone predicates over
|
||||
the vector. That is the whole precondition `partition_point` needs, and it
|
||||
is pinned by `state::tests::the_token_stream_rises_and_never_overlaps` —
|
||||
the test that would fail first if the lexer ever changed shape. Nothing
|
||||
here assumes tokens are non-empty: the `Eof` sentinel is zero-width, and
|
||||
every argument below survives it.
|
||||
- **No benchmark dependency**, unchanged from round 1: `std::time::Instant`,
|
||||
`#[ignore]`d tests, no `criterion`. `CLAUDE.md` requires a written
|
||||
justification for a new dependency and there is none to write.
|
||||
- **A measurement asserts nothing about duration.** A test that fails when
|
||||
the machine is busy is a test that gets deleted.
|
||||
- **The e2e round trip is a real session.** It spawns the shipped binary and
|
||||
speaks framed JSON-RPC at it, so the number includes the pipes, the JSON,
|
||||
the debounce timer and the flush. It cannot be taken from inside the crate,
|
||||
which is exactly why round 1 could not take it.
|
||||
- **The generated module is uniform, and real RTL is not.** Both generators
|
||||
build the same repeated four-line block. The numbers are a scale, not a
|
||||
prediction for any given file.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser` → this crate (consumed, unchanged).** The binary searches
|
||||
consume the ordering property of `tokenize`'s output described above.
|
||||
Nothing was asked of `vlog_parser` and nothing in it changed. If it ever
|
||||
emits tokens out of order, the pinning test in `state.rs` fails before any
|
||||
handler answers wrongly.
|
||||
- **`state.rs` → `selection.rs`, `on_type.rs`, `completion.rs` (new,
|
||||
internal).** Two free functions, `first_token_reaching` and
|
||||
`first_token_from`, are published from `state.rs` beside `Document`. They
|
||||
are the single place the monotonicity argument is written down; every call
|
||||
site is one comparison on top of one of them. `inline.rs` uses a third
|
||||
predicate (`span.end <= offset`) written at its own call site, because it
|
||||
has one user and its own local proof.
|
||||
- **`e2e.rs`'s `Live::finish` now returns the publish count** it saw on the
|
||||
way out. Existing callers ignore the value, which compiles unchanged. The
|
||||
count is what turns "the debounce coalesces a burst" from arithmetic into a
|
||||
measurement.
|
||||
- **Two copies of one generator.** `perf::generated_module` and the copy in
|
||||
`tests/e2e.rs` must stay the same shape, or the in-crate table and the
|
||||
over-the-wire table in `docs/perf/README.md` stop being readable against
|
||||
one another. `lucisv_server` is a binary crate, so an integration test
|
||||
cannot import the original; the copy is commented as such at both ends.
|
||||
- **Nothing was asked of `vlog_linter`.** The lint pass costs 1.40 ms of a
|
||||
32 ms flush at 10 000 lines and walks the tree once per rule; that is
|
||||
recorded in `docs/perf/README.md` as a future round's work, not requested
|
||||
here.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Phase 1 — a stage-by-stage breakdown of one flush at 1k and 10k lines:
|
||||
`tokenize`, `tokens.clone()`, `parse_tolerant`, `collect_defines`,
|
||||
`analyze`, `resolve_external`, `LineIndex::new`, and the
|
||||
`diagnostics::all` pass a publish runs (which is *not* inside
|
||||
`Document::new`, and which round 1's table did not account for).
|
||||
`perf::breaking_down_one_flushed_keystroke`.
|
||||
- [x] Phase 1 — the end-to-end round trip round 1 listed as its own open
|
||||
TODO: `didChange` → `publishDiagnostics` against the real binary, for a
|
||||
single change, for a burst of ten, and for the change-then-request
|
||||
shape a real editor produces.
|
||||
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`.
|
||||
- [x] Phase 2 — six token lookups swapped from a sweep to a binary search,
|
||||
each with a test that walks **every byte** of a buffer written to have
|
||||
plenty of touching tokens and asserts the search returns exactly what
|
||||
the sweep returned.
|
||||
- [x] Phase 2 — the three sweeps that are inherent left alone, with the
|
||||
reason written down (below).
|
||||
- [x] Phase 3 — decided against every change the breakdown did not justify,
|
||||
with the number for each (below).
|
||||
- [x] Phase 4 — `docs/perf/README.md` refreshed: both of round 1's open
|
||||
TODOs resolved or restated, every figure re-measured on this machine.
|
||||
|
||||
Not done, deliberately, and each with the number that would justify it — the
|
||||
list lives in `docs/perf/README.md`'s *What it would take to go faster* so it
|
||||
sits beside the measurements rather than in a feature's checklist.
|
||||
|
||||
## The Phase 2 call sites, one by one
|
||||
|
||||
The predicate each site wants is *not* always "the token containing this
|
||||
offset", so `Document::token_at` is not a drop-in for any of them. Each swap
|
||||
below is argued from the ordering property, and each argument is pinned by a
|
||||
test that compares the new expression against the old one at every byte of
|
||||
`state::mixed_buffer(20)` — a buffer written with `a=b;`-style adjacent
|
||||
punctuation, comments and strings precisely because the bytes that could tell
|
||||
a search from a sweep are the ones two tokens share.
|
||||
|
||||
**Changed and proven.**
|
||||
|
||||
| site | wanted | now | test |
|
||||
|---|---|---|---|
|
||||
| `selection.rs` `enclosing` | the first token with `start <= offset <= end` | `first_token_reaching`, then one `covers` check | `selection::tests::the_innermost_step_is_the_token_the_sweep_returned_at_every_offset` |
|
||||
| `on_type.rs` `statement_edit` | the token with `end == offset` | `first_token_reaching`, then one `==` | `on_type::tests::the_token_ending_at_the_cursor_is_the_one_the_sweep_returned` |
|
||||
| `on_type.rs` `first_on_line` | the first non-`Eof` token with `start >= content` | `first_token_from`, then `find` over the tail | `on_type::tests::the_first_token_on_a_line_is_the_one_the_sweep_returned` |
|
||||
| `completion.rs` `is_procedural` | the *index* of the token with `start == offset` | `first_token_from`, then one `==` | `completion::tests::the_scope_gates_answer_what_their_sweeps_answered` |
|
||||
| `completion.rs` `balanced` | every token whose start is in `[from, at)` | a slice between two `first_token_from`s | the same test |
|
||||
| `inline.rs` `triggered` | the **last** non-`Eof` token with `end <= offset` | `partition_point`, then `rposition` over the prefix | `inline::tests::the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found` |
|
||||
|
||||
Two of these deserve their reasoning spelled out, because they are the two
|
||||
where a careless swap would have changed an answer:
|
||||
|
||||
- **`selection.rs` takes `span.end` inclusively.** At a byte two adjacent
|
||||
tokens share, `find(covers)` returned the *earlier* of the two, while
|
||||
`Document::token_at` — which uses `TextRange::contains`, end exclusive —
|
||||
would return the later one. `first_token_reaching` returns the earlier one,
|
||||
which is why it is the right primitive here and `token_at` is not.
|
||||
- **`completion.rs`'s `balanced` was sweeping the whole buffer.** Its filter
|
||||
had no upper bound to break on, so a cursor anywhere in a 10 000-line file
|
||||
walked all 94 961 tokens to reach a window a few dozen tokens wide. It is
|
||||
the largest of the six by some way: 130 µs → 36 ns.
|
||||
|
||||
**Left alone, with the reason.**
|
||||
|
||||
- **`signature.rs` `enclosing_list` (:138) and `active_entry` (:231).**
|
||||
Inherent. Both maintain a parenthesis-depth stack, and a depth at the
|
||||
cursor is a function of *every* bracket before it — there is no prefix a
|
||||
binary search may skip without recomputing what it skipped. Both already
|
||||
break at the cursor rather than running to the end of the buffer, so
|
||||
neither is a whole-buffer sweep; bounding the loop with a binary search
|
||||
instead of the `break` would save one comparison per token and change
|
||||
nothing else, which is not worth the edit.
|
||||
- **`pairs.rs` `analyze` (:230).** Inherent, and not a position query at
|
||||
all: it matches *every* scope keyword in the stream and returns the whole
|
||||
pair set. There is no offset to search for.
|
||||
- **`completion.rs` `in_comment_or_string` (:553).** Left, and its existing
|
||||
doc comment already says why: comments are lexer trivia hanging off
|
||||
whichever token happens to follow or precede them, so the token whose
|
||||
`leading` holds a comment at a given byte is not the token a search for
|
||||
that byte would find. A correct search would have to reason about
|
||||
attachment; a wrong one would offer a completion list inside a comment.
|
||||
This is the one remaining per-keystroke whole-buffer walk, and it is
|
||||
recorded as such in `docs/perf/README.md` rather than guessed at.
|
||||
- **`completion.rs` `word_tier` (:355), `candidates.rs` (:218),
|
||||
`folding.rs` (:58).** Inherent: each needs every token in the file, not a
|
||||
token at an offset.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev (round 2).**
|
||||
|
||||
*Phase 1, measured first.* Added
|
||||
`perf::breaking_down_one_flushed_keystroke` and
|
||||
`perf::finding_one_token_against_sweeping_the_stream` to the existing
|
||||
`perf.rs` module, and `a_keystroke_round_trip_over_the_wire` to `e2e.rs`.
|
||||
The e2e measurement reuses the `Live` session helper that already existed in
|
||||
that file for the watched-files test rather than adding a second one; the
|
||||
only change to shared code is that `Live::finish` now returns the number of
|
||||
`publishDiagnostics` it saw while shutting down. That count is the point: a
|
||||
buffer left dirty by a burst is flushed before the next *request* is
|
||||
answered, so by the time `shutdown` comes back every publish the burst was
|
||||
going to produce has arrived. A burst of ten keystrokes produces **one**.
|
||||
|
||||
The breakdown decided everything that followed. At 10 000 lines a flush is
|
||||
31 ms, and 24.5 ms of it is `tokenize` plus `parse_tolerant`. `analyze` is
|
||||
11 %, the diagnostics pass another 4 % on top of the flush, and
|
||||
`resolve_external` — which the round's brief named as a possible target — is
|
||||
**49 µs, one part in six hundred**. There is nothing to skip there.
|
||||
|
||||
*Phase 2.* Six sweeps became binary searches, on the strength of the
|
||||
`finding_one_token` measurement: 77 µs → 20 ns for a cursor lookup at 10 000
|
||||
lines, and 130 µs → 36 ns for `balanced`'s window. The two primitives live in
|
||||
`state.rs` beside `Document::token_at`, which is where the one-paragraph
|
||||
monotonicity argument they all rest on is written; `inline.rs`'s third
|
||||
predicate is written at its own call site because it has one user.
|
||||
|
||||
Every swap is pinned by a test that compares it against the code it replaced
|
||||
at every byte of a shared awkward buffer (`state::mixed_buffer`, whose one
|
||||
job is to have plenty of tokens that touch). Two of the six are *not* what
|
||||
`Document::token_at` would have answered, and the table above says which and
|
||||
why; a seventh candidate, `completion.rs`'s comment gate, was left alone
|
||||
because no search of the token stream answers the question it asks.
|
||||
|
||||
*Phase 3 — nothing, on purpose.* The breakdown does not justify a change:
|
||||
|
||||
- Lex and parse are 79 % of a flush. Making them incremental is the only
|
||||
lever left, and it is a large change under `CLAUDE.md`'s hard invariants 1
|
||||
and 2. Written up in `docs/perf/README.md` with the number that would pay
|
||||
for it; not attempted.
|
||||
- `tokens.clone()` is 2.40 ms, 7.7 % of a flush, and is **load-bearing**:
|
||||
`parse_tolerant` takes its token vector by value and steals the comments
|
||||
out of it (`std::mem::take(&mut self.tokens[pos].leading)`,
|
||||
`self.tokens[pos].trailing.take()`), so `Document.tokens` cannot be the
|
||||
same vector — folding, the on-type comment test and completion's comment
|
||||
gate all read that trivia. The clone is also already a win: before the
|
||||
one-lex change it was a second `tokenize`, which this round measures at
|
||||
12.5 ms. Removing it needs a cheaply-clonable `Token`, which is a
|
||||
`vlog_parser` type change reaching the formatter. Written up, not
|
||||
attempted.
|
||||
- The lint pass walks the tree once per rule (`vlog_linter::lint`'s
|
||||
`for rule in enabled`), but it is 1.40 ms against a 32 ms flush. Fusing the
|
||||
walks is a `vlog_linter` refactor for 4 %. Written up, not attempted.
|
||||
- `resolve_external` is 49 µs. Skipping it when the index generation has not
|
||||
moved would save one part in six hundred of a flush and add a cache
|
||||
invalidation rule to a path that currently has none. Not attempted, and
|
||||
the number is the reason.
|
||||
|
||||
*The finding worth acting on is not a code change.* Over the wire, a lone
|
||||
keystroke's round trip is 156 ms at 1 000 lines — of which 150 ms is the
|
||||
change debounce's own quiet period, and 4.8 ms is the work. The same
|
||||
keystroke followed by a request, which is what a real editor sends, is
|
||||
**4.8 ms at 1 000 lines and 37 ms at 10 000**. So for the editors that ask
|
||||
for anything after a change (VS Code asks for semantic tokens, inlay hints
|
||||
and highlights), the debounce timer never runs and the flush is the whole
|
||||
cost; for a client that asks for nothing, the felt latency is the timer.
|
||||
`CHANGE_DEBOUNCE` is a product decision the previous round made deliberately
|
||||
at 150 ms, so it was not touched — but it is now a measured number rather
|
||||
than an assumed one, and `docs/perf/README.md` says so.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** Verdict: **SHIP WITH FIXES noted, none applied** — one
|
||||
methodology finding on the e2e measurement (not shipped code a user can hit),
|
||||
one informational note verified harmless. Everything else attacked and held.
|
||||
|
||||
Gates, verbatim:
|
||||
|
||||
- `cargo fmt --check` — clean, no output.
|
||||
- `cargo clippy --all-targets --workspace -- -D warnings` — clean, no
|
||||
warnings.
|
||||
- `cargo test --workspace` — every crate green: lucisv_server's unit binary
|
||||
1192 passed / 21 ignored, its `e2e` integration binary 55 passed / 1
|
||||
ignored (the perf test, run separately below), every other crate green
|
||||
too. No `FAILED`, no `error[`.
|
||||
- `cargo test -p vlog_formatter` — 31 + 1 + 4 + 6 + 2 + 22 + 114 + 0 passed
|
||||
across its binaries, 0 failed.
|
||||
- `cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1`
|
||||
— 12 passed. Numbers reproduced within the noise the README itself budgets
|
||||
(see below).
|
||||
- `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
|
||||
— 1 passed: `1000 lines: one change alone 161.9ms, a burst of ten 160.4ms
|
||||
for 1 publish(es), one change a request follows 4.7ms` /
|
||||
`10000 lines: one change alone 205.7ms, a burst of ten 199.0ms for 1
|
||||
publish(es), one change a request follows 38.5ms` — matches
|
||||
`docs/perf/README.md`'s 156/205/157/205/1/4.76/37.4 within reason.
|
||||
|
||||
**Attack angle 1 (identity claims).** All six call sites re-derived from the
|
||||
source and checked against their sweep predicates by hand (`selection.rs`
|
||||
`enclosing`, `on_type.rs` `statement_edit` and `first_on_line`,
|
||||
`completion.rs` `is_procedural` and `balanced`, `inline.rs` `triggered`).
|
||||
Every one of the existing per-site tests already walks **every byte** of
|
||||
`mixed_buffer(20)` (not just a handful of offsets), so the exhaustive-diff
|
||||
form the brief asked for is already what shipped, not something to widen.
|
||||
Checked by hand and confirmed safe at the edges the brief named: offset 0,
|
||||
the last byte, the `Eof` sentinel, an empty file, a file that fails to lex
|
||||
(empty `tokens`), and a large-file fast-path document — `on_type.rs`'s own
|
||||
`OnTypeFormatting::METHOD` arm in `server.rs:832` answers the empty edit list
|
||||
before `level_at`/`first_on_line` ever run on a large doc; `completion.rs`'s
|
||||
`completions` guards `doc.tokens.is_empty()` at `completion.rs:154` before
|
||||
`is_procedural`/`balanced` are reachable; `inline.rs`'s `inline_completions`
|
||||
guards the same at `inline.rs:237`; `selection.rs`'s `enclosing` and the two
|
||||
`first_token_*` primitives themselves degrade safely on an empty slice
|
||||
(`partition_point` on `&[]` is `0`, `.get(0)` on an empty `Vec` is `None`).
|
||||
`selection.rs`'s inclusive-`covers`/exclusive-`token_at` distinction is real
|
||||
and correctly *not* used — traced through `first_token_reaching` +
|
||||
`covers` by hand at a shared boundary byte and it does return the earlier of
|
||||
two touching tokens, matching the sweep it replaced.
|
||||
|
||||
**Attack angle 2 (the precondition).** `state::tests::the_token_stream_rises_and_never_overlaps`
|
||||
exercises exactly one hand-written buffer
|
||||
(`mixed_buffer(20)`), which is narrow on its own — no macros, no directives,
|
||||
no unterminated constructs. Delegated to a sub-agent to read
|
||||
`vlog_parser`'s lexer directly rather than trust the docstring's claim.
|
||||
Finding: `vlog_parser`'s own `tests/spans.rs::assert_covers_source` already
|
||||
asserts the same invariant (non-overlap, source order, full byte coverage,
|
||||
comments included) over 40+ deliberately adversarial fixtures — macros,
|
||||
`` `ifdef``/`` `include`` interleaving, attributes, CRLF, BOM, multi-byte
|
||||
UTF-8 in strings and comments — and `tests/error_recovery.rs` fuzzes every
|
||||
byte-prefix and every single-byte deletion of a corpus without panicking.
|
||||
Every lexer error path (`skip_string`, `skip_block_comment`, the attribute
|
||||
scanner) returns `Err` rather than a partial, possibly-violating `Vec<Token>`,
|
||||
and `TextRange::new` clamps `end` to `max(start)` structurally. No plausible
|
||||
gap found: the one narrow test in `state.rs` is sufficient because it rests
|
||||
on an invariant `vlog_parser` proves far more thoroughly one layer down, and
|
||||
the docs correctly point there rather than re-arguing it.
|
||||
|
||||
**Attack angle 3 (the e2e measurement's methodology) — one finding.**
|
||||
|
||||
- **IL-1 (medium) — the burst's "1 publish(es)" figure is not the robust,
|
||||
order-independent count the code and the docs describe.**
|
||||
`crates/lucisv_server/tests/e2e.rs:4696-4727`. `published` is computed as
|
||||
`1 + live.finish()` (line 4727): the `1` is an unstated assumption that the
|
||||
lone `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
|
||||
right after the burst (line 4704) consumed *exactly* the burst's own
|
||||
publish and nothing else, and `live.finish()`'s count only starts
|
||||
accumulating after the "one change a request follows" loop ten lines later
|
||||
(4714-4725) has already run — ten more iterations, each with its own
|
||||
generic `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
|
||||
(line 4722) that accepts *any* publish, not specifically the one its own
|
||||
request just triggered. A stray or duplicate publish arriving from the
|
||||
burst in that window would be silently absorbed by one of those ten waits
|
||||
and never increment `published` or surface anywhere in the printed line.
|
||||
The doc comment above the burst (line 4696-4699: "the count below is that
|
||||
claim measured rather than reasoned about: any publish still to come
|
||||
arrives before `shutdown` does") is true of `live.finish()`'s own drain —
|
||||
nothing gets past *that* point unnoticed — but it is not true of the
|
||||
window between the burst and the drain, which is exactly where a second
|
||||
publish would have to be counted to falsify "exactly one". As written, the
|
||||
test would print "1" whether the burst produced one publish or secretly
|
||||
produced two, which is indistinguishable from the claim it's supposed to
|
||||
be checking. In practice the debounce is understood to always coalesce to
|
||||
one flush, so this is a soundness gap in the *measurement*, not evidence
|
||||
of a real double-publish — but it means the "counted rather than reasoned
|
||||
about" claim is itself partly reasoned about. Not fixed: closing it cleanly
|
||||
means either running the burst as its own `Live` session finished
|
||||
immediately after (so nothing else can absorb a stray), or having
|
||||
`wait_for` tally every `publishDiagnostics` it ever passes over for the
|
||||
life of the session — both are design choices for the dev, not a
|
||||
QA drive-by edit.
|
||||
- Everything else in this angle held. `Live::finish`'s drain (`e2e.rs:2231`)
|
||||
really does read to `shutdown`'s response before returning, so nothing
|
||||
published after the last explicit `wait_for` in a test is lost *at that
|
||||
point* — it is specifically the mid-test absorption above that is the gap.
|
||||
The 150 ms figure in the lone-keystroke row is the timer and not a stall:
|
||||
reproduced at 161.9 ms / 205.7 ms against a documented 150 ms
|
||||
`CHANGE_DEBOUNCE` plus a single flush (2.6 ms / 31.2 ms measured
|
||||
separately), which accounts for the total without residue.
|
||||
|
||||
**Attack angle 4 (duplication) — one informational note, verified harmless.**
|
||||
`perf::generated_module` (`crates/lucisv_server/src/perf.rs:42-57`) and its
|
||||
copy in `crates/lucisv_server/tests/e2e.rs:4634-4649` are not byte-identical:
|
||||
the `e2e.rs` copy appends ` // typing\n` before `endmodule` that the
|
||||
original does not have, so the test has a stable, comment-only line to land
|
||||
keystrokes on. The doc comment on the copy ("The two must stay the same
|
||||
shape, or the two tables ... stop being readable against one another")
|
||||
slightly overstates it — they differ by one line. Verified harmless: a
|
||||
comment is lexer trivia and is never its own token, so `tokens.len()` is
|
||||
identical between the two generators at the same `lines`, and the added ~12
|
||||
bytes is noise against 29 KB / 309 KB files. The two perf tables do stay
|
||||
readable against one another; no fix needed.
|
||||
|
||||
**Attack angle 5 (perf honesty).** Every figure in `docs/perf/README.md`'s
|
||||
round-2 tables reproduced within the noise the document itself budgets for,
|
||||
on a fresh `--release` run (see gates above for the two exact commands and
|
||||
their output). Spot check on "the breakdown sums to `Document::new`'s
|
||||
31.1 ms" — a claim the brief asked about but which, checked directly, is
|
||||
**not actually written anywhere in either README**; nowhere does the text
|
||||
assert the eight-stage breakdown sums to the `Document::new` figure. As a
|
||||
sanity check anyway: summing this run's own breakdown stages inside
|
||||
`Document::new` (tokenize 12.512 + parse_tolerant-with-clone 14.149 +
|
||||
collect_defines 0.115 + analyze 3.174 + resolve_external 0.012 +
|
||||
`LineIndex::new` 0.105 ≈ 30.07 ms) against the dedicated `Document::new`
|
||||
figure from the same run (31.22 ms) leaves about 1.15 ms — 3.7% —
|
||||
unaccounted for, which is consistent with the README's own caveat that the
|
||||
breakdown "runs eight measurements back to back on one heap" and should be
|
||||
read as *shares*, not as a sum that has to close exactly. No finding, since
|
||||
no stronger claim than that is actually made.
|
||||
|
||||
**Attack angle 6 (regression sweep).** `cargo test --workspace` exercises
|
||||
every one of the four handlers' existing suites unchanged and green
|
||||
(selection.rs, on_type.rs, completion.rs, inline.rs — see gates above).
|
||||
Adversarial shapes the brief named are already covered by name in the
|
||||
existing suites and were spot-read to confirm they exercise the *changed*
|
||||
code paths and not just the surrounding handler: `on_type.rs`
|
||||
`a_semicolon_the_lexer_never_saw_ends_no_statement`,
|
||||
`a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`,
|
||||
`a_crlf_line_ending_is_never_touched_by_the_edit`; `completion.rs`
|
||||
`a_buffer_that_does_not_lex_is_declined`; `inline.rs`
|
||||
`a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at`,
|
||||
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost`,
|
||||
`crlf_line_endings_still_trigger`; `selection.rs`
|
||||
`a_file_that_does_not_lex_still_answers_the_file_range`,
|
||||
`an_empty_file_still_answers_one_degenerate_chain`.
|
||||
|
||||
**PDS-1..4 and CD-1, spot-checked in code rather than trusted from the
|
||||
README.** `hover.rs:361` (`only_a_closer_on`) and `:373` (`is_closer_word`)
|
||||
exist and `another_port_on`/`is_port_grammar_word` are gone — PDS-1 real.
|
||||
`hover.rs:292-295` strips a trailing `\r` in the one line reader all three
|
||||
`attached_lines` collections pass through — PDS-4 real. `server.rs:1247-1262`
|
||||
(`notification`): the `dirty.retain` for `DidCloseTextDocument::METHOD` sits
|
||||
*above* the `if method != DidChangeTextDocument::METHOD { self.flush_dirty() }`
|
||||
call, guarded on the method name via a borrowed, cloned `closing_uri`
|
||||
(`server.rs:2214`, reads `params` without consuming the notification) — CD-1
|
||||
genuinely closed, not dead code any more. PDS-2/PDS-3 not independently
|
||||
re-derived (no code-shape claim to check beyond what PDS-1/PDS-4 already
|
||||
verify the same file's discipline on); taken on the strength of the named
|
||||
tests, which are present and green.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted, with one methodology fix applied by me
|
||||
(below). Gates re-run independently: fmt clean, clippy silent, workspace
|
||||
tests green, formatter snapshot + idempotency suite green, the twelve `perf::`
|
||||
measurements and the wire measurement both reproduce.
|
||||
|
||||
This round did the thing that makes a performance round worth anything: it
|
||||
measured first and then declined to optimise three of the four things it had
|
||||
been pointed at, with a number for each refusal. `resolve_external` at 49 µs
|
||||
of a 31 ms flush disproved the brief's own hypothesis, and saying so is a
|
||||
better outcome than a speculative cache on a path that has no invalidation
|
||||
rule today. Lex and parse at 79 % is the real answer, and leaving incremental
|
||||
parsing to a planned round rather than starting it opportunistically is
|
||||
right — that work lands directly on hard invariants 1 and 2 and is not
|
||||
something to attempt as the tail of a perf sweep.
|
||||
|
||||
The Phase 2 swaps are the part I looked at hardest, because six "obviously
|
||||
identical" rewrites is exactly where a silent behaviour change hides. The
|
||||
dev found the one that was *not* identical: `selection.rs`'s `covers` treats
|
||||
`span.end` inclusively, so at a byte two tokens share, the sweep returned the
|
||||
earlier token and `Document::token_at` would have returned the later one.
|
||||
Building `first_token_reaching` instead of reaching for the existing helper
|
||||
is the correct instinct, and differential-testing each new expression against
|
||||
the predicate it replaced at every byte of a purpose-built buffer is the
|
||||
right proof. Three call sites were left alone with reasons — signature help's
|
||||
paren depth is inherently a prefix scan, `pairs.rs` is not a position query,
|
||||
and completion's comment gate cannot be answered by any search of the token
|
||||
stream because comments are trivia. Recording the last of those as the
|
||||
remaining per-keystroke whole-buffer walk is more useful than a forced fix.
|
||||
|
||||
**Fix applied at review.** QA's IL-1 was right and I closed it directly
|
||||
rather than spending another round: the burst-of-ten publish count was
|
||||
`1 + finish()`, but the ten-iteration request loop sat between the burst and
|
||||
the drain, and each of its `wait_for`s accepts *any* publish — so a second
|
||||
publish the burst had produced would have been absorbed there and the figure
|
||||
would still have read "1". The burst now runs last, immediately before the
|
||||
drain, with the keystroke versions renumbered to stay monotonic. Re-measured
|
||||
after the change: still exactly one publish at both sizes, and the row is now
|
||||
counted rather than assumed. IL-2's overstated doc comment is corrected in
|
||||
place — the two `generated_module` copies differ by one trivia line, which is
|
||||
not a token and does not move a number.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,6 +12,26 @@ loop, document state, position arithmetic, and one small handler per
|
||||
capability. It deliberately contains no analysis of its own; anything that
|
||||
looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
|
||||
## Starting it: the argument contract
|
||||
|
||||
`lucisv-server` needs **no arguments** — that is the spawn every editor uses,
|
||||
the one `editors/vscode/smoke.js` drives, and it is unchanged. Since
|
||||
2026-08-29 it also *accepts* exactly one:
|
||||
|
||||
| argument | effect |
|
||||
|---|---|
|
||||
| *(none)* | The shipped server. Silent unless something is worth saying. |
|
||||
| `--verbose` | Every operation says how long it took, as `timing:` lines in the client's log channel (`window/logMessage`, `MessageType::LOG`). Repeats are idempotent. See `docs/features/verbose-timing/README.md` |
|
||||
| `--stdio` | Accepted and changes nothing: stdio is the only transport this server has. It is here because `vscode-languageclient` appends it for `TransportKind.stdio` — the spawn every real VS Code session makes — and rejecting it crashed the extension the moment strict parsing shipped (lead hotfix, 2026-08-29). The smoke and restart harnesses spawn the binary directly, which is why nothing in the loop caught it; `smoke.js` now spawns with `--stdio` so the library's real spawn shape stays covered. |
|
||||
| anything else | `error: unknown option: <arg>` and `usage: lucisv-server [--verbose] [--stdio]` on **stderr**, exit **2** — the CLI's own wording and its "an error occurred" code. Nothing is started |
|
||||
|
||||
There is no `-v`, no `--help` and no `--version`: one spelling for the one
|
||||
flag, and the version number lives on the `lucisv` CLI, which is where
|
||||
`tools/release.sh` reads it. Anything that is not a startup decision is an
|
||||
`lucisv.*` setting instead, pushed or pulled over the protocol — a flag can
|
||||
only be changed by spawning again, which is why `lucisv.verbose` is the one
|
||||
VS Code setting that restarts the server.
|
||||
|
||||
## Capabilities as shipped
|
||||
|
||||
| LSP request | Engine it consumes | Notes |
|
||||
@@ -21,19 +41,19 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` |
|
||||
| `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` |
|
||||
| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didSave` once per notification, and for a `didChange` once per **flush** (a typing burst publishes once, not once per keystroke — `docs/features/change-debounce/README.md`) — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, and the composed text is held **dirty** — one `set_document` + one `publish` per *flush*, which is the next request, the next other notification, or a 150 ms quiet period. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` and `docs/features/change-debounce/README.md` |
|
||||
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
|
||||
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it |
|
||||
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md` |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` |
|
||||
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built |
|
||||
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md`. The `file:line` half of a cross-file heading costs **no file access**: the line is recorded when the file is indexed (`Def::lines`), so only the snippet still reads, once per file per generation of it through `Workspace::file_view`: `docs/features/hover-line-index/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
|
||||
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
|
||||
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
|
||||
| `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` |
|
||||
| `textDocument/references` | `WorkspaceIndex::references_to`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port). Saved uses are declaration-to-occurrence postings built with the project index; open buffers overlay live semantics. No request-time project scan; returned spans are converted per touched file in one batch. See `docs/features/references-nav/README.md` |
|
||||
| `textDocument/documentHighlight` | `pairs::analyze`, else `Semantics::references_of` | A scope keyword highlights its own closer; anything else highlights the symbol's occurrences in this file. Kind is always `Text`; neither answer means `null`, so the editor keeps its word highlighting. Same feature README |
|
||||
| `textDocument/foldingRange` | `pairs::analyze` + comment trivia | One `Region` per matched scope pair, folded through the line *before* the closer so `end`/`endmodule` stays visible, plus one `Comment` per multi-line block comment. An unmatched opener folds nothing. Same feature README |
|
||||
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
|
||||
@@ -43,12 +63,12 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README |
|
||||
| `textDocument/inlayHint` | `vlog_refactor::instantiation_plan` | Ghost port names on an **ordered** connection list (`u1 (clk, rst_n)`) and parameter names on ordered `#( ... )` overrides, read from the instantiated module's declaration. Range-scoped; named lists, `.*`, omitted positions, connections past the last port, gate primitives and modules the index cannot resolve get nothing at all — a hint is decoration and never guesses. No `resolveProvider`. See `docs/features/inlay-hints/README.md` |
|
||||
| `textDocument/prepareCallHierarchy` | `instantiations::{sites,declarations}`, `WorkspaceIndex::units` | The module under the cursor as a hierarchy node (`SymbolKind::Module`), from its own declaration or from any instantiation of it. Every other position answers `null`; an ambiguous name returns every declaration, as `definition` does. See `docs/features/hierarchy/README.md` |
|
||||
| `callHierarchy/incomingCalls` | `instantiations::sites` over `Workspace::sources` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. Walks the in-scope files — the index holds no instantiation edges — skipping any file whose text does not contain the name (56 ms over the 860-file corpus). Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README |
|
||||
| `callHierarchy/incomingCalls` | `WorkspaceIndex::instantiations_of` | "Who instantiates X": one call per **instantiating module**, `fromRanges` naming every site inside it. A **lookup in the index's instantiation-edge table** since 2026-08-27 (it walked every in-scope file before, 56 ms over the 860-file corpus); only the files that really do instantiate the name are read, to turn recorded spans into ranges. The census is as of the index — its last build or update, both of which fold every open buffer in. Since 2026-08-26 this is `hierarchy::callers_of_each` with a one-name batch; the batched form is what `textDocument/codeLens` counts from, so there is exactly one census. Same feature README |
|
||||
| `callHierarchy/outgoingCalls` | `instantiations::sites`, `WorkspaceIndex::units` | "What X instantiates": one call per **distinct instantiated module**, `fromRanges` naming its sites. A target the index does not hold, or holds twice, is skipped silently. Same feature README |
|
||||
| `textDocument/prepareTypeHierarchy` | the class walk over `Document.tree`, then `ExternalResolutions::definition_of` | The **class** under the cursor as a type hierarchy node (`SymbolKind::Class`), from its own declaration or from any use of its name (an `extends` base, a property's type, a method local's type). Every other position answers `null`; a name two files declare returns both, as `definition` does. Advertised by hand — `lsp-types` 0.97's `ServerCapabilities` has no `typeHierarchyProvider` field. See `docs/features/type-hierarchy/README.md` |
|
||||
| `typeHierarchy/supertypes` | `ClassDecl::extends` + `ExternalResolutions::definition_of` | "What X extends": its base class, resolved by the same two layers F12 uses — in-file first, then the workspace overlay — asked at the **last byte** of the extends name, which is the tail of `pkg::base` and the whole of a bare `base`. A parameterized base resolves by its bare name; a base the workspace does not index (every UVM chain top) yields **no** item rather than a guess. Same feature README |
|
||||
| `typeHierarchy/subtypes` | the class walk over `Workspace::sources` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. Walks the in-scope files — the index holds no inheritance edges — skipping any file whose text does not contain the name (55 ms over the 860-file corpus, 53 ms of it file I/O). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README |
|
||||
| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same walk asked about every module in the file at once, so the two can never disagree. `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` |
|
||||
| `typeHierarchy/subtypes` | `WorkspaceIndex::subclasses_of` | "Who extends X": every class in scope whose `extends` names it, sorted by file then position. A **lookup in the index's inheritance-edge table** since 2026-08-27 (it walked every in-scope file before, 55 ms over the corpus; 0.71 ms now). A **qualified** base is not matched by a bare name, the `callHierarchy` precedent; 0 of the corpus's 270 `extends` clauses are qualified. Same feature README |
|
||||
| `textDocument/codeLens` | `instantiations::declarations` + `hierarchy::callers_of_each` | **"N instantiations"** above every module and interface declaration in the buffer, on the declaration's own name span. N is the number of instantiation *sites* across the workspace — the same population `callHierarchy/incomingCalls` reports, from the same edge table asked about every module in the file at once, so the two can never disagree (92 ms → 0.26 ms for a three-module file, 2026-08-27). `resolveProvider: false`: every lens is complete. Clicking runs `lucisv.showInstantiations`; a module with **no** instantiations gets a display-only lens (empty `command`) instead of a click that leads nowhere. Unopened buffer → `null`; a declaration with no name span gets no lens. See `docs/features/code-lens/README.md` |
|
||||
| `workspace/executeCommand` → `lucisv.showInstantiations` | `hierarchy::callers_of_each` | The code lens's own jump: `["module-name"]` in, every site as a `Location` out — one per site, file-then-position order. For a client that advertised `window.showDocument`, the server also pushes a `window/showDocument` for the **first** site, which is what makes the click navigate; LSP has no server-initiated peek-references, and this repo's extension declares no client-side command. A name with no sites answers `[]`; a missing or empty name is `RequestFailed`. Same feature README |
|
||||
| `workspace/codeLens/refresh` | — | Server-**initiated**, once per workspace rescan, straight after the indexing bar comes down: a rescan can change any count on screen. Only for a client that advertised `workspace.codeLens.refreshSupport`; never at startup, where no buffer holds lenses. Same feature README |
|
||||
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
|
||||
@@ -233,21 +253,110 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`.
|
||||
|
||||
| layer | rebuilt when | cost |
|
||||
|---|---|---|
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
|
||||
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist` (pushed **or** pulled) | full re-scan of the roots |
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`, and every **flush** of the buffers a `didChange` left dirty — once per flush, however many ranges *and* however many notifications it coalesced (`docs/features/change-debounce/README.md`) | one file, full recompute — 2.6 ms at 1 000 lines, 31 ms at 10 000 (`docs/perf/README.md`) |
|
||||
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) |
|
||||
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
|
||||
| the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) |
|
||||
|
||||
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
|
||||
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
|
||||
deferred there. Incremental *sync* did not change that: the wire now carries
|
||||
ranges, but a `didChange` still throws the whole `Document` away and builds a
|
||||
new one — one reparse per notification, which is also the one generation bump
|
||||
the pull-diagnostics `resultId` depends on.
|
||||
**Per-file recompute** is the strategy TODO.md §6 states ("per-file recompute
|
||||
is fine at Verilog file sizes"); salsa is explicitly deferred there.
|
||||
Incremental *sync* did not change that: the wire carries ranges, but a flush
|
||||
still throws the whole `Document` away and builds a new one. What changed on
|
||||
2026-08-28 is *how often*: a `didChange` no longer triggers that recompute
|
||||
itself, so a typing burst costs one reparse and one generation bump — still
|
||||
exactly one of each per flush, which is what the pull-diagnostics `resultId`
|
||||
depends on (`docs/features/change-debounce/README.md`).
|
||||
|
||||
**Open buffers override disk** in every index rebuild: the roots are walked,
|
||||
**Which files exist: the folder scope, since 2026-08-27** (index-scope). The
|
||||
index no longer walks the whole workspace by default. The ladder, highest
|
||||
first: a **filelist** defines the scope exactly, as it always has; else
|
||||
`lucisv.index.scope: "workspace"` walks every workspace folder, which is what
|
||||
every session did before this round and is now opt-in; else — the default —
|
||||
the scope is **the folders the open buffers live in**, each raised
|
||||
`lucisv.index.scopeDepth` levels (0 by default, clamped so it never climbs out
|
||||
of the workspace folder containing it) and walked with every filter the wide
|
||||
walk applies. Opening a file in a folder the scope does not cover **widens the
|
||||
scope and rebuilds**, on the same bar and the same generation bump every other
|
||||
rescan gets; closing one narrows nothing, ever. The startup index is therefore
|
||||
empty until the first `didOpen`, which is the whole saving on a large project.
|
||||
|
||||
**Stated plainly, because it is what a user notices:** every cross-file answer
|
||||
in the table above is **scope-relative**. A definition, a `workspace/symbol`
|
||||
hit, an `incomingCalls` census, a `subtypes` list, a references lookup or
|
||||
a workspace rename covers the files in scope and no others — a symbol in a
|
||||
folder the scope has not reached does not exist as far as this server is
|
||||
concerned, exactly as one outside a filelist never did. Opening a file in that
|
||||
folder brings it into scope. `"lucisv.index.scope": "workspace"` restores the
|
||||
pre-2026-08-27 behaviour in full. Rules, the clamp, the close decision and the
|
||||
one `.gitignore` gap: `docs/features/index-scope/README.md`.
|
||||
|
||||
**And scope-relative in *time*, since 2026-08-28** (scan-interleave). A
|
||||
**startup** scan of more than 64 files no longer blocks the message loop: it
|
||||
indexes one file at a time and answers whatever the client has already sent
|
||||
between two of them, so the first request of a session comes back in
|
||||
milliseconds instead of waiting out the whole scan (780 ms → 15.5 ms cold over
|
||||
200 files). The price is that such an answer reflects the index **as of that
|
||||
moment** — a declaration in a file the scan has not reached yet does not exist
|
||||
yet, in exactly the sense a declaration outside the scope does not exist. Two
|
||||
narrowings keep that from reaching anywhere it is not worth it: a scan of 64
|
||||
files or fewer runs one shot as it always did, and a request queued *behind* a
|
||||
message that asked for a rescan waits for that rescan, so the loop's order
|
||||
contract is unchanged. `docs/features/scan-interleave/README.md`.
|
||||
|
||||
**Open buffers override disk** in every index rebuild: the scope is walked,
|
||||
each file read, and then every open document with a path replaces the disk
|
||||
copy (adding itself if it exists only in the editor). So the index never
|
||||
disagrees with a buffer the user is looking at.
|
||||
disagrees with a buffer the user is looking at. The open buffers' own files are
|
||||
also fed to the index builder **first**, so a long rescan's progress bar
|
||||
completes them before anything else; the builder sorts by path internally, so
|
||||
that ordering cannot change the index it produces.
|
||||
|
||||
**What a scan learned survives the session, since 2026-08-27**
|
||||
(index-persistence). Every file a scan parses is written to a store — its
|
||||
`FileFacts`, the whole of its contribution to the index, under the FNV-1a hash
|
||||
of the bytes it was read from — and the next scan takes back every record
|
||||
whose file still holds exactly those bytes instead of parsing it again. So
|
||||
reopening a workspace, or reopening one whose first scan was interrupted, is a
|
||||
rescan that costs the reads and not the parses: **181 ms warm against the
|
||||
328 ms it cost cold** over the 860-file corpus in a release build, with the bar
|
||||
saying `860 files indexed, 860 from cache` and the output log saying `cached:`
|
||||
where it says `indexing:`. The store lives in
|
||||
`initializationOptions.storagePath` (VS Code's per-workspace storage folder),
|
||||
or wherever `lucisv.index.cachePath` says, or in this platform's cache
|
||||
directory; `lucisv.index.persist: false` turns it off in both directions and
|
||||
restores the pre-2026-08-27 behaviour exactly. **It is a performance artifact
|
||||
and never a correctness input**: every record is verified against the file's
|
||||
current content before it is used, and a stale, corrupt or foreign record
|
||||
costs one parse and can change no answer. Rules, the record format and the
|
||||
crash-safety argument: `docs/features/index-persistence/README.md`.
|
||||
|
||||
**A buffer over `lucisv.largeFile.threshold` (4 MiB by default) is never
|
||||
analyzed at all, since 2026-08-27** (large-file-mode). `Workspace::set_document`
|
||||
— the one place a `Document` is built — puts it on a fast path that indexes its
|
||||
*lines* and stops: no lex, no parse, no semantics, no diagnostics, no index
|
||||
entry. 41 ms for 100 MB, against the 930 ms 10 MB costs through the full
|
||||
pipeline. Its `Document` holds the analysis of the **empty file**, so every
|
||||
handler that reads the analysis answers empty without knowing the mode exists;
|
||||
only the handlers that would read the **text** are gated, in one table in
|
||||
`Server::large_file_answer`. What still works is colour — `semanticTokens/range`
|
||||
lexes the requested window and nothing else — plus same-file `definition` and
|
||||
`references` by one linear scan. `semanticTokens/full` is answered with an
|
||||
*error*, which is the one shape that leaves VS Code's viewport provider
|
||||
painting. A file on the fast path leaves the workspace index entirely, which is
|
||||
the one exception to "an open buffer is never capped". The rules, the
|
||||
approximations, the dispatch table and the measurements:
|
||||
`docs/features/large-file-mode/README.md`.
|
||||
|
||||
**Walked files over `lucisv.index.maxFileSize` (1 MiB by default) are not read
|
||||
at all** — the size is taken from `fs::metadata` before the read, so a
|
||||
generated netlist costs one `stat` rather than minutes of parsing. The cap is
|
||||
on the *walk* only: an open buffer is folded in above, uncapped, because the
|
||||
user opened it deliberately. `0` disables the cap, and the skipped count is
|
||||
named in the progress bar's `end` message. Since the whole cap lives in
|
||||
`collect_sources`, `Workspace::sources()` sees it too, so a workspace rename
|
||||
does not rewrite a file the index does not hold. Rules, corpus numbers and the
|
||||
per-file `window/logMessage` that accompanies a rescan:
|
||||
`docs/features/indexing-ux/README.md`.
|
||||
|
||||
**The staleness window, stated plainly.** The index is rebuilt on save, not on
|
||||
change. Between editing file A and saving it, file B's cross-file answers
|
||||
@@ -257,19 +366,24 @@ which the override above keeps current. Rebuilding on every keystroke would
|
||||
re-parse the whole workspace per character; rebuilding on save is the cheapest
|
||||
point where the answer is expected to change anyway. Measured cost of a
|
||||
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
|
||||
plus the file reads.
|
||||
plus the file reads — **and about half that when the persistent index cache
|
||||
answers for the files that have not changed** (index-persistence, below).
|
||||
|
||||
**Every rescan is visible since 2026-08-26**, for a client that advertised
|
||||
`window.workDoneProgress`: the startup build and all three `reindex()` triggers
|
||||
are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
|
||||
**Every *whole* rescan is visible since 2026-08-26**, for a client that
|
||||
advertised `window.workDoneProgress`: the startup build and every whole
|
||||
`reindex()` trigger are wrapped in one `window/workDoneProgress/create` plus a `$/progress`
|
||||
begin/end pair on a fresh `lucisv-index-N` token, so a multi-second index on a
|
||||
big filelist reads as work rather than as a hang. The `begin` does not wait for
|
||||
the create's answer (the rescan blocks the loop immediately after), the answer
|
||||
is ignored on the same path the watcher registrations' is, there is no
|
||||
percentage and no intermediate report — the rescan is one opaque call — and the
|
||||
`end` names the indexed file count. A client that did not advertise the
|
||||
capability is sent nothing at all, which the spec requires. Rules and the
|
||||
startup-legality argument: `docs/features/work-done-progress/README.md`.
|
||||
capability is sent nothing at all, which the spec requires. **A rescan that
|
||||
names exactly one file the index already holds puts no bar up** since
|
||||
2026-08-27: it is one parse, sub-perceptual, and a bar that appears and
|
||||
vanishes inside a frame is noise rather than progress
|
||||
(`docs/features/incremental-index/README.md`). Rules and the startup-legality
|
||||
argument: `docs/features/work-done-progress/README.md`.
|
||||
|
||||
**Changes made outside the editor close on the next notification, not on the
|
||||
next save** (M9, `docs/features/file-watching/README.md`). The server registers
|
||||
@@ -331,6 +445,15 @@ not see.
|
||||
drive-letter rule (`file:///C:/x` → `C:\x`) is written and compiled but
|
||||
**untested on Windows** — it is behind `cfg!(windows)` so it cannot misfire
|
||||
on a POSIX path legitimately named `/C:`.
|
||||
- ~~**The workspace walk is plain.** `initialize`'s `workspace_folders`
|
||||
(falling back to `root_uri`) are walked recursively.~~ **Superseded
|
||||
(index-scope, 2026-08-27): the folders are the *clamp* now, not the work
|
||||
list. What is walked by default is the folders the open buffers live in,
|
||||
raised `lucisv.index.scopeDepth` levels; `lucisv.index.scope: "workspace"`
|
||||
asks for the walk this paragraph describes. See the model section above and
|
||||
`docs/features/index-scope/README.md`.** The rest of the paragraph — the
|
||||
extensions, the `.gitignore` handling, the mid-session folder changes — is
|
||||
unchanged and still applies to whichever directories are walked.
|
||||
- **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling
|
||||
back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`.
|
||||
~~They are read once and frozen for the session.~~ **Superseded
|
||||
@@ -373,24 +496,27 @@ spans, and `defines::{collect_defines, Define, DefineTable}`.
|
||||
reference_at, references_of, document_symbols, symbol, symbols, references,
|
||||
reference_id_at, scope}`, `Symbol { name, kind, name_span, decl_span, scope,
|
||||
child_scope }`, `Scope::owner`, `SymbolKind`, `Resolution`, `DocumentSymbol`,
|
||||
and the workspace layer — `WorkspaceIndex::{build, path, units, member,
|
||||
find_define, workspace_symbols}`, `resolve_external`,
|
||||
and the workspace layer — `WorkspaceIndex::{build, path, file_id, units,
|
||||
member, find_define, references_to, references_are_ambiguous,
|
||||
workspace_symbols}`, `resolve_external`,
|
||||
`ExternalResolutions::{definition_of, get}`, `ExternalTarget::best`,
|
||||
`Definition`, `Def`.
|
||||
|
||||
**Consumed from `vlog_refactor`:** `prepare_rename`, `rename`,
|
||||
`instantiation_plan` and friends, the port refactorings, and — since
|
||||
references-nav (M7) — `find_references(files, file, offset,
|
||||
include_declaration) -> Result<Vec<(PathBuf, TextRange)>, String>`, which is
|
||||
the cross-file half of `textDocument/references`. Every one of them takes the
|
||||
same `Workspace::sources()` file set.
|
||||
`instantiation_plan` and friends, and the port refactorings. Rename consumes
|
||||
the `Workspace::sources()` file set. `find_references` remains available and
|
||||
is the equivalence oracle for the indexed references test, but is no longer
|
||||
called by the request handler.
|
||||
|
||||
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
|
||||
Result<String, FormatError>` and `Config { max_width, indent_width }`.
|
||||
|
||||
**Promised to nobody yet.** This crate is a leaf: it has no library target and
|
||||
nothing depends on it. The editor packaging round (TODO.md §6) will consume
|
||||
the binary's name and its stdio contract, nothing else.
|
||||
**Promised to the editors:** the binary's name, its stdio contract, and — since
|
||||
2026-08-29 — its *argument* contract: no arguments required, `--verbose` the
|
||||
only one accepted, every other one refused with exit 2 (the table under
|
||||
"Starting it" above; TOPO.md §1.2's `editors/vscode ◀──▶ lucisv_server` row;
|
||||
`docs/features/verbose-timing/README.md`). Beyond that this crate is a leaf: it
|
||||
has no library target and nothing in the workspace depends on it.
|
||||
|
||||
**Requested of other modules** — none of these block this round, and none was
|
||||
done here:
|
||||
@@ -500,14 +626,29 @@ overlap trap and the round-trip property:
|
||||
(`docs/features/include-nav/README.md`).
|
||||
2. **A reference** resolved in-file: the symbol's kind, its name, and the
|
||||
source lines its `decl_span` covers.
|
||||
3. **A reference** answered only by the workspace overlay: the kind and name,
|
||||
plus each target's file and line.
|
||||
3. **A reference** answered only by the workspace overlay: the kind, each
|
||||
target's file and line, and — since 2026-08-27 — **that declaration's own
|
||||
source line(s)** beneath each heading.
|
||||
4. **A declaration** the cursor is sitting on: its own kind, name and
|
||||
snippet.
|
||||
|
||||
The snippet is `decl_span` widened to whole lines, so a declaration reads as
|
||||
it was written rather than starting mid-line.
|
||||
|
||||
**The cross-file snippet (case 3).** The index holds no file contents, so the
|
||||
line is fetched per hover: from the **live buffer** when the target file is
|
||||
open — matched to the indexed `Def` logically through
|
||||
`nav::indexed_def_for_symbol`, because an unsaved edit above a declaration has
|
||||
already moved the span the index recorded — and from disk otherwise, where the
|
||||
recorded span is the one the index was built from. Either way the chosen text
|
||||
is sliced at the chosen name span and required to spell the hovered name; on
|
||||
any mismatch, unreadable file or unmatched buffer the snippet is dropped and
|
||||
the card is exactly what it was before this feature. It is capped at 5 lines
|
||||
and 400 characters (a module's `decl_span` is its whole body; a netlist line
|
||||
has no bound), with a footnote naming whichever cap cut it. Rules, the
|
||||
deliberate span asymmetry between the two paths, and the guard's attack tests:
|
||||
`docs/features/hover-declarations/README.md`.
|
||||
|
||||
**A macro card has a second half since M14 (0.5.0).** Under the definition it
|
||||
shows what the hovered *use* expands to in one step — the body with this call's
|
||||
arguments substituted for the parameters — fenced identically, with a footnote
|
||||
@@ -529,8 +670,10 @@ registered for exactly that language id, and that grammar is the *only* thing
|
||||
that colours a hover card: semantic tokens cannot reach markdown, and VS Code
|
||||
resolves a fence's info string against the language registry rather than
|
||||
against the hovered document. Changing the tag, or fencing a new surface with a
|
||||
different one, silently returns every card to flat grey. The three call sites
|
||||
pin the exact fenced string in their own tests; the registration is pinned by
|
||||
different one, silently returns every card to flat grey. Every call site —
|
||||
`define_text`, `expansion_text`, `local_text`, the cross-file `fenced` and the
|
||||
completion templates' documentation panel — pins the exact fenced string in its
|
||||
own tests; the registration is pinned by
|
||||
`crates/lucisv_server/tests/grammar.rs`, which also holds the extension's keyword
|
||||
list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
`docs/features/editor-packaging/README.md`.
|
||||
@@ -589,11 +732,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
answering across the workspace means resolving every other file's
|
||||
references *into* this one — an inverted index the workspace layer does
|
||||
not build. It is a real feature, not a small addition.~~ Delivered by
|
||||
**references-nav** (M7). The inverted index was never built: M2's rename
|
||||
already resolves every *other* file's references and asks whether each
|
||||
one lands on this declaration, so the answer came from sharing that walk
|
||||
(`vlog_refactor::find_references`) rather than from new machinery. The
|
||||
same round added `documentHighlight` for symbols and `foldingRange`.
|
||||
**references-nav** (M7). It initially shared M2's rename walk; on
|
||||
2026-08-27 `WorkspaceIndex` gained persisted declaration-to-occurrence
|
||||
postings and the request moved to indexed lookup, with the old walk kept
|
||||
as a correctness oracle. The same round added `documentHighlight` for
|
||||
symbols and `foldingRange`.
|
||||
`docs/features/references-nav/README.md`.
|
||||
- [x] ~~**Not done:**~~ `lucisv.toml` discovery, `.gitignore`-aware indexing —
|
||||
delivered by lucisv-core-lift (both Handshakes below marked DELIVERED).
|
||||
@@ -635,6 +778,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
3.18 items **parked** with their evidence and re-check triggers: snippet
|
||||
`WorkspaceEdit` edits and `workspace/textDocumentContent`, neither of
|
||||
which the pinned `[email protected]` can consume.
|
||||
- [x] The **large-file fast path** — delivered by **large-file-mode**
|
||||
(2026-08-27): a buffer over `lucisv.largeFile.threshold` is line-indexed
|
||||
and nothing else, coloured a viewport at a time by
|
||||
`semanticTokens/range`, and answers everything else empty.
|
||||
`docs/features/large-file-mode/README.md`.
|
||||
- [ ] **Not done:** editor packaging (the VS Code extension and the
|
||||
`lspconfig` snippet are their own TODO.md §6 item).
|
||||
|
||||
@@ -665,12 +813,14 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
is the tail of `pkg::base` and the whole of a bare `base`. That gets in-file
|
||||
bases, cross-file bases, package-qualified bases and parameterized bases from
|
||||
one line, and can never disagree with F12 on the same token.
|
||||
- **`subtypes` is `callers_of_each`'s census in another key**: one
|
||||
- **`subtypes` is `callers_of_each`'s census in another key**: ~~one
|
||||
`sources()` pass, a substring prefilter before any parse, a deterministic
|
||||
sort. 55 ms over the 860-file corpus, 53 ms of it file I/O — the same shape
|
||||
`incomingCalls` measured, and the same backlog item (an edge table in
|
||||
`WorkspaceIndex`, now filed for inheritance edges beside the instantiation
|
||||
ones).
|
||||
ones).~~ **The backlog item shipped (incremental-index, 2026-08-27):** both
|
||||
are index lookups now, in the same deterministic sort, at 0.71 ms and
|
||||
0.26 ms.
|
||||
- **What the class model lacked:** interface classes. `vlog_parser` rejects
|
||||
`interface class` outright, so `implements` can never resolve and no item can
|
||||
carry `SymbolKind::Interface`; both facts are pinned by tests named to force a
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
# out-of-class constraints
|
||||
|
||||
## Goal
|
||||
|
||||
Parse the **out-of-block constraint definition** — `constraint C::name { ... }`
|
||||
written at file or package scope, the body of a class's `extern constraint`
|
||||
prototype (IEEE 1800 §18.5.2) — in both strict and tolerant modes. It is the
|
||||
constraint sibling of `function C::method(...)`, which lucisv has parsed since
|
||||
the `classes` round. `syntax_coverage.md`'s bucket 1 measured it as the single
|
||||
largest gap in the OpenTitan sweep: **45 files** blocked outright, and — the
|
||||
real damage — a tolerant-mode recovery cascade that turned one construct into
|
||||
up to **322** spurious diagnostics in a single buffer, because the parse error
|
||||
lands one token into a construct whose body the recovery loop then resynchronizes
|
||||
inside. A widely-`` `include``d DV base class in that state is not "slightly
|
||||
degraded" in an editor; it is unusable for diagnostics.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The scope prefix carries no meaning lucisv needs.** The whole item is an
|
||||
`ItemKind::Verbatim` leaf, so nothing downstream asks which class a
|
||||
constraint belongs to. The chain is consumed and discarded, exactly as the
|
||||
body's `dist`/`solve`/`->` grammar is copied rather than modelled. If a
|
||||
future round wants "go to the `extern constraint` prototype from its
|
||||
definition," it will need a real node — see Handshakes.
|
||||
- **Any `::` chain length is accepted** (`pkg::cls::name`), because
|
||||
`parse_method_name` — the out-of-body method path being reused — accepts
|
||||
one, and rejecting longer chains would be extra code buying nothing. The
|
||||
corpus only exhibits the two-part form (88 of 88 occurrences across the 45
|
||||
files; measured, not assumed).
|
||||
- **No new legal-position check.** `constraint C::name { ... }` is now accepted
|
||||
wherever a plain `constraint name { ... }` was, including inside a class
|
||||
body, where the LRM does not permit it. lucisv is a formatter, not an
|
||||
elaborator; the existing `parse_constraint` already accepts a bare
|
||||
`constraint c;` prototype at file scope for the same reason. Being more
|
||||
permissive than the LRM in a position no real code writes costs nothing and
|
||||
keeps the change to one call.
|
||||
- The `.cases` and fixture harnesses auto-discover their files, so a new
|
||||
`.cases` file is additive (relied on when placing the formatter coverage —
|
||||
see Handshakes).
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed, unchanged:**
|
||||
|
||||
- `classes` — `verbatim_since` / `skip_balanced` / `RawText`, and
|
||||
`ItemKind::Verbatim` as the leaf. No change to any of them. This round is
|
||||
the sixth producer of `ItemKind::Verbatim` and adds no variant, so the
|
||||
`topo.md` §2.2 new-AST-variant checklist (formatter arm, `bind.rs` arm,
|
||||
`spans.rs` arm, `visit.rs` arm) **does not apply**: every consumer already
|
||||
has its `ItemKind::Verbatim` arm and none of them changed.
|
||||
- `classes` — `parse_method_name`, the out-of-body `C::method` scoped-name
|
||||
path, now called from `parse_constraint` as well. Its contract is unchanged
|
||||
(it splits a `::` chain into scope + final name); this caller keeps neither
|
||||
half.
|
||||
- `error-recovery` — `parse_source_tolerant` is untouched. The cascade
|
||||
collapse is a pure consequence of the construct parsing: no error node is
|
||||
produced, so there is nothing to resynchronize from.
|
||||
|
||||
**Promised to others:**
|
||||
|
||||
- **Semantics / index: an out-of-block constraint contributes nothing** — no
|
||||
symbol for the constraint name, no reference for any name inside the body,
|
||||
no scope. This is *deliberately identical* to the in-class case, which
|
||||
`class-semantics`'s README already states as rule 2 ("Verbatim members stay
|
||||
opaque") and pins with a test. Mechanically it is the same
|
||||
`ItemKind::Verbatim(_) => {}` arm in `bind.rs:372`, reached by the same item
|
||||
walker; item position never entered into it. Verified empirically on the
|
||||
shape (a class with `extern constraint`, its out-of-block definition, and an
|
||||
out-of-body method): symbols are exactly `{Class my_seq, Var num_trans,
|
||||
Function configure}`, zero references anywhere inside the constraint block,
|
||||
and every offset in the file is panic-free for `definition_of` /
|
||||
`symbol_at` / `reference_at`.
|
||||
- **Request to the lead (not acted on):** if that promise should be *pinned*
|
||||
rather than documented, the edit is one new test in
|
||||
`crates/vlog_semantic/tests/classes.rs`, next to the existing
|
||||
`constraint`/`covergroup` opacity test at line ~604, asserting the same
|
||||
three facts on the out-of-block shape. Not written here because
|
||||
`crates/vlog_semantic` is in this lane's file list only "if an arm is
|
||||
needed", and no arm is needed.
|
||||
- **Ownership note (flagged for merge):** requirement 3 of this lane's brief
|
||||
asks for formatter snapshot + idempotency coverage, but
|
||||
`crates/vlog_formatter/tests/*` belongs to Lane B. Resolved by adding
|
||||
**one new file** and editing none:
|
||||
`crates/vlog_formatter/tests/cases/out_of_class_constraints.cases`. The
|
||||
`cases.rs` harness auto-discovers `tests/cases/*.cases` and asserts *both*
|
||||
the expected output and idempotency of that output, so this single file
|
||||
satisfies the requirement with zero textual overlap with Lane B's work.
|
||||
- **Handed on:** `hw/dv/sv/cip_lib/seq_lib/cip_base_vseq.sv` — the worst
|
||||
cascade in the corpus — now advances past this blocker to bucket 10
|
||||
(`type_t'{...}`, a cast applied to an assignment-pattern literal) at
|
||||
`cip_base_vseq.sv:1462`. That bucket belongs to TODO §11's mop-up round.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Parser: `parse_constraint` accepts an optional `Ident ::` scope chain
|
||||
before the constraint name, via `parse_method_name`.
|
||||
- [x] All 45 bucket-1 OpenTitan files stop failing on this construct;
|
||||
44 parse and format clean, 1 advances to a different bucket.
|
||||
- [x] No new failure anywhere in the 3,943-file sweep (set difference, not
|
||||
just counts).
|
||||
- [x] Tolerant cascade measured before and after with the standalone
|
||||
`parse_source_tolerant` probe.
|
||||
- [x] Parser unit tests (5) in `parser.rs`'s test module.
|
||||
- [x] Tolerant regression test in `crates/vlog_parser/tests/error_recovery.rs`.
|
||||
- [x] Span-walker coverage: a new `SOURCES` entry in
|
||||
`crates/vlog_parser/tests/spans.rs` (byte coverage, span nesting,
|
||||
name spans, token reconstruction — all reused, no new assertions needed).
|
||||
- [x] Formatter snapshot + idempotency: 5 cases in a new
|
||||
`out_of_class_constraints.cases`.
|
||||
- [x] Corpus gate: 813/820, exactly the baseline, no regression.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
- [ ] **Not done, deliberately:** no node for the constraint name, so
|
||||
go-to-definition from `constraint C::x` to `extern constraint x;` does
|
||||
not work. Same gap the in-class form has had since `classes`; closing it
|
||||
is a real-AST decision, not a parser fix.
|
||||
- [ ] **Not done, out of scope:** `cip_base_vseq.sv`'s next blocker
|
||||
(bucket 10, cast-to-assignment-pattern).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-29 — dev (Lane A)
|
||||
|
||||
**Root cause, confirmed by reading not by inference.** `parse_constraint`
|
||||
(`crates/vlog_parser/src/parser.rs`) called `self.expect_name()?` — one
|
||||
identifier — and then demanded `{` or `;`. On `constraint C::name {` that
|
||||
fails at the `::`, reporting `expected `{` (found "::")` positioned on the
|
||||
class name, one token *before* the real surprise. Exactly the diagnosis
|
||||
`syntax_coverage.md` recorded.
|
||||
|
||||
**The fix is one call.** `self.expect_name()?` → `self.parse_method_name()?`.
|
||||
`parse_method_name` is the existing out-of-body-method path (`function void
|
||||
my_class::configure(...)`); it consumes a `::` chain and splits scope from
|
||||
name. `parse_constraint` keeps neither, because the item it returns is a
|
||||
`RawText` span. Plus a doc-comment paragraph saying why.
|
||||
|
||||
**Design choice: verbatim reuse, no new AST variant.** The brief's expectation
|
||||
held up against the code. `ItemKind::Constraint` does not exist — a constraint
|
||||
has always been an `ItemKind::Verbatim(RawText)` leaf (`classes`' deliberate
|
||||
"don't model the grammar, copy the bytes"), and `parse_item_kind` already
|
||||
dispatches `"constraint"` at item position (line 1332), which is the same
|
||||
function that parses file-scope, package-scope and module-scope items. So the
|
||||
out-of-block form was *already* routed to the right parser from the right
|
||||
position; only the name grammar was too narrow. Consequences: no `ast.rs`
|
||||
change, no `format.rs` arm, no `bind.rs` arm, no `spans.rs` arm, no
|
||||
`visit.rs` arm, no `verify.rs` change (invariant 4 does not engage — nothing
|
||||
in the safety net was widened). Blast radius: one function body.
|
||||
|
||||
**Measured on the real OpenTitan checkout** (`/Users/guoliangchen/repo/opentitan`,
|
||||
3,943 `.sv`/`.svh` files, `--no-cache --check`, read-only; the tree's one
|
||||
pre-existing modification, `hw/ip/aes/dv/tb/tb.sv`, was there before and after
|
||||
and is not this round's).
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| files failing (whole sweep) | 151 | **107** |
|
||||
| bucket-1 files failing on `expected `{` (found "::")` | 45 | **0** |
|
||||
| bucket-1 files parsing + formatting clean | 0 | **44** |
|
||||
| bucket-1 files advanced to a *different* bucket | — | 1 |
|
||||
| files that newly fail (set difference) | — | **0** |
|
||||
|
||||
The single file that still fails, `hw/dv/sv/cip_lib/seq_lib/cip_base_vseq.sv`,
|
||||
no longer fails on a constraint: it now reaches line 1462 and stops on
|
||||
`addr_mask_t'{addr, mask}` — bucket 10, a distinct documented gap owned by the
|
||||
mop-up round. This is the ordinary corpus-check "a fix advances a file into
|
||||
the next bucket" outcome, and it is why the honest headline is *45 of 45
|
||||
unblocked, 44 of 45 fully clean*.
|
||||
|
||||
**Tolerant-mode cascade, the LSP half.** Probed with a standalone crate
|
||||
path-depending on this worktree's `vlog_parser` and calling
|
||||
`parse_source_tolerant` directly (`syntax_coverage.md`'s method 1 — necessary
|
||||
because `lucisv check`'s exit code deliberately discards `ParseDiagnostic`s).
|
||||
Over the same 45 files:
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| total tolerant diagnostics | **1 349** | **1** |
|
||||
| files with any diagnostic | 45 | 1 |
|
||||
| mean per file | 30.0 | 0.02 |
|
||||
| `cip_base_vseq.sv` (worst) | 322 | 1 *(the bucket-10 cast, not a cascade)* |
|
||||
| `hmac_base_vseq.sv` | 274 | **0** |
|
||||
| `aon_timer_base_vseq.sv` | 79 | **0** |
|
||||
| `ac_range_check_base_vseq.sv` | 67 | **0** |
|
||||
| `tl_seq_item.sv` | 60 | **0** |
|
||||
|
||||
The cascade does not shrink, it disappears: the construct parses, so no error
|
||||
node is created and the recovery loop is never entered. The one surviving
|
||||
diagnostic is a clean single-point report of a different, real gap.
|
||||
|
||||
**Formatter round-trip.** Idempotency was checked on all 45 real corpus files
|
||||
by formatting each through stdin twice (never writing to the corpus):
|
||||
**44 idempotent, 0 non-idempotent, 1 unformattable** (the bucket-10 file). For
|
||||
each of the 44, every `constraint C::name` header present in the input is
|
||||
present in the output — the verbatim capture reproduces the block byte for
|
||||
byte, and `format_source`'s own token-equivalence check (invariant 1) passed
|
||||
on all 44, which is what actually guarantees no comment or token was lost.
|
||||
Layout behaviour matches the in-class constraint exactly and needed no printer
|
||||
work: the block's *absolute* indent is re-set to its item position, its
|
||||
*relative* interior layout is untouched (`classes`' documented rule).
|
||||
|
||||
**Corpus gate.** `scripts/corpus_gate.sh` against the pinned 820-file corpus:
|
||||
`{"passing":813,"total":820,...}`, 0 verification errors, 0 crashes — exactly
|
||||
the recorded baseline, no regression. The pinned corpus contains no
|
||||
out-of-block constraint, which is precisely why this gap went unmeasured until
|
||||
the full-OpenTitan sweep; the strict-superset rule holds.
|
||||
|
||||
**Tests added.**
|
||||
|
||||
- `crates/vlog_parser/src/parser.rs` (test module, new section):
|
||||
- `an_out_of_block_constraint_is_a_file_scope_verbatim_item` — the leaf, and
|
||||
that its text is its own source slice.
|
||||
- `an_out_of_block_constraint_scope_may_be_a_chain` — `pkg::cls::name`.
|
||||
- `an_out_of_block_constraint_lives_in_a_package_too` — package scope.
|
||||
- `an_out_of_block_constraint_keeps_its_trailing_semicolon_and_comments` —
|
||||
the stray `;` is inside the capture, the leading and trailing comments are
|
||||
outside it and both survive (invariant 3).
|
||||
- `an_in_class_constraint_still_rejects_a_scope_free_syntax_error` — the
|
||||
widened name must not swallow `constraint c:: {` or `constraint 4::x`;
|
||||
both still error, with the message pinned.
|
||||
- `crates/vlog_parser/tests/error_recovery.rs`:
|
||||
`out_of_block_constraints_do_not_cascade` — the miniature of the real shape
|
||||
(class with two `extern constraint` prototypes and an `extern function`,
|
||||
then their out-of-block definitions), asserting **zero** tolerant
|
||||
diagnostics and strict/tolerant agreement.
|
||||
- `crates/vlog_parser/tests/spans.rs`: one new `SOURCES` entry, which the
|
||||
file's existing exhaustive walkers pick up for free — token/byte coverage,
|
||||
span nesting, name-span slicing, source reconstruction.
|
||||
- `crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` (new
|
||||
file): 5 cases — prototype + definition, package re-indent, scope chain with
|
||||
a stray `;` and comments on both sides, empty body, and a body exercising
|
||||
the constraint sub-grammar (`dist`, `->`, `foreach`, `if`/`else`). The
|
||||
harness asserts expected-output *and* idempotency for each.
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
|
||||
clean (no new warnings, no `#[allow]`); `cargo test --workspace` green —
|
||||
35 test binaries, 0 failures.
|
||||
|
||||
**Deviations from the brief.** One, declared above under Handshakes: the
|
||||
formatter coverage requirement (3) lands in a directory Lane B owns. Handled
|
||||
as a single new file with no edits to any existing Lane B file, flagged here
|
||||
and in the lane report rather than done silently.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-29 — QA (Lane A)
|
||||
|
||||
Verdict: **SHIP**. No corruption, no cascade regression, no gate slippage
|
||||
found. One test added (see below); everything else in this entry is
|
||||
verification, not redesign.
|
||||
|
||||
**Grammar-widening attacks** (charter item 1) — probed the built
|
||||
`lucisv --stdout -` on adversarial inputs, all behaving safely (correct
|
||||
error or correct accept, never a crash, never silent corruption):
|
||||
|
||||
- `constraint ::name { a == 0; }` → `1:12: expected identifier (found "::")`.
|
||||
- `constraint C:: { a == 0; }` → `1:16: expected identifier (found "{")`
|
||||
(already pinned by the dev's own
|
||||
`an_in_class_constraint_still_rejects_a_scope_free_syntax_error`).
|
||||
- `constraint pkg::cls::inner::deep_c { ... }` (3-part chain) — **accepts**.
|
||||
Judged and pinned here: a 3+-part chain is not realizable SV (classes
|
||||
don't nest, so the longest legal chain a real out-of-body definition can
|
||||
have is `pkg::class::name`), but this is a pure-verbatim leaf — the chain
|
||||
text is consumed and discarded, nothing downstream trusts its structure —
|
||||
so accepting more than the LRM allows costs nothing and matches the
|
||||
README's own Assumptions section, which already makes this call. Not a
|
||||
defect.
|
||||
- `constraint new { a == 0; }` (keyword-shaped name) — accepts, because
|
||||
`"new"` is deliberately not a lexer keyword
|
||||
(`crates/vlog_parser/src/token.rs:334`) and `expect_name` only checks
|
||||
`TokenKind::Ident`. Pre-existing `expect_name` behavior, not a widening
|
||||
`parse_method_name` introduces.
|
||||
- Escaped identifiers on either side of `::` (`` \my-class ::name ``) —
|
||||
accept; the lexer already tags an escaped identifier `Ident`
|
||||
(`crates/vlog_parser/src/lexer.rs:301-314`), so this is old lexer behavior,
|
||||
not new surface from this round.
|
||||
- `constraint C::name;` (a scope on a *prototype*, no body) — **accepts**,
|
||||
producing a verbatim `constraint C::name;` item. This shape doesn't occur
|
||||
in the corpus and isn't a real `extern constraint` (those live in-class,
|
||||
unscoped) — but same reasoning as the chain-depth point: pure verbatim
|
||||
capture, no data trusted downstream, matches "no new legal-position check"
|
||||
in Assumptions. Flagging it here so it's a documented, not accidental,
|
||||
permissiveness.
|
||||
- `constraint C::name { ... }` at **module scope** (illegal SV) — accepts,
|
||||
exactly as the Assumptions section already states it would (the bare form
|
||||
already had this permissiveness pre-round). Not new.
|
||||
- `constraint` as the last token of the file, and `constraint C::name` with
|
||||
no body at EOF — both give clean, correctly-positioned parse errors
|
||||
(`expected identifier (found "<eof>")`, `` expected `{` (found "<eof>") ``),
|
||||
no panic, no hang.
|
||||
- `constraint 4::x { ... }` — `1:12: expected identifier (found "4")`
|
||||
(already pinned by the dev's test of the same name).
|
||||
|
||||
None of these findings block shipping: every widened-acceptance case is
|
||||
already named and justified in the feature's own Assumptions section, and
|
||||
none of them can corrupt output because the whole item stays a byte-exact
|
||||
verbatim span. No new test added for this item — the two shapes worth
|
||||
pinning (`::` with no name, digit as scope) were already covered by the
|
||||
dev's tests, and I've recorded the judgment on chain depth and the
|
||||
prototype-with-scope shape here rather than in code, since they're accepted
|
||||
permissiveness, not bugs.
|
||||
|
||||
**Verbatim integrity** (charter item 2) — built `lucisv` release binary from
|
||||
this worktree and round-tripped by hand (format twice, diff outputs; also
|
||||
compared against source where relevant):
|
||||
|
||||
- String containing `}` inside the body — idempotent, brace inside the
|
||||
string does not confuse `skip_balanced`.
|
||||
- Block comment containing `{`/`}` inside the body — idempotent.
|
||||
- `` `ifdef ``/`` `else ``/`` `endif `` inside the body — idempotent (the
|
||||
whole conditional is inside the verbatim span, never interpreted).
|
||||
- CRLF line endings inside the body — idempotent; CRLF is normalized to LF
|
||||
on the way in, which is pre-existing whole-file lexer behavior unrelated
|
||||
to this round, not something this change introduces.
|
||||
- A `constraint C::name { ... }` nested three packages deep with
|
||||
inconsistent absolute indentation and extra relative indentation in the
|
||||
body — confirmed the `RawText.col` dedent contract (topo §2.2) holds: the
|
||||
block's absolute indent resets to its item position, every line's
|
||||
*relative* offset from the original `constraint` line is preserved
|
||||
exactly, and the result is idempotent.
|
||||
- All 5 cases in the dev's new
|
||||
`crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` pass,
|
||||
confirmed the harness (`crates/vlog_formatter/tests/cases.rs:178`) actually
|
||||
asserts idempotency per case, not just expected output.
|
||||
|
||||
**Cascade honesty** (charter item 3) — built a standalone probe crate
|
||||
depending on this worktree's `vlog_parser` (`parse_source_tolerant`
|
||||
directly), run against the real `/Users/guoliangchen/repo/opentitan`
|
||||
checkout, read-only throughout (`git status --porcelain` before and after:
|
||||
only the pre-existing `hw/ip/aes/dv/tb/tb.sv` modification, untouched).
|
||||
|
||||
- Reproduced the dev's 5 named files exactly, both sides, via
|
||||
`git stash`/`stash pop` on `crates/vlog_parser/src/parser.rs` alone:
|
||||
|
||||
| file | before | after |
|
||||
|---|---|---|
|
||||
| `cip_base_vseq.sv` | 322 | 1 (bucket-10, not a cascade) |
|
||||
| `hmac_base_vseq.sv` | 274 | 0 |
|
||||
| `aon_timer_base_vseq.sv` | 79 | 0 |
|
||||
| `ac_range_check_base_vseq.sv` | 67 | 0 |
|
||||
| `tl_seq_item.sv` | 60 | 0 |
|
||||
|
||||
- 5 more bucket-1 files of my own choosing (`alert_esc_seq_item.sv`,
|
||||
`dv_base_env_cfg.sv`, `kmac_app_agent_cfg.sv`,
|
||||
`adc_ctrl_filter_cfg.sv`, `aon_timer_common_vseq.sv`): before 3/40/1/10/5,
|
||||
after all 0. Cascade collapse confirmed on a sample the dev didn't hand-pick.
|
||||
- 20 files sampled from outside the failing set (mixed `dv/`/`rtl/`,
|
||||
various IPs, one from `vendor/`) probed before and after the same
|
||||
stash/pop: **byte-identical diagnostic counts both sides** (one file,
|
||||
`rng_agent/rng_driver.sv`, carries 1 diagnostic both before and after —
|
||||
pre-existing, unrelated to this change). No new tolerant diagnostic
|
||||
anywhere in the sample.
|
||||
|
||||
**Strict-superset discipline** (charter item 4) — reproduced independently,
|
||||
not trusted from the write-up:
|
||||
|
||||
- Corpus gate: `scripts/corpus_gate.sh` against
|
||||
`/Users/guoliangchen/repo/verilogrustformatter/corpus` (the worktree has
|
||||
no local `corpus/`, it's gitignored) → `{"passing":813,"total":820,...}`,
|
||||
0 verification errors, 0 crashes. Exact match to the claimed baseline.
|
||||
- Whole-sweep count: built the release binary with the fix stashed out and
|
||||
back in, ran `lucisv --no-cache --check` over all 3,943 real-OpenTitan
|
||||
`.sv`/`.svh` files both ways. **151 → 107**, exact match.
|
||||
- Set difference: `comm -23` between the after-failing and before-failing
|
||||
file lists → **0 newly-failing files**; `comm -13` → 44 newly-fixed files
|
||||
(151 − 107 = 44, consistent). The 45th named file
|
||||
(`cip_base_vseq.sv`) confirmed still failing, but on a *different*
|
||||
diagnostic: `1462:65: expected `)` (found "'{")`, i.e. line 1462's
|
||||
`addr_mask_t'{addr, mask}` — exactly the claimed bucket-10 advance, not a
|
||||
constraint failure.
|
||||
- Idempotency on all 44 newly-clean files (not the dev's sampled subset —
|
||||
the full 44): scripted format-twice-and-diff over each; **0 failures, 0
|
||||
non-idempotent**.
|
||||
|
||||
**The three flagged deviations** (charter item 5):
|
||||
|
||||
- (a) `crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` —
|
||||
`git status --porcelain` shows it `??` (untracked, new-file-only); no
|
||||
existing Lane B file touched. Confirmed the harness exercises idempotency
|
||||
for it (see above). Genuinely additive, as claimed.
|
||||
- (b) `TODO.md` §11 — diffed the worktree's version against
|
||||
`git show master:TODO.md`: the only difference is Lane A's own checkbox
|
||||
(unchecked → checked) and one added summary line under Lane A's item.
|
||||
Lane B's subsection and the "serial, after Lane A merges" section are
|
||||
byte-identical to trunk. The trivially-parallel merge claim holds.
|
||||
- (c) The un-pinned `vlog_semantic` opacity promise — per my small-fix
|
||||
license and the charter's explicit instruction, added the test the dev
|
||||
specified in Handshakes:
|
||||
`crates/vlog_semantic/tests/classes.rs::an_out_of_block_constraint_is_absent_but_nothing_crashes`,
|
||||
next to the existing `verbatim_members_are_absent_but_nothing_crashes`.
|
||||
One correction while writing it: my first draft assumed the *out-of-block
|
||||
definition* was the only opaque part and that the in-class `extern
|
||||
constraint num_trans_c;` prototype would still produce a `num_trans_c`
|
||||
symbol — it does not; the prototype is itself an `ItemKind::Verbatim`
|
||||
leaf too (parsed by the same `parse_constraint`), so neither the
|
||||
prototype nor the definition binds a symbol. Fixed the assertion to match
|
||||
reality (confirmed by running the test against the actual analyzer output
|
||||
before asserting) rather than the assumption. Test passes.
|
||||
|
||||
**Full gates** (charter item 6), re-run after adding the `vlog_semantic`
|
||||
test: `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
|
||||
clean, 0 warnings; `cargo test --workspace` green (35 test binaries, 0
|
||||
failures, includes the new test); corpus gate 813/820 as above.
|
||||
|
||||
**Findings summary** (severity — all informational/non-blocking, nothing
|
||||
found that requires rework):
|
||||
|
||||
- INFO: `parse_constraint` now accepts several shapes the OpenTitan corpus
|
||||
never exercises and the LRM doesn't sanction (chains deeper than 2,
|
||||
a scoped prototype with no body, module-scope placement) — all already
|
||||
named as deliberate in the feature's Assumptions section and all
|
||||
incapable of corrupting output, since the entire item is a byte-exact
|
||||
verbatim capture. No action needed; recorded here so the judgment call is
|
||||
visible to reviewers who don't re-derive it.
|
||||
- INFO: the dev's Handshakes-proposed `vlog_semantic` test had a wrong
|
||||
assumption baked into its own description (that `extern constraint
|
||||
num_trans_c;` binds a symbol); the corrected version now pins the real
|
||||
behavior (neither prototype nor definition binds a symbol).
|
||||
|
||||
**Tests added:** 1 —
|
||||
`crates/vlog_semantic/tests/classes.rs::an_out_of_block_constraint_is_absent_but_nothing_crashes`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead.** Reviewed after QA's clean SHIP; gates re-run on
|
||||
the worktree. This round is the loop at its best-case: the analysis
|
||||
sweep named the bucket, the fix is one line reusing a path the grammar
|
||||
already had, the blast radius is zero by construction (verbatim leaf,
|
||||
no new variant), and the payoff is the largest single coverage move
|
||||
available — 45 files unblocked and a 1,349-diagnostic tolerant cascade
|
||||
reduced to one honest report. QA's stash-based before/after on
|
||||
previously-clean files is the check that matters for a grammar
|
||||
widening (a cascade that moved would have hidden), and its correction
|
||||
of the dev's own specified-but-wrong semantic test (extern prototypes
|
||||
are verbatim too) is exactly why the QA leg exists. The deliberate
|
||||
over-acceptances (deep scope chains, scoped prototypes, module-scope
|
||||
placement) are recorded as judgment calls with the corruption argument
|
||||
attached — acceptable for a byte-exact capture. Accepted; merged by
|
||||
the lead. parser.rs is now free for the directive-split round.
|
||||
@@ -30,12 +30,13 @@ same invocation, regardless of thread count.
|
||||
rather than streaming. For the sizes lucisv targets (a large RTL tree is tens
|
||||
of MiB of source) this is acceptable; it is the reason `--stdout` over a
|
||||
huge tree is no longer incremental.
|
||||
- **8 MiB of worker stack is enough.** Taken from
|
||||
`docs/features/recursion-limit/README.md`, which measured the worst-case
|
||||
full-pipeline peak at ~3.9 MiB in a debug build and ~0.5 MiB in release.
|
||||
The pool is built with exactly that number; rayon's own default is 2 MiB,
|
||||
which would silently reintroduce the stack-overflow crash that feature
|
||||
fixed.
|
||||
- **Worker stacks are `vlog_parser::PARSE_STACK_SIZE`, not a number of this
|
||||
feature's own.** Superseded 2026-08-28: this used to assume "8 MiB is
|
||||
enough", from recursion-limit's then-measured ~3.9 MiB debug peak. That
|
||||
peak is now measured at ~5.9 MiB (rustc 1.97, nested `case`), so the size
|
||||
is no longer this feature's to pick — `build_pool` spells the parser's
|
||||
constant, and recursion-limit owns the number. rayon's own default is
|
||||
2 MiB, which would silently reintroduce the stack-overflow crash.
|
||||
- **The `.gitignore` support is a documented subset, not git.** It is the
|
||||
`--exclude` matcher plus anchoring, directory-only and negation. See
|
||||
"gitignore subset" below for exactly what is and is not honoured. It is
|
||||
@@ -98,11 +99,13 @@ A path named directly on the command line is never ignored, exactly as with
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `docs/features/recursion-limit/README.md`'s request:** that
|
||||
README asks whoever lands parallelism to build the rayon pool with
|
||||
`stack_size(8 * 1024 * 1024)` or larger, because a 2 MiB worker cannot
|
||||
reach `MAX_NESTING_DEPTH` in a debug build (~3.9 MiB measured). Done in
|
||||
`main.rs::build_pool`, with a test (`deep_file_formats_under_the_pool`)
|
||||
that fails if the stack size is ever removed.
|
||||
README asks whoever lands parallelism to build the rayon pool with a stack
|
||||
big enough to reach `MAX_NESTING_DEPTH`, because a 2 MiB worker cannot.
|
||||
Done in `main.rs::build_pool`. Since 2026-08-28 the size is the parser's
|
||||
own `vlog_parser::PARSE_STACK_SIZE` rather than a literal here, so a
|
||||
re-measurement of the worst case moves every parse site at once; the pin
|
||||
test (`a_deeply_nested_file_formats_on_a_worker_thread`) still fails if
|
||||
the pool's stack size is dropped.
|
||||
- **Discharges `docs/features/cli-polish/README.md`'s handshake:** that
|
||||
feature's `catch_panic` swapped the process-global panic hook with
|
||||
`take_hook`/`set_hook` around every call, and flagged it as sound only
|
||||
@@ -126,7 +129,9 @@ A path named directly on the command line is never ignored, exactly as with
|
||||
|
||||
- [x] `rayon` as the workspace's first third-party dependency, pinned
|
||||
exactly, justified below.
|
||||
- [x] Global pool built once at startup with an 8 MiB worker stack.
|
||||
- [x] Global pool built once at startup with an 8 MiB worker stack
|
||||
(re-pointed at `vlog_parser::PARSE_STACK_SIZE` on 2026-08-28, when the
|
||||
worst case was re-measured past what 8 MiB comfortably covers).
|
||||
- [x] One panic hook installed at startup; `catch_panic` uses a thread-local
|
||||
flag instead of swapping hooks.
|
||||
- [x] Per-file loop parallelised; outcomes reported in input order.
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
# port-detail-spans
|
||||
|
||||
## Goal
|
||||
|
||||
A non-ANSI port is declared in two places: the header names it (`data_in,`)
|
||||
and a body declaration finishes it (`input signed [31:0] data_in;`). Every
|
||||
fact a reader wants — direction, signedness, width — is in the second place,
|
||||
and until this round hover and go-to-definition both pointed only at the
|
||||
first, so hovering a port of an older-style module showed a bare name and a
|
||||
comma. `vlog_semantic` now records, on the header symbol, the span of the body
|
||||
declaration that completes it (`Symbol::detail_span`); the server shows both
|
||||
in one hover card and offers both as definition locations, detail first. The
|
||||
same field travels through the workspace index and its on-disk facts, so a
|
||||
*cross-file* hover into a closed file gets the same two sections. Attached to
|
||||
that, because a card that shows a declaration should show what the author
|
||||
wrote about it: each section carries the comment that documents it.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **One name, one symbol, per scope.** `bind::declare` already turns a second
|
||||
declaration of a name into a *reference* to the first, which is exactly how
|
||||
a non-ANSI body declaration attaches to its header port. `detail_span` rides
|
||||
on that existing mechanism; nothing new decides what "the same port" means.
|
||||
- **First writer wins.** If a header somehow names a port twice, the first
|
||||
body declaration to arrive records its span and later ones are ignored. The
|
||||
result is deterministic, which is what matters here; a duplicated port is
|
||||
the linter's complaint to make, not hover's.
|
||||
- **`detail_span` is `None` for everything else.** An ANSI port, a wire, a
|
||||
module — anything complete where it is named — has no detail site, and both
|
||||
consumers render exactly the card they always did.
|
||||
- **A real span is never empty**, so `(0, 0)` is free to mean `None` in the
|
||||
facts codec. `bind_port_decl` only ever records a declaration's own span.
|
||||
- **Comment attachment is textual, and errs towards attaching nothing.** The
|
||||
disk path of a cross-file hover has no parse to ask, so the attachment rules
|
||||
work on lines. Only `//` lines and single-line `/* … */` count as
|
||||
comment-only; the interior of a multi-line block comment is
|
||||
indistinguishable from code without lexing, and a hover card that guessed
|
||||
would be the wrong-line lie the snippet guards exist to prevent.
|
||||
- **A comment below a declaration belongs to the *next* declaration unless
|
||||
nothing else could claim it.** `only_a_closer_on` answers that with a
|
||||
whitelist, not a blacklist: the block attaches only when every word on the
|
||||
line after it is a block terminator (`end`, `endmodule`, `endinterface`,
|
||||
`endtask`, `endfunction`) — which includes a line with no words at all
|
||||
(`);`, a blank line, punctuation) — or when there is no line after it at
|
||||
all. Everything else, a bare `input` on the first line of a *wrapped*
|
||||
declaration included, reads as another declaration. The bias is the whole
|
||||
point: a false "another declaration is here" only ever declines to attach a
|
||||
comment, the direction that cannot lie, while a false "nothing here" shows
|
||||
one declaration's comment on another's card. (QA, PDS-1: the previous
|
||||
keyword-blacklist form got that backwards and did lie.)
|
||||
- **The three comment sources are independent**, as the owner's rule states
|
||||
them: a declaration takes the comment on its own line *and* the block above
|
||||
it *and* the block below it, each guarded on its own. Order is source
|
||||
order. (QA, PDS-2: the first implementation ran them as a priority chain
|
||||
and dropped a below-comment nothing else claimed.)
|
||||
- **Comment attachment renders, it never rewrites.** A CRLF file's line ends
|
||||
before its `\n` but after its `\r`, so `attached_lines` strips that `\r` as
|
||||
it composes each line — display text only; no buffer is touched (QA,
|
||||
PDS-4).
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_semantic::Symbol` gains a field** — `detail_span:
|
||||
Option<TextRange>`. Additive, like `refactor-rename`'s `Target::Declaration`
|
||||
before it (§2.6 of `topo.md`): every existing reader of `Symbol` compiles
|
||||
and behaves identically, and the two struct literals that build a `Symbol`
|
||||
(`bind.rs`) set it. `bind_port_decl` is where it is written.
|
||||
- **`vlog_semantic::Def` gains the same field**, carried by the index's
|
||||
internal `Decl`. `Def` is what `lucisv_server` navigates by, so this is the
|
||||
wire that makes a *cross-file* hover show the body declaration. `Def`
|
||||
derives `PartialEq`; two `Def`s that differ only in `detail_span` cannot
|
||||
arise, because both come from the same `Decl`.
|
||||
- **`facts.rs`'s on-disk format changes** — every declaration record now
|
||||
carries two more numbers, written unconditionally (`0 0` for the `None`
|
||||
that every ordinary declaration has) so the stream stays flat and the
|
||||
reader stays a straight sequence of `num()`s. **`FACTS_FORMAT` is bumped
|
||||
(2 → 3)**, so a store written by an earlier build is discarded whole:
|
||||
`index_cache.rs`'s header line carries the number, and a header that is not
|
||||
this build's means the file is not read at all. Without the bump an old
|
||||
record would be *reinterpreted* — every field after a declaration's name
|
||||
span shifted by two — rather than dropped, and only the reader's `done()`
|
||||
check would stand between a shifted parse and a wrong answer. Dropping the
|
||||
store costs one rescan, once, which is what the persistent index is for
|
||||
(`docs/features/index-persistence/README.md`); it is the
|
||||
`vlog_semantic/src/workspace.rs` choke-point rule in `topo.md` §3.3.
|
||||
- **`nav.rs` and `hover.rs` agree, by construction.** Hover shows two
|
||||
sections — header, then detail — and `nav::definition` returns two
|
||||
locations in the same order, detail first, so "jump" lands where the card's
|
||||
second block is and the card's first block is the second location. Both
|
||||
read `symbol.detail_span`; there is no second rule for what a port's
|
||||
declaration is. An empty detail span is filtered out in `nav.rs` rather
|
||||
than trusted.
|
||||
- **Consumes `hover-declarations`' guards unchanged.** `spells_exactly` still
|
||||
gates every snippet read out of a file the index may be stale against;
|
||||
`fenced_sections` is applied *after* that guard on the disk path, and after
|
||||
`live_symbol` on the live path.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `Symbol::detail_span`, written by `bind_port_decl`, first writer wins —
|
||||
for a module's non-ANSI port and for an old-style task/function
|
||||
argument, which merge through the same `bind::declare`.
|
||||
- [x] `Def::detail_span` + the index's `Decl` carrying it.
|
||||
- [x] `facts.rs` codec: unconditional pair, `(0,0)` = `None`, `FACTS_FORMAT`
|
||||
bumped so a stale store is not read as a fresh one.
|
||||
- [x] `hover::fenced_sections` — one section, or header + detail.
|
||||
- [x] `nav::definition` returns the detail location first.
|
||||
- [x] Comment attachment (`attached_lines`): same-line, above and below, each
|
||||
guarded on its own, all three at once where all three are written.
|
||||
- [x] Tests: `vlog_semantic` records the span for a split port and not for an
|
||||
ANSI one; hover shows two sections from either end of the port;
|
||||
comments attach above, below, and are not stolen from the next port;
|
||||
a cross-file split port shows both sections from the index.
|
||||
- [x] **2026-08-28**: the below-comment guard is a closer whitelist, so a
|
||||
*wrapped* next declaration keeps its own leading comment (QA, PDS-1).
|
||||
- [x] **2026-08-28**: above / beside / below are independent (QA, PDS-2).
|
||||
- [x] **2026-08-28**: an old-style task or function argument gets a
|
||||
`detail_span` too (QA, PDS-3).
|
||||
- [x] **2026-08-28**: a CRLF file's snippet carries no `\r` into the fence
|
||||
(QA, PDS-4).
|
||||
- [ ] Not done: `detail_span` for anything other than a port or a
|
||||
task/function argument. An `extern`
|
||||
method prototype and its out-of-body definition are the same
|
||||
two-places-one-symbol shape and would fit the field exactly, but no
|
||||
hover complaint has been filed about them and speculative generality is
|
||||
what `CLAUDE.md` says not to build.
|
||||
- [ ] Not done: a *doc-comment* model. The attachment above is positional and
|
||||
deliberately dumb — no `///` convention, no markdown rendering of the
|
||||
comment body, no stripping of `//`. That is a feature of its own if it
|
||||
is ever wanted.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev.** Implemented as part of the LSP performance round
|
||||
(plan: "Improve LSP performance + hover accuracy", part B), continued by a
|
||||
second dev after the first stopped mid-round; the code below is the first
|
||||
dev's except where noted.
|
||||
|
||||
- `bind_port_decl` looks the declarator's name up in the scope it is binding
|
||||
into *before* `bind_declarators` runs, because `declare` will turn the name
|
||||
into a reference and there would be no symbol id to write on afterwards.
|
||||
The lookup is the scope's own `names` map — the same map `declare` consults
|
||||
— so "the same port" is decided in exactly one place.
|
||||
- The codec writes the pair unconditionally rather than with a presence flag.
|
||||
A flag would have kept old records readable at the cost of a branch in the
|
||||
hot reader and a second thing to get wrong; dropping a stale record costs
|
||||
one reparse of that file, once.
|
||||
- Comment attachment was not in the plan. It is here because the first card
|
||||
the two-section change produced looked wrong without it: a port's comment
|
||||
sits on the line above or beside it, and showing the declaration without it
|
||||
loses the only prose the author wrote. The rules are the narrowest ones
|
||||
that never steal another declaration's comment, and each has a test.
|
||||
- **Second dev, 2026-08-28**: **bumped `FACTS_FORMAT` 2 → 3**, which the
|
||||
first dev's change owed and did not take. Its comment argued that a
|
||||
pre-field record is "one field short, fails `done()`, and is dropped" —
|
||||
true for the last declaration in a record, but a record with a declaration
|
||||
followed by anything else is not short, it is *shifted*, and relying on a
|
||||
trailing-length check to catch a field-order change is exactly what the
|
||||
format number exists to make unnecessary. The workspace `VERSION` is also
|
||||
in the store's header, but it has not moved this round, so without the bump
|
||||
a store written by the released 0.12.1 would have been read by the new
|
||||
codec. Otherwise no behavioral change: this README is the documentation the
|
||||
round owed, and `cargo fmt` was run over `hover.rs`.
|
||||
|
||||
**2026-08-28 — dev (QA fixes, third dev).** Every finding in the QA log below
|
||||
is addressed; each is marked fixed or left, with the reason.
|
||||
|
||||
- **PDS-1 — fixed.** `another_port_on`/`is_port_grammar_word` are gone,
|
||||
replaced by `only_a_closer_on`/`is_closer_word` (`hover.rs`). The old
|
||||
predicate asked "does this line carry an identifier the port grammar cannot
|
||||
account for?", which is a blacklist: a line that is *only* keywords — the
|
||||
first line of a wrapped `input\n [7:0] result;` — answered "no other
|
||||
port here" and handed `result`'s comment to `data_in`. The new one asks the
|
||||
question the other way round: every word on the line must be a block
|
||||
terminator, so a line with any word the whitelist does not name (a bare
|
||||
`input` included) reads as another declaration and the comment stays put.
|
||||
A line with no words at all — `);`, blank, punctuation — passes, which is
|
||||
what a last port's trailing comment is really followed by, and so does the
|
||||
end of the file, where there is no line left to claim anything. The doc
|
||||
comment now states that bias and why only that direction is safe.
|
||||
- `name` fell out of the predicate, and with it out of `attached_lines` and
|
||||
`fenced_sections` — the guard no longer needs to know which port it is
|
||||
guarding, only whether anything follows the comment. Three call sites
|
||||
simplified; no behaviour rides on the removal.
|
||||
- Pinned: `a_wrapped_next_declaration_keeps_its_own_leading_comment` (the
|
||||
QA repro verbatim, plus the assertion that the comment does reach
|
||||
`result`'s own card) and `a_wrapped_declaration_keeps_the_comment_below_it`
|
||||
(the same wrapped shape as the *last* declaration still takes it). The
|
||||
existing `a_comments_below_a_declaration_attach_only_when_no_port_follows_them`
|
||||
— comment block above `endmodule` — still passes unchanged.
|
||||
- **PDS-2 — fixed.** `attached_lines` no longer runs a priority chain: the
|
||||
above walk, the declaration's own lines (which carry the same-line comment
|
||||
inherently) and the below walk are three independent collections joined in
|
||||
source order. `has_comment_after` was the chain's only reader and is
|
||||
deleted. Each guard is exactly as strict as before — the above walk still
|
||||
stops at the first line that is not comment-only, and the below guard got
|
||||
*stricter* with PDS-1 — so nothing new can be stolen; what changes is only
|
||||
that a below-comment nothing else claims is no longer silently dropped
|
||||
because something was also written above.
|
||||
- Pinned: `a_declaration_shows_the_comments_above_beside_and_below_it_at_once`
|
||||
(all three on one body declaration) and
|
||||
`a_header_port_shows_the_comments_above_and_below_it_at_once`, which is
|
||||
QA's repro 1 and repro 2 in one header — with the negative half (the same
|
||||
block *is* left alone when another port follows it) in the same test.
|
||||
- **PDS-3 — fixed, not documented as a gap.** Checked the binder first, as
|
||||
the brief asked: `bind_tf_args` declares `task t(a);`'s `a` as a `TfArg` in
|
||||
the task's own scope, and `input [7:0] a;` at statement position reaches
|
||||
`bind_port_decl` with that same scope, so `declare` turns it into a
|
||||
reference to the header symbol — the identical header→body merge a module
|
||||
port gets, one symbol and not two (verified by probe before changing
|
||||
anything). So the recording is extended rather than parked: the
|
||||
`kind == SymbolKind::Port` gate is gone and the inner test is
|
||||
`symbol.kind == kind`, which is the same condition for a port and now also
|
||||
holds for an argument. Pinned in `vlog_semantic`
|
||||
(`an_old_style_task_argument_records_its_body_declaration_too`, including
|
||||
that an ANSI-style argument still has none) and in hover
|
||||
(`an_old_style_task_argument_hovers_as_two_sections_too`).
|
||||
- **PDS-4 — fixed.** `attached_lines`'s line reader strips a trailing `\r`
|
||||
from every line it composes, so a CRLF file's fenced block is `\n`-joined
|
||||
like any other. It is done there, at the one place all three collections
|
||||
(above, declaration, below) pass through, rather than in `cut_to_size`,
|
||||
which would have had to re-split the joined string. Display text only —
|
||||
nothing writes to the buffer. QA's pinned test
|
||||
`a_crlf_multiline_snippet_keeps_interior_carriage_returns` was the
|
||||
regression test for the old behaviour; it is now
|
||||
`a_crlf_multiline_snippet_carries_no_carriage_returns`, asserting no `\r`
|
||||
survives *and* that the lines read as written. (Editing a QA-authored test
|
||||
rather than deleting it: the finding it pins is the one being closed, and
|
||||
the same file's `local_text` path goes through the same helper, so it
|
||||
covers both branches QA named.)
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** Verified against the owner's own spec ("two sections
|
||||
… same line, or above it (if no other port on the line above), or below it
|
||||
(if no other port on the line below)"), and attacked with the shapes named in
|
||||
the QA brief. Gates green (see change-debounce's QA log for the shared run).
|
||||
All reproductions used temporary `#[test]`s in `hover.rs`, run once, and
|
||||
removed after confirming — none are left in the tree, except the one noted
|
||||
below as a kept, permanent regression test.
|
||||
|
||||
- **Finding PDS-1 (high — a wrong comment shown, the one invariant this
|
||||
feature explicitly promises never to violate).** `another_port_on`
|
||||
(`hover.rs:355`) — the guard that decides whether a below-comment block
|
||||
belongs to *this* declaration or the next one — inspects only the single
|
||||
line immediately following the comment block. When the next port's own
|
||||
declaration **wraps**, with its direction keyword alone on the first line
|
||||
and its name on a later line, every word on that first line is in
|
||||
`is_port_grammar_word`'s list (`hover.rs:368`, which includes bare
|
||||
`input`/`output`/etc.), so `another_port_on` returns `false` — "no other
|
||||
port here" — and the comment attaches to the **wrong** declaration.
|
||||
- Repro:
|
||||
```systemverilog
|
||||
module alu (data_in, result);
|
||||
input [7:0] data_in;
|
||||
// about result
|
||||
input
|
||||
[7:0] result;
|
||||
endmodule
|
||||
```
|
||||
Hovering `data_in` shows a detail section reading
|
||||
`input [7:0] data_in;\n// about result` — `result`'s own leading comment,
|
||||
attached to `data_in`'s card. Confirmed live (temporary test asserting
|
||||
the comment is *not* present failed with exactly this text).
|
||||
- This is precisely the failure mode `docs/features/port-detail-spans/
|
||||
README.md`'s own Assumptions section rules out: "a false 'yes' only ever
|
||||
declines to attach a comment — the direction that cannot lie." Here a
|
||||
false *no* (failing to recognize `result`'s declaration as a port) makes
|
||||
it lie. Left unfixed — not small/unambiguous; the honest fix wants
|
||||
`another_port_on` (or its caller) to look past a line that is *entirely*
|
||||
grammar words with no other identifier, to the line(s) after it, which
|
||||
is a real design change to a predicate three call sites and several
|
||||
tests depend on.
|
||||
|
||||
- **Finding PDS-2 (medium — divergence from the stated spec, not corruption;
|
||||
the one the QA brief asked to check explicitly).** The owner's rule reads
|
||||
as three independently-checked sources (same line, above, below). The
|
||||
implementation instead runs a strict priority chain in `attached_lines`
|
||||
(`hover.rs:297`): below-comment collection is skipped **entirely** whenever
|
||||
there is *any* above-comment, or *any* same-line trailing comment
|
||||
(`hover.rs:313`, `if above.is_empty() && !decl.last()...has_comment_after`)
|
||||
— even when the below comment is otherwise unclaimed by anything else
|
||||
(no other port follows it).
|
||||
- Repro 1 (above blocks below):
|
||||
```systemverilog
|
||||
module alu (
|
||||
// above
|
||||
data_in
|
||||
// below
|
||||
);
|
||||
input [7:0] data_in;
|
||||
endmodule
|
||||
```
|
||||
Header section shows `// above` + `data_in` only; `// below` is silently
|
||||
dropped, though nothing else claims it (the next line is `);`).
|
||||
- Repro 2 (same-line trailing comment blocks below):
|
||||
```systemverilog
|
||||
module alu (
|
||||
data_in // right here
|
||||
// below
|
||||
);
|
||||
input [7:0] data_in;
|
||||
endmodule
|
||||
```
|
||||
Header section shows `data_in // right here` only; `// below` dropped.
|
||||
- Not unsafe (never shows the wrong comment — just fewer than the literal
|
||||
spec asks for), so lower severity than PDS-1, but a real, reproducible
|
||||
divergence. Left unfixed — a design call (should a declaration ever show
|
||||
*two* attached comments at once?) belongs to the dev/lead, not QA.
|
||||
|
||||
- **Finding PDS-3 (low — silent feature-completeness gap, not a bug).**
|
||||
`bind_port_decl`'s `detail_span`-recording branch is gated on `kind ==
|
||||
SymbolKind::Port` (`bind.rs:512`), which excludes `SymbolKind::TfArg` —
|
||||
**old-style (non-ANSI) task/function port declarations**
|
||||
(`task t(a);\n input a;\n ...\nendtask`) never get a `detail_span`, even
|
||||
though they are exactly the same two-places-one-symbol shape a module's
|
||||
non-ANSI port is, and `bind_port_decl` is already reached at statement
|
||||
position for them (`bind.rs:1030`, `StmtKind::PortDecl`). The feature's own
|
||||
"Not done" list names only extern method prototypes as the deliberately
|
||||
parked case; task/function old-style ports are a second, unmentioned one.
|
||||
Falls back to the single-section card exactly as before this round — no
|
||||
regression, just an undocumented gap, worth a line in Status/TODO if the
|
||||
dev wants it.
|
||||
|
||||
- **Finding PDS-4 (low/cosmetic — pre-existing, amplified by this round, not
|
||||
introduced by it).** On a CRLF file, a multi-line fenced snippet embeds a
|
||||
raw `\r` byte in the *middle* of the code fence for every joined line
|
||||
except the last (whose trailing `\r` happens to be stripped because
|
||||
`cut_to_size`'s `trim_end()` only trims the very end of the whole joined
|
||||
string, not each line). This is pre-existing behavior of
|
||||
`Positions::whole_lines` / `cut_to_size` — `local_text` already had the
|
||||
same characteristic for any multi-line `decl_span` before this round — but
|
||||
comment attachment now makes multi-line snippets routine (any port with a
|
||||
nearby comment, not just a rare multi-line declaration), so the gap is hit
|
||||
far more often in practice. Repro: a CRLF split-port module with an
|
||||
above-comment; the header section's rendered text contains a literal `\r`
|
||||
between the comment line and the declaration line. Cosmetic only (a stray
|
||||
control character, not wrong text); not fixed, flagged for whoever touches
|
||||
`cut_to_size` next.
|
||||
|
||||
- **Attack angles checked and clean (no finding):**
|
||||
- *A port declared twice* — first-writer-wins confirmed: the second body
|
||||
declaration's comment (`// second (duplicate...)`) never appears; only
|
||||
the first's (`// first`) does, matching `bind_port_decl`'s documented
|
||||
policy.
|
||||
- *ANSI mixed with non-ANSI in one header* — a full ANSI port (`input wire
|
||||
clk,`) and a split non-ANSI port (`data_in`) in the same header list:
|
||||
`clk` renders exactly one fenced section, `data_in` exactly two, no
|
||||
cross-contamination.
|
||||
- *A comment containing `//` inside a string on the declaration line* —
|
||||
the whole line is shown verbatim regardless (the attachment logic never
|
||||
parses the line's meaning, only whether `has_comment_after` sees `//`/
|
||||
`/*` after the name), so there is no wrong-line risk, only the expected
|
||||
line reproduced as written.
|
||||
- *`` `ifdef``/`` `endif`` between the header and the body declaration* —
|
||||
correctly ignored as neither comment-only nor a stolen declaration; the
|
||||
detail section is exactly the body decl's own line(s). (Note: a
|
||||
`` `endif``/`` `ifdef``/`` `define`` line sitting where "no other port"
|
||||
is required is itself treated as "another port" by `another_port_on`'s
|
||||
conservative word-matching — a false positive that only *declines* to
|
||||
attach, so it is safe, just another instance of the documented
|
||||
conservative-below-the-fold behavior, not a new bug.)
|
||||
- *An attribute (`(* foo *)`) prefixing the next port's declaration* —
|
||||
correctly detected as "another port" (the attribute's own words split
|
||||
out as ordinary non-grammar identifiers), so the comment is not stolen.
|
||||
- *A block comment `/* … */` spanning multiple lines* — the interior lines
|
||||
are (by design, and correctly) not recognized as comment-only, so the
|
||||
walk stops there and nothing is attached from inside the block — safe
|
||||
(declines rather than guesses), matching the documented limitation.
|
||||
|
||||
- **Facts-format bump (2 → 3): verified the drop, not a shifted read.**
|
||||
Wrote and kept a permanent regression test,
|
||||
`a_store_from_the_previous_facts_format_is_dropped_not_misread`
|
||||
(`crates/lucisv_server/src/index_cache.rs`, next to the existing
|
||||
`a_store_from_another_version_is_dropped_whole_and_replaced` and
|
||||
`a_store_from_the_previous_store_format_is_dropped_whole_and_replaced`,
|
||||
which cover a `VERSION` mismatch and a `CACHE_FORMAT` mismatch but, before
|
||||
this, never a `FACTS_FORMAT`-only mismatch). It writes a store whose header
|
||||
says `FACTS_FORMAT` `2` with today's `CACHE_FORMAT` and `VERSION`
|
||||
otherwise unchanged, opens it, and asserts `facts_for` returns `None` (the
|
||||
whole store is unread, not field-shifted) and that the first write since
|
||||
replaces it under today's header, readable afterward. Passes. This closes
|
||||
a real test gap the round left — the design (the format number lives in
|
||||
the header line `IndexCache::open` compares byte-for-byte,
|
||||
`index_cache.rs:103`) was sound but untested for this exact axis.
|
||||
|
||||
- **A3 tie-break: confirmed correct**, both via the shipped
|
||||
`looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
|
||||
(passes) and by re-deriving it: `by_name` is built with a **stable** sort
|
||||
(`Vec::sort_by`, `lib.rs`), so symbols sharing a name keep declaration
|
||||
order, and `symbols_named`'s two `partition_point` binary searches over
|
||||
that name-sorted table can only reorder within a name if the sort were
|
||||
unstable — it is not.
|
||||
|
||||
- **`nav::definition` / hover agreement:** confirmed the detail location is
|
||||
filtered by `!span.is_empty()` (`nav.rs`) exactly as documented, and that a
|
||||
detail-less symbol (ANSI port, ordinary declaration) still returns exactly
|
||||
one location, unchanged from before this round.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted after one fix round. Gates re-run
|
||||
independently: fmt clean, clippy silent, `cargo test --workspace` green
|
||||
(2 396 passing at the time of review), `cargo test -p vlog_formatter` green.
|
||||
|
||||
`detail_span` is the right adaptation of the "detail range" idea to this
|
||||
model: the non-ANSI merge already produced one symbol, so the only thing
|
||||
missing was *where the declaration is completed*, and recording that as an
|
||||
optional second span leaves every complete-where-named declaration
|
||||
untouched. Hover and go-to-definition read the same field, which keeps
|
||||
`topo.md`'s one-matcher rule intact.
|
||||
|
||||
Two things in this feature deserved the scrutiny they got.
|
||||
|
||||
**The facts-format bump.** The first implementation added two numbers per
|
||||
declaration record without moving `FACTS_FORMAT`, on the argument that a
|
||||
short record fails `done()` and is dropped. That argument only holds for the
|
||||
*last* declaration in a record; every earlier one would have been read
|
||||
field-shifted by two, which is a persisted cache handing back wrong spans —
|
||||
the exact shape invariant 4 exists to catch, in the same family as the
|
||||
macro-items corruption. Bumping 2→3 is correct and QA's added regression test
|
||||
(`index_cache.rs`, a store from the previous format is dropped, not misread)
|
||||
closes a gap no existing test covered, since nothing varied `FACTS_FORMAT`
|
||||
alone.
|
||||
|
||||
**The comment attachment.** This began as scope creep — round 1's plan
|
||||
explicitly deferred doc comments on hover — and then turned out to be
|
||||
precisely what the user asked for, so it stays. But it is a *textual*
|
||||
heuristic running over disk text on the cross-file path, and QA's PDS-1 found
|
||||
it lying: `another_port_on` was a keyword blacklist, so a wrapped declaration
|
||||
whose first line is bare `input` looked like an empty line and the next
|
||||
port's comment attached to the previous port's card. Replacing the blacklist
|
||||
with a closer whitelist (`only_a_closer_on`) inverts the bias in the one
|
||||
direction that is safe — an unrecognised line now declines to attach rather
|
||||
than mis-attaching — and the doc comment states that bias as the contract.
|
||||
That is the correct resolution; a predicate over source text that guesses
|
||||
must fail closed.
|
||||
|
||||
PDS-2 was a genuine divergence from the user's stated rule and is fixed by
|
||||
making the three comment sources independent rather than a priority chain.
|
||||
PDS-3 was worth chasing rather than parking: the binder does perform the same
|
||||
header/body merge for `TfArg`, so old-style task and function arguments now
|
||||
get detail spans too, and the gap is closed rather than documented. PDS-4's
|
||||
CRLF strip is display-only and does not touch the buffer.
|
||||
|
||||
The dev renamed and inverted a QA-authored test, and flagged it. Correct call
|
||||
and correctly surfaced: the behaviour that test pinned *was* the finding.
|
||||
|
||||
@@ -50,16 +50,28 @@ not by 64 × 256.
|
||||
`parse_unary`), one nested generate `if` costs 2 (`parse_item` +
|
||||
`parse_gen_if`), one `.b` or one `+` costs 1 link. The limits are a
|
||||
stack-safety budget, not a style rule.
|
||||
- **8 MiB of stack is available.** That is the default main-thread stack on
|
||||
macOS and Linux, and `lucisv` parses on the main thread. Anything that parses
|
||||
on a *spawned* thread must give it a comparable stack — the default 2 MiB
|
||||
is not enough to reach the limit in an unoptimized build (see Handshakes;
|
||||
the tests here spawn 16 MiB threads for exactly this reason).
|
||||
- ~~**8 MiB of stack is available.**~~ **Retired 2026-08-28 — it is now
|
||||
enforced, not assumed.** This used to say "8 MiB is the default main-thread
|
||||
stack on macOS and Linux, and `lucisv` parses on the main thread". Both
|
||||
halves were hazards: the default is not 8 MiB everywhere (`ulimit -s` in a
|
||||
container, 1 MiB on Windows), and "parses on the main thread" stopped being
|
||||
true the moment anything spawned. `MAX_NESTING_DEPTH` bounds how *many*
|
||||
levels run, not what one costs, so the guard only converts an overflow into
|
||||
an error on a stack big enough to reach level 64. That size is now a
|
||||
constant — `vlog_parser::PARSE_STACK_SIZE` — and every thread that can
|
||||
reach a parse is spawned with it, including the two `main`s. See "The stack
|
||||
the limit needs" and the parse-site table in Handshakes.
|
||||
- **Unoptimized builds are the worst case.** Debug stack frames in this
|
||||
parser are large (`parse_keyword_stmt` alone is a ~50 KiB frame at
|
||||
`opt-level=0`, because rustc gives every match arm's temporaries their own
|
||||
slot and does not merge them). The limit is picked for debug builds, so
|
||||
release builds have an order of magnitude more headroom.
|
||||
- **Frame sizes drift upward, so the stack constant carries margin, not a
|
||||
fit.** The same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB on
|
||||
2026-08-28 (rustc 1.97.1) without a line of the parser changing. Nothing in
|
||||
the build pins a compiler version, and the failure mode is an abort rather
|
||||
than a diagnostic, so `PARSE_STACK_SIZE` is set at ~2.7× the measured worst
|
||||
case instead of just above it.
|
||||
- **Rejecting an over-deep file is acceptable behavior.** The file is left
|
||||
untouched with a diagnostic and exit 2, exactly like any other parse error.
|
||||
No real RTL is expected anywhere near the limit; machine-generated
|
||||
@@ -75,9 +87,16 @@ not by 64 × 256.
|
||||
```
|
||||
MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs)
|
||||
MAX_CHAIN_LENGTH = 256
|
||||
PARSE_STACK_SIZE = 16 MiB
|
||||
```
|
||||
|
||||
Going one past either produces an ordinary parse error:
|
||||
The first two bound the input. The third bounds nothing — it is what the
|
||||
first two *cost*, and it is the size every thread that can reach a parse is
|
||||
spawned with. The three only work together: a depth limit on a stack too
|
||||
small to reach it converts nothing, because the overflow (an abort, with no
|
||||
`Result` to return) happens first.
|
||||
|
||||
Going one past either limit produces an ordinary parse error:
|
||||
|
||||
```
|
||||
error: rtl/deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk")
|
||||
@@ -117,9 +136,12 @@ trips the limit (bisected the same way, minimum surviving thread stack):
|
||||
| nested `{...}` / `(...)` | 983–1047 KiB | 103 KiB |
|
||||
| `? :` chains, stacked `~` | 135–423 KiB | — |
|
||||
|
||||
So the worst case is **~3.9 MiB in a debug build, ~0.5 MiB in release**,
|
||||
against an 8 MiB main-thread stack: 2× headroom in the profile with the fat
|
||||
frames, 16× in the profile users actually run.
|
||||
So the worst case *as measured in 2026-08* is **~3.9 MiB in a debug build,
|
||||
~0.5 MiB in release**. Both the number and the stack it was compared against
|
||||
have since been superseded — see "The stack the limit needs" below, which
|
||||
re-measures it at ~5.9 MiB over a wider family sweep and replaces "the 8 MiB
|
||||
main-thread stack" with a stated constant. The table is kept because it is
|
||||
what 64 was chosen from; the choice still holds under the new numbers.
|
||||
|
||||
Why not larger: 128 would need ~7.9 MiB in a debug build — i.e. the CLI
|
||||
integration tests, which run the *debug* binary, would still overflow before
|
||||
@@ -168,6 +190,62 @@ fits). Charging chain links against `MAX_NESTING_DEPTH` instead would have
|
||||
capped those at ~60 terms and rejected real code; that is why chains get
|
||||
their own, larger budget rather than sharing the nesting one.
|
||||
|
||||
### The stack the limit needs — re-measured 2026-08-28
|
||||
|
||||
Same method as above (subprocess per trial, bisect the smallest thread stack
|
||||
that survives), but over the *whole* consumer pipeline this time —
|
||||
`tokenize` → `parse_tolerant` → `analyze` → `FileFacts`, i.e. what the
|
||||
language server runs, alongside `format_source`. Two things changed since the
|
||||
2026-08 numbers: the sweep now covers block families the first round did not
|
||||
(`case`, `fork`, `foreach`, `while`, `for`, nested modules), and the compiler
|
||||
moved (rustc 1.97.1).
|
||||
|
||||
Peak stack on input sized to *trip* the limit — the global worst case, since
|
||||
tripping it walks one level further than any legal input can:
|
||||
|
||||
| family | debug | release |
|
||||
|---|---|---|
|
||||
| nested `case` (any flavour: `casez`, `unique`, `inside`) | **6023 KiB** | **823 KiB** |
|
||||
| nested `case` + `begin` per level | 5847 KiB | 775 KiB |
|
||||
| `else if` chains | 5751 KiB | 807 KiB |
|
||||
| nested `if … begin` | 5735 KiB | 775 KiB |
|
||||
| nested `begin`, `fork`/`join`, labelled `begin : b` | 5591 KiB | 711 KiB |
|
||||
| `foreach` / `do … while` | 5447 KiB | 679 KiB |
|
||||
| `while` / `repeat` / `wait` / `assert … else` | 5367 KiB | 663 KiB |
|
||||
| generate `for` | 3879 KiB | 583 KiB |
|
||||
| generate `if` | 1895 KiB | 343 KiB |
|
||||
| nested `(...)` | 1623 KiB | 183 KiB |
|
||||
| `@(posedge clk)` chains | 1255 KiB | — |
|
||||
| nested `module` … `endmodule` | 103 KiB | 23 KiB |
|
||||
|
||||
So **~5.9 MiB debug, ~0.8 MiB release**, and ~94 KiB per gated level in a
|
||||
debug build rather than the ~62 KiB measured in 2026-08. Nested `module` is
|
||||
cheap because item frames are small; `case` is the ceiling because
|
||||
`parse_keyword_stmt` carries the fattest frame in the grammar and a `case`
|
||||
spends two of them per source level (the `case` itself, then the arm's
|
||||
statement).
|
||||
|
||||
Three things the same sweep settles:
|
||||
|
||||
- **The peak is entirely in the parser.** `analyze` and `FileFacts` measured
|
||||
byte-identical to `parse_tolerant` alone in every family, and `analyze` run
|
||||
*by itself* on a max-legal tree (parsed and dropped on a separate large
|
||||
thread) needs **71 KiB** — ~1.2 KiB per level. It does not need a bound of
|
||||
its own; it is two orders of magnitude under the walk that produced the
|
||||
tree. Same for the tolerant recovery: strict and tolerant parses of the
|
||||
same limit-tripping input bisect to the same byte.
|
||||
- **Chains still do not move the worst case.** A 256-link chain alone peaks
|
||||
at 2487 KiB debug (~9 KiB per link); the same chain inside 58 nested `case`
|
||||
measures 5895 KiB — identical to that nesting without any chain, because
|
||||
the two peak in different phases. The additive-composition argument above
|
||||
is unchanged.
|
||||
- **16 MiB is the constant, and it is margin rather than a fit.** 8 MiB —
|
||||
what the CLI's pool used and what a stock main thread happens to have —
|
||||
is 1.33× the debug worst case, and the last two years of this number moving
|
||||
(3.9 → 5.9 MiB, no parser change) say that is not enough room. 16 MiB is
|
||||
2.7×, costs address space rather than memory (thread stacks are committed a
|
||||
page at a time), and is the size the feature's tests already spawned.
|
||||
|
||||
## Where the counters sit
|
||||
|
||||
`Parser::enter()` / `Parser::leave()` bracket each gated function; `enter`
|
||||
@@ -286,17 +364,41 @@ not inflate depth — the output of a max-depth file re-parses inside
|
||||
expression it has already built — the `Box::new(previous)` shape — must
|
||||
charge `link()`, or it reopens exactly the hole QA found. Loops that push
|
||||
into a `Vec` widen the tree instead and need nothing.
|
||||
- **Request to TODO.md §3's parallel-file-processing item (rayon):** rayon
|
||||
worker threads default to 2 MiB of stack, which is *not* enough to reach
|
||||
the depth limit in a debug build (~3.9 MiB needed). Whoever lands
|
||||
parallelism must set `ThreadPoolBuilder::stack_size(8 * 1024 * 1024)` or
|
||||
larger, otherwise this feature's guarantee silently regresses to a crash.
|
||||
Same applies to any future LSP server thread that parses.
|
||||
- **Promised to every consumer: `vlog_parser::PARSE_STACK_SIZE`.** The depth
|
||||
limit converts an overflow into a diagnostic *only* on a stack of at least
|
||||
this size. It is a `pub const` next to the two limits, so no consumer picks
|
||||
a number of its own and none can drift from the measurement. The rule is
|
||||
one line: **any thread that can reach `tokenize`/`parse`/`analyze` is
|
||||
spawned with `stack_size(PARSE_STACK_SIZE)`** — including the thread a
|
||||
`main` hands its work to, because a process's main stack is set by the OS
|
||||
and `ulimit`, not by us.
|
||||
- **Request to TODO.md §6's error-tolerant parsing mode:** recovery must not
|
||||
reset `depth` while unwinding — it is decremented by `leave()` on the way
|
||||
out of every gated frame, including error paths, and a sync-and-continue
|
||||
recovery has to resume from the frame it recovered in.
|
||||
|
||||
### Every parse site and the stack it runs on
|
||||
|
||||
Audited 2026-08-28 by reading every `thread::spawn` / `thread::Builder` /
|
||||
`ThreadPoolBuilder` / `par_iter` in `crates/` outside `#[cfg(test)]`. This
|
||||
table is the enforcement: a new row without a stated stack is the bug.
|
||||
|
||||
| site | thread | stack |
|
||||
|---|---|---|
|
||||
| `lucisv/src/main.rs` — the whole run (`run_stdin`, `run_files`, `run_check`) | spawned `"lucisv"` | `PARSE_STACK_SIZE` |
|
||||
| `lucisv/src/main.rs::build_pool` — rayon global pool, used by `run_files`' and `lint.rs`' `par_iter` | rayon workers | `PARSE_STACK_SIZE` |
|
||||
| `lucisv_server/src/main.rs` — the LSP message loop, which analyses every buffer | spawned `"lucisv-main"` | `PARSE_STACK_SIZE` |
|
||||
| `lucisv_server/src/server.rs::queue` — forwards `Message`s off the rendezvous channel | spawned `"lucisv-queue"` | default; **never parses** (moves messages, touches no server state) |
|
||||
| `lsp-server`'s `Connection::stdio()` reader/writer | inside the dependency | default; **never parses** (JSON framing only) |
|
||||
| both `main` threads | OS-given | irrelevant by construction — they only parse arguments and the LSP handshake, then hand off |
|
||||
|
||||
Two sites were the actual hole this round closed. The rayon pool was already
|
||||
sized (`8 * 1024 * 1024`, from the older ~3.9 MiB measurement, now 1.33× a
|
||||
re-measured worst case and re-pointed at the constant); the two `main`
|
||||
threads were not sized at all, which is what "8 MiB of stack is available"
|
||||
assumed away. `lucisv -` and `lucisv check -` format on the calling thread
|
||||
and never reach the pool at all, so the CLI's spawn is not redundant with it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Depth counter (`Parser::depth`) + `enter`/`leave` guard pair.
|
||||
@@ -334,6 +436,34 @@ From QA round 1 (2026-08-19):
|
||||
one).
|
||||
- [x] TODO.md §1 recursion-depth item re-checked after the fix.
|
||||
|
||||
Round 3 — the stack the limit needs (2026-08-28, from a QA finding on
|
||||
`vlog_semantic::FileFacts::of`):
|
||||
|
||||
- [x] Diagnosis verified by measurement, not by reading: the overflow is in
|
||||
the parser's own descent, at level ~30 of an in-budget 64, on a 2 MiB
|
||||
thread. `analyze`, `FileFacts` and the tolerant recovery add nothing to
|
||||
the peak.
|
||||
- [x] Worst case re-measured over every nesting family, debug and release,
|
||||
through both the LSP pipeline and `format_source`: ~5.9 MiB / ~0.8 MiB,
|
||||
~94 KiB per gated level in debug. New table above.
|
||||
- [x] `analyze`'s own walk measured on a max-legal tree (71 KiB, ~1.2 KiB per
|
||||
level) — no second bound needed, and no second limit constant added.
|
||||
- [x] `PARSE_STACK_SIZE` (16 MiB) added next to the two limits, `pub`, with
|
||||
the measured rationale and the margin argument.
|
||||
- [x] Every production parse site audited and given that stack: the CLI's run
|
||||
thread, the rayon pool, the language server's message loop. Table in
|
||||
Handshakes; the two threads that do not parse are named there too.
|
||||
- [x] `MAX_NESTING_DEPTH` left at 64 — the stack fits the limit, not the
|
||||
other way round.
|
||||
- [x] Regression tests on controlled stacks: the reported repro through
|
||||
`FileFacts::of`, a 14-shape block sweep, at-limit parses for the two
|
||||
fattest families, and the stdin path through the real binary.
|
||||
- [x] Existing 16 MiB test threads re-pointed at the constant (`parse_deep`,
|
||||
`format_deep`), so a shrunk guarantee fails the suite.
|
||||
- [x] Batch/`catch_unwind` behaviour re-checked end-to-end after the change.
|
||||
- [x] `cargo test --workspace` (2425), `cargo clippy --all-targets`,
|
||||
`cargo fmt --check` all clean.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
@@ -468,6 +598,104 @@ Files touched: `crates/vlog_parser/src/parser.rs`,
|
||||
grew a second pathological file). `cargo clippy --all-targets` silent.
|
||||
`cargo fmt --check` clean. Same files touched as the first round.
|
||||
|
||||
### 2026-08-28 — dev agent, the stack the limit needs
|
||||
|
||||
- **Reproduced first, diagnosed second.** Built a scratchpad probe crate
|
||||
(path-dependencies on the real crates, never inside the repo) that runs one
|
||||
shape, one depth, one phase on a thread of a chosen size, as a
|
||||
*subprocess*, so a stack overflow — which aborts and cannot be caught — is
|
||||
just a non-zero exit to bisect on. The reported input (500 nested `begin`
|
||||
through `FileFacts::of`) dies on a 2 MiB thread exactly as reported.
|
||||
- **The lead's reading is confirmed, and sharper than "64 levels is too
|
||||
much".** Splitting the pipeline into phases, the minimum surviving stack is
|
||||
*byte-identical* for `parse_tolerant` alone, `parse_tolerant` + `analyze`,
|
||||
and the full `FileFacts::of`, in all 25 shapes measured — so the peak is
|
||||
the parser's own descent, and neither `analyze` nor the record-building
|
||||
adds a frame above it. Strict and tolerant parses of the same input also
|
||||
bisect to the same byte, so recovery adds nothing either. At ~94 KiB per
|
||||
gated level the overflow lands around level 30 of an in-budget 64: the
|
||||
limiter never gets to fire. Nothing was missing a counter.
|
||||
- **`analyze` measured on its own** (parse and drop the tree on a separate
|
||||
256 MiB thread, analyse on the thread being bisected) to make sure the
|
||||
identical numbers were not masking: **71 KiB** on a max-legal tree, ~1.2 KiB
|
||||
per level. Two orders of magnitude under the parse. So no second bound and,
|
||||
per the brief, no second limit constant.
|
||||
- **Swept 25 shapes rather than the reported one**, because the reported one
|
||||
is not the worst: nested `case` (6023 KiB debug) beats nested `begin`
|
||||
(5591 KiB), and neither was in the 2026-08 table. Also measured
|
||||
`casez`/`unique`/`inside` flavours, `case`+`begin` per level, `fork`/`join`,
|
||||
labelled blocks, `foreach`, `while`, `for`, `repeat`, `wait`, `do … while`,
|
||||
`assert … else`, `@(posedge)` chains, generate `if`/`for`, nested modules
|
||||
and nested tasks. Full table above. The old ~3.9 MiB figure is now ~5.9 MiB
|
||||
on rustc 1.97.1 without a parser change, which is the argument for margin
|
||||
rather than a fit.
|
||||
- **`PARSE_STACK_SIZE = 16 MiB`, and one constant for everything.** 8 MiB —
|
||||
what the rayon pool already used, and what a stock main thread happens to
|
||||
have — is 1.33× the debug worst case; 16 MiB is 2.7×, costs address space
|
||||
rather than resident memory, and is the number the feature's own tests were
|
||||
already spawning. Putting it in `vlog_parser` beside `MAX_NESTING_DEPTH` is
|
||||
what stops it drifting: the tests now spell the constant instead of
|
||||
`16 * 1024 * 1024`, so cutting the guarantee below what the limit needs
|
||||
fails the suite rather than the user.
|
||||
- **Audited every parse site** (`thread::spawn`, `thread::Builder`,
|
||||
`ThreadPoolBuilder`, `par_iter` across `crates/`, excluding
|
||||
`#[cfg(test)]`); table in Handshakes. The rayon pool was the only one that
|
||||
had a stated stack. The two `main` threads had none — that is what "8 MiB
|
||||
of stack is available" was assuming, and it is not true on Windows, under a
|
||||
tuned `ulimit -s`, or for anyone who later moves work onto a thread. Both
|
||||
`main`s now hand their work to a thread sized by the constant.
|
||||
- **The CLI's spawn is not redundant with the pool.** `docs/features/
|
||||
parallel-files` established (with a probe, and re-verified by QA) that
|
||||
rayon's `par_iter` called from outside the pool *blocks* the caller instead
|
||||
of running jobs on it. But `lucisv -` and `lucisv check -` never build a
|
||||
pool at all: they format the buffer on the calling thread. That path had no
|
||||
stated stack until this change, and it is the one the new CLI test covers.
|
||||
- **Deliberately not done: lowering `MAX_NESTING_DEPTH`.** Per the brief, and
|
||||
because it would change which real files parse. The stack fits the limit.
|
||||
- **Deliberately not done: shrinking the parser's frames.** The 2026-08 round
|
||||
measured that experiment (extracting one `match` arm moved
|
||||
`parse_keyword_stmt` 50,528 → 47,872 B) and rejected it; nothing has
|
||||
changed that calculus, and this round's fix does not need it.
|
||||
- **Tests, all on controlled stacks so they cannot be flaky across
|
||||
environments** — `vlog_semantic/tests/deep_nesting.rs` is new
|
||||
(`five_hundred_nested_blocks_are_indexed_not_aborted` — the reported repro,
|
||||
which now indexes module `m` with the unparsable body recovered;
|
||||
`no_block_shape_can_abort_the_parse_stack` — 14 shapes at 400 levels
|
||||
including nested modules, tasks, functions, fork/join, generate blocks and
|
||||
else-if chains; `nesting_just_under_the_limit_still_yields_its_facts`).
|
||||
`vlog_parser` gained `deep_nesting_errors_for_every_block_form` and
|
||||
`the_fattest_block_forms_still_parse_at_the_limit`; `lucisv` gained
|
||||
`a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash`.
|
||||
- **Sabotage-verified the new tests the way QA does**: set
|
||||
`PARSE_STACK_SIZE` to 2 MiB, rebuilt, and `cargo test -p vlog_semantic
|
||||
--test deep_nesting` died with `SIGABRT` / "fatal runtime error: stack
|
||||
overflow" instead of failing an assertion — i.e. the tests are pinned to
|
||||
the constant, not merely passing beside it. Restored and re-ran green.
|
||||
- **Re-checked the batch/`catch_unwind` claims** end-to-end with the real
|
||||
debug binary on a 4-file directory (`good`, 500 nested `begin`, 400 nested
|
||||
`case`, `good`): `2 files reformatted, 2 files failed to format`, exit 2,
|
||||
both deep files left untouched, no abort. Also drove the real
|
||||
`lucisv-server` over stdio with the 500-level buffer: `initialize`,
|
||||
`didOpen`, `publishDiagnostics`, a `documentSymbol` answer naming module
|
||||
`m`, clean `shutdown`/`exit` 0.
|
||||
- **Touched two files outside this feature, both because they now contradict
|
||||
the code:** `docs/features/parallel-files/README.md`'s "8 MiB of worker
|
||||
stack is enough" assumption and its recursion-limit handshake bullet, and
|
||||
the same number in TODO.md §3's parallel-file item. Only the living
|
||||
contract sentences — that feature's work log and QA log are history and
|
||||
were left alone.
|
||||
|
||||
**Results:** `cargo test --workspace` **2425 passed, 0 failed** (up 8: +2
|
||||
`vlog_parser` unit, +3 `vlog_semantic` `deep_nesting`, +1 `lucisv` CLI, and
|
||||
two pre-existing helpers re-pointed at the constant). `cargo clippy
|
||||
--all-targets` silent. `cargo fmt --check` clean. Files touched:
|
||||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_parser/src/lib.rs`,
|
||||
`crates/lucisv/src/main.rs`, `crates/lucisv_server/src/main.rs`,
|
||||
`crates/lucisv_server/src/server.rs` (one doc comment),
|
||||
`crates/vlog_formatter/tests/deep_nesting.rs`, `crates/lucisv/tests/cli.rs`,
|
||||
`crates/vlog_semantic/tests/deep_nesting.rs` (new),
|
||||
`docs/features/parallel-files/README.md`, `TODO.md`, this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
@@ -884,8 +1112,208 @@ No new BLOCKING finding. No code changes made this round (the one finding
|
||||
is a documentation number, not something I judged a "small unambiguous
|
||||
fix" worth touching without the dev confirming their construction).
|
||||
|
||||
### 2026-08-28 — QA agent, the stack the limit needs
|
||||
|
||||
**Tooling results (verbatim):** `cargo fmt --check`: clean, exit 0.
|
||||
`cargo clippy --all-targets`: silent, no warnings. `cargo test --workspace`:
|
||||
every binary green, 0 failed across the run (`vlog_parser` lib 1204 passed/23
|
||||
ignored, `vlog_semantic` 82 + 62 + 3 new `deep_nesting`, `vlog_formatter` 4
|
||||
`deep_nesting`, `lucisv` 217 + the new stdin test, `lucisv_server` 190 + 20 +
|
||||
114 + others, doc-tests all 0/0 except `vlog_linter`'s 1/1) — matches the
|
||||
dev's "2425 passed, 0 failed" claim (one transient doctest failure on a first
|
||||
run, `vlog_linter`'s, traced to a stale rlib left by my own concurrent
|
||||
`git stash`/rebuild during the ulimit test below, not a real regression —
|
||||
reran `cargo test -p vlog_linter --doc` clean on its own and the next full
|
||||
`cargo test --workspace` was clean too).
|
||||
|
||||
**Independent audit of every thread/pool/par_iter outside `#[cfg(test)]`
|
||||
(charter item 1) — matches the dev's table exactly, no missed site.**
|
||||
`grep -rn "thread::spawn\|thread::Builder\|ThreadPoolBuilder\|par_iter\|\.spawn("
|
||||
crates --include="*.rs"` and traced every hit:
|
||||
|
||||
- `lucisv/src/main.rs`'s own spawn (the "lucisv" thread) and `build_pool`
|
||||
(rayon global pool): both `PARSE_STACK_SIZE`, as claimed.
|
||||
- `lucisv/src/lint.rs:48`'s `jobs.par_iter()` (the `check` subcommand,
|
||||
charter's "vlog_linter/vlog_refactor entry points from the CLI pool"):
|
||||
confirmed it runs on the *same* rayon global pool `build_pool` sizes —
|
||||
`run_check` calls `gather(opts).and_then(|jobs| build_pool(opts).map(...))`
|
||||
before `lint::check_files`, same as `run_files`. `check`'s stdin path
|
||||
(`lint::check_stdin`) never touches the pool at all; it runs on `run_check`
|
||||
called from `run()`, which is the body of the spawned "lucisv" thread — so
|
||||
it inherits `PARSE_STACK_SIZE` the same way `run_stdin` does. Not a missed
|
||||
site; the dev's table entry ("the whole run") already covers it, just not
|
||||
spelled out by name.
|
||||
- `lucisv_server/src/main.rs`'s spawn and `server.rs::queue`'s forwarder:
|
||||
match the table.
|
||||
- `lucisv_server/src/index_cache.rs:921,1194` and `state.rs:3374` (a
|
||||
`qa_attack_…` test spawning at a deliberate 64 MiB, with a comment citing a
|
||||
*different*, pre-existing recursion ceiling filed in `index-scope`'s own
|
||||
2026-08-28 QA log) — all three are inside `#[cfg(test)] mod tests`
|
||||
(checked with `grep -n "#\[cfg(test)\]"` in each file), so they are
|
||||
correctly outside the dev's stated audit scope ("outside `#[cfg(test)]`")
|
||||
and outside production risk. Tried to find a production path to them
|
||||
anyway (workspace-scan-on-`initialize`, watched-file rescans) — found none;
|
||||
`index_cache`'s writers only run inside its own test module.
|
||||
- `lsp-server` 0.10.0's own threads (`stdio.rs`): read the vendored source at
|
||||
`~/.cargo/registry/src/…/lsp-server-0.10.0/src/stdio.rs` — reader and
|
||||
writer threads only frame/deframe `Message` (JSON-RPC header parsing via
|
||||
`usize::parse`, unrelated to `vlog_parser`), no `vlog_parser` symbol
|
||||
anywhere in the crate. Confirms charter item 2's second half directly from
|
||||
the dependency's source, not by inference.
|
||||
- `server.rs::queue` (charter item 2's first half): read `queue()` and
|
||||
`run()` in full. The forwarder thread's closure captures only
|
||||
`source`/`sender`, does `source.recv()` → `sender.send()` → break on
|
||||
`is_shutdown`/`Err`, touches no field of `Server`; `run()` and
|
||||
`process_batch` are the only things that call `self.request`/
|
||||
`self.notification` (which reach analysis), and they execute on the
|
||||
thread `Server::run` was called on, i.e. the spawned `"lucisv-main"`
|
||||
thread. The module doc at `server.rs:1` ("one burst in, one response per
|
||||
request, on one thread") holds; `didChangeWatchedFiles` and every other
|
||||
notification dispatch through `Server::notification` (`server.rs:1249`),
|
||||
called only from `process_batch`, same thread.
|
||||
|
||||
No un-gated production parse-reachable spawn found. Dev's table is accurate
|
||||
and complete.
|
||||
|
||||
**Charter item 3 (library-consumer footgun) — real gap found, fixed
|
||||
directly as a small unambiguous doc fix.** The README's Handshakes section
|
||||
states the contract plainly ("any thread that can reach
|
||||
`tokenize`/`parse`/`analyze` is spawned with `stack_size(PARSE_STACK_SIZE)`"),
|
||||
but that is an internal project document, not rustdoc — a consumer of
|
||||
`vlog_parser`/`vlog_semantic`/`vlog_formatter` as a library reads the public
|
||||
items' own doc comments, and none of them said anything: `vlog_parser::parse`
|
||||
(`parser.rs:271`), `parse_tolerant` (`parser.rs:283`), `vlog_semantic::
|
||||
FileFacts::of` (`workspace.rs:741`), `vlog_formatter::format_source`
|
||||
(`format.rs:80`) and `format_range` (`format.rs:101`) — the five public
|
||||
entry points that actually recurse over caller-supplied input — carried no
|
||||
stack-size mention at all. Confirmed by reading each doc comment before this
|
||||
fix; `tokenize` (`lexer.rs:731`) checked too and correctly excluded — it is
|
||||
loop-based with no recursion on nesting, so it carries no such requirement.
|
||||
Added a one- to three-line note to each of the five, referencing
|
||||
`PARSE_STACK_SIZE` and (except `parse`/`parse_tolerant`, which are right next
|
||||
to the constant) `docs/features/recursion-limit/README.md`. Files touched:
|
||||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_semantic/src/workspace.rs`,
|
||||
`crates/vlog_formatter/src/format.rs`. Re-ran `cargo fmt --check` and
|
||||
`cargo clippy --all-targets` after — both still clean.
|
||||
|
||||
**Charter item 4 (sabotage re-verify), on a scratchpad copy, never the
|
||||
repo under review.**
|
||||
|
||||
- `PARSE_STACK_SIZE` 16 MiB → 2 MiB, rebuilt: `cargo test -p vlog_semantic
|
||||
--test deep_nesting`, `cargo test -p vlog_formatter --test deep_nesting`
|
||||
and `cargo test -p vlog_parser --lib` (which builds `parse_deep` on the
|
||||
same constant) **all SIGABRT** ("stack overflow, aborting", signal 6) —
|
||||
every deep-nesting test suite genuinely depends on the constant rather
|
||||
than merely running beside it. Restored to 16 MiB and reran: all three
|
||||
green again (`vlog_semantic`: 3/3, `vlog_formatter`: 4/4, `vlog_parser`
|
||||
lib: full suite).
|
||||
- `MAX_NESTING_DEPTH` 64 → 128, `PARSE_STACK_SIZE` left at 16 MiB (the
|
||||
"double the limit, keep the stack" margin check): `vlog_semantic`'s
|
||||
`deep_nesting` (3/3), `vlog_formatter`'s `deep_nesting` (4/4) and
|
||||
`vlog_parser`'s `nesting_just_below_the_limit_parses`,
|
||||
`chain_just_below_the_limit_parses`, `the_fattest_block_forms_still_
|
||||
parse_at_the_limit` and `deep_nesting_errors_for_every_block_form` all
|
||||
**passed** — including `the_fattest_block_forms_still_parse_at_the_limit`,
|
||||
which now parses 122-deep `fork`/`case` nesting (`MAX_NESTING_DEPTH - 6`)
|
||||
on the same 16 MiB stack that only had to reach 58 before. The 2.7×
|
||||
margin is real, not illusory: it survives doubling the depth the tests
|
||||
actually walk. Reverted `MAX_NESTING_DEPTH` to 64. Verified afterward that
|
||||
the working tree's `parser.rs` shows only the intended diff (`grep -n
|
||||
"MAX_NESTING_DEPTH: u32\|PARSE_STACK_SIZE: usize"` → `64` and
|
||||
`16 * 1024 * 1024`, matching what `git status` shows for the round under
|
||||
review).
|
||||
|
||||
**Charter item 5 (binary end-to-end) — both scenarios behave as claimed,
|
||||
and the pre-fix binary was rebuilt to confirm the deviation is load-bearing,
|
||||
not cosmetic.**
|
||||
|
||||
- Directory run: a temp dir with `good.sv` and a 500-nested-`begin` file
|
||||
through `./target/debug/lucisv .`: `error: ./deep500.sv: parse error:
|
||||
64:1: nesting too deep (limit 64) (found "begin")` /
|
||||
`1 file left unchanged, 1 file failed to format`, exit 2. `good.sv`
|
||||
untouched (it was already formatted), `deep500.sv`'s first 60 bytes
|
||||
confirmed byte-identical to the input. No abort.
|
||||
- `ulimit -s 1024; lucisv - < deep500.sv` (1 MiB main-thread stack) on the
|
||||
**fixed** binary: `error: <stdin>: parse error: 64:1: nesting too deep
|
||||
(limit 64) (found "begin")`, exit 2, no crash.
|
||||
- To confirm this isn't true regardless of the fix (i.e. that the moved-main
|
||||
deviation actually matters, not just the depth counter): stashed the
|
||||
round's diff (`git stash`, working tree confirmed clean via `git status`),
|
||||
rebuilt `lucisv`, and ran the identical `ulimit -s 1024` command against
|
||||
the **pre-fix** binary: `thread 'main' (…) has overflowed its stack /
|
||||
fatal runtime error: stack overflow, aborting`, exit 134 (SIGABRT) — same
|
||||
input, same shell, only the binary differs. Popped the stash (`git stash
|
||||
pop`, confirmed all twelve modified files and the new test file were back)
|
||||
and rebuilt the fixed binary; reran the same command to reconfirm exit 2.
|
||||
This is the one experiment in this round that actually falsifies "the
|
||||
depth counter alone was always going to be enough" — it was not, on a
|
||||
shell with a small `ulimit -s`, until `main` stopped running on the OS-given
|
||||
stack.
|
||||
|
||||
**Charter item 5, LSP half — independently reproduced via a standalone LSP
|
||||
client (not the dev's own manual verification, not the checked-in `e2e.rs`
|
||||
suite, which has no test for this exact repro).** Wrote a small Python
|
||||
script (framed JSON-RPC over the real `lucisv-server` binary's stdio) that
|
||||
sends `initialize` → `initialized` → `didOpen` (the 500-nested-`begin` file)
|
||||
→ `documentSymbol` → `shutdown` → `exit`. Result: `publishDiagnostics` with
|
||||
`"nesting too deep (limit 64) (found \"begin\")"` at line 63, a second
|
||||
diagnostic for the resulting `endmodule` mismatch, `documentSymbol` still
|
||||
answers with module `m` (`range` spanning the whole 564-line file), clean
|
||||
`shutdown` (`id: 99, result: null`) and process exit code 0. No crash, no
|
||||
hang, matches the dev's manual claim independently.
|
||||
|
||||
**Charter item 6 (idempotency/corruption) — holds.** On the fixed binary:
|
||||
a 58-nested-`begin` file (one under the dev's stated 59/60 with-statement
|
||||
boundary — chosen so the *statement* inside costs its extra levels too, same
|
||||
construction the boundary table uses) formats once, then formats again from
|
||||
its own output: `diff` reports the two outputs identical, i.e.
|
||||
`format(format(x)) == format(x)`. The 500-nested-`begin` file piped through
|
||||
`lucisv -`: stdout is exactly 0 bytes (no partial output), stderr carries
|
||||
the one-line diagnostic, exit 2 — the "verified-correct output or the input
|
||||
unchanged with an error, never partial" invariant holds for the rejection
|
||||
path on the CLI's own thread, consistent with the directory-run and
|
||||
`vlog_semantic` test evidence that the tolerant/LSP path never produces a
|
||||
corrupted tree either (recovery yields an `ItemKind::Error` leaf, not
|
||||
partial/wrong facts).
|
||||
|
||||
**Verdict: SHIP.** No blocking or medium finding. One low finding (the
|
||||
library-consumer stack-size contract living only in an internal README, not
|
||||
in any public item's rustdoc) fixed directly per CLAUDE.md's "small
|
||||
unambiguous fix" allowance — five doc comments, no behavior change, gates
|
||||
re-confirmed clean after. The round's own claims all independently
|
||||
reproduced: the audit table is complete, the forwarder and `lsp-server`
|
||||
threads are confirmed parse-free by reading their code (not just trusting
|
||||
the comment), the stack-size guarantee is real under sabotage in both
|
||||
directions (shrinking it breaks the tests it should break; doubling the
|
||||
depth limit under the existing stack does not), and both the CLI and LSP
|
||||
binaries handle the original repro gracefully end-to-end, including the one
|
||||
scenario (`ulimit -s 1024`) where the pre-fix binary provably still crashes.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead, stack-budget round.** Reviewed after QA's SHIP;
|
||||
gates re-run independently (fmt clean, clippy silent, 2425 workspace
|
||||
tests green). The round did the right thing with the diagnosis: nothing
|
||||
was missing a counter — the 2026-08 feature's own "8 MiB is available"
|
||||
Assumption was the unenforced hole, and its measured basis had silently
|
||||
drifted (~62→~94 KiB per level under rustc 1.97, worst family now
|
||||
nested `case`, never measured in the original round). Turning the
|
||||
assumption into one code-enforced constant (`PARSE_STACK_SIZE`, 16 MiB,
|
||||
2.7× over the re-measured worst case) applied at every parse-reaching
|
||||
spawn site is the boring fix the situation wanted; the dev's deviation
|
||||
of moving both binaries' work off the main thread is load-bearing, not
|
||||
cosmetic — QA proved the pre-fix binary aborts under `ulimit -s 1024`
|
||||
where the fixed one emits a diagnostic, and the win32 target's 1 MiB
|
||||
default main stack made this a real shipped-binary risk, not just a
|
||||
test-thread artifact. QA's independent spawn-site audit matched the
|
||||
dev's table exactly, the sabotage runs prove the tests exercise the
|
||||
guarantee (2 MiB → SIGABRT) and the margin survives doubling the depth
|
||||
limit, and its doc fix — the caller-side stack contract on every public
|
||||
parse entry point's rustdoc — closes the library-consumer footgun the
|
||||
lead's charter flagged. Invariant 1 spot-checks (no partial output on
|
||||
rejection, idempotent round-trip at depth) held. Accepted; committed by
|
||||
the lead.
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed after one rejection
|
||||
and a verified rework.**
|
||||
|
||||
|
||||
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user